Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions src/devops_cli/security/sanitizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,39 @@
from __future__ import annotations

import re
from collections.abc import Callable
from typing import Any
from urllib.parse import urlsplit, urlunsplit

_SECRET_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
# The keyword patterns below match a word following "secret", "token" or "password". In
# prose that word is usually English: "unify secret resolution" was rewritten to "unify
# <masked-token>", and that corruption reached published release descriptions before anyone
# noticed, because the changelog is masked on its way out. A credential is distinguishable
# from a word -- it carries a digit, a capital, or a separator, or it is longer than any
# English word -- so the value is inspected rather than assumed.
_CREDENTIAL_MIN_OPAQUE_LENGTH = 24


def _looks_like_a_credential(value: str) -> bool:
"""Report whether a value following a credential keyword is plausibly a secret."""
if len(value) >= _CREDENTIAL_MIN_OPAQUE_LENGTH:
return True
return any(char.isdigit() or char.isupper() or char in "_-." for char in value)


def _mask_credential_like_value(match: re.Match[str]) -> str:
"""Replace a keyword-prefixed value only when it looks like a credential."""
value = match.group(1)
if not _looks_like_a_credential(value):
return match.group(0)
return match.group(0).replace(value, "<masked-token>")


# A replacement is a literal for a pattern whose whole match is the secret, or a
# callable where the match also covers surrounding text that must survive.
_Replacement = str | Callable[[re.Match[str]], str]

_SECRET_PATTERNS: tuple[tuple[re.Pattern[str], _Replacement], ...] = (
(
re.compile(
r"(?<![a-zA-Z0-9<])(?:ghp_[A-Za-z0-9_]{10,}|gho_[A-Za-z0-9_]{10,}|github_pat_[A-Za-z0-9_]{20,})\b"
Expand Down Expand Up @@ -81,7 +110,7 @@
r"\b(?:token|bearer|secret|password|api_key)\s+([A-Za-z0-9_\-.]{10,})\b",
re.IGNORECASE,
),
"<masked-token>",
_mask_credential_like_value,
),
(
re.compile(
Expand Down
55 changes: 55 additions & 0 deletions tests/test_consolidation_security_sanitizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,3 +393,58 @@ def test_mask_secrets_word_boundaries_and_safe_paths() -> None:
mask_secrets("Authorization: Bearer sk-proj-1234567890abcdef12345678")
== "Authorization: Bearer <masked-openai-key>"
)


# =============================================================================
# Prose that merely mentions credentials
# =============================================================================


def test_a_sentence_about_secrets_is_not_a_secret() -> None:
"""`\\bsecret\\s+(\\S{10,})` matches any English word of ten characters or more.

"unify secret resolution and manage Vault lease lifecycle" became "unify
<masked-token> and manage ...", and because the changelog is masked on its way out,
that corruption reached the published release description for v0.2.21 before anyone
noticed. "secret storage" survived only because "storage" is seven characters.
"""
from devops_cli.security.sanitizer import mask_secrets

subject = "unify secret resolution and manage Vault lease lifecycle"
assert mask_secrets(subject) == subject


def test_other_credential_keywords_are_safe_in_prose() -> None:
"""The same pattern covers token, password and api_key, so all four need the guard."""
from devops_cli.security.sanitizer import mask_secrets

for subject in (
"token counting inside loops",
"password management policy",
"api_key rotation scheduling",
"bearer instrumentation coverage",
):
assert mask_secrets(subject) == subject


def test_a_space_separated_credential_is_still_masked() -> None:
"""`Bearer <token>` and `token <value>` are the real space-separated forms."""
from devops_cli.security.sanitizer import mask_secrets

assert "abc123def456ghi789" not in mask_secrets("token abc123def456ghi789")


def test_a_long_opaque_lowercase_value_is_still_masked() -> None:
"""No English word runs to twenty-four characters, so length alone is enough signal."""
from devops_cli.security.sanitizer import mask_secrets

secret = "abcdefghijklmnopqrstuvwxyz"
assert secret not in mask_secrets(f"secret {secret}")


def test_assigned_credentials_are_unaffected_by_the_guard() -> None:
"""The keyword rule is one of many; narrowing it must not weaken the specific ones."""
from devops_cli.security.sanitizer import mask_secrets

masked = mask_secrets("export AWS_SECRET_ACCESS_KEY=AKIAIOSFODNN7EXAMPLE")
assert "AKIAIOSFODNN7EXAMPLE" not in masked
Loading