Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(security): detect GitLab and Azure DevOps tokens and git remote credentials (#3356)
Raghav Chamadiya931387d30b44
diff --git a/docs/layers/SECURITY.md b/docs/layers/SECURITY.mdindex d2f207dcf..7cb5803a8 100644--- a/docs/layers/SECURITY.md+++ b/docs/layers/SECURITY.md@@ -1,7 +1,7 @@# Security signalsRepowise records security signals while it indexes: matches from a registry of-22 patterns over source text, plus a scan for security-relevant symbol names.+25 patterns over source text, plus a scan for security-relevant symbol names.It also scans git history for leaked credentials, and gates pull requests onwhat a change adds.@@ -40,7 +40,7 @@ page, and over REST at `GET /api/repos/{repo_id}/security`.### What the registry catches-22 pattern kinds plus the symbol-name scan: 23 kinds in all, in three+25 pattern kinds plus the symbol-name scan: 26 kinds in all, in threeseverities. Severity is fixed per kind, with one exception: a finding in testmaterial, or under a directory named `test`, `tests`, `__tests__`, `__test__`,`fixtures`, `__fixtures__`, `spec`, `specs`, `mock`, `mocks`, `__mocks__`,@@ -60,6 +60,9 @@ material, or under a directory named `test`, `tests`, `__tests__`, `__test__`,| `slack_token` | high | `xoxb-`, `xoxa-`, `xoxp-`, `xoxr-`, `xoxs-` tokens || `google_api_key` | high | `AIza` + 35 chars, not from inside a base64 run || `stripe_key` | high | `sk_` or `rk_` then `live_`/`test_`/`prod_`. Publishable `pk_` keys do not fire |+| `gitlab_token` | high | `glpat-` (classic and routable), `gldt-`, `glrt-`, `glptt-`, `gloas-`, `glimt-`, `glcbt-` and `GR1348941` runner registration tokens |+| `azure_devops_pat` | high | the 84-char Azure DevOps PAT with `AZDO` at offset 76. The legacy 52-char PAT is only caught by `hardcoded_secret` |+| `git_url_credentials` | high | a password in a git remote URL (`https://user:password@host/repo`): a GitHub, GitLab, Bitbucket or Azure DevOps host, or a path ending in `.git`. Database URLs, local and `example.*` hosts, `$VAR`/`${VAR}`/`%VAR%`/`<slot>` and word-like passwords do not fire || `private_key_pem` | high | a `-----BEGIN ... PRIVATE KEY-----` header followed by a base64 body line (an escaped `\n` counts) || `public_env_secret` | high | `API_KEY`/`SECRET`/`TOKEN`/`PASSWORD` behind `NEXT_PUBLIC_` or `VITE_`, excluding `..._ANON_...` || `new_function_call` | high | `new Function(...)` |@@ -75,8 +78,9 @@ material, or under a directory named `test`, `tests`, `__tests__`, `__test__`,`security_sensitive_symbol` is informational: it marks where security codelives, not a problem.-The eight **secret kinds** are `hardcoded_password`, `hardcoded_secret` and-the six vendor shapes (AWS, GitHub, Slack, Google, Stripe, PEM). History mode+The eleven **secret kinds** are `hardcoded_password`, `hardcoded_secret`,+`git_url_credentials` and the eight vendor shapes (AWS, GitHub, GitLab, Azure+DevOps, Slack, Google, Stripe, PEM). History modeand the in-change commit scan report only these by default.### What fires and what does not@@ -231,7 +235,7 @@ result with that in mind.idioms. On Go, Rust or Java, `eval`/`exec` and the secret kinds are most ofwhat can fire, and a quiet report reflects the registry's shape.- **Secret detection is shallow.** No entropy scoring; providers outside the- six vendor shapes are invisible unless you add custom patterns. Use gitleaks+ eight vendor shapes are invisible unless you add custom patterns. Use gitleaksor trufflehog for secret scanning proper.- **No dependency or CVE scanning.**- **False positives happen.** `weak_hash` fires on `md5` in a comment.diff --git a/packages/cli/src/repowise/cli/ui/progress.py b/packages/cli/src/repowise/cli/ui/progress.pyindex ddf408c0c..45675fbdc 100644--- a/packages/cli/src/repowise/cli/ui/progress.py+++ b/packages/cli/src/repowise/cli/ui/progress.py@@ -43,7 +43,12 @@ _SECRET_PATTERNS = (re.compile(r"\bsk-[A-Za-z0-9_-]{8,}"), # OpenAI / Anthropicre.compile(r"\bAIza[A-Za-z0-9_-]{10,}"), # Googlere.compile(r"\bgh[pousr]_[A-Za-z0-9]{10,}"), # GitHub+ re.compile(r"\bgl(?:pat|dt|rt|ptt|oas|imt|cbt)-[\w.-]{10,}"), # GitLab+ re.compile(r"\bGR1348941[\w-]{10,}"), # GitLab runner registration+ re.compile(r"\b[0-9A-Za-z]{76}AZDO[0-9A-Za-z]{4}\b"), # Azure DevOps)+# A git remote quoted in a clone or fetch error carries its credentials.+_URL_USERINFO = re.compile(r"://[^\s/@:]+:[^\s/@]+@")def redact_secrets(text: str) -> str:@@ -56,7 +61,7 @@ def redact_secrets(text: str) -> str:"""for pattern in _SECRET_PATTERNS:text = pattern.sub("[redacted]", text)- return text+ return _URL_USERINFO.sub("://***@", text)class MaybeCountColumn(ProgressColumn):diff --git a/packages/core/src/repowise/core/analysis/security_gate.py b/packages/core/src/repowise/core/analysis/security_gate.pyindex 42b58042b..f981b2e84 100644--- a/packages/core/src/repowise/core/analysis/security_gate.py+++ b/packages/core/src/repowise/core/analysis/security_gate.py@@ -48,8 +48,13 @@ SEVERITIES = ("low", "med", "high")_RANK = {s: i for i, s in enumerate(SEVERITIES)}#: Secret kinds matched by the value's own vendor format rather than a variable-#: name; see :func:`fingerprint_of`.-_KEY_SHAPE_KINDS = SECRET_KINDS - {"hardcoded_password", "hardcoded_secret"}+#: name; see :func:`fingerprint_of`. A remote URL password can be as weak as+#: any other, so it stays out.+_KEY_SHAPE_KINDS = SECRET_KINDS - {+ "hardcoded_password",+ "hardcoded_secret",+ "git_url_credentials",+}class ShallowHistoryError(ValueError):@@ -92,6 +97,9 @@ _RULE_TEXT: dict[str, str] = {"slack_token": "A Slack token.","google_api_key": "A Google API key.","stripe_key": "A Stripe secret or restricted key.",+ "gitlab_token": "A GitLab token (personal, deploy, runner, trigger, CI job or OAuth).",+ "azure_devops_pat": "An Azure DevOps personal access token.",+ "git_url_credentials": "A password or token embedded in a git remote URL.","private_key_pem": "A PEM private key with its body.","fstring_sql": "An f-string holding SQL and an interpolation.","concat_sql": "SQL built by string concatenation.",diff --git a/packages/core/src/repowise/core/analysis/security_scan.py b/packages/core/src/repowise/core/analysis/security_scan.pyindex 8df2a4232..0537865bd 100644--- a/packages/core/src/repowise/core/analysis/security_scan.py+++ b/packages/core/src/repowise/core/analysis/security_scan.py@@ -224,6 +224,47 @@ _PATTERNS: list[tuple[re.Pattern, str, str]] = ["stripe_key","high",),+ # GitLab's prefixed tokens: personal (also the routable form, whose payload+ # ends in ``.`` plus a 9-char version and checksum), deploy, runner,+ # pipeline trigger, OAuth app secret, incoming mail, CI job, and the legacy+ # runner registration token. Minimum lengths, since newer forms run longer.+ (+ re.compile(+ r"(?<![\w-])("+ r"glpat-[\w-]{20,300}(?:\.[0-9a-z]{9})?"+ r"|(?:gldt|glrt)-[\w-]{20,300}"+ r"|glptt-[0-9a-f]{40}"+ r"|gloas-[\w-]{64,300}"+ r"|glimt-[\w-]{25,300}"+ r"|glcbt-[0-9A-Za-z]{1,5}_[\w-]{20,300}"+ r"|GR1348941[\w-]{20,300}"+ r")(?![\w-])"+ ),+ "gitlab_token",+ "high",+ ),+ # The 84-char Azure DevOps PAT carries ``AZDO`` at a fixed offset. The legacy+ # 52-char lowercase base32 PAT has no marker and reads like any hash, so it+ # is left to ``hardcoded_secret``, which needs a key-named variable.+ (re.compile(r"\b([0-9A-Za-z]{76}AZDO[0-9A-Za-z]{4})\b"), "azure_devops_pat", "high"),+ # ``https://user:password@host/repo``, only on a git remote: a forge host or a+ # path ending in ``.git``. Database and broker URLs are left alone, since most+ # in source are local dev defaults. A password that opens a variable+ # (``$TOKEN``, ``${VAR}``, ``%VAR%``) or a slot (``<token>``, ``****``) is a+ # template. ``git@host:o/r`` and ``ssh://git@host`` have no ``user:`` part.+ (+ re.compile(+ r"(?i:\b(?:https?|git\+https|ssh)://)[^\s:/?#@'\"`<>]{1,100}:"+ r"(?![$%{<*])([^\s/?#@'\"`<>]{1,200})@"+ r"(?!(?i:localhost|127\.0\.0\.1|(?:[\w-]+\.)*example\.(?:com|org)|[\w.-]*\.local)"+ r"(?![\w.-]))"+ r"(?:(?i:(?:[\w-]+\.)*(?:github\.com|gitlab\.com|bitbucket\.org|dev\.azure\.com"+ r"|visualstudio\.com)|(?:[\w-]+\.)*gitlab(?:\.[\w-]+)+)(?![\w.-])"+ r"|[\w.-]+(?::\d+)?/[^\s'\"`<>?#]*\.git(?![\w-]))"+ ),+ "git_url_credentials",+ "high",+ ),(re.compile(r'f[\'"].*SELECT.*\{.*\}'), "fstring_sql", "med"),(re.compile(r"\.execute\(\s*[\'\"]\s*SELECT.*\+"), "concat_sql", "med"),(re.compile(r"verify\s*=\s*False"), "tls_verify_false", "med"),@@ -351,6 +392,9 @@ SECRET_KINDS: frozenset[str] = frozenset("slack_token","google_api_key","stripe_key",+ "gitlab_token",+ "azure_devops_pat",+ "git_url_credentials","private_key_pem",})@@ -365,6 +409,16 @@ SYMBOL_NAME_KINDS: frozenset[str] = frozenset({"security_sensitive_symbol"})_KEYWORD_KINDS: frozenset[str] = frozenset({"hardcoded_password", "hardcoded_secret"})+# Which kind names a value several kinds saw; vendor shapes are the unlisted 2.+# ``token = "https://oauth2:glpat-...@host"`` matches all three tiers at once.+# ``git_url_credentials`` ranks lowest so it only adds findings: a keyword finding+# that kept its kind keeps its baseline fingerprint.+_SECRET_SPECIFICITY: dict[str, int] = {+ "git_url_credentials": 0,+ "hardcoded_password": 1,+ "hardcoded_secret": 1,+}+# A snake_case or kebab-case name (``x-api-key``, ``repowise-security-ignore``)# is a key's or marker's name, a constant holding its own name, and a template# placeholder or shell substitution is filled in when it runs; none of them is a@@ -374,6 +428,7 @@ _SCHEME_TEMPLATE_VALUE = re.compile(r"(?i:(?:bearer|basic|token))\s+(?:\{\{.*\}\}|\$\{[^}]*\}|\$\(.*\))")_OWN_NAME_VALUE = re.compile(r"[A-Za-z_-]+")+_CONSTANT_NAME = re.compile(r"[A-Z][A-Z0-9_]*")_KEY_NAME_VALUE = re.compile(r"[a-z]+(?:[_-][a-z]+)+|[a-z_]*_[a-z_]*")@@ -396,6 +451,20 @@ def _is_secret_value(kind: str, val: str, name: str = "") -> bool:"""True when *val*, captured by a *kind* pattern, looks like a real credential."""if not _is_valid_credential_value(val):return False+ if kind == "git_url_credentials":+ # ``ci:deploykey@``, ``user:pass1234@``: a word, not a token, and+ # ``USER:PERSONAL_ACCESS_TOKEN@`` or ``user:glpat-secret@`` names one. A+ # real token is long and mixed, or short and mixes three of lower,+ # upper, digits and symbols.+ if (+ _is_plain_word(val)+ or _CONSTANT_NAME.fullmatch(val)+ or _KEY_NAME_VALUE.fullmatch(val)+ ):+ return False+ classes = (str.islower, str.isupper, str.isdigit, lambda c: not c.isalnum())+ mixed = sum(any(map(f, val)) for f in classes)+ return mixed >= 3 or (mixed >= 2 and len(val) >= 12)if kind not in _KEYWORD_KINDS:return Truevalue = val.strip()@@ -805,8 +874,7 @@ def scan_source(file_path: str, source: str, symbols: Iterable[Any] = ()) -> lisif not _ANY_PATTERN.search(line):continuesnippet: str | None = None- keyword_hits: list[tuple[dict, str]] = []- vendor_values: list[str] = []+ secret_hits: list[tuple[dict, str, int]] = []for pattern, kind, severity in _PATTERNS:if kind in _CALL_KINDS:continue@@ -843,13 +911,12 @@ def scan_source(file_path: str, source: str, symbols: Iterable[Any] = ()) -> lis"line": lineno,}findings.append(finding)- if kind in _KEYWORD_KINDS:- keyword_hits.append((finding, value))- elif kind in SECRET_KINDS:- vendor_values.append(value)- # One secret, one finding: the vendor shape already names what the keyword saw.- for finding, value in keyword_hits:- if any(vendor in value for vendor in vendor_values):+ if kind in SECRET_KINDS:+ secret_hits.append((finding, value, _SECRET_SPECIFICITY.get(kind, 2)))+ # One secret, one finding: the highest-ranked kind that saw it names it.+ # Either value can hold the other: a keyword's runs to the closing quote.+ for finding, value, rank in secret_hits:+ if any(r > rank and (o in value or value in o) for _, o, r in secret_hits):findings.remove(finding)# Calls that open on one line and set ``shell=True`` on a later one; reporteddiff --git a/tests/unit/analysis/test_security_gate.py b/tests/unit/analysis/test_security_gate.pyindex e36c47670..e7125886d 100644--- a/tests/unit/analysis/test_security_gate.py+++ b/tests/unit/analysis/test_security_gate.py@@ -324,6 +324,12 @@ def test_every_gating_kind_has_a_sarif_rule():assert kinds == set(security_gate._RULE_TEXT)+def test_only_high_entropy_shapes_hash_their_material():+ # A URL password can be weak enough to guess back from its hash.+ assert "git_url_credentials" not in security_gate._KEY_SHAPE_KINDS+ assert {"gitlab_token", "azure_devops_pat"} <= security_gate._KEY_SHAPE_KINDS++# ---------------------------------------------------------------------------# Review regressions# ---------------------------------------------------------------------------diff --git a/tests/unit/analysis/test_security_scan.py b/tests/unit/analysis/test_security_scan.pyindex f54bb5ebc..b4a0767dc 100644--- a/tests/unit/analysis/test_security_scan.py+++ b/tests/unit/analysis/test_security_scan.py@@ -826,6 +826,9 @@ class TestScanSource:"slack_token","google_api_key","stripe_key",+ "gitlab_token",+ "azure_devops_pat",+ "git_url_credentials","private_key_pem",})@@ -1004,6 +1007,143 @@ class TestVendorShapeEdges:assert "google_api_key" not in self._kinds(source, "package-lock.json")+# Built from parts so no complete token sits in one literal for push protection.+_BODY = "0123456789abcdefghij"+_GLPAT = "glpat" + "-" + _BODY+_AZDO_PAT = "0123456789ABCDEFGHIJ" * 3 + _BODY[:16] + "AZDO" + "0123"+++class TestForgeSecretShapes:+ """GitLab and Azure DevOps tokens, and credentials embedded in URLs."""++ @staticmethod+ def _kinds(source: str, path: str = "config.py") -> list[str]:+ return [f["kind"] for f in scan_source(path, source)]++ @pytest.mark.parametrize(+ "token",+ [+ _GLPAT,+ # The routable form: a longer payload, then a version and checksum.+ "glpat" + "-" + _BODY + "_ABCDEFG" + ".01" + "2abcdef",+ "gldt" + "-" + _BODY,+ "glrt" + "-" + _BODY,+ "glptt" + "-" + "0123456789abcdef" * 2 + "01234567",+ "gloas" + "-" + _BODY * 4,+ "glimt" + "-" + _BODY + "ABCDE",+ "glcbt" + "-" + "64" + "_" + _BODY,+ "GR1348941" + _BODY,+ ],+ )+ def test_gitlab_tokens_fire(self, token: str) -> None:+ assert self._kinds(f'client = Gitlab(url, "{token}")\n') == ["gitlab_token"]++ @pytest.mark.parametrize(+ "source",+ [+ 'tok = "glpat' + '-0123456789"\n', # too short+ 'tok = "myglpat-' + _BODY + '"\n', # inside a longer word+ 'tok = "glptt-' + _BODY * 2 + '"\n', # trigger tokens are hex+ 'tok = "glpat-' + "xxxx" + _BODY + '"\n', # placeholder+ ],+ )+ def test_gitlab_lookalikes_do_not_fire(self, source: str) -> None:+ assert "gitlab_token" not in self._kinds(source)++ def test_azure_devops_pat_fires_on_shape_alone(self) -> None:+ assert len(_AZDO_PAT) == 84+ assert self._kinds(f'auth = ("", "{_AZDO_PAT}")\n') == ["azure_devops_pat"]++ def test_azure_devops_signature_must_sit_at_its_offset(self) -> None:+ shifted = "A" + _AZDO_PAT[:-1]+ assert "azure_devops_pat" not in self._kinds(f'auth = ("", "{shifted}")\n')++ def test_legacy_azure_pat_needs_a_key_name(self) -> None:+ legacy = "abcdefghijklmnopqrstuvwxyz234567" + "abcdefghijklmnopqrst"+ assert self._kinds(f'auth = ("", "{legacy}")\n') == []+ assert self._kinds(f'AZURE_DEVOPS_TOKEN = "{legacy}"\n') == ["hardcoded_secret"]++ @pytest.mark.parametrize(+ "url",+ [+ "https://deploy:[email protected]/group/repo.git",+ "https://ci:[email protected]/owner/repo",+ "https://ci:[email protected]:443/o/r",+ "git+https://ci:[email protected]/o/r",+ "https://org:[email protected]/org/p/_git/r",+ "https://org:[email protected]/p/_git/r",+ "ssh://ci:[email protected]:2222/o/r.git",+ "http://ci:[email protected]/o/r.git/info/refs",+ ],+ )+ def test_git_remote_credentials_fire(self, url: str) -> None:+ hits = [f for f in scan_source("settings.py", f'DB = "{url}"\n')]+ assert [f["kind"] for f in hits] == ["git_url_credentials"]+ password = url.split("://")[1].split("@")[0].split(":")[1]+ _assert_no_raw(hits[0]["snippet"], password)++ @pytest.mark.parametrize(+ "url",+ [+ "[email protected]:owner/repo.git",+ "ssh://[email protected]/owner/repo.git",+ "ssh://[email protected]:22/owner/repo.git",+ "https://user:[email protected]/repo.git",+ "https://USERNAME:[email protected]/repo.git",+ "https://oauth2:${GITLAB_TOKEN}@gitlab.com/o/r.git",+ "https://oauth2:[email protected]/o/r.git",+ "https://user:%AZURE_PAT%@dev.azure.com/org/p/_git/r",+ "https://user:<token>@host.com/repo.git",+ "https://user:********@host.com/repo.git",+ "https://user:[email protected]/repo.git",+ "postgres://postgres:postgres@localhost:5432/db",+ # Not a git remote: connection strings and plain web URLs.+ "postgres://app:[email protected]:5432/app",+ "amqp://svc:k9Rt2xVb7Lp@[::1]:5672/",+ "redis://default:[email protected]:6379",+ "https://ci:[email protected]/v1/items",+ "https://ci:[email protected]/o/r",+ # Local and documentation hosts.+ "https://ci:Zq8vT2mLw9@localhost/o/r.git",+ "https://ci:[email protected]:3000/o/r.git",+ "https://ci:[email protected]/o/r.git",+ "https://ci:[email protected]/o/r.git",+ # Words, not tokens.+ "https://ci:[email protected]/o/r",+ "https://ci:[email protected]/o/r",+ "https://ci:[email protected]/o/r",+ "https://user:[email protected]/o/r.git",+ "https://user:[email protected]/g/p.git",+ # A constant's name stands in for the token in docs.+ "https://USERNAME:[email protected]/org/proj/_git/repo",+ "https://host.com/path:abcdefgh12@other",+ ],+ )+ def test_non_remotes_placeholders_and_ssh_do_not_fire(self, url: str) -> None:+ assert "git_url_credentials" not in self._kinds(f'REMOTE = "{url}"\n')++ def test_token_in_a_url_is_one_finding_named_by_its_vendor(self) -> None:+ source = f'token = "https://oauth2:{_GLPAT}@gitlab.com/o/r.git"\n'+ (hit,) = scan_source("ci.py", source)+ assert hit["kind"] == "gitlab_token"+ _assert_no_raw(hit["snippet"], _GLPAT)++ @pytest.mark.parametrize(+ ("source", "kind"),+ [+ ('password = "https://ci:[email protected]/o/r.git"\n', "hardcoded_password"),+ ('API_KEY = "https://svc:[email protected]/o/r"\n', "hardcoded_secret"),+ ],+ )+ def test_keyword_named_url_credential_keeps_its_kind(self, source: str, kind: str) -> None:+ # Baselines key on kind, so a finding that predates git_url_credentials must not move.+ assert self._kinds(source) == [kind]++ def test_url_credentials_in_prose_fire(self) -> None:+ source = "Clone with `git clone https://ci:[email protected]/r.git`.\n"+ assert self._kinds(source, "README.md") == ["git_url_credentials"]++class TestCallKindsIgnoreProseAndText:"""pickle.loads / os.system / shell=True only count as code, not as text."""diff --git a/tests/unit/analysis/test_security_scan_history.py b/tests/unit/analysis/test_security_scan_history.pyindex 100096bac..dac6f53b8 100644--- a/tests/unit/analysis/test_security_scan_history.py+++ b/tests/unit/analysis/test_security_scan_history.py@@ -310,6 +310,9 @@ def test_secret_kinds_are_the_genuine_credential_patterns() -> None:"slack_token","google_api_key","stripe_key",+ "gitlab_token",+ "azure_devops_pat",+ "git_url_credentials","private_key_pem",} == SECRET_KINDSdiff --git a/tests/unit/cli/test_progress_non_tty.py b/tests/unit/cli/test_progress_non_tty.pyindex 94b6f9c4d..db2ff068a 100644--- a/tests/unit/cli/test_progress_non_tty.py+++ b/tests/unit/cli/test_progress_non_tty.py@@ -239,6 +239,28 @@ def test_a_key_quoted_back_by_a_provider_is_not_written_to_disk() -> None:assert kept == "No parser installed for: bash (1,204 files) at /repo/.repowise/.env"+ ("text", "expected"),+ [+ ("auth failed: glpat" + "-0123456789abcdefghij", "auth failed: [redacted]"),+ ("register: GR1348941" + "0123456789abcdefghij", "register: [redacted]"),+ ("pat " + "0123456789ABCDEFGHIJ" * 3 + "0123456789abcdef" + "AZDO0123", "pat [redacted]"),+ (+ "fatal: could not read https://ci:[email protected]/r.git",+ "fatal: could not read https://***@git.internal/r.git",+ ),+ # Nothing to hide: a username alone, an scp-style remote, a plain URL.+ ("ssh://[email protected]/o/r.git", "ssh://[email protected]/o/r.git"),+ ("[email protected]:o/r.git", "[email protected]:o/r.git"),+ ("see https://host:8443/a@b", "see https://host:8443/a@b"),+ ],+)+def test_forge_tokens_and_url_credentials_are_redacted(text: str, expected: str) -> None:+ from repowise.cli.ui.progress import redact_secrets++ assert redact_secrets(text) == expected++@pytest.mark.parametrize("phase_fn",[