<commit_before>"""
.. module: lemur.plugins.lemur_kubernetes.plugin
    :platform: Unix
    :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
    :license: Apache, see LICENSE for more details.


    The plugin inserts certificates and the private key as Kubernetes secret that
     can later be used to secure service endpoints running in Kubernetes pods

.. moduleauthor:: <NAME> <<EMAIL>>
"""
import itertools
import os

import requests
from flask import current_app

from lemur.common.defaults import common_name
from lemur.common.utils import parse_certificate, base64encode
from lemur.plugins.bases import DestinationPlugin

DEFAULT_API_VERSION = "v1"


def ensure_resource(k8s_api, k8s_base_uri, namespace, kind, name, data):
    # _resolve_uri(k8s_base_uri, namespace, kind, name, api_ver=DEFAULT_API_VERSION)
    url = _resolve_uri(k8s_base_uri, namespace, kind)
    current_app.logger.debug("K8S POST request URL: %s", url)

    create_resp = k8s_api.post(url, json=data)
    current_app.logger.debug("K8S POST response: %s", create_resp)

    if 200 <= create_resp.status_code <= 299:
        return None
    elif create_resp.json().get("reason", "") != "AlreadyExists":
        return create_resp.content

    url = _resolve_uri(k8s_base_uri, namespace, kind, name)
    current_app.logger.debug("K8S PUT request URL: %s", url)

    update_resp = k8s_api.put(url, json=data)
    current_app.logger.debug("K8S PUT response: %s", update_resp)

    if not 200 <= update_resp.status_code <= 299:
        return update_resp.content

    return


def _resolve_ns(k8s_base_uri, namespace, api_ver=DEFAULT_API_VERSION):
    api_group = "api"
    if "/" in api_ver:
        api_group = "apis"
    return "{base}/{api_group}/{api_ver}/namespaces".format(
        base=k8s_base_uri, api_group=api_group, api_ver=api_ver
    ) + ("/" + namespace if namespace else "")


def _resolve_uri(k8s_base_uri, namespace, kind, name=None, api_ver=DEFAULT_API_VERSION):
    if not namespace:
        namespace = "default"

    return "/".join(
        itertools.chain.from_iterable(
            [
                (_resolve_ns(k8s_base_uri, namespace, api_ver=api_ver),),
                ((kind + "s").lower(),),
                (name,) if name else (),
            ]
        )
    )


def build_secret(secret_format, secret_name, body, private_key, cert_chain):
    secret = {
        "apiVersion": "v1",
        "kind": "Secret",
        "type": "Opaque",
        "metadata": {"name": secret_name},
    }
    if secret_format == "Full":
        secret["data"] = {
            "combined.pem": base64encode("%s\n%s" % (body, private_key)),
            "ca.crt": base64encode(cert_chain),
            "service.key": base64encode(private_key),
            "service.crt": base64encode(body),
        }
    if secret_format == "TLS":
        secret["type"] = "kubernetes.io/tls"
        secret["data"] = {
            "tls.crt": base64encode(body),
            "tls.key": base64encode(private_key),
        }
    if secret_format == "Certificate":
        secret["data"] = {"tls.crt": base64encode(cert_chain)}
    return secret


class KubernetesDestinationPlugin(DestinationPlugin):
    title = "Kubernetes"
    slug = "kubernetes-destination"
    description = "Allow the uploading of certificates to Kubernetes as secret"

    author = "<NAME>"<commit_msg>Corrected delivery of TLS format<commit_after>"""
.. module: lemur.plugins.lemur_kubernetes.plugin
    :platform: Unix
    :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
    :license: Apache, see LICENSE for more details.


    The plugin inserts certificates and the private key as Kubernetes secret that
     can later be used to secure service endpoints running in Kubernetes pods

.. moduleauthor:: <NAME> <<EMAIL>>
"""
import base64
import itertools
import os

import requests
from flask import current_app

from lemur.common.defaults import common_name
from lemur.common.utils import parse_certificate
from lemur.plugins.bases import DestinationPlugin

DEFAULT_API_VERSION = "v1"


def ensure_resource(k8s_api, k8s_base_uri, namespace, kind, name, data):
    # _resolve_uri(k8s_base_uri, namespace, kind, name, api_ver=DEFAULT_API_VERSION)
    url = _resolve_uri(k8s_base_uri, namespace, kind)
    current_app.logger.debug("K8S POST request URL: %s", url)

    create_resp = k8s_api.post(url, json=data)
    current_app.logger.debug("K8S POST response: %s", create_resp)

    if 200 <= create_resp.status_code <= 299:
        return None
    elif create_resp.json().get("reason", "") != "AlreadyExists":
        return create_resp.content

    url = _resolve_uri(k8s_base_uri, namespace, kind, name)
    current_app.logger.debug("K8S PUT request URL: %s", url)

    update_resp = k8s_api.put(url, json=data)
    current_app.logger.debug("K8S PUT response: %s", update_resp)

    if not 200 <= update_resp.status_code <= 299:
        return update_resp.content

    return


def _resolve_ns(k8s_base_uri, namespace, api_ver=DEFAULT_API_VERSION):
    api_group = "api"
    if "/" in api_ver:
        api_group = "apis"
    return "{base}/{api_group}/{api_ver}/namespaces".format(
        base=k8s_base_uri, api_group=api_group, api_ver=api_ver
    ) + ("/" + namespace if namespace else "")


def _resolve_uri(k8s_base_uri, namespace, kind, name=None, api_ver=DEFAULT_API_VERSION):
    if not namespace:
        namespace = "default"

    return "/".join(
        itertools.chain.from_iterable(
            [
                (_resolve_ns(k8s_base_uri, namespace, api_ver=api_ver),),
                ((kind + "s").lower(),),
                (name,) if name else (),
            ]
        )
    )


# Performs Base64 encoding of string to string using the base64.b64encode() function
# which encodes bytes to bytes.
def base64encode(string):
    return base64.b64encode(string.encode()).decode()


def build_secret(secret_format, secret_name, body, private_key, cert_chain):
    secret = {
        "apiVersion": "v1",
        "kind": "Secret",
        "type": "Opaque",
        "metadata": {"name": secret_name},
    }
    if secret_format == "Full":
        secret["data"] = {
            "combined.pem": base64encode("%s\n%s" % (body, private_key)),
            "ca.crt": base64encode(cert_chain),
            "service.key": base64encode(private_key),
            "service.crt": base64encode(body),
        }
    if secret_format == "TLS":
        secret["type"] = "kubernetes.io/tls"
        secret["data"] = {
            "tls.crt": base64encode("%s\n%s" % (body, cert_chain)),
            "tls.key": base64encode(private_key),
        }
    if secret_format == "Certificate":
        secret["data"] = {"tls.crt": base64encode(cert_chain)}
    return secret


class KubernetesDestinationPlugin(DestinationPlugin):
    title = "Kubernetes"
    slug = "kubernetes-destination"
    description = "Allow the uploading of certificates to Kubernetes as secret"

    author = "<NAME>"
{'fraction_non_alphanumeric': 0.12033971498488556, 'fraction_numerical': 0.015834173024327047, 'mean_word_length': 3.2032667876588024, 'pattern_counts': {'":': 32, '<': 19, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '398943', 'n_tokens_mistral': 2298, 'n_tokens_neox': 2163, 'n_words': 528}