Coverage for src/governed_harness/agents/risk_terms.py: 100%
36 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""The ``security`` risk flag of a task, read from its text before any change.
3Two detectors exist. ``legacy_security_words`` is the substring list of 1.x: any of its words
4anywhere in the intent, the constraints or the requirements flags the task, so "discard" (card),
5"tokenize" (token) or "the encrypted backup is out of scope" all count. It stays the behaviour of
6a project without ``governance.riskProfile``.
8``security_terms`` is the contextual detector a project with ``governance.riskProfile`` uses:
10* a **strong** term flags the task on its own: passwords and passphrases, credentials,
11 authentication and authorisation, OAuth, JWT, CSRF, MFA, encryption and decryption, API,
12 private, secret and signing keys, access, refresh, bearer, session, auth and reset tokens,
13 credit, debit and payment cards, card numbers, CVV and CVC, and their Spanish equivalents
14 (contraseña, credencial, autenticación, autorización, cifrado, encriptar, tarjeta de crédito);
15* a **weak** term (``token``, ``secret``, ``card``, ``payment``) flags the task only next to a
16 word of its own context (within three words), or when one of the files the task owns has a
17 sensitive path component (``auth``, ``security``, ``crypto``, ``payment``...).
19So "count the tokens of the tokenizer" or "rename the product card" stay low risk, while "store
20the API secret in the vault" or "mask the card number" do not. The ChangeSet's own risk factors
21(``checks.risk``) are read later from the diff whatever the task says.
22"""
24from __future__ import annotations
26import re
27from collections.abc import Sequence
28from pathlib import PurePosixPath
29from typing import Final
31LEGACY_SECURITY_WORDS: Final[tuple[str, ...]] = (
32 "password",
33 "secret",
34 "token",
35 "authentic",
36 "authoriz",
37 "credential",
38 "card",
39 "payment",
40 "encrypt",
41)
42"""The 1.x substring list (``orchestration/agent_results.py``), kept as it was."""
44_STRONG = re.compile(
45 r"""\b(?:
46 pass(?:word|phrase)s?|passwd|
47 credentials?|
48 authenticat\w*|authoriz\w*|authoris\w*|authn|authz|
49 oauth\w*|jwts?|csrf|mfa|2fa|two[\s-]factor|
50 (?:en|de)crypt\w*|
51 (?:api|private|secret|signing)[\s_-]?keys?|
52 (?:access|refresh|bearer|session|auth|reset)[\s_-]?tokens?|
53 (?:credit|debit|payment)[\s_-]?cards?|card[\s_-]?numbers?|cvv|cvc|
54 contrase(?:ñ|n)as?|credencial(?:es)?|autentica\w*|autoriza\w*|
55 (?:des)?cifrad[oa]s?|(?:des)?cifrar|(?:des)?encript\w*|
56 tarjetas?\s+de\s+(?:cr[eé]dito|d[eé]bito)
57 )\b""",
58 re.VERBOSE | re.IGNORECASE,
59)
61_WEAK: Final[dict[str, re.Pattern[str]]] = {
62 "token": re.compile(
63 r"auth\w*|log(?:in|on)s?|sessions?|bearer|apis?|access|refresh\w*|csrf|oauth\w*|jwts?|"
64 r"secrets?|passwords?|credentials?|users?|sign(?:in|ed|ing)?|revok\w*|rotat\w*|"
65 r"expir\w*|leak\w*|headers?|cookies?|usuarios?|sesi[oó]n"
66 ),
67 "secret": re.compile(
68 r"apis?|keys?|tokens?|passwords?|credentials?|env|environment|vaults?|leak\w*|"
69 r"expos\w*|rotat\w*|clients?|stor\w*|manager|claves?"
70 ),
71 "card": re.compile(
72 r"credit|debit|payments?|pay|number|numbers|cvv|cvc|pan|expir\w*|billing|holders?|"
73 r"banks?|banking|cr[eé]dito|d[eé]bito|pagos?"
74 ),
75 "payment": re.compile(
76 r"cards?|charg\w*|refund\w*|gateways?|checkout|billing|process\w*|transactions?|"
77 r"banks?|credit|tarjetas?"
78 ),
79}
80_WEAK_FORMS: Final[dict[str, str]] = { # nosec B105 - word forms of the risk terms, not credentials
81 "token": "token",
82 "tokens": "token",
83 "secret": "secret",
84 "secrets": "secret",
85 "card": "card",
86 "cards": "card",
87 "tarjeta": "card",
88 "tarjetas": "card",
89 "payment": "payment",
90 "payments": "payment",
91 "pago": "payment",
92 "pagos": "payment",
93}
94_WINDOW = 3
95_WORD = re.compile(r"[a-z0-9ñáéíóúü]+")
96SENSITIVE_PATH_PARTS: Final[frozenset[str]] = frozenset(
97 {
98 "auth",
99 "authn",
100 "authz",
101 "authentication",
102 "authorization",
103 "security",
104 "crypto",
105 "cryptography",
106 "secret",
107 "secrets",
108 "credential",
109 "credentials",
110 "password",
111 "passwords",
112 "payment",
113 "payments",
114 "billing",
115 "session",
116 "sessions",
117 "login",
118 "oauth",
119 "jwt",
120 }
121)
122"""Path components that make a weak term count: ``src/auth/tokens.py`` is sensitive,
123``src/tokenizer.py`` is not."""
126def legacy_security_words(text: str) -> bool:
127 """The 1.x rule: any word of :data:`LEGACY_SECURITY_WORDS` anywhere in ``text``."""
128 lowered = text.lower()
129 return any(word in lowered for word in LEGACY_SECURITY_WORDS)
132def sensitive_path(path: str) -> bool:
133 """Whether a component of ``path`` (split on ``/``, ``.``, ``_`` and ``-``) is sensitive."""
134 parts = re.split(r"[/\\._-]+", PurePosixPath(path.replace("\\", "/")).as_posix().lower())
135 return any(part in SENSITIVE_PATH_PARTS for part in parts)
138def security_terms(text: str, paths: Sequence[str] = ()) -> tuple[str, ...]:
139 """The terms of ``text`` that make the task a security task, empty when there are none.
141 A strong term is returned as written (``password``); a weak one with the word of context
142 that made it count (``token~bearer``) or with the sensitive path (``secret@src/auth.py``).
143 """
144 found: list[str] = [match.group(0).lower() for match in _STRONG.finditer(text)]
145 words = _WORD.findall(text.lower())
146 sensitive = next((path for path in paths if sensitive_path(path)), None)
147 for index, word in enumerate(words):
148 weak = _WEAK_FORMS.get(word)
149 if weak is None:
150 continue
151 context = _WEAK[weak]
152 near = words[max(0, index - _WINDOW) : index] + words[index + 1 : index + 1 + _WINDOW]
153 neighbour = next((item for item in near if context.fullmatch(item)), None)
154 if neighbour is not None:
155 found.append(f"{weak}~{neighbour}")
156 elif sensitive is not None:
157 found.append(f"{weak}@{sensitive}")
158 return tuple(dict.fromkeys(found))