<commit_before>"""
.. module: lemur.plugins.lemur_aws.iam
    :platform: Unix
    :synopsis: Contains helper functions for interactive with AWS IAM Apis.
    :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
    :license: Apache, see LICENSE for more details.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import botocore

from retrying import retry
from sentry_sdk import capture_exception

from lemur.extensions import metrics
from lemur.plugins.lemur_aws.sts import sts_client


def retry_throttled(exception):
    """
    Determines if this exception is due to throttling
    :param exception:
    :return:
    """
    if isinstance(exception, botocore.exceptions.ClientError):
        if exception.response["Error"]["Code"] == "NoSuchEntity":
            return False

        # No need to retry deletion requests if there is a DeleteConflict error.
        # This error indicates that the certificate is still attached to an entity
        # and cannot be deleted.
        if exception.response["Error"]["Code"] == "DeleteConflict":
            return False

    metrics.send("iam_retry", "counter", 1, metric_tags={"exception": str(exception)})
    return True


def get_name_from_arn(arn):
    """
    Extract the certificate name from an arn.
    examples:
    'arn:aws:iam::123456789012:server-certificate/example.com'
    'arn:aws:iam::123456789012:server-certificate/cloudfront/example.com-cloudfront'
    'arn:aws:acm:us-west-2:123456789012:certificate/example.com'


    :param arn: IAM SSL arn
    :return: name of the certificate as uploaded to AWS
    """
    return arn.split("/")[-1]


def get_path_from_arn(arn):
    """
        examples:
    'arn:aws:iam::123456789012:server-certificate/example.com'
    'arn:aws:iam::123456789012:server-certificate/cloudfront/example.com-cloudfront'
    'arn:aws:acm:us-west-2:123456789012:certificate/example.com'

    :param arn:
    :return: iam or acm or unkown
    """
    # cloudfront/example.com-cloudfront
    file_path = arn.split("/", 1)[1]
    if '/' in file_path:
        # remove the filename, and return the path
        return '/'.join(file_path.split("/")[:-1])
    else:
        return ''


def get_registry_type_from_arn(arn):
    """
        examples:
    'arn:aws:iam::123456789000:server-certificate/example.com'
    'arn:aws:iam::123456789000:server-certificate/cloudfront/example.com-cloudfront'
    'arn:aws:acm:us-west-2:123456789000:certificate/example.com'

    :param arn:
    :return: iam or acm or unkown
    """
    if arn.startswith("arn:aws:iam"):
        return 'iam'
    elif arn.startswith("arn:aws:acm"):
        return 'acm'
    else:
        return 'unknown'


def create_arn_from_cert(account_number, region, certificate_name, path=''):
    """
    Create an ARN from a certificate.
    :param path:<commit_msg>improved docs formatting<commit_after>"""
.. module: lemur.plugins.lemur_aws.iam
    :platform: Unix
    :synopsis: Contains helper functions for interactive with AWS IAM Apis.
    :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
    :license: Apache, see LICENSE for more details.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import botocore

from retrying import retry
from sentry_sdk import capture_exception

from lemur.extensions import metrics
from lemur.plugins.lemur_aws.sts import sts_client


def retry_throttled(exception):
    """
    Determines if this exception is due to throttling
    :param exception:
    :return:
    """
    if isinstance(exception, botocore.exceptions.ClientError):
        if exception.response["Error"]["Code"] == "NoSuchEntity":
            return False

        # No need to retry deletion requests if there is a DeleteConflict error.
        # This error indicates that the certificate is still attached to an entity
        # and cannot be deleted.
        if exception.response["Error"]["Code"] == "DeleteConflict":
            return False

    metrics.send("iam_retry", "counter", 1, metric_tags={"exception": str(exception)})
    return True


def get_name_from_arn(arn):
    """
    Extract the certificate name from an arn.

    examples:
    'arn:aws:iam::123456789012:server-certificate/example.com'
    'arn:aws:iam::123456789012:server-certificate/cloudfront/example.com-cloudfront'
    'arn:aws:acm:us-west-2:123456789012:certificate/example.com'

    :param arn: IAM TLS certificate arn
    :return: name of the certificate as uploaded to AWS
    """
    return arn.split("/")[-1]


def get_path_from_arn(arn):
    """
    Get the certificate path from the certificate arn.

    examples:
    'arn:aws:iam::123456789012:server-certificate/example.com'
    'arn:aws:iam::123456789012:server-certificate/cloudfront/example.com-cloudfront'
    'arn:aws:acm:us-west-2:123456789012:certificate/example.com'

    :param arn: IAM TLS certificate arn
    :return: empty or the certificate path without the certificate name
    """
    # cloudfront/example.com-cloudfront
    file_path = arn.split("/", 1)[1]
    if '/' in file_path:
        # remove the filename, and return the path
        return '/'.join(file_path.split("/")[:-1])
    else:
        return ''


def get_registry_type_from_arn(arn):
    """
    Get the registery type based on the arn.

    examples:
    'arn:aws:iam::123456789000:server-certificate/example.com'
    'arn:aws:iam::123456789000:server-certificate/cloudfront/example.com-cloudfront'
    'arn:aws:acm:us-west-2:123456789000:certificate/example.com'

    :param arn: IAM TLS certificate arn
    :return: iam or acm or unkown
    """
    if arn.startswith("arn:aws:iam"):
        return 'iam'
    elif arn.startswith("arn:aws:acm"):
        return 'acm'
    else:
        return 'unknown'


def create_arn_from_cert(account_number, region, certificate_name, path=''):
    """
    Create an ARN from a certificate.
    :param path:
{'fraction_non_alphanumeric': 0.1178086896788597, 'fraction_numerical': 0.04121586810922205, 'mean_word_length': 3.432267884322679, 'pattern_counts': {'":': 6, '<': 9, '<?xml version=': 0, '>': 9, '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': '3720403', 'n_tokens_mistral': 2024, 'n_tokens_neox': 1801, 'n_words': 458}