diff options
| author | Claude <noreply@anthropic.com> | 2026-10-15 21:55:42 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-15 21:55:42 +0000 |
| commit | 1067950c2bacdb7a9627cadcb8514df34c8754c3 (patch) | |
| tree | 709a8961bb02aaa49ef99eece5913575f6db5a80 /plugins | |
| parent | 4e0888ee4bd63c231ce722a60a9079182eea43d5 (diff) | |
| parent | 83e004a98e1fc268a94cc6a74b1b054630542696 (diff) | |
Merge remote-tracking branch 'origin/main' into mhegazy/sg-fewer-bash-hook-entriesmhegazy/sg-fewer-bash-hook-entries
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 28 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 202 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/llm.py | 29 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 38 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_custom_headers.py | 27 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_diff_parsing.py | 99 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_findings_delivery.py | 1 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_secret_shaped_paths.py | 95 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_untracked_cap.py | 85 |
9 files changed, 562 insertions, 42 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index be839212..74870c15 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -8,6 +8,7 @@ to work without retargeting. """ import os import subprocess +import time from _base import debug_log, _PV from gitutil import ( @@ -351,6 +352,12 @@ def _append_reviewed_shas(repo_root, shas, vulns_found=0): # ===================================================================== UNTRACKED_BASELINE_CAP = 2000 +# Set in a snapshot that hit the cap, to the time the listing started. NUL +# cannot occur in a path, so the key never collides with a file. +UNTRACKED_CAPPED_AT_KEY = "\0capped_at_ns" +# Coarse filesystem timestamps (1 s on ext3, 2 s on FAT) can stamp a file +# created just after the snapshot as slightly older than it. +_CAPPED_BASELINE_SLACK_NS = 2_000_000_000 def _list_untracked(cwd): @@ -377,6 +384,7 @@ def _list_untracked(cwd): the holdouts.""" try: repo = _git_toplevel(cwd) or cwd + started_ns = time.time_ns() # core.quotePath=false comes from GIT_CMD globally (see gitutil.py). r = subprocess.run( [*GIT_CMD, "ls-files", "--others", "--exclude-standard", "-z"], @@ -397,6 +405,10 @@ def _list_untracked(cwd): out[p] = 0 if len(out) >= UNTRACKED_BASELINE_CAP: debug_log(f"_list_untracked: capped at {UNTRACKED_BASELINE_CAP}") + # The files past the cap are not recorded one by one. Record + # when the snapshot was taken so the Stop hook can still tell + # them from files created or edited during the turn. + out[UNTRACKED_CAPPED_AT_KEY] = started_ns break return out except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: @@ -442,14 +454,24 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel if tracked_dirty is None: return [], "HEAD", repo, [], {"dirty_now_count": -1, "changed_since_count": -1, "review_set_count": 0} + capped_at_ns = untracked_at_baseline.get(UNTRACKED_CAPPED_AT_KEY) + def _unchanged_since_baseline(p): base_mtime = untracked_at_baseline.get(p) - if base_mtime is None: - return False try: - return os.stat(os.path.join(repo, p)).st_mtime_ns == base_mtime + st = os.stat(os.path.join(repo, p)) except OSError: return False + if base_mtime is not None: + return st.st_mtime_ns == base_mtime + if not capped_at_ns: + return False + # The snapshot stopped at the cap, so this file may simply be one it + # never reached. Without this, every pre-existing file past the cap + # looks new on every turn and the same files are reviewed again and + # again. A file created or edited during the turn has a later mtime + # or ctime than the snapshot; anything older was already there. + return max(st.st_mtime_ns, st.st_ctime_ns) < capped_at_ns - _CAPPED_BASELINE_SLACK_NS preexisting_unchanged = {p for p in untracked if _unchanged_since_baseline(p)} new_untracked = untracked - preexisting_unchanged diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 2036b45e..96aa88d2 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -856,6 +856,77 @@ SKIP_FILE_SUFFIXES = ( '.lock', '_pb2.py', '.pb.go', ) +# Files that hold secrets by naming convention are never sent for review. The +# review covers everything dirty in the work tree, including files the user +# changed and Claude never opened, so a key file or an encrypted dotfile source +# would otherwise leave the machine in the review request. The list is kept to +# names that are secret stores by convention; ordinary source such as +# `private_api.py` or `id_generator.py` stays reviewable. +_SSH_PRIVATE_KEY_BASENAMES = frozenset(( + 'id_rsa', 'id_dsa', 'id_ecdsa', 'id_ecdsa_sk', 'id_ed25519', + 'id_ed25519_sk', 'id_xmss', +)) +_PRIVATE_KEY_NAME_SUFFIXES = ('_rsa', '_dsa', '_ecdsa', '_ed25519') +_CREDENTIAL_BASENAMES = frozenset(( + 'credentials', '.netrc', '.pgpass', '.npmrc', '.pypirc', + '.git-credentials', '.dockercfg', +)) +# chezmoi encodes a target file's attributes as stacked name prefixes +# (`private_dot_netrc`, `encrypted_private_token`); `dot_` stands for a +# leading dot. +_CHEZMOI_ATTR_PREFIXES = ( + 'after_', 'before_', 'create_', 'empty_', 'encrypted_', 'exact_', + 'executable_', 'external_', 'literal_', 'modify_', 'once_', 'onchange_', + 'private_', 'readonly_', 'remove_', 'run_', 'symlink_', +) +# An `encrypted_` source keeps its target's name, so `encrypted_store.py` could +# be either ciphertext or code about encryption. Treat it as ciphertext only +# when it has no extension or a data-file one. +_ENCRYPTED_DATA_EXTENSIONS = frozenset(( + '', '.json', '.yaml', '.yml', '.toml', '.properties', '.tfvars', +)) + + +# Paths skipped as secret-shaped during this hook run. The Stop hook reports +# the count (never the names) so the skip can be watched in telemetry. +_secret_shaped_skipped = set() + + +def _skip_secret_shaped(file_path): + if not _is_secret_shaped(file_path): + return False + _secret_shaped_skipped.add(file_path) + return True + + +def _is_secret_shaped(file_path): + base = os.path.basename(file_path.replace("\\", "/")).lower() + target = base + encrypted = False + stripped = True + while stripped: + stripped = False + for prefix in _CHEZMOI_ATTR_PREFIXES: + if target.startswith(prefix) and len(target) > len(prefix): + target = target[len(prefix):] + encrypted = encrypted or prefix == 'encrypted_' + stripped = True + break + if target.startswith('dot_'): + target = '.' + target[4:] + ext = os.path.splitext(target)[1] + if encrypted and ext in _ENCRYPTED_DATA_EXTENSIONS: + return True + for name in {base, target}: + if name.startswith('.env'): + return True + if name in _SSH_PRIVATE_KEY_BASENAMES or name in _CREDENTIAL_BASENAMES: + return True + if '.' not in name and name.endswith(_PRIVATE_KEY_NAME_SUFFIXES): + return True + return False + + # Path tokens that bump a file's review priority when a commit exceeds # MAX_DIFF_FILES and we have to pick a subset. These are exactly the surfaces # single-shot and agentic reviews disagree on most (auth, routing, IPC, @@ -933,6 +1004,8 @@ def _is_reviewable_source(file_path): norm = "/" + file_path.replace("\\", "/") if any(("/" + p) in norm for p in SKIP_PATH_PATTERNS): return False + if _skip_secret_shaped(file_path): + return False if file_path.endswith(SKIP_FILE_SUFFIXES): return False ext = os.path.splitext(file_path)[1].lower() @@ -962,32 +1035,103 @@ def _is_reviewable_source(file_path): return False +# A file's section starts at a `diff --git ` line. Inside a section every line +# of file content carries a `+`, `-` or space prefix, so only a real header can +# start a line with it; source text that merely contains the words cannot. +_DIFF_SECTION_RE = re.compile(r'^diff --git ', re.MULTILINE) +_UNQUOTED_HEADER_RE = re.compile(r'^a/(.+?) b/(.+)$') +_C_ESCAPES = { + 'a': b'\a', 'b': b'\b', 'f': b'\f', 'n': b'\n', 'r': b'\r', 't': b'\t', + 'v': b'\v', '\\': b'\\', '"': b'"', +} + + +def _read_quoted_path(text, start): + """Decode the C-quoted path whose opening quote is at text[start]. + Returns (path, index after the closing quote), or None if unterminated.""" + out = bytearray() + i = start + 1 + while i < len(text): + c = text[i] + if c == '"': + return out.decode("utf-8", errors="replace"), i + 1 + if c == '\\' and i + 1 < len(text): + n = text[i + 1] + if n in _C_ESCAPES: + out += _C_ESCAPES[n] + i += 2 + continue + octal = re.match(r'[0-7]{1,3}', text[i + 1:i + 4]) + if octal: + out.append(int(octal.group(0), 8) & 0xFF) + i += 1 + len(octal.group(0)) + continue + out += c.encode("utf-8") + i += 1 + return None + + +def _parse_diff_header(header): + """(old_path, new_path) from the text after `diff --git `, or None. + + core.quotePath=false keeps non-ASCII names raw, but git still C-quotes a + name that contains a double quote, a backslash or a control character: + `"a/we\\"ird.py" "b/we\\"ird.py"`. Either side can be quoted on its own. + """ + old = new = None + if header.startswith('"'): + first = _read_quoted_path(header, 0) + if not first: + return None + old, end = first + rest = header[end:].lstrip(' ') + if rest.startswith('"'): + second = _read_quoted_path(rest, 0) + new = second[0] if second else None + else: + new = rest + elif header.endswith('"') and ' "b/' in header: + split_at = header.index(' "b/') + old = header[:split_at] + second = _read_quoted_path(header, split_at + 1) + new = second[0] if second else None + else: + m = _UNQUOTED_HEADER_RE.match(header) + return (m.group(1), m.group(2)) if m else None + if not old or not new or not old.startswith('a/') or not new.startswith('b/'): + return None + return old[2:], new[2:] + + +# Section headers that could not be parsed during this hook run; that file is +# left out of the review. The Stop hook reports the count so a header shape +# this parser misses shows up in telemetry instead of passing silently. +_unparsed_diff_headers = set() + + +def _iter_diff_sections(diff_output): + """Yield (new_path, old_path, lines after the header line) per file section.""" + for section in _DIFF_SECTION_RE.split(diff_output)[1:]: + lines = section.split('\n') + paths = _parse_diff_header(lines[0]) + if paths: + yield paths[1] or paths[0], paths[0], lines[1:] + else: + _unparsed_diff_headers.add(lines[0]) + + def extract_file_paths_from_diff(diff_output): """ Extract file paths from unified diff output (without content). Only includes files with source code extensions. - Returns a list of file paths. """ if not diff_output or not diff_output.strip(): return [] - paths = [] - file_diffs = diff_output.split("diff --git ") - - for file_diff in file_diffs: - if not file_diff.strip(): - continue - lines = file_diff.split('\n') - header_match = re.match(r'^a/(.+?) b/(.+)$', lines[0]) - if not header_match: - continue - file_path = header_match.group(2) or header_match.group(1) or '' - if not _is_reviewable_source(file_path): - continue - paths.append(file_path) - - return paths - + return [ + file_path for file_path, old_path, _ in _iter_diff_sections(diff_output) + if _is_reviewable_source(file_path) and not _skip_secret_shaped(old_path) + ] def parse_diff_into_files(diff_output): @@ -999,28 +1143,16 @@ def parse_diff_into_files(diff_output): return [] files = [] - file_diffs = diff_output.split("diff --git ") - - for file_diff in file_diffs: - if not file_diff.strip(): - continue - - # Extract filename from first line: "a/path/to/file b/path/to/file" - lines = file_diff.split('\n') - header_match = re.match(r'^a/(.+?) b/(.+)$', lines[0]) - if not header_match: - continue - - file_path = header_match.group(2) or header_match.group(1) or '' - - # Filter to source code files only - if not _is_reviewable_source(file_path): + for file_path, old_path, lines in _iter_diff_sections(diff_output): + # Filter to source code files only. A rename away from a secret-shaped + # name still carries the secret's content, so the old name counts too. + if not _is_reviewable_source(file_path) or _skip_secret_shaped(old_path): continue # Extract the diff content (from first @@ onwards) diff_lines = [] in_hunks = False - for line in lines[1:]: + for line in lines: if line.startswith('@@'): in_hunks = True if in_hunks: diff --git a/plugins/security-guidance/hooks/llm.py b/plugins/security-guidance/hooks/llm.py index e021c495..3f7607c6 100644 --- a/plugins/security-guidance/hooks/llm.py +++ b/plugins/security-guidance/hooks/llm.py @@ -28,6 +28,7 @@ import tempfile import threading import time import traceback +import urllib.parse import urllib.request from typing import Optional, Tuple, Dict, Any, List @@ -320,6 +321,24 @@ def _custom_headers() -> List[Tuple[str, str]]: return pairs +def gateway_cfg() -> int: + """How the plugin's own API calls are routed, for telemetry: bit 1 when + ANTHROPIC_BASE_URL names a host other than api.anthropic.com, bit 2 when + at least one ANTHROPIC_CUSTOM_HEADERS line is sent. 0 when neither. A + number only: no host, header name or value.""" + cfg = 0 + base = _anthropic_base_url() + try: + host = (urllib.parse.urlsplit(base).hostname or "").lower() + except ValueError: + host = "" + if base and host != "api.anthropic.com": + cfg |= 1 + if any(name.lower() != "anthropic-beta" for name, _ in _custom_headers()): + cfg |= 2 + return cfg + + def _build_auth_headers(use_token, betas=("structured-outputs-2025-11-13",)): betas = list(betas) headers = { @@ -1572,8 +1591,12 @@ def agentic_review( # Claude Code shows Claude as the review notice. Log it instead. child_stderr_lines = [0] + def _child_stderr_metric() -> Dict[str, int]: + return {"child_stderr": child_stderr_lines[0]} if child_stderr_lines[0] else {} + def _on_child_stderr(line: str) -> None: child_stderr_lines[0] += 1 + metrics["child_stderr"] = child_stderr_lines[0] if child_stderr_lines[0] <= 20: debug_log(f"agentic reviewer's CLI stderr | {str(line).rstrip()}") elif child_stderr_lines[0] == 21: @@ -1687,12 +1710,14 @@ def agentic_review( f"{json.dumps(inv, indent=2) if inv else '<none>'}") except Exception as e: debug_log(f"agentic_review: investigate failed ({e}); falling back") - return None, [], {"agentic_fallback": f"investigate:{type(e).__name__}"} + return None, [], {"agentic_fallback": f"investigate:{type(e).__name__}", + **_child_stderr_metric()} metrics["investigate_ms"] = int((_t.time() - t0) * 1000) metrics["investigate_turns"] = inv_turns if inv is None: reason = inv_subtype or "no_structured_output" - return None, [], {"agentic_fallback": f"investigate:{reason}"} + return None, [], {"agentic_fallback": f"investigate:{reason}", + **_child_stderr_metric()} # Keep medium-severity candidates through self-refute — that pass is the # real precision gate, and the model's investigate-stage severity rating # is conservative (it defaults to "medium"). Filtering to high/critical diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 1dcb865c..afc5c190 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -125,6 +125,7 @@ from reporesolve import ( # noqa: E402,F401 toplevel_from_command, repo_containing_commit, scan_roots, resolve_repo_root, save_repo_hint, load_repo_hint, ) +import gitutil # noqa: E402 module ref for per-run counters import llm # noqa: E402 module ref for reassignable globals (_last_call_claude_http_error etc.) from llm import ( # noqa: E402,F401 ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, HAS_API_CREDENTIALS, @@ -198,6 +199,10 @@ CONTINUATION_SUFFIX = ( "response." ) +# Extra keys emit_metrics appends to every row this invocation emits. +_TAIL_METRICS: Dict[str, Any] = {} + + def emit_metrics( metrics, rewake_summary=None, @@ -261,9 +266,21 @@ def emit_metrics( head = {} if _PV and "pv" not in metrics: head["pv"] = _PV - head.update(_usage_metrics()) + usage = _usage_metrics() + head.update(usage) if head: metrics = {**head, **metrics} + # Diagnostic keys go last, so they are the first dropped when a row is + # over CC's key cap and never displace an existing key. + tail = {} + if usage or "review_ms" in metrics or metrics.get("review_failed"): + # Review rows say whether the plugin's calls went through a gateway, + # so the error rate behind gateways can be read per plugin version. + cfg = llm.gateway_cfg() + if cfg: + tail["gateway_cfg"] = cfg + tail.update(_TAIL_METRICS) + metrics = {**metrics, **{k: v for k, v in tail.items() if k not in metrics}} out = {"metrics": metrics} if rewake_summary: out["rewakeSummary"] = rewake_summary @@ -1507,6 +1524,11 @@ def handle_commit_review_posttooluse(input_data): repo_root, diff_files, rel_touched, previous_findings ) agentic_metrics.update(_am) + if _am.get("child_stderr"): + # Lines the inner CLI wrote to stderr during the review: how often + # the condition that used to replace the findings body occurs. Not + # counted when the single-shot fallback wins the race. + _TAIL_METRICS["child_stderr"] = _am["child_stderr"] review_failed = bool(agentic_metrics.get("review_failed")) api_status = agentic_metrics.get("api_error") # Fall back to single-shot only on agentic FAILURE (SDK/investigate @@ -1919,6 +1941,8 @@ def handle_push_sweep_posttooluse(input_data): concrete_guidance, vulns, agentic_metrics = _agentic_review_with_race( repo_root, diff_files, rel_touched, previous_findings ) + if agentic_metrics.get("child_stderr"): + _TAIL_METRICS["child_stderr"] = agentic_metrics["child_stderr"] review_failed = bool(agentic_metrics.get("review_failed")) api_status = agentic_metrics.get("api_error") if agentic_metrics.get("agentic_fallback"): @@ -2095,6 +2119,10 @@ def handle_stop_hook(input_data): "skipped": True, "skip_reason": reason, "fire_index": fire_count + 1, "diff_strategy_v2": True, **v2_metrics, **extra, **sweep, + **({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)} + if gitutil._unparsed_diff_headers else {}), + **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} + if gitutil._secret_shaped_skipped else {}), }) sys.exit(0) @@ -2308,6 +2336,10 @@ def handle_stop_hook(input_data): if llm._last_review_truncated_bytes else {}), **({"repo_resolution": repo_res} if res_metrics else {}), **sweep_trimmed, + **({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)} + if gitutil._unparsed_diff_headers else {}), + **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} + if gitutil._secret_shaped_skipped else {}), }, rewake_summary=_format_vulns_summary(vulns), additional_context=(PROVENANCE_BANNER + "\n\n" + concrete_guidance + CONTINUATION_SUFFIX + "\n"), @@ -2341,6 +2373,10 @@ def handle_stop_hook(input_data): **({"diff_truncated": llm._last_review_truncated_bytes} if llm._last_review_truncated_bytes else {}), **v2_metrics, + **({"diff_hdr_unparsed": len(gitutil._unparsed_diff_headers)} + if gitutil._unparsed_diff_headers else {}), + **({"secret_shaped_skipped": len(gitutil._secret_shaped_skipped)} + if gitutil._secret_shaped_skipped else {}), }) sys.exit(0) diff --git a/plugins/security-guidance/tests/test_custom_headers.py b/plugins/security-guidance/tests/test_custom_headers.py index 2d9fa3ef..fe019d52 100644 --- a/plugins/security-guidance/tests/test_custom_headers.py +++ b/plugins/security-guidance/tests/test_custom_headers.py @@ -1,6 +1,6 @@ """ANTHROPIC_CUSTOM_HEADERS reach every call the plugin makes.""" from conftest import ( - STUB_VULN, VULN_PY, edit_payload, run_hook, stop_payload, ups_payload, + STUB_VULN, VULN_PY, edit_payload, metrics_of, run_hook, stop_payload, ups_payload, ) import llm @@ -63,8 +63,33 @@ class TestCustomHeaders: rc, so, se = run_hook(stop_payload(repo), e) assert rc == 2, (so, se) assert "command_injection" in se + assert metrics_of(so)["gateway_cfg"] == 3 # custom base URL and custom headers calls = [(m, p.split("?")[0]) for m, p, _ in gateway.requests] assert ("GET", "/v1/models") in calls and ("POST", "/v1/messages") in calls for method, path, headers in gateway.requests: if path.startswith("/v1/"): assert headers.get(GATEWAY_KEY[0]) == GATEWAY_KEY[1], (method, path) + + def test_gateway_cfg_is_a_number_with_no_names_or_values(self, monkeypatch): + monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False) + monkeypatch.delenv("ANTHROPIC_CUSTOM_HEADERS", raising=False) + assert llm.gateway_cfg() == 0 + for same_host in ("https://api.anthropic.com/", "https://API.anthropic.com:443"): + monkeypatch.setenv("ANTHROPIC_BASE_URL", same_host) + assert llm.gateway_cfg() == 0 + monkeypatch.setenv("ANTHROPIC_BASE_URL", "https://gw.example.com") + assert llm.gateway_cfg() == 1 + monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "anthropic-beta: extra-1") + assert llm.gateway_cfg() == 1 # beta lines are not sent + monkeypatch.setenv("ANTHROPIC_CUSTOM_HEADERS", "X-Ok: 1") + assert llm.gateway_cfg() == 3 + monkeypatch.delenv("ANTHROPIC_BASE_URL") + assert llm.gateway_cfg() == 2 + + def test_gateway_cfg_is_left_out_when_no_api_call_was_made(self, env, gateway, workspace): + """Only rows that made API calls carry gateway_cfg.""" + _, repo = workspace + rc, so, se = run_hook(stop_payload(repo), env) + assert rc == 0, (so, se) + row = metrics_of(so) + assert row["skipped"] is True and "gateway_cfg" not in row diff --git a/plugins/security-guidance/tests/test_diff_parsing.py b/plugins/security-guidance/tests/test_diff_parsing.py new file mode 100644 index 00000000..7665a064 --- /dev/null +++ b/plugins/security-guidance/tests/test_diff_parsing.py @@ -0,0 +1,99 @@ +import os +import subprocess + +from conftest import GIT_ENV, git, make_repo + +import gitutil + +VULN = "import os\nos.system(input())\n" + + +def staged_diff(repo): + r = subprocess.run( + [*gitutil.GIT_CMD, "diff", "--cached", "--no-color"], cwd=repo, + capture_output=True, env={**os.environ, **GIT_ENV}, + ) + assert r.returncode == 0, r.stderr + return r.stdout.decode("utf-8", errors="replace") + + +def stage(tmp_path, files): + repo = make_repo(tmp_path / "repo") + for name, content in files.items(): + (repo / name).write_text(content) + git(repo, "add", "-A") + return staged_diff(repo) + + +class TestEmbeddedHeaderText: + SOURCE = ( + 'HEADER = """\n' + "diff --git a/other.py b/other.py\n" + '"""\n' + "import os\n" + "os.system(input()) # AFTER_EMBEDDED_HEADER\n" + ) + + def test_content_after_embedded_header_text_is_kept(self, tmp_path): + files = dict(gitutil.parse_diff_into_files(stage(tmp_path, {"embed.py": self.SOURCE}))) + assert list(files) == ["embed.py"] + assert "AFTER_EMBEDDED_HEADER" in files["embed.py"] + + def test_embedded_header_text_adds_no_path(self, tmp_path): + diff = stage(tmp_path, {"embed.py": self.SOURCE}) + assert gitutil.extract_file_paths_from_diff(diff) == ["embed.py"] + + def test_following_file_is_still_parsed(self, tmp_path): + diff = stage(tmp_path, {"embed.py": self.SOURCE, "z_next.py": VULN}) + assert [p for p, _ in gitutil.parse_diff_into_files(diff)] == ["embed.py", "z_next.py"] + + +class TestQuotedPaths: + def test_names_git_quotes_are_reviewed(self, tmp_path): + names = ['we"ird.py', "tab\there.py", "back\\slash.py", "café.py", "plain.py"] + diff = stage(tmp_path, {n: VULN for n in names}) + assert '"a/we\\"ird.py"' in diff # git did quote it + parsed = gitutil.parse_diff_into_files(diff) + assert sorted(p for p, _ in parsed) == sorted(names) + assert all("os.system" in c for _, c in parsed) + assert sorted(gitutil.extract_file_paths_from_diff(diff)) == sorted(names) + + def test_rename_to_a_quoted_name(self, tmp_path): + repo = make_repo(tmp_path / "repo", {"plain.py": VULN * 20}) + git(repo, "mv", "plain.py", 'qu"ote.py') + (repo / 'qu"ote.py').write_text(VULN * 20 + "eval(input())\n") + git(repo, "add", "-A") + diff = staged_diff(repo) + assert 'a/plain.py "b/qu\\"ote.py"' in diff + assert [p for p, _ in gitutil.parse_diff_into_files(diff)] == ['qu"ote.py'] + + def test_octal_escapes_decode_as_utf8(self): + header = '"a/caf\\303\\251.py" "b/caf\\303\\251.py"' + assert gitutil._parse_diff_header(header) == ("café.py", "café.py") + + def test_unterminated_quote_is_skipped(self): + assert gitutil._parse_diff_header('"a/x.py b/x.py') is None + + +class TestCommitOutput: + def test_git_show_preamble_is_ignored(self, tmp_path): + repo = make_repo(tmp_path / "repo") + (repo / "app.py").write_text(VULN) + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "diff --git a/fake.py b/fake.py") + r = subprocess.run( + [*gitutil.GIT_CMD, "show", "-p", "--no-color", "HEAD", "--"], cwd=repo, + capture_output=True, env={**os.environ, **GIT_ENV}, + ) + parsed = gitutil.parse_diff_into_files(r.stdout.decode()) + assert [p for p, _ in parsed] == ["app.py"] + + +def test_unparsed_headers_are_counted_for_telemetry(): + import gitutil + gitutil._unparsed_diff_headers.clear() + diff = 'diff --git "a/x.py b/x.py\n@@ -0,0 +1 @@\n+x = 1\n' + assert gitutil.parse_diff_into_files(diff) == [] + assert gitutil.extract_file_paths_from_diff(diff) == [] + assert len(gitutil._unparsed_diff_headers) == 1 + gitutil._unparsed_diff_headers.clear() diff --git a/plugins/security-guidance/tests/test_findings_delivery.py b/plugins/security-guidance/tests/test_findings_delivery.py index b71fc8d6..0989ed4b 100644 --- a/plugins/security-guidance/tests/test_findings_delivery.py +++ b/plugins/security-guidance/tests/test_findings_delivery.py @@ -32,6 +32,7 @@ class TestAgenticReviewerOn: sha, rc, so, se = _commit(repo, agentic_env) assert rc == 2, (so, se) assert metrics_of(so)["agentic_fallback"] == 2 + assert metrics_of(so)["child_stderr"] >= 1 # the warning was counted, not shown body = _rewake_body(so, se) assert "command_injection" in body assert "connectors are disabled" not in body diff --git a/plugins/security-guidance/tests/test_secret_shaped_paths.py b/plugins/security-guidance/tests/test_secret_shaped_paths.py new file mode 100644 index 00000000..bfd5180d --- /dev/null +++ b/plugins/security-guidance/tests/test_secret_shaped_paths.py @@ -0,0 +1,95 @@ +import os +import subprocess + +import pytest + +from conftest import ( + GIT_ENV, git, make_repo, metrics_of, run_hook, stop_payload, ups_payload, +) + +import gitutil + + +@pytest.mark.parametrize("path", [ + "dot_config/private_example/encrypted_private_token", + "encrypted_private_dot_netrc", + "home/encrypted_config.yaml", + "id_ed25519", + ".ssh/id_rsa", + "private_dot_ssh/private_id_ecdsa", + "deploy_rsa", + "keys/github_ed25519", + ".env.production.json", + ".env.local.yaml", + "config/dot_env.toml", + "private_dot_netrc", + "dot_aws/credentials", + "Deploy_RSA", +]) +def test_secret_shaped_names_are_not_reviewable(path): + assert gitutil._is_secret_shaped(path) + assert not gitutil._is_reviewable_source(path) + + +@pytest.mark.parametrize("path", [ + "src/private_api.py", + "src/id_generator.py", + "lib/encrypted_store.py", + "crypto/rsa.py", + "auth/sign_rsa.go", + "app/credentials.py", + "scripts/run_migrations.sh", + "dot_product.py", + "config/environment.json", + "bin/deploy", + "Dockerfile.dev", + "executable_backup.sh", +]) +def test_ordinary_source_stays_reviewable(path): + assert not gitutil._is_secret_shaped(path) + assert gitutil._is_reviewable_source(path) + + +def _staged_diff(repo): + r = subprocess.run( + [*gitutil.GIT_CMD, "diff", "--cached", "--no-color", "-M"], cwd=repo, + capture_output=True, env={**os.environ, **GIT_ENV}, + ) + assert r.returncode == 0, r.stderr + return r.stdout.decode("utf-8", errors="replace") + + +def test_secret_content_is_left_out_of_the_parsed_diff(tmp_path): + repo = make_repo(tmp_path / "repo") + (repo / "encrypted_private_token").write_text("CIPHERTEXT_BODY\n") + (repo / "id_ed25519").write_text("PRIVATE_KEY_BODY\n") + (repo / ".env.production.json").write_text('{"API_KEY": "ENV_SECRET_BODY"}\n') + (repo / "app.py").write_text("import os\nos.system(input())\n") + git(repo, "add", "-A") + diff = _staged_diff(repo) + parsed = gitutil.parse_diff_into_files(diff) + assert [p for p, _ in parsed] == ["app.py"] + assert "_BODY" not in "".join(c for _, c in parsed) + assert gitutil.extract_file_paths_from_diff(diff) == ["app.py"] + + +def test_rename_away_from_a_secret_name_is_left_out(tmp_path): + body = "".join(f"KEY_{i}=SECRET_VALUE_{i}\n" for i in range(30)) + repo = make_repo(tmp_path / "repo", {"deploy_rsa": body}) + git(repo, "mv", "deploy_rsa", "notes.sh") + (repo / "notes.sh").write_text(body + "KEY_NEW=SECRET_VALUE_NEW\n") + git(repo, "add", "-A") + diff = _staged_diff(repo) + assert "rename from deploy_rsa" in diff + assert gitutil.parse_diff_into_files(diff) == [] + assert gitutil.extract_file_paths_from_diff(diff) == [] + + +def test_stop_hook_reports_how_many_files_it_left_out(tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo") + run_hook(ups_payload(repo), hook_env) + (repo / "id_ed25519").write_text("-----BEGIN OPENSSH PRIVATE KEY-----\n") + (repo / ".env.local").write_text("TOKEN=abc\n") + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + assert metrics_of(stdout).get("secret_shaped_skipped") == 2 + assert stub_api.calls == [] diff --git a/plugins/security-guidance/tests/test_untracked_cap.py b/plugins/security-guidance/tests/test_untracked_cap.py new file mode 100644 index 00000000..00fd4015 --- /dev/null +++ b/plugins/security-guidance/tests/test_untracked_cap.py @@ -0,0 +1,85 @@ +import os +import time + +from conftest import make_repo, metrics_of, run_hook, stop_payload, ups_payload + +import diffstate + +SRC = "import os\nos.system(input())\n" + + +def _review(repo, snapshot): + paths, _base, root, _untracked, metrics = diffstate.compute_v2_review_set( + str(repo), None, None, snapshot) + return sorted(os.path.relpath(p, root) for p in paths), metrics + + +class TestCappedSnapshot: + def _repo(self, tmp_path, monkeypatch, n=30, cap=10): + monkeypatch.setattr(diffstate, "UNTRACKED_BASELINE_CAP", cap) + monkeypatch.setattr(diffstate, "_CAPPED_BASELINE_SLACK_NS", 20_000_000) + repo = make_repo(tmp_path / "repo") + for i in range(n): + (repo / f"old_{i:03d}.py").write_text(SRC) + time.sleep(0.1) + return repo + + def test_snapshot_records_when_it_was_capped(self, tmp_path, monkeypatch): + repo = self._repo(tmp_path, monkeypatch) + before = time.time_ns() + snap = diffstate._list_untracked(str(repo)) + assert before <= snap[diffstate.UNTRACKED_CAPPED_AT_KEY] <= time.time_ns() + assert len(snap) == 10 + 1 + + def test_uncapped_snapshot_has_no_marker(self, tmp_path, monkeypatch): + repo = self._repo(tmp_path, monkeypatch, n=5) + assert diffstate.UNTRACKED_CAPPED_AT_KEY not in diffstate._list_untracked(str(repo)) + + def test_files_past_the_cap_are_not_reviewed_when_untouched(self, tmp_path, monkeypatch): + repo = self._repo(tmp_path, monkeypatch) + snap = diffstate._list_untracked(str(repo)) + review, metrics = _review(repo, snap) + assert review == [] + assert metrics["preexisting_untracked_excluded"] == 30 + + def test_new_and_edited_files_past_the_cap_are_reviewed(self, tmp_path, monkeypatch): + repo = self._repo(tmp_path, monkeypatch) + snap = diffstate._list_untracked(str(repo)) + time.sleep(0.1) + (repo / "zz_new.py").write_text(SRC) + (repo / "old_025.py").write_text(SRC + "eval(input())\n") + (repo / "old_003.py").write_text(SRC + "eval(input())\n") # inside the cap + review, _ = _review(repo, snap) + assert review == ["old_003.py", "old_025.py", "zz_new.py"] + + def test_file_moved_in_with_an_old_mtime_is_reviewed(self, tmp_path, monkeypatch): + repo = self._repo(tmp_path, monkeypatch) + snap = diffstate._list_untracked(str(repo)) + time.sleep(0.1) + new = repo / "zz_extracted.py" + new.write_text(SRC) + os.utime(new, (1_600_000_000, 1_600_000_000)) # as tar or cp -p would leave it + review, _ = _review(repo, snap) + assert review == ["zz_extracted.py"] + + +def test_stop_hook_does_not_re_review_files_past_the_cap(tmp_path, hook_env, stub_api): + """More untracked files than the snapshot holds: the same old files must + not be sent for review turn after turn (#6407).""" + repo = make_repo(tmp_path / "repo") + n_files = diffstate.UNTRACKED_BASELINE_CAP + 60 + for i in range(n_files): + (repo / f"old_{i:05d}.py").write_text(SRC) + time.sleep(2.2) # older than the snapshot by more than the timestamp slack + + for _turn in range(2): + run_hook(ups_payload(repo), hook_env) + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + # Telemetry: a count above the cap is how this path shows up. + assert metrics_of(stdout)["preexisting_untracked_excluded"] == n_files + assert stub_api.calls == [] + + run_hook(ups_payload(repo), hook_env) + (repo / "zz_new.py").write_text(SRC) + run_hook(stop_payload(repo), hook_env) + assert len([c for c in stub_api.calls if "messages" in c]) == 1 |
