"""
This plugin searches for GitLab tokens
"""
import re

from detect_secrets.plugins.base import RegexBasedDetector


class GitLabTokenDetector(RegexBasedDetector):
    """Scans for GitLab tokens."""

    secret_type = 'GitLab Token'

    denylist = [
        # ref:
        #  - https://docs.gitlab.com/ee/security/token_overview.html#gitlab-tokens
        #  - https://gitlab.com/groups/gitlab-org/-/epics/8923
        #  - https://github.com/gitlabhq/gitlabhq/blob/master/gems
        #        /gitlab-secret_detection/lib/gitleaks.toml#L6-L76

        # `gl..-` prefix and a token of length >20
        #    characters are typically alphanumeric, underscore, dash
        # Most tokens are generated either with:
        #  - `Devise.friendly_token`, a string with a default length of 20, or
        #  - `SecureRandom.hex`, default data size of 16 bytes, encoded in different ways.
        # String length may vary depending on the type of token, and probably
        # even GL-settings in the future, so we expect between 20 and 50 chars.

        # Personal Access Token - glpat
        # Deploy Token - gldt
        # Feed Token - glft
        # OAuth Access Token - glsoat
        # Runner Token - glrt
        re.compile(
            r'(glpat|gldt|glft|glsoat|glrt)-'
            r'[A-Za-z0-9_\-]{20,50}(?!\w)',
        ),

        # Runner Registration Token
        re.compile(r'GR1348941[A-Za-z0-9_\-]{20,50}(?!\w)'),

        # CI/CD Token - `glcbt` or `glcbt-XY_` where XY is a 2-char hex 'partition_id'
        re.compile(r'glcbt-([0-9a-fA-F]{2}_)?[A-Za-z0-9_\-]{20,50}(?!\w)'),

        # Incoming Mail Token - generated by SecureRandom.hex, default length 16 bytes
        # resulting token length is 26 when Base-36 encoded
        re.compile(r'glimt-[A-Za-z0-9_\-]{25}(?!\w)'),

        # Trigger Token - generated by `SecureRandom.hex(20)`
        re.compile(r'glptt-[A-Za-z0-9_\-]{40}(?!\w)'),

        # Agent Token - generated by `Devise.friendly_token(50)`
        # tokens have a minimum length of 50 chars, up to 1024 chars
        re.compile(r'glagent-[A-Za-z0-9_\-]{50,1024}(?!\w)'),

        # GitLab OAuth Application Secret - generated by `SecureRandom.hex(32)`
        # -> becomes 64 base64-encoded characters
        re.compile(r'gloas-[A-Za-z0-9_\-]{64}(?!\w)'),
    ]
