<commit_before>/*
 * Copyright 2017 Red Hat Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.enmasse.controller.auth;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import io.enmasse.config.LabelKeys;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.openshift.client.OpenShiftClient;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Controller that creates self-signed certificates for instances.
 */
public class OpenSSLCertManager implements CertManager {
    private static final Logger log = LoggerFactory.getLogger(OpenSSLCertManager.class.getName());
    private final OpenShiftClient client;
    private final File caKey;
    private final File caCert;
    private final File certDir;
    private final String globalNamespace;

    public OpenSSLCertManager(OpenShiftClient controllerClient,
                              File caKey,
                              File caCert,
                              File certDir,
                              final String globalNamespace) {
        this.client = controllerClient;
        this.caKey = caKey;
        this.caCert = caCert;
        this.certDir = certDir;
        this.globalNamespace = globalNamespace;
    }

    @Override
    public void issueRouteCert(String secretName, String namespace, String ... hostnames) throws Exception {
        Secret secret = client.secrets().inNamespace(namespace).withName(secretName).get();
        if (secret != null) {
            // TODO: Have this sign certificates with OpenShift CA

            String keyKey = "server-key.pem";
            String certKey = "server-cert.pem";
            if (secret.getData() != null && secret.getData().containsKey(keyKey) && secret.getData().containsKey(certKey)) {
                return;
            }

            log.info("Creating self-signed certificates for " + Arrays.toString(hostnames));
            File keyFile = new File("/tmp/server-key.pem");
            File certFile = new File("/tmp/server-cert.pem");

            createSelfSignedCert(keyFile, certFile);
            createSecretFromCertAndKeyFiles(secretName, namespace, keyKey, certKey, keyFile, certFile, client);
        }
    }

    private static void createSelfSignedCert(final File keyFile, final File certFile) {
        runCommand("openssl", "req", "-new", "-days", "11000", "-x509", "-batch", "-nodes",
                "-out", certFile.getAbsolutePath(), "-keyout", keyFile.getAbsolutePath());
    }

    private static void createSecretFromCertAndKeyFiles(final String secretName,
                                                        final String namespace,
                                                        final File keyFile,
                                                        final File certFile,
                                                        final OpenShiftClient client)
            throws IOException {
        createSecretFromCertAndKeyFiles(secretName, namespace, "tls.key", "tls.crt", keyFile, certFile, client);
    }

    private static void createSecretFromCertAndKeyFiles(final String secretName,
                                                        final String namespace,
                                                        final String keyKey,
                                                        final String certKey,
                                                        final File keyFile,
                                                        final File certFile,
                                                        final OpenShiftClient client)
            throws IOException {
        Map<String, String> data = new LinkedHashMap<>();
        Base64.Encoder encoder = Base64.getEncoder();
        data.put(keyKey, encoder.encodeToString(FileUtils.readFileToByteArray(keyFile)));
        data.put(certKey, encoder.encodeToString(FileUtils.readFileToByteArray(certFile)));
        client.secrets().inNamespace(namespace).withName(secretName).edit()
                .addToData(data)
                .done();
    }

    private static void runCommand(String ... cmd) {
        ProcessBuilder keyGenBuilder = new ProcessBuilder(cmd).redirectErrorStream(true);

        log.info("Running command '{}'", keyGenBuilder.command());
        Process keyGen = null;
        try {
            keyGen = keyGenBuilder.start();
            if (!keyGen.waitFor(1, TimeUnit.MINUTES)) {
                throw new RuntimeException("Command timed out");
            }
        } catch (InterruptedException ignored) {
        } catch (IOException e) {
            throw new UncheckedIOException(e);<commit_msg>Create new secret if it doesn't exist<commit_after>/*
 * Copyright 2017 Red Hat Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.enmasse.controller.auth;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import io.enmasse.config.LabelKeys;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.openshift.client.OpenShiftClient;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Controller that creates self-signed certificates for instances.
 */
public class OpenSSLCertManager implements CertManager {
    private static final Logger log = LoggerFactory.getLogger(OpenSSLCertManager.class.getName());
    private final OpenShiftClient client;
    private final File caKey;
    private final File caCert;
    private final File certDir;
    private final String globalNamespace;

    public OpenSSLCertManager(OpenShiftClient controllerClient,
                              File caKey,
                              File caCert,
                              File certDir,
                              final String globalNamespace) {
        this.client = controllerClient;
        this.caKey = caKey;
        this.caCert = caCert;
        this.certDir = certDir;
        this.globalNamespace = globalNamespace;
    }

    @Override
    public void issueRouteCert(String secretName, String namespace, String ... hostnames) throws Exception {
        Secret secret = client.secrets().inNamespace(namespace).withName(secretName).get();
        if (secret != null) {
            // TODO: Have this sign certificates with OpenShift CA

            String keyKey = "server-key.pem";
            String certKey = "server-cert.pem";
            if (secret.getData() != null && secret.getData().containsKey(keyKey) && secret.getData().containsKey(certKey)) {
                return;
            }

            log.info("Creating self-signed certificates for " + Arrays.toString(hostnames));
            File keyFile = new File("/tmp/server-key.pem");
            File certFile = new File("/tmp/server-cert.pem");

            createSelfSignedCert(keyFile, certFile);
            createSecretFromCertAndKeyFiles(secretName, namespace, keyKey, certKey, keyFile, certFile, client);
        }
    }

    private static void createSelfSignedCert(final File keyFile, final File certFile) {
        runCommand("openssl", "req", "-new", "-days", "11000", "-x509", "-batch", "-nodes",
                "-out", certFile.getAbsolutePath(), "-keyout", keyFile.getAbsolutePath());
    }

    private static void createSecretFromCertAndKeyFiles(final String secretName,
                                                        final String namespace,
                                                        final File keyFile,
                                                        final File certFile,
                                                        final OpenShiftClient client)
            throws IOException {
        createSecretFromCertAndKeyFiles(secretName, namespace, "tls.key", "tls.crt", keyFile, certFile, client);
    }

    private static void createSecretFromCertAndKeyFiles(final String secretName,
                                                        final String namespace,
                                                        final String keyKey,
                                                        final String certKey,
                                                        final File keyFile,
                                                        final File certFile,
                                                        final OpenShiftClient client)
            throws IOException {
        Map<String, String> data = new LinkedHashMap<>();
        Base64.Encoder encoder = Base64.getEncoder();
        data.put(keyKey, encoder.encodeToString(FileUtils.readFileToByteArray(keyFile)));
        data.put(certKey, encoder.encodeToString(FileUtils.readFileToByteArray(certFile)));
        client.secrets().inNamespace(namespace).withName(secretName).createOrReplaceWithNew()
                .addToData(data)
                .done();
    }

    private static void runCommand(String ... cmd) {
        ProcessBuilder keyGenBuilder = new ProcessBuilder(cmd).redirectErrorStream(true);

        log.info("Running command '{}'", keyGenBuilder.command());
        Process keyGen = null;
        try {
            keyGen = keyGenBuilder.start();
            if (!keyGen.waitFor(1, TimeUnit.MINUTES)) {
                throw new RuntimeException("Command timed out");
            }
        } catch (InterruptedException ignored) {
        } catch (IOException e) {
            throw new UncheckedIOException(e);
{'fraction_non_alphanumeric': 0.08645243746576593, 'fraction_numerical': 0.004929706043454446, 'mean_word_length': 2.054084192918874, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 40, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1699685', 'n_tokens_mistral': 2611, 'n_tokens_neox': 2539, 'n_words': 731}