fix(security): close redaction gaps in rationale labels
Follow-up to #4566. Credential shapes that still reached rationale labels
in 0.9.93:
- URL userinfo with an empty user (`redis://:pw@host`) or `@` / `/` in the
password
- PEM private-key body after the BEGIN line
- tokens glued to identifiers by `_` (`AKIA..._prod`, `token_ghp_...`)
- Slack `xoxe-` tokens and JWTs with a short payload segment
- Common Lisp docstrings, which never went through redaction
Rationale labels from every extractor are now redacted centrally in
`_safe_extract`, so a new extractor can't skip it. `sk-` now requires a
digit so hyphenated prose isn't redacted. Bumps `_AST_CACHE_SCHEMA` so
labels cached with credentials re-extract, and terraform reuses
`REDACTED_MARKER`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 147f78628b)
This commit is contained in:
1 parent
a0cea18ddc
commit
38046fcfa7
6 files changed
+123
-16
No files matched your search
+16
-2
@@ -206,13 +206,27 @@ def _raise_recursion_limit() -> None:
|
||||
sys.setrecursionlimit(_RECURSION_LIMIT)
|
||||
|
||||
|
||||
def _redact_rationale_labels(result: dict) -> dict:
|
||||
"""Redact credential shapes from every rationale node label.
|
||||
|
||||
Rationale labels are free text copied out of comments and docstrings, so
|
||||
this runs on every extractor's output (before it is cached) rather than
|
||||
relying on each language extractor to call ``redact_secrets`` itself.
|
||||
"""
|
||||
for node in result.get("nodes") or ():
|
||||
label = node.get("label")
|
||||
if node.get("file_type") == "rationale" and isinstance(label, str):
|
||||
node["label"] = redact_secrets(label)
|
||||
return result
|
||||
|
||||
|
||||
def _safe_extract(
|
||||
extractor: Callable, path: Path, *, scan_root: Path | None = None
|
||||
) -> dict:
|
||||
try:
|
||||
if extractor is extract_python:
|
||||
return extractor(path, root=scan_root)
|
||||
return extractor(path)
|
||||
return _redact_rationale_labels(extractor(path, root=scan_root))
|
||||
return _redact_rationale_labels(extractor(path))
|
||||
except RecursionError:
|
||||
print(f" warning: skipped {path} (recursion limit exceeded)", file=sys.stderr, flush=True)
|
||||
return {"nodes": [], "edges": [], "error": "recursion_limit_exceeded"}
|
||||
|
||||
@@ -5,6 +5,7 @@ import warnings
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.extractors.base import _file_stem, _make_id, _read_source_bytes
|
||||
from graphify.security import redact_secrets
|
||||
|
||||
|
||||
# Standard CL definer forms that introduce data/type/variable bindings
|
||||
@@ -330,7 +331,7 @@ def extract_commonlisp(path: Path) -> dict:
|
||||
doc_text = _text(child).strip('"')
|
||||
if doc_text:
|
||||
doc_nid = _cl_id(func_nid, "rationale")
|
||||
add_node(doc_nid, doc_text[:120], child.start_point[0] + 1, file_type="rationale")
|
||||
add_node(doc_nid, redact_secrets(doc_text)[:120], child.start_point[0] + 1, file_type="rationale")
|
||||
add_edge(doc_nid, func_nid, "rationale_for",
|
||||
child.start_point[0] + 1)
|
||||
break
|
||||
@@ -420,7 +421,7 @@ def extract_commonlisp(path: Path) -> dict:
|
||||
doc_text = _text(child).strip('"')
|
||||
if doc_text:
|
||||
doc_nid = _cl_id(nid, "rationale")
|
||||
add_node(doc_nid, doc_text[:120], child.start_point[0] + 1, file_type="rationale")
|
||||
add_node(doc_nid, redact_secrets(doc_text)[:120], child.start_point[0] + 1, file_type="rationale")
|
||||
add_edge(doc_nid, nid, "rationale_for",
|
||||
child.start_point[0] + 1)
|
||||
break
|
||||
|
||||
@@ -9,6 +9,7 @@ from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
from graphify.extractors.base import _make_id, _read_source_bytes
|
||||
from graphify.security import (
|
||||
REDACTED_MARKER,
|
||||
_CONTROL_CHAR_RE,
|
||||
_METADATA_MAX_ATTRIBUTES,
|
||||
_METADATA_MAX_LIST_ITEMS,
|
||||
@@ -31,7 +32,7 @@ _SENSITIVE_KEY_RE = re.compile(
|
||||
r"sas[-_]?token|auth|passphrase)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_REDACTED = "[redacted]"
|
||||
_REDACTED = REDACTED_MARKER
|
||||
_PAIRED_VALUE_KEYS = frozenset({"value", "valuefrom", "value_from"})
|
||||
|
||||
|
||||
|
||||
+21
-11
@@ -408,19 +408,29 @@ _MAX_LABEL_LEN = 256
|
||||
|
||||
# Credential shapes redacted from free text that is persisted into the graph
|
||||
# (rationale/comment labels). Shape-based only, so it is risk reduction rather
|
||||
# than a guarantee: vendor-prefixed tokens and PEM private-key headers.
|
||||
# than a guarantee: vendor-prefixed tokens, PEM private-key blocks and URL
|
||||
# userinfo. Boundaries are alphanumeric-only lookarounds rather than \b so a
|
||||
# token glued to an identifier by `_` (`token_ghp_...`, `AKIA..._prod`) still
|
||||
# matches.
|
||||
_SECRET_SHAPE_RE = re.compile(
|
||||
r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----"
|
||||
r"|\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"
|
||||
r"|\bgh[pousr]_[A-Za-z0-9]{36,}"
|
||||
r"|\bgithub_pat_[A-Za-z0-9_]{22,}"
|
||||
r"|\bxox[baprs]-[A-Za-z0-9-]{10,}"
|
||||
r"|\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}"
|
||||
r"|\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}"
|
||||
r"|\bAIza[0-9A-Za-z_-]{35}\b"
|
||||
r"|\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}"
|
||||
# Header through the END line, or to end of text when the block is cut off:
|
||||
# the base64 body is the secret, not the header.
|
||||
r"(?s:-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----"
|
||||
r"(?:.*?-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|.*))"
|
||||
r"|(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])"
|
||||
r"|(?<![A-Za-z0-9])gh[pousr]_[A-Za-z0-9]{36,}"
|
||||
r"|(?<![A-Za-z0-9])github_pat_[A-Za-z0-9_]{22,}"
|
||||
r"|(?<![A-Za-z0-9])xox[abeoprs]-[A-Za-z0-9-]{10,}"
|
||||
r"|(?<![A-Za-z0-9])[sr]k_(?:live|test)_[A-Za-z0-9]{10,}"
|
||||
# Require a digit so hyphenated prose (`sk-learn-compatible-...`) is left alone.
|
||||
r"|(?<![A-Za-z0-9])sk-(?:ant-|proj-)?(?=[A-Za-z0-9_-]*[0-9])[A-Za-z0-9_-]{20,}"
|
||||
r"|(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{35}"
|
||||
# Payload segment may be tiny (`e30` is `{}`).
|
||||
r"|(?<![A-Za-z0-9])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{2,}\.[A-Za-z0-9_-]{10,}"
|
||||
r"|(?<=\bBearer )[A-Za-z0-9._~+/=-]{16,}"
|
||||
r"|(?<=://)[^\s/:@]+:[^\s/@]+(?=@)"
|
||||
# Userinfo up to the LAST `@` before the host: the user may be empty
|
||||
# (`redis://:pw@host`) and the password may contain `@` or `/`.
|
||||
r"|(?<=://)[^\s/@]*:[^\s?#]*(?=@[^\s@/?#]+)"
|
||||
)
|
||||
|
||||
REDACTED_MARKER = "[redacted]"
|
||||
|
||||
@@ -665,3 +665,29 @@ def test_ordinary_rationale_untouched(tmp_path):
|
||||
labels = _labels(extract_python(path))
|
||||
assert any("chunked processing because the dataset exceeds RAM" in label for label in labels)
|
||||
assert not any("[redacted]" in label for label in labels)
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
__import__("importlib.util").util.find_spec("tree_sitter_commonlisp") is None,
|
||||
reason="tree-sitter-commonlisp not installed (optional [commonlisp] extra)",
|
||||
)
|
||||
def test_commonlisp_docstring_secret_redacted(tmp_path):
|
||||
# Common Lisp builds rationale labels itself rather than via
|
||||
# _shorten_rationale_label; the token must still not reach the label.
|
||||
from graphify.extract import extract
|
||||
path = tmp_path / "deploy.lisp"
|
||||
path.write_text(f'(defun deploy () "token {_GH_TOKEN} for CI" (push))\n')
|
||||
result = extract([path])
|
||||
labels = _labels(result)
|
||||
assert labels and not any("ghp_a1B2" in label for label in labels)
|
||||
|
||||
|
||||
def test_redact_rationale_labels_covers_any_extractor():
|
||||
from graphify.extract import _redact_rationale_labels
|
||||
result = {"nodes": [
|
||||
{"id": "r", "label": f"WHY: {_GH_TOKEN}", "file_type": "rationale"},
|
||||
{"id": "c", "label": "deploy", "file_type": "code"},
|
||||
]}
|
||||
out = _redact_rationale_labels(result)
|
||||
assert out["nodes"][0]["label"] == "WHY: [redacted]"
|
||||
assert out["nodes"][1]["label"] == "deploy"
|
||||
@@ -541,3 +541,58 @@ def test_redact_secrets_does_not_mangle_hashes_and_ids():
|
||||
"class AkiaConfigProvider implements Provider",
|
||||
):
|
||||
assert redact_secrets(benign) == benign, benign
|
||||
|
||||
|
||||
def test_redact_secrets_url_userinfo_edge_cases():
|
||||
# Empty user (redis), `@` and `/` inside the password: all redacted up to
|
||||
# the last `@`, host kept.
|
||||
from graphify.security import redact_secrets
|
||||
assert redact_secrets("redis://:s3cretpass@cache.internal") == "redis://[redacted]@cache.internal"
|
||||
assert redact_secrets("https://svc:p@ss@host/x") == "https://[redacted]@host/x"
|
||||
assert redact_secrets("https://svc:ab/cd@host") == "https://[redacted]@host"
|
||||
|
||||
|
||||
def test_redact_secrets_url_without_userinfo_untouched():
|
||||
from graphify.security import redact_secrets
|
||||
for benign in (
|
||||
"https://host:8080/path?email=a@b.com",
|
||||
"see https://example.com:443/a and mail ops@example.com",
|
||||
):
|
||||
assert redact_secrets(benign) == benign, benign
|
||||
|
||||
|
||||
def test_redact_secrets_pem_body_redacted():
|
||||
from graphify.security import redact_secrets
|
||||
body = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASC"
|
||||
full = f"key:\n-----BEGIN RSA PRIVATE KEY-----\n{body}\n-----END RSA PRIVATE KEY-----\nafter"
|
||||
assert redact_secrets(full) == "key:\n[redacted]\nafter"
|
||||
# No END line (e.g. a truncated docstring): everything after the header goes.
|
||||
assert body not in redact_secrets(f"-----BEGIN PRIVATE KEY-----\n{body}")
|
||||
|
||||
|
||||
def test_redact_secrets_tokens_glued_to_identifiers():
|
||||
from graphify.security import redact_secrets
|
||||
for secret, text in (
|
||||
("AKIAIOSFODNN7EXAMPLE", "AKIAIOSFODNN7EXAMPLE_prod"),
|
||||
("ghp_" + "a" * 36, "token_ghp_" + "a" * 36),
|
||||
("AIza" + "b" * 35, "AIza" + "b" * 35 + "_backup"),
|
||||
):
|
||||
out = redact_secrets(text)
|
||||
assert secret not in out and "[redacted]" in out, text
|
||||
|
||||
|
||||
def test_redact_secrets_slack_refresh_and_short_jwt():
|
||||
from graphify.security import redact_secrets
|
||||
for secret in (
|
||||
"xoxe-1-" + "c" * 40,
|
||||
"eyJhbGciOiJIUzI1NiJ9.e30." + "d" * 43,
|
||||
):
|
||||
out = redact_secrets(f"see {secret} here")
|
||||
assert secret not in out and "[redacted]" in out, secret
|
||||
|
||||
|
||||
def test_redact_secrets_sk_prefix_prose_untouched():
|
||||
from graphify.security import redact_secrets
|
||||
benign = "# NOTE: use the sk-learn-compatible-estimator-wrapper here"
|
||||
assert redact_secrets(benign) == benign
|
||||
assert "[redacted]" in redact_secrets("key sk-proj-" + "a1" * 12)
|
||||
Reference in new issue
Block a user