Search in sources :

Example 1 with SecretBuilder

use of io.fabric8.kubernetes.api.model.SecretBuilder 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 2 with SecretBuilder

use of io.fabric8.kubernetes.api.model.SecretBuilder in project fabric8-maven-plugin by fabric8io.

the class DockerRegistrySecretEnricherTest method createBaseSecret.

private Secret createBaseSecret(boolean withAnnotation) {
    ObjectMetaBuilder metaBuilder = new ObjectMetaBuilder().withNamespace("default");
    if (withAnnotation) {
        Map<String, String> annotations = new HashMap<>();
        annotations.put(annotation, dockerUrl);
        metaBuilder = metaBuilder.withAnnotations(annotations);
    }
    Map<String, String> data = new HashMap<>();
    return new SecretBuilder().withData(data).withMetadata(metaBuilder.build()).withType(SecretConstants.DOCKER_CONFIG_TYPE).build();
}
Also used : SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) HashMap(java.util.HashMap) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder)

Example 3 with SecretBuilder

use of io.fabric8.kubernetes.api.model.SecretBuilder in project fabric8-maven-plugin by fabric8io.

the class SecretEnricher method addMissingResources.

@Override
public void addMissingResources(KubernetesListBuilder builder) {
    Map<String, String> config = getRawConfig();
    SecretBuilder secretBuilder = createSecretBuilder();
    for (Map.Entry<String, String> entry : config.entrySet()) {
        if (!isTypedKey(entry.getKey())) {
            addToSecretBuilder(secretBuilder, entry.getKey(), entry.getValue());
        }
    }
    if (secretBuilder.hasData() && secretBuilder.getData().size() > 0) {
        builder.addToSecretItems(secretBuilder.build());
    }
}
Also used : SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) Map(java.util.Map)

Example 4 with SecretBuilder

use of io.fabric8.kubernetes.api.model.SecretBuilder in project syndesis by syndesisio.

the class OpenShiftServiceImplTest method testDeploy.

@SuppressWarnings({ "PMD.ExcessiveMethodLength", "PMD.JUnitTestsShouldIncludeAssert" })
@Test
public void testDeploy() {
    String name = "test-deployment";
    OpenShiftConfigurationProperties config = new OpenShiftConfigurationProperties();
    OpenShiftServiceImpl service = new OpenShiftServiceImpl(client, config);
    DeploymentData deploymentData = new DeploymentData.Builder().addAnnotation("testName", testName.getMethodName()).addLabel("type", "test").addSecretEntry("secret-key", "secret-val").withImage("testimage").build();
    ImageStream expectedImageStream = new ImageStreamBuilder().withNewMetadata().withName(name).endMetadata().build();
    Secret expectedSecret = new SecretBuilder().withNewMetadata().withName(name).addToAnnotations(deploymentData.getAnnotations()).addToLabels(deploymentData.getLabels()).endMetadata().withStringData(deploymentData.getSecret()).build();
    DeploymentConfig expectedDeploymentConfig = new DeploymentConfigBuilder().withNewMetadata().withName(OpenShiftServiceImpl.openshiftName(name)).addToAnnotations(deploymentData.getAnnotations()).addToLabels(deploymentData.getLabels()).endMetadata().withNewSpec().withReplicas(1).addToSelector("integration", name).withNewStrategy().withType("Recreate").withNewResources().addToLimits("memory", new Quantity(config.getDeploymentMemoryLimitMi() + "Mi")).addToRequests("memory", new Quantity(config.getDeploymentMemoryRequestMi() + "Mi")).endResources().endStrategy().withRevisionHistoryLimit(0).withNewTemplate().withNewMetadata().addToLabels("integration", name).addToLabels(OpenShiftServiceImpl.COMPONENT_LABEL, "integration").addToLabels(deploymentData.getLabels()).addToAnnotations(deploymentData.getAnnotations()).addToAnnotations("prometheus.io/scrape", "true").addToAnnotations("prometheus.io/port", "9779").endMetadata().withNewSpec().addNewContainer().withImage(deploymentData.getImage()).withImagePullPolicy("Always").withName(name).addToEnv(new EnvVarBuilder().withName("LOADER_HOME").withValue(config.getIntegrationDataPath()).build()).addToEnv(new EnvVarBuilder().withName("AB_JMX_EXPORTER_CONFIG").withValue("/tmp/src/prometheus-config.yml").build()).addNewPort().withName("jolokia").withContainerPort(8778).endPort().addNewVolumeMount().withName("secret-volume").withMountPath("/deployments/config").withReadOnly(false).endVolumeMount().endContainer().addNewVolume().withName("secret-volume").withNewSecret().withSecretName(expectedSecret.getMetadata().getName()).endSecret().endVolume().endSpec().endTemplate().addNewTrigger().withType("ConfigChange").endTrigger().endSpec().withNewStatus().withLatestVersion(1L).endStatus().build();
    server.expect().withPath("/oapi/v1/namespaces/test/imagestreams").andReturn(200, expectedImageStream).always();
    server.expect().withPath("/api/v1/namespaces/test/secrets").andReturn(200, expectedSecret).always();
    server.expect().withPath("/oapi/v1/namespaces/test/deploymentconfigs").andReturn(200, expectedDeploymentConfig).always();
    server.expect().withPath("/oapi/v1/namespaces/test/deploymentconfigs/i-test-deployment").andReturn(200, expectedDeploymentConfig).always();
    server.expect().withPath("/oapi/v1/namespaces/test/deploymentconfigs/test-deployment").andReturn(200, expectedDeploymentConfig).always();
    service.deploy(name, deploymentData);
}
Also used : DeploymentConfigBuilder(io.fabric8.openshift.api.model.DeploymentConfigBuilder) ImageStream(io.fabric8.openshift.api.model.ImageStream) Quantity(io.fabric8.kubernetes.api.model.Quantity) EnvVarBuilder(io.fabric8.kubernetes.api.model.EnvVarBuilder) ImageStreamBuilder(io.fabric8.openshift.api.model.ImageStreamBuilder) Secret(io.fabric8.kubernetes.api.model.Secret) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) DeploymentConfig(io.fabric8.openshift.api.model.DeploymentConfig) Test(org.junit.Test)

Example 5 with SecretBuilder

use of io.fabric8.kubernetes.api.model.SecretBuilder in project fabric8-maven-plugin by fabric8io.

the class ImportMojo method findOrCreateGitSecret.

private Secret findOrCreateGitSecret(KubernetesClient kubernetes, String secretName, String repositoryHost) {
    String secretNamespace = getSecretNamespace();
    ensureNamespaceExists(kubernetes, secretNamespace);
    Secret gogsSecret = kubernetes.secrets().inNamespace(secretNamespace).withName(secretName).get();
    if (gogsSecret == null) {
        // lets create a new secret!
        Map<String, String> labels = new HashMap<>();
        labels.put("provider", "fabric8");
        labels.put("repository", repositoryHost);
        labels.put("scm", "git");
        gogsSecret = new SecretBuilder().withNewMetadata().withName(secretName).withLabels(labels).endMetadata().withData(new HashMap<String, String>()).build();
    }
    return gogsSecret;
}
Also used : Secret(io.fabric8.kubernetes.api.model.Secret) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) HashMap(java.util.HashMap)

Aggregations

SecretBuilder (io.fabric8.kubernetes.api.model.SecretBuilder)7 Secret (io.fabric8.kubernetes.api.model.Secret)4 ObjectMetaBuilder (io.fabric8.kubernetes.api.model.ObjectMetaBuilder)3 DefaultKubernetesClient (io.fabric8.kubernetes.client.DefaultKubernetesClient)3 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)3 IOException (java.io.IOException)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 File (java.io.File)2 StringWriter (java.io.StringWriter)2 KeyPair (java.security.KeyPair)2 KeyPairGenerator (java.security.KeyPairGenerator)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 NoSuchProviderException (java.security.NoSuchProviderException)2 SecureRandom (java.security.SecureRandom)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 X500Principal (javax.security.auth.x500.X500Principal)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 YAMLFactory (com.fasterxml.jackson.dataformat.yaml.YAMLFactory)1