Search in sources :

Example 6 with Config

use of io.fabric8.agent.model.Config in project curiostack by curioswitch.

the class RequestNamespaceCertTask method exec.

@TaskAction
public void exec() {
    ImmutableClusterExtension cluster = getProject().getExtensions().getByType(ClusterExtension.class);
    final KeyPairGenerator keygen;
    try {
        keygen = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new IllegalStateException("Could not find RSA, can't happen.", e);
    }
    keygen.initialize(256, new SecureRandom());
    KeyPair keyPair = keygen.generateKeyPair();
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Principal("CN=" + cluster.namespace() + ".ns.cluster.stellarstation.com"), keyPair.getPublic());
    Stream<GeneralName> generalNames = Streams.concat(Stream.of(new GeneralName(GeneralName.dNSName, "*." + cluster.namespace()), new GeneralName(GeneralName.dNSName, "*." + cluster.namespace() + ".svc"), new GeneralName(GeneralName.dNSName, "*." + cluster.namespace() + ".svc.cluster.local")), cluster.extraNamespaceTlsHosts().stream().map(name -> new GeneralName(GeneralName.dNSName, name)));
    GeneralNames subjectAltNames = new GeneralNames(generalNames.toArray(GeneralName[]::new));
    ExtensionsGenerator extensions = new ExtensionsGenerator();
    try {
        extensions.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
        p10Builder.setAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensions.generate());
    } catch (IOException e) {
        throw new IllegalStateException("Could not encode cert name, can't happen.", e);
    }
    final ContentSigner signer;
    try {
        signer = new JcaContentSignerBuilder("SHA256withECDSA").build(keyPair.getPrivate());
    } catch (OperatorCreationException e) {
        throw new IllegalStateException("Could not find signer, can't happen.", e);
    }
    PKCS10CertificationRequest csr = p10Builder.build(signer);
    StringWriter csrWriter = new StringWriter();
    try (JcaPEMWriter pemWriter = new JcaPEMWriter(csrWriter)) {
        pemWriter.writeObject(csr);
    } catch (IOException e) {
        throw new IllegalStateException("Could not encode csr, can't happen.", e);
    }
    String encodedCsr = Base64.getEncoder().encodeToString(csrWriter.toString().getBytes(StandardCharsets.UTF_8));
    Map<Object, Object> csrApiRequest = ImmutableMap.of("apiVersion", "certificates.k8s.io/v1beta1", "kind", "CertificateSigningRequest", "metadata", ImmutableMap.of("name", cluster.namespace() + ".server.crt"), "spec", ImmutableMap.of("request", encodedCsr, "usages", ImmutableList.of("digital signature", "key encipherment", "server auth", "client auth")));
    final byte[] encodedApiRequest;
    try {
        encodedApiRequest = OBJECT_MAPPER.writeValueAsBytes(csrApiRequest);
    } catch (JsonProcessingException e) {
        throw new IllegalStateException("Could not encode yaml", e);
    }
    ImmutableGcloudExtension config = getProject().getRootProject().getExtensions().getByType(GcloudExtension.class);
    String command = config.download() ? CommandUtil.getGcloudSdkBinDir(getProject()).resolve("kubectl").toAbsolutePath().toString() : "kubectl";
    getProject().exec(exec -> {
        exec.executable(command);
        exec.args("create", "-f", "-");
        exec.setStandardInput(new ByteArrayInputStream(encodedApiRequest));
    });
    getProject().exec(exec -> {
        exec.executable(command);
        exec.args("certificate", "approve", cluster.namespace() + ".server.crt");
    });
    // Need to wait a bit for certificate to propagate before fetching.
    try {
        TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    // Gradle Exec seems to be flaky when reading from stdout, so use normal ProcessBuilder.
    final byte[] certificateBytes;
    try {
        Process getCertProcess = new ProcessBuilder(command, "get", "csr", cluster.namespace() + ".server.crt", "-o", "jsonpath={.status.certificate}").start();
        certificateBytes = ByteStreams.toByteArray(getCertProcess.getInputStream());
    } catch (IOException e) {
        throw new UncheckedIOException("Could not fetch certificate.", e);
    }
    String certificate = new String(Base64.getDecoder().decode(certificateBytes), StandardCharsets.UTF_8);
    final JcaPKCS8Generator keyGenerator;
    final PemObject keyObject;
    try {
        keyGenerator = new JcaPKCS8Generator(keyPair.getPrivate(), null);
        keyObject = keyGenerator.generate();
    } catch (PemGenerationException e) {
        throw new IllegalStateException("Could not encode to pkcs8.", e);
    }
    StringWriter keyWriter = new StringWriter();
    try (JcaPEMWriter pemWriter = new JcaPEMWriter(keyWriter)) {
        pemWriter.writeObject(keyObject);
    } catch (IOException e) {
        throw new IllegalStateException("Could not encode csr, can't happen.", e);
    }
    String key = keyWriter.toString();
    KubernetesClient client = new DefaultKubernetesClient();
    Secret certificateSecret = new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName("server-tls").withNamespace(cluster.namespace()).build()).withType("Opaque").withData(ImmutableMap.of("server.crt", Base64.getEncoder().encodeToString(certificate.getBytes(StandardCharsets.UTF_8)), "server-key.pem", Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8)))).build();
    client.resource(certificateSecret).createOrReplace();
}
Also used : KeyPair(java.security.KeyPair) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) Extension(org.bouncycastle.asn1.x509.Extension) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) Security(java.security.Security) SecureRandom(java.security.SecureRandom) TaskAction(org.gradle.api.tasks.TaskAction) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) DefaultTask(org.gradle.api.DefaultTask) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KeyPairGenerator(java.security.KeyPairGenerator) PemObject(org.bouncycastle.util.io.pem.PemObject) ImmutableMap(com.google.common.collect.ImmutableMap) Streams(com.google.common.collect.Streams) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) Base64(java.util.Base64) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Stream(java.util.stream.Stream) GcloudExtension(org.curioswitch.gradle.plugins.gcloud.GcloudExtension) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteStreams(com.google.common.io.ByteStreams) Secret(io.fabric8.kubernetes.api.model.Secret) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) X500Principal(javax.security.auth.x500.X500Principal) PKCSObjectIdentifiers(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers) ContentSigner(org.bouncycastle.operator.ContentSigner) ImmutableGcloudExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableGcloudExtension) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ImmutableClusterExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableClusterExtension) ImmutableList(com.google.common.collect.ImmutableList) ClusterExtension(org.curioswitch.gradle.plugins.gcloud.ClusterExtension) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) StringWriter(java.io.StringWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) TimeUnit(java.util.concurrent.TimeUnit) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) CommandUtil(org.curioswitch.gradle.plugins.shared.CommandUtil) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) JcaPKCS8Generator(org.bouncycastle.openssl.jcajce.JcaPKCS8Generator) NoSuchProviderException(java.security.NoSuchProviderException) ImmutableGcloudExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableGcloudExtension) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) UncheckedIOException(java.io.UncheckedIOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ImmutableClusterExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableClusterExtension) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) StringWriter(java.io.StringWriter) JcaPKCS8Generator(org.bouncycastle.openssl.jcajce.JcaPKCS8Generator) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) KeyPairGenerator(java.security.KeyPairGenerator) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) Secret(io.fabric8.kubernetes.api.model.Secret) PemObject(org.bouncycastle.util.io.pem.PemObject) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) ByteArrayInputStream(java.io.ByteArrayInputStream) X500Principal(javax.security.auth.x500.X500Principal) PemObject(org.bouncycastle.util.io.pem.PemObject) GeneralName(org.bouncycastle.asn1.x509.GeneralName) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) NoSuchProviderException(java.security.NoSuchProviderException) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) TaskAction(org.gradle.api.tasks.TaskAction)

Example 7 with Config

use of io.fabric8.agent.model.Config in project carbon-apimgt by wso2.

the class ServiceDiscovererKubernetes method buildConfig.

/**
 * Builds the Config required by DefaultOpenShiftClient
 * Also sets the system properties
 * (1) to not refer .kube/config file and
 * (2) the client to use service account procedure to get authenticated and authorised
 *
 * @return {@link io.fabric8.kubernetes.client.Config} object to build the client
 * @throws ServiceDiscoveryException if an error occurs while building the config using externally stored token
 */
private Config buildConfig(Map<String, String> implParameters) throws ServiceDiscoveryException, APIMgtDAOException {
    System.setProperty(TRY_KUBE_CONFIG, "false");
    System.setProperty(TRY_SERVICE_ACCOUNT, "true");
    /*
         *  Common to both situations,
         *      - Token found inside APIM pod
         *      - Token stored in APIM resources/security folder }
         */
    ConfigBuilder configBuilder = new ConfigBuilder().withMasterUrl(implParameters.get(MASTER_URL)).withCaCertFile(implParameters.get(CA_CERT_PATH));
    /*
         *  Check if a service account token File Name is given in the configuration
         *      - if not : assume APIM is running inside a pod and look for the pod's token
         */
    String externalSATokenFileName = implParameters.get(EXTERNAL_SA_TOKEN_FILE_NAME);
    if (StringUtils.isEmpty(externalSATokenFileName)) {
        log.debug("Looking for service account token in " + POD_MOUNTED_SA_TOKEN_FILE_PATH);
        String podMountedSAToken = APIFileUtils.readFileContentAsText(implParameters.get(POD_MOUNTED_SA_TOKEN_FILE_PATH));
        return configBuilder.withOauthToken(podMountedSAToken).build();
    } else {
        log.info("Using externally stored service account token");
        return configBuilder.withOauthToken(resolveToken("encrypted" + externalSATokenFileName)).build();
    }
}
Also used : ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder)

Example 8 with Config

use of io.fabric8.agent.model.Config in project docker-maven-plugin by fabric8io.

the class DockerAccessFactory method getDefaultDockerHostProviders.

/**
 * Return a list of providers which could delive connection parameters from
 * calling external commands. For this plugin this is docker-machine, but can be overridden
 * to add other config options, too.
 *
 * @return list of providers or <code>null</code> if none are applicable
 */
private List<DockerConnectionDetector.DockerHostProvider> getDefaultDockerHostProviders(DockerAccessContext dockerAccessContext, Logger log) {
    DockerMachineConfiguration config = dockerAccessContext.getMachine();
    if (dockerAccessContext.isSkipMachine()) {
        config = null;
    } else if (config == null) {
        Properties projectProps = dockerAccessContext.getProjectProperties();
        if (projectProps.containsKey(DockerMachineConfiguration.DOCKER_MACHINE_NAME_PROP)) {
            config = new DockerMachineConfiguration(projectProps.getProperty(DockerMachineConfiguration.DOCKER_MACHINE_NAME_PROP), projectProps.getProperty(DockerMachineConfiguration.DOCKER_MACHINE_AUTO_CREATE_PROP));
        }
    }
    List<DockerConnectionDetector.DockerHostProvider> ret = new ArrayList<>();
    ret.add(new DockerMachine(log, config));
    return ret;
}
Also used : DockerMachine(io.fabric8.maven.docker.access.DockerMachine) DockerMachineConfiguration(io.fabric8.maven.docker.config.DockerMachineConfiguration) ArrayList(java.util.ArrayList) Properties(java.util.Properties)

Example 9 with Config

use of io.fabric8.agent.model.Config in project docker-maven-plugin by fabric8io.

the class AuthConfigFactory method createAuthConfig.

/**
 * Create an authentication config object which can be used for communication with a Docker registry
 *
 * The authentication information is looked up at various places (in this order):
 *
 * <ul>
 *    <li>From system properties</li>
 *    <li>From the provided map which can contain key-value pairs</li>
 *    <li>From the openshift settings in ~/.config/kube</li>
 *    <li>From the Maven settings stored typically in ~/.m2/settings.xml</li>
 *    <li>From the Docker settings stored in ~/.docker/config.json</li>
 * </ul>
 *
 * The following properties (prefix with 'docker.') and config key are evaluated:
 *
 * <ul>
 *     <li>username: User to authenticate</li>
 *     <li>password: Password to authenticate. Can be encrypted</li>
 *     <li>email: Optional EMail address which is send to the registry, too</li>
 * </ul>
 *
 *  If the repository is in an aws ecr registry and skipExtendedAuth is not true, if found
 *  credentials are not from docker settings, they will be interpreted as iam credentials
 *  and exchanged for ecr credentials.
 *
 * @param isPush if true this AuthConfig is created for a push, if false it's for a pull
 * @param skipExtendedAuth if false, do not execute extended authentication methods
 * @param authConfig String-String Map holding configuration info from the plugin's configuration. Can be <code>null</code> in
 *                   which case the settings are consulted.
 * @param settings the global Maven settings object
 * @param user user to check for
 * @param registry registry to use, might be null in which case a default registry is checked,
 * @return the authentication configuration or <code>null</code> if none could be found
 *
 * @throws MojoFailureException
 */
public AuthConfig createAuthConfig(boolean isPush, boolean skipExtendedAuth, Map authConfig, Settings settings, String user, String registry) throws MojoExecutionException {
    AuthConfig ret = createStandardAuthConfig(isPush, authConfig, settings, user, registry);
    if (ret != null) {
        if (registry == null || skipExtendedAuth) {
            return ret;
        }
        try {
            return extendedAuthentication(ret, registry);
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
    // Finally check ~/.docker/config.json
    ret = getAuthConfigFromDockerConfig(registry);
    if (ret != null) {
        log.debug("AuthConfig: credentials from ~.docker/config.json");
        return ret;
    }
    log.debug("AuthConfig: no credentials found");
    return null;
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) AuthConfig(io.fabric8.maven.docker.access.AuthConfig) IOException(java.io.IOException)

Example 10 with Config

use of io.fabric8.agent.model.Config in project docker-maven-plugin by fabric8io.

the class PropertyConfigHandlerTest method testDockerFileDir.

@Test
public void testDockerFileDir() {
    String[] testData = new String[] { k(ConfigKey.NAME), "image", k(ConfigKey.DOCKER_FILE_DIR), "dir" };
    ImageConfiguration config = resolveExternalImageConfig(testData);
    assertNotNull(config.getBuildConfiguration());
}
Also used : BuildImageConfiguration(io.fabric8.maven.docker.config.BuildImageConfiguration) AbstractConfigHandlerTest(io.fabric8.maven.docker.config.handler.AbstractConfigHandlerTest)

Aggregations

Test (org.junit.Test)107 BuildImageConfiguration (io.fabric8.maven.docker.config.BuildImageConfiguration)37 HashMap (java.util.HashMap)36 IOException (java.io.IOException)34 File (java.io.File)30 ResourceConfig (io.fabric8.maven.core.config.ResourceConfig)28 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)27 Map (java.util.Map)27 ProcessorConfig (io.fabric8.maven.core.config.ProcessorConfig)23 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)21 Expectations (mockit.Expectations)20 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)19 ArrayList (java.util.ArrayList)19 ConfigMapBuilder (io.fabric8.kubernetes.api.model.ConfigMapBuilder)17 VolumeConfig (io.fabric8.maven.core.config.VolumeConfig)15 AbstractConfigHandlerTest (io.fabric8.maven.docker.config.handler.AbstractConfigHandlerTest)15 AuthConfig (io.fabric8.maven.docker.access.AuthConfig)13 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)12 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)12 Before (org.junit.Before)12