forgottenvaultkeys 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: forgottenvaultkeys
3
+ Version: 0.2.0
4
+ Summary: Stopping & remediating Idiot-in-the-Middle (IitM) leaks before and after push
5
+ Author: DevSpecOps
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/DevSpecOps/forgottenvaultkeys
8
+ Project-URL: Repository, https://github.com/DevSpecOps/forgottenvaultkeys
9
+ Project-URL: Issues, https://github.com/DevSpecOps/forgottenvaultkeys/issues
10
+ Keywords: security,devsecops,secret-scanner,pre-commit,cryptography,remediation,sarif
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Security
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+
21
+ # ForgottenVaultKeys (`fvk`)
22
+
23
+ > **Stopping & remediating Idiot-in-the-Middle before and after push.**
24
+
25
+ While tech headlines speculate about frontier AI models or planetary-scale quantum computers breaking RSA-2048 and lattice-based cryptography, **over 99% of real-world breaches still occur via the *Idiot-in-the-Middle (IitM)* attack vector**:
26
+ * `.env` files and cloud credentials accidentally pushed to public repositories;
27
+ * Weak hardcoded passwords (`password`, `qwerty`, `123456`) left in staging configs;
28
+ * `chmod 777` applied "temporarily" to fix a deployment blocker; <!-- fvk:ignore -->
29
+ * Redis, PostgreSQL, or Elasticsearch instances bound to `0.0.0.0` without authentication.
30
+
31
+ **ForgottenVaultKeys** is a zero-dependency CLI scanner, `pre-commit` guardrail, and **active remediation engine** that not only detects leaks in local files and pushed Git histories, but immediately patches code, exports 4-class CSPRNG replacement secrets outside Git, and generates history-purge scripts.
32
+
33
+ *(For a formal analysis of why asymptotic cryptographic breakthroughs rarely translate into practical threat models—and why operational hygiene dominates security economics—see [THEORY.md](THEORY.md).)*
34
+
35
+ ## Quick Start
36
+
37
+ ### Installation
38
+ ```bash
39
+ git clone https://github.com
40
+ cd ForgottenVaultKeys
41
+ pip install .
42
+ ```
43
+
44
+ ### Core Commands
45
+ ```bash
46
+ # 1. Scan current directory with sarcastic security engineer commentary
47
+ fvk . --roast
48
+
49
+ # 2. Scan both working tree AND full local Git commit history
50
+ fvk . --git-history --roast
51
+
52
+ # 3. Clone and audit an already-pushed remote repository URL
53
+ fvk --remote https://github.com --roast
54
+
55
+ # 4. Active Remediation: patch code, export 4-class CSPRNG secrets outside Git & generate purge script
56
+ fvk . --roast --remediate --secret-length 32
57
+ ```
58
+
59
+ ## Test Drive: Try It in 30 Seconds
60
+
61
+ Want to see `fvk` catch classic junior mistakes and auto-remediate them? Run this sandbox test in a temporary directory:
62
+
63
+ ```bash
64
+ mkdir /tmp/fvk-sandbox && cd /tmp/fvk-sandbox
65
+
66
+ # Create a vulnerable config with classic weak passwords
67
+ cat << 'EOF' > vulnerable_app.py
68
+ DB_PASSWORD = "password" <!-- fvk:ignore -->
69
+ ADMIN_PASS = "qwerty" <!-- fvk:ignore -->
70
+ BACKUP_PIN = "123456"
71
+ EOF
72
+
73
+ # Step 1: Detect the leaks
74
+ fvk . --roast
75
+
76
+ # Step 2: Run Active Remediation (patches file, hardens .gitignore, exports CSPRNG keys to ~/.fvk-vault/)
77
+ fvk . --roast --remediate
78
+
79
+ # Step 3: Inspect the patched code and your new external vault
80
+ cat vulnerable_app.py
81
+ cat ~/.fvk-vault/fvk-sandbox/rotated_secrets.env
82
+ ```
83
+
84
+ ### What `--remediate` Does Under the Hood
85
+ 1. **4-Class CSPRNG Secret Generation:** Generates high-entropy replacement secrets enforcing all 4 character classes (uppercase, lowercase, digits, special symbols) shuffled via `secrets.SystemRandom()` (Fisher-Yates).
86
+ 2. **Out-of-Band Vault Export:** Writes rotated credentials to `~/.fvk-vault/<project>/rotated_secrets.env` with strict `chmod 600` permissions—completely outside Git coverage.
87
+ 3. **Code & `.gitignore` Hardening:** Rewrites hardcoded Python assignments to `os.environ.get("...")` and appends `.env`, `*.pem`, and `*.key` to `.gitignore`.
88
+ 4. **History Purge Script:** Generates an executable `~/.fvk-vault/<project>/purge_git_history.sh` wrapper around `git-filter-repo` to scrub already-pushed commits.
89
+
90
+ ## Pre-Commit Integration
91
+
92
+ Add the following to your repository's `.pre-commit-config.yaml`:
93
+
94
+ ```yaml
95
+ repos:
96
+ - repo: https://github.com
97
+ rev: v0.2.0
98
+ hooks:
99
+ - id: forgotten-vault-keys
100
+ ```
101
+
102
+ Install the hook:
103
+ ```bash
104
+ pre-commit install
105
+ ```
@@ -0,0 +1,13 @@
1
+ fvk/__init__.py,sha256=r7fIlLekyON7F-t_A1WTI347FAmN6PYMBOIiKYAAxOA,1379
2
+ fvk/attestation.py,sha256=PsP542RT0CXbJli3TT1PLBOfA5SP99I6WforovhFTFA,8380
3
+ fvk/auditor.py,sha256=7uFp5I3KSXO1rxTvUIbaQUGPieyA2lGzbp-8Y1DiEp8,3094
4
+ fvk/blast_radius.py,sha256=YV7IyNuSd4P2ykgQY-H6ToR35Qd7-i17r36o2jwo50o,6711
5
+ fvk/git_shield.py,sha256=1EiuXeM7Z5i6uqy4aw6cHiVvaG_I2ronLj5lLrYtN8E,2888
6
+ fvk/ml_filter.py,sha256=L-MbxSs9VMTt-lWUn8s5Lhopg72ua-riLqGfliky8Yc,1598
7
+ fvk/runtime.py,sha256=kRoJX3QvTZkq4rZYFttdWYNQwPAQTXcHuVESNmxSclA,1859
8
+ fvk/scanner.py,sha256=CEGGQh4821GpwPHpVNh7DIZM6XLXEJCmZfbZPseyVcc,24121
9
+ forgottenvaultkeys-0.2.0.dist-info/METADATA,sha256=PvCdFSHmblJajWRnOxCa96cG7PpLBVxFEmSrgkGck_Q,4380
10
+ forgottenvaultkeys-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ forgottenvaultkeys-0.2.0.dist-info/entry_points.txt,sha256=7aOjtKSNMjwpI-_WxPwg1T5nPmyxhPJiICpJKziYZQs,41
12
+ forgottenvaultkeys-0.2.0.dist-info/top_level.txt,sha256=l4UmgNRujv878isIJRoIgva20YPq__Aixiq3v0e1rgU,4
13
+ forgottenvaultkeys-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ fvk = fvk.scanner:main
@@ -0,0 +1 @@
1
+ fvk
fvk/__init__.py ADDED
@@ -0,0 +1,52 @@
1
+ """
2
+ ForgottenVaultKeys (fvk) — Zero-dependency programmatic API & CLI for secret
3
+ detection, ML false-positive suppression, AST blast-radius analysis, runtime
4
+ secret injection, and cryptographic commit attestation.
5
+ """
6
+
7
+ from fvk.attestation import (
8
+ compute_merkle_root,
9
+ detect_semantic_drift,
10
+ generate_attestation,
11
+ verify_attestation,
12
+ )
13
+ from fvk.auditor import audit_local_machine, inspect_jwt
14
+ from fvk.blast_radius import analyze_blast_radius
15
+ from fvk.git_shield import build_commit_trailer, verify_head_commit
16
+ from fvk.ml_filter import is_likely_secret, markov_log_likelihood
17
+ from fvk.runtime import load_vault_env, run_with_vault
18
+ from fvk.scanner import (
19
+ apply_remediation,
20
+ export_sarif,
21
+ generate_strong_secret,
22
+ scan_directory,
23
+ scan_file,
24
+ scan_git_history,
25
+ shannon_entropy,
26
+ )
27
+
28
+ __version__ = "0.2.0"
29
+
30
+ __all__ = [
31
+ "__version__",
32
+ "analyze_blast_radius",
33
+ "apply_remediation",
34
+ "audit_local_machine",
35
+ "build_commit_trailer",
36
+ "compute_merkle_root",
37
+ "detect_semantic_drift",
38
+ "export_sarif",
39
+ "generate_attestation",
40
+ "generate_strong_secret",
41
+ "inspect_jwt",
42
+ "is_likely_secret",
43
+ "load_vault_env",
44
+ "markov_log_likelihood",
45
+ "run_with_vault",
46
+ "scan_directory",
47
+ "scan_file",
48
+ "scan_git_history",
49
+ "shannon_entropy",
50
+ "verify_attestation",
51
+ "verify_head_commit",
52
+ ]
fvk/attestation.py ADDED
@@ -0,0 +1,216 @@
1
+ """
2
+ Zero-Leak Cryptographic Attestation & Semantic Security Drift (`fvk attest` / `fvk drift`).
3
+ """
4
+
5
+ import ast
6
+ import hashlib
7
+ import hmac
8
+ import json
9
+ import os
10
+ import time
11
+ from pathlib import Path
12
+
13
+ from fvk.blast_radius import analyze_blast_radius
14
+ from fvk.scanner import IGNORED_DIRS, IGNORED_EXTS, scan_directory
15
+
16
+
17
+ class _SecurityPostureVisitor(ast.NodeVisitor):
18
+ """Detect weak cryptographic primitives and TLS verification bypasses in Python AST."""
19
+
20
+ def __init__(self) -> None:
21
+ self.weak_crypto_calls: list[str] = []
22
+ self.tls_bypass_calls: list[str] = []
23
+
24
+ def visit_Call(self, node: ast.Call) -> None:
25
+ if isinstance(node.func, ast.Attribute) and node.func.attr in {"md5", "sha1"}:
26
+ self.weak_crypto_calls.append(f"{node.func.attr}@line:{node.lineno}")
27
+
28
+ for kw in node.keywords:
29
+ if (
30
+ kw.arg == "verify"
31
+ and isinstance(kw.value, ast.Constant)
32
+ and kw.value.value is False
33
+ ):
34
+ self.tls_bypass_calls.append(f"verify=False@line:{node.lineno}")
35
+
36
+ self.generic_visit(node)
37
+
38
+
39
+ def compute_merkle_root(project_root: Path) -> tuple[str, int]:
40
+ """Compute a deterministic SHA-256 Merkle tree root over all scannable files."""
41
+ leaf_hashes: list[str] = []
42
+
43
+ if project_root.is_file():
44
+ files_to_hash = [project_root]
45
+ base_dir = project_root.parent
46
+ else:
47
+ files_to_hash = []
48
+ base_dir = project_root
49
+ for root, dirs, files in os.walk(project_root):
50
+ dirs[:] = sorted(d for d in dirs if d not in IGNORED_DIRS)
51
+ for fname in sorted(files):
52
+ fpath = Path(root) / fname
53
+ if fpath.suffix.lower() not in IGNORED_EXTS:
54
+ files_to_hash.append(fpath)
55
+
56
+ for fpath in sorted(files_to_hash, key=lambda p: p.relative_to(base_dir).as_posix()):
57
+ rel_posix = fpath.relative_to(base_dir).as_posix().encode("utf-8")
58
+ content_bytes = fpath.read_bytes()
59
+ leaf = hashlib.sha256(rel_posix + b"\x00" + content_bytes).hexdigest()
60
+ leaf_hashes.append(leaf)
61
+
62
+ if not leaf_hashes:
63
+ return hashlib.sha256(b"EMPTY_TREE").hexdigest(), 0
64
+
65
+ file_count = len(leaf_hashes)
66
+ level = leaf_hashes
67
+ while len(level) > 1:
68
+ next_level: list[str] = []
69
+ for i in range(0, len(level), 2):
70
+ left = level[i]
71
+ right = level[i + 1] if i + 1 < len(level) else left
72
+ combined = hashlib.sha256((left + right).encode("utf-8")).hexdigest()
73
+ next_level.append(combined)
74
+ level = next_level
75
+
76
+ return level[int(0)], file_count
77
+
78
+
79
+ def _extract_ast_posture(project_root: Path) -> dict:
80
+ """Summarize AST security invariants across all Python files."""
81
+ blast_items = analyze_blast_radius(project_root)
82
+ env_isolated = sum(1 for i in blast_items if i["source_kind"] == "env_lookup")
83
+ hardcoded = sum(1 for i in blast_items if i["source_kind"] == "hardcoded_literal")
84
+
85
+ weak_crypto: list[str] = []
86
+ tls_bypasses: list[str] = []
87
+
88
+ py_files = (
89
+ [project_root]
90
+ if project_root.is_file() and project_root.suffix == ".py"
91
+ else list(project_root.rglob("*.py"))
92
+ )
93
+ for py_file in py_files:
94
+ if any(part in IGNORED_DIRS for part in py_file.parts):
95
+ continue
96
+ try:
97
+ tree = ast.parse(py_file.read_text(encoding="utf-8", errors="ignore"))
98
+ except SyntaxError:
99
+ continue
100
+ visitor = _SecurityPostureVisitor()
101
+ visitor.visit(tree)
102
+ weak_crypto.extend(visitor.weak_crypto_calls)
103
+ tls_bypasses.extend(visitor.tls_bypass_calls)
104
+
105
+ return {
106
+ "env_isolated_secrets": env_isolated,
107
+ "hardcoded_secrets": hardcoded,
108
+ "weak_crypto_count": len(weak_crypto),
109
+ "tls_bypass_count": len(tls_bypasses),
110
+ }
111
+
112
+
113
+ def generate_attestation(
114
+ project_root: Path,
115
+ signing_key: str | None = None,
116
+ output_path: Path | None = None,
117
+ ) -> dict:
118
+ """Generate a Zero-Leak Cryptographic Hygiene Attestation JSON document."""
119
+ findings = scan_directory(project_root)
120
+ merkle_root, file_count = compute_merkle_root(project_root)
121
+ posture = _extract_ast_posture(project_root)
122
+
123
+ status = (
124
+ "PASS_ZERO_LEAK"
125
+ if len(findings) == 0
126
+ and posture["hardcoded_secrets"] == 0
127
+ and posture["tls_bypass_count"] == 0
128
+ else "FAIL_HYGIENE_VIOLATION"
129
+ )
130
+
131
+ payload = {
132
+ "schema": "fvk-attestation-v1",
133
+ "tool_version": "0.2.0",
134
+ "timestamp_utc": int(time.time()),
135
+ "project": project_root.resolve().name,
136
+ "status": status,
137
+ "merkle_root_sha256": merkle_root,
138
+ "files_hashed": file_count,
139
+ "findings_count": len(findings),
140
+ "ast_security_posture": posture,
141
+ }
142
+
143
+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
144
+ if signing_key:
145
+ sig = hmac.new(signing_key.encode("utf-8"), canonical, hashlib.sha256).hexdigest()
146
+ payload["signature"] = {"algorithm": "HMAC-SHA256", "value": sig}
147
+ else:
148
+ payload["signature"] = {
149
+ "algorithm": "SHA256-UNKEYED-DIGEST",
150
+ "value": hashlib.sha256(canonical).hexdigest(),
151
+ }
152
+
153
+ if output_path:
154
+ output_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
155
+
156
+ return payload
157
+
158
+
159
+ def verify_attestation(
160
+ attestation: dict, project_root: Path, signing_key: str | None = None
161
+ ) -> tuple[bool, list[str]]:
162
+ """Verify cryptographic signature and current directory Merkle root."""
163
+ errors: list[str] = []
164
+ sig_block = attestation.get("signature", {})
165
+ payload_copy = {k: v for k, v in attestation.items() if k != "signature"}
166
+ canonical = json.dumps(payload_copy, sort_keys=True, separators=(",", ":")).encode("utf-8")
167
+
168
+ alg = sig_block.get("algorithm")
169
+ expected_sig = sig_block.get("value", "")
170
+
171
+ if alg == "HMAC-SHA256":
172
+ if not signing_key:
173
+ errors.append("Attestation requires an HMAC signing key for verification.")
174
+ else:
175
+ actual_sig = hmac.new(signing_key.encode("utf-8"), canonical, hashlib.sha256).hexdigest()
176
+ if not hmac.compare_digest(actual_sig, expected_sig):
177
+ errors.append("HMAC-SHA256 signature mismatch — attestation was tampered with!")
178
+ else:
179
+ actual_digest = hashlib.sha256(canonical).hexdigest()
180
+ if not hmac.compare_digest(actual_digest, expected_sig):
181
+ errors.append("SHA-256 digest mismatch — attestation payload was altered!")
182
+
183
+ current_root, _ = compute_merkle_root(project_root)
184
+ if current_root != attestation.get("merkle_root_sha256"):
185
+ errors.append("Merkle root mismatch — repository files have changed since attestation!")
186
+
187
+ if attestation.get("status") != "PASS_ZERO_LEAK":
188
+ errors.append(f"Attestation status is {attestation.get('status')} (not PASS_ZERO_LEAK).")
189
+
190
+ return len(errors) == 0, errors
191
+
192
+
193
+ def detect_semantic_drift(baseline_attestation: dict, candidate_attestation: dict) -> list[str]:
194
+ """Compare two attestations to detect silent security posture degradation."""
195
+ drifts: list[str] = []
196
+ base_p = baseline_attestation.get("ast_security_posture", {})
197
+ cand_p = candidate_attestation.get("ast_security_posture", {})
198
+
199
+ if cand_p.get("hardcoded_secrets", 0) > base_p.get("hardcoded_secrets", 0):
200
+ drifts.append(
201
+ f"DRIFT [CRITICAL]: Hardcoded secrets increased ({base_p.get('hardcoded_secrets')} -> {cand_p.get('hardcoded_secrets')})."
202
+ )
203
+ if cand_p.get("env_isolated_secrets", 0) < base_p.get("env_isolated_secrets", 0):
204
+ drifts.append(
205
+ f"DRIFT [HIGH]: Environment-isolated secrets dropped ({base_p.get('env_isolated_secrets')} -> {cand_p.get('env_isolated_secrets')})."
206
+ )
207
+ if cand_p.get("tls_bypass_count", 0) > base_p.get("tls_bypass_count", 0):
208
+ drifts.append(
209
+ f"DRIFT [CRITICAL]: TLS verification bypasses ('verify=False') introduced ({base_p.get('tls_bypass_count')} -> {cand_p.get('tls_bypass_count')})."
210
+ )
211
+ if cand_p.get("weak_crypto_count", 0) > base_p.get("weak_crypto_count", 0):
212
+ drifts.append(
213
+ f"DRIFT [MEDIUM]: Weak hash primitives (MD5/SHA1) increased ({base_p.get('weak_crypto_count')} -> {cand_p.get('weak_crypto_count')})."
214
+ )
215
+
216
+ return drifts
fvk/auditor.py ADDED
@@ -0,0 +1,89 @@
1
+ """
2
+ Offline Cryptographic Hygiene Auditor (`fvk audit`).
3
+ Inspects JWT tokens and local developer keystores (~/.ssh, ~/.aws) for staleness.
4
+ """
5
+
6
+ import base64
7
+ import json
8
+ import re
9
+ import time
10
+ from pathlib import Path
11
+
12
+ JWT_PATTERN = re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]*\b")
13
+
14
+
15
+ def _b64url_decode(segment: str) -> bytes:
16
+ padding = "=" * ((4 - len(segment) % 4) % 4)
17
+ return base64.urlsafe_b64decode(segment + padding)
18
+
19
+
20
+ def inspect_jwt(token: str) -> list[str]:
21
+ """Decode JWT header & payload offline and flag security/lifecycle issues."""
22
+ issues: list[str] = []
23
+ parts = token.split(".")
24
+ if len(parts) < 2:
25
+ return issues
26
+
27
+ try:
28
+ header = json.loads(_b64url_decode(parts[0]).decode("utf-8"))
29
+ payload = json.loads(_b64url_decode(parts[1]).decode("utf-8"))
30
+ except Exception:
31
+ return issues
32
+
33
+ alg = str(header.get("alg", "")).lower()
34
+ if alg == "none" or not alg:
35
+ issues.append("CRITICAL: JWT uses unsigned 'alg: none' — trivial signature forgery.")
36
+
37
+ now = int(time.time())
38
+ exp = payload.get("exp")
39
+ iat = payload.get("iat")
40
+
41
+ if exp is None:
42
+ issues.append("HIGH: JWT has no 'exp' claim — immortal token risk.")
43
+ elif isinstance(exp, (int, float)) and exp < now:
44
+ days_expired = int((now - exp) // 86400)
45
+ issues.append(f"INFO: Expired JWT left in codebase (expired {days_expired}d ago).")
46
+
47
+ if isinstance(iat, (int, float)) and (now - iat) > 90 * 86400:
48
+ age_days = int((now - iat) // 86400)
49
+ issues.append(f"WARN: Forgotten JWT issued {age_days} days ago (>90d rotation policy).")
50
+
51
+ return issues
52
+
53
+
54
+ def audit_local_machine(max_age_days: int = 90) -> list[dict]:
55
+ """Audit ~/.ssh and ~/.aws on the local workstation for stale, unrotated keys."""
56
+ findings: list[dict] = []
57
+ now = time.time()
58
+ max_age_sec = max_age_days * 86400
59
+
60
+ ssh_dir = Path.home() / ".ssh"
61
+ if ssh_dir.is_dir():
62
+ for key_file in ssh_dir.iterdir():
63
+ if (
64
+ not key_file.is_file()
65
+ or key_file.suffix == ".pub"
66
+ or key_file.name in {"config", "known_hosts", "authorized_keys"}
67
+ ):
68
+ continue
69
+ age_days = int((now - key_file.stat().st_mtime) // 86400)
70
+ if (now - key_file.stat().st_mtime) > max_age_sec:
71
+ findings.append(
72
+ {
73
+ "target": str(key_file),
74
+ "issue": f"Forgotten SSH private key unrotated for {age_days} days (threshold: {max_age_days}d).",
75
+ }
76
+ )
77
+
78
+ aws_creds = Path.home() / ".aws" / "credentials"
79
+ if aws_creds.is_file():
80
+ age_days = int((now - aws_creds.stat().st_mtime) // 86400)
81
+ if (now - aws_creds.stat().st_mtime) > max_age_sec:
82
+ findings.append(
83
+ {
84
+ "target": str(aws_creds),
85
+ "issue": f"Local AWS credentials untouched for {age_days} days — rotate IAM keys.",
86
+ }
87
+ )
88
+
89
+ return findings
fvk/blast_radius.py ADDED
@@ -0,0 +1,178 @@
1
+ """
2
+ AST Data-Flow & Blast Radius Analyzer (`fvk blast-radius`).
3
+ """
4
+
5
+ import ast
6
+ import os
7
+ from collections import defaultdict, deque
8
+ from pathlib import Path
9
+
10
+ IGNORED_DIRS = {
11
+ ".git", ".venv", "venv", "node_modules", "__pycache__",
12
+ ".idea", ".vscode", "dist", "build", "tests",
13
+ }
14
+
15
+ SENSITIVE_NAME_TOKENS = (
16
+ "secret", "token", "passwd", "password", "api_key",
17
+ "apikey", "auth", "credential", "private_key",
18
+ )
19
+
20
+ EXTERNAL_SINKS = (
21
+ "boto3", "requests", "httpx", "urllib", "psycopg2",
22
+ "asyncpg", "pymysql", "redis", "pymongo", "stripe",
23
+ "smtplib", "paramiko", "openai", "anthropic",
24
+ )
25
+
26
+
27
+ def _is_sensitive_name(name: str) -> bool:
28
+ low = name.lower()
29
+ return low == "key" or low.endswith("_key") or any(tok in low for tok in SENSITIVE_NAME_TOKENS)
30
+
31
+
32
+ class _ModuleVisitor(ast.NodeVisitor):
33
+ def __init__(self) -> None:
34
+ self.secret_vars: dict[str, dict] = {}
35
+ self.imports: set[str] = set()
36
+ self.sinks_used: set[str] = set()
37
+ self.func_tainted_by: dict[str, set[str]] = defaultdict(set)
38
+ self._current_func: str | None = None
39
+ self.used_attributes: set[str] = set()
40
+
41
+
42
+ def visit_Import(self, node: ast.Import) -> None:
43
+ for alias in node.names:
44
+ root_pkg = alias.name.split(".")[0]
45
+ self.imports.add(alias.name)
46
+ if root_pkg in EXTERNAL_SINKS:
47
+ self.sinks_used.add(root_pkg)
48
+ self.generic_visit(node)
49
+
50
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
51
+ if node.module:
52
+ root_pkg = node.module.split(".")
53
+ self.imports.add(node.module)
54
+ if root_pkg in EXTERNAL_SINKS:
55
+ self.sinks_used.add(root_pkg)
56
+ self.generic_visit(node)
57
+
58
+ def visit_Assign(self, node: ast.Assign) -> None:
59
+ for target in node.targets:
60
+ if isinstance(target, ast.Name) and _is_sensitive_name(target.id):
61
+ source_kind = "env_lookup"
62
+ if isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
63
+ source_kind = "hardcoded_literal"
64
+ self.secret_vars[target.id] = {
65
+ "line": node.lineno,
66
+ "source_kind": source_kind,
67
+ }
68
+ self.generic_visit(node)
69
+
70
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
71
+ prev = self._current_func
72
+ self._current_func = node.name
73
+ self.generic_visit(node)
74
+ self._current_func = prev
75
+
76
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
77
+ prev = self._current_func
78
+ self._current_func = node.name
79
+ self.generic_visit(node)
80
+ self._current_func = prev
81
+
82
+ def visit_Name(self, node: ast.Name) -> None:
83
+ if isinstance(node.ctx, ast.Load) and node.id in self.secret_vars:
84
+ scope = self._current_func or "<module>"
85
+ self.func_tainted_by[node.id].add(scope)
86
+ self.generic_visit(node)
87
+
88
+ def visit_Attribute(self, node: ast.Attribute) -> None:
89
+ self.used_attributes.add(node.attr)
90
+ self.generic_visit(node)
91
+
92
+
93
+
94
+ def analyze_blast_radius(project_root: Path) -> list[dict]:
95
+ """Build repository import and AST taint graph to compute secret blast radius."""
96
+ py_files: list[Path] = []
97
+ if project_root.is_file() and project_root.suffix == ".py":
98
+ py_files.append(project_root)
99
+ else:
100
+ for root, dirs, files in os.walk(project_root):
101
+ dirs[:] = [d for d in dirs if d not in IGNORED_DIRS]
102
+ for fname in files:
103
+ if fname.endswith(".py"):
104
+ py_files.append(Path(root) / fname)
105
+
106
+ base_dir = project_root.parent if project_root.is_file() else project_root
107
+ module_visitors: dict[str, _ModuleVisitor] = {}
108
+ module_paths: dict[str, str] = {}
109
+ reverse_import_graph: dict[str, set[str]] = defaultdict(set)
110
+
111
+ for fpath in py_files:
112
+ try:
113
+ source = fpath.read_text(encoding="utf-8", errors="ignore")
114
+ tree = ast.parse(source, filename=str(fpath))
115
+ except SyntaxError:
116
+ continue
117
+
118
+ rel = fpath.relative_to(base_dir).with_suffix("")
119
+ mod_name = ".".join(rel.parts)
120
+ visitor = _ModuleVisitor()
121
+ visitor.visit(tree)
122
+ module_visitors[mod_name] = visitor
123
+ module_paths[mod_name] = fpath.relative_to(base_dir).as_posix()
124
+
125
+ for mod_name, visitor in module_visitors.items():
126
+ for imp in visitor.imports:
127
+ for candidate in module_visitors:
128
+ if imp == candidate or imp.startswith(candidate + ".") or candidate.endswith("." + imp):
129
+ if candidate != mod_name:
130
+ reverse_import_graph[candidate].add(mod_name)
131
+
132
+ report: list[dict] = []
133
+ for mod_name, visitor in module_visitors.items():
134
+ for var_name, meta in visitor.secret_vars.items():
135
+ visited = {mod_name}
136
+ queue = deque([mod_name])
137
+ while queue:
138
+ curr = queue.popleft()
139
+ for downstream in reverse_import_graph.get(curr, set()):
140
+ if downstream not in visited:
141
+ visited.add(downstream)
142
+ queue.append(downstream)
143
+
144
+ downstream_files = sorted(
145
+ module_paths[m]
146
+ for m in visited
147
+ if m != mod_name
148
+ and (
149
+ var_name in module_visitors[m].used_attributes
150
+ or var_name in module_visitors[m].imports
151
+ )
152
+ )
153
+ local_scopes = sorted(visitor.func_tainted_by.get(var_name, set()))
154
+ reachable_sinks = sorted(
155
+ {sink for m in visited for sink in module_visitors[m].sinks_used}
156
+ )
157
+
158
+ is_dead = not local_scopes and not downstream_files
159
+ if is_dead:
160
+ impact = "DEAD / FORGOTTEN (Safe to revoke immediately — zero references)"
161
+ elif reachable_sinks or downstream_files:
162
+ impact = "CRITICAL / ACTIVE (Coordinate rotation — reaches downstream services/sinks)"
163
+ else:
164
+ impact = "LOCAL / MODERATE (Referenced locally, no external network sink detected)"
165
+
166
+ report.append(
167
+ {
168
+ "variable": var_name,
169
+ "defined_in": f"{module_paths[mod_name]}:{meta['line']}",
170
+ "source_kind": meta["source_kind"],
171
+ "local_scopes": local_scopes,
172
+ "downstream_files": downstream_files,
173
+ "reachable_sinks": reachable_sinks,
174
+ "impact": impact,
175
+ }
176
+ )
177
+
178
+ return report