diff options
| author | Mohamed Hegazy <mhegazy@anthropic.com> | 2026-10-18 17:04:53 +0000 |
|---|---|---|
| committer | Claude <noreply@anthropic.com> | 2026-10-18 17:04:53 +0000 |
| commit | 9f7575d2ccde33ed2a9491da69caded068c5926d (patch) | |
| tree | 0cb9af399f9c8b7fb61ec09888dbf7936b1da023 /plugins | |
| parent | ded17af4aac57cbe4f3b027dc46a5c338f41afa9 (diff) | |
security-guidance: keep secret renames out and report the right skip when paths do not fit one command
When the changed paths are too long for one git command:
- secret-shaped paths gone from the work tree go into every batch, so a
rename away from such a name is still paired and its content stays out
of the review
- the batch size follows the system's own argument limit when it is lower
- giving up is reported as skip 8 and a set with no source files as skip 7,
instead of 6 (no changes)
MAX_REVIEW_SET_PATHS counts only reviewable paths, read from the repo root,
so an unignored dependency directory does not hide an edited source file.
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 60 | ||||
| -rwxr-xr-x | plugins/security-guidance/hooks/security_reminder_hook.py | 22 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_stop_review_paths.py | 123 |
3 files changed, 189 insertions, 16 deletions
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index aceb9071..3e025f2b 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -165,12 +165,30 @@ _MAX_PATH_ARGS_BYTES = ( _MAX_PATH_BATCHES = 4 -def _path_batches(paths): +def _arg_cost(path): + # The exec limit also counts a terminator and a pointer per argument. + return len(os.fsencode(path)) + 9 + + +def _path_args_budget(env=None): + """_MAX_PATH_ARGS_BYTES, or less where this system's own limit is lower + (a small stack limit, a BSD, a very large environment). Half of what the + system leaves after the environment, so the rest of the command fits.""" + try: + arg_max = os.sysconf("SC_ARG_MAX") + except (AttributeError, ValueError, OSError): + return _MAX_PATH_ARGS_BYTES + env_bytes = sum(len(k) + len(v) + 2 for k, v in (env or os.environ).items()) + return min(_MAX_PATH_ARGS_BYTES, max(4096, (arg_max - env_bytes) // 2)) + + +def _path_batches(paths, budget=None): + if budget is None: + budget = _MAX_PATH_ARGS_BYTES batch, size = [], 0 for p in paths: - # The exec limit also counts a terminator and a pointer per argument. - n = len(os.fsencode(p)) + 9 - if batch and size + n > _MAX_PATH_ARGS_BYTES: + n = _arg_cost(p) + if batch and size + n > budget: yield batch batch, size = [], 0 batch.append(p) @@ -179,6 +197,12 @@ def _path_batches(paths): yield batch +# Why a path list too long for one command left the last get_git_diff call +# without a diff, for the Stop review's skip reason: "gave_up" (still too +# long once cut down) or "none_reviewable". +_path_list_too_long = set() + + def _too_many_args(e): """The OS refused to start the command because its arguments are too long. Windows reports ERROR_FILENAME_EXCED_RANGE, which Python turns into @@ -196,9 +220,13 @@ def _run_git_on_review_paths(args, paths, timeout, **kwargs): those need more than _MAX_PATH_BATCHES commands, the refusal is raised again. - After a refusal, `git diff` pairs a rename only when both of its paths - are reviewable source and in the same command; otherwise it shows as a - delete or an add. + Secret-shaped paths that are gone from the work tree go into every one + of those commands: `git diff` must still pair a rename away from such a + name, or the secret's content would show as a new source file. A new file + that only resembles the secret may be paired with it too and left out of + the review. Any other rename is paired only when both of its paths are + reviewable source and in the same command; otherwise it shows as a delete + or an add. """ cmd = [*GIT_CMD, *args, "--"] paths = list(paths) @@ -210,11 +238,20 @@ def _run_git_on_review_paths(args, paths, timeout, **kwargs): if not _too_many_args(e): raise too_long = e - batches = list(_path_batches([p for p in paths if _is_reviewable_source(p)])) + budget = _path_args_budget(kwargs.get("env")) + batches = list(_path_batches( + [p for p in paths if _is_reviewable_source(p)], budget)) + root = kwargs.get("cwd") or os.getcwd() + secret = [p for p in paths if _is_secret_shaped(p) + and not os.path.lexists(os.path.join(root, p))] debug_log(f"git {args[0]}: {len(paths)} paths do not fit one command; " f"{len(batches)} command(s) for the reviewable ones") - if len(batches) > _MAX_PATH_BATCHES: + # The secret-shaped paths ride along with every batch, so they get a + # small share of a command of their own. + if (len(batches) > _MAX_PATH_BATCHES + or sum(map(_arg_cost, secret)) > budget // 4): raise too_long + cmd += secret results = [] for batch in batches: left = deadline - time.monotonic() @@ -856,6 +893,7 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa `untracked_paths` (repo-root-relative) is forwarded to _temp_index so it can add only those files instead of scanning the whole worktree. """ + _path_list_too_long.clear() pathspec = _diff_pathspec(cwd, paths) if paths and not pathspec: # Caller restricted to specific paths but none are inside this repo @@ -872,6 +910,8 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa results = _run_git_on_review_paths(args, pathspec[1:], timeout=30, cwd=cwd, env=env) else: results = [subprocess.run([*GIT_CMD, *args], cwd=cwd, capture_output=True, timeout=30, env=env)] + if not results: + _path_list_too_long.add("none_reviewable") for result in results: if result.returncode != 0: debug_log(f"git diff failed: {result.stderr[:200].decode('utf-8', errors='replace')}") @@ -890,6 +930,8 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa return _run(env) except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e: debug_log(f"git diff error: {e}") + if isinstance(e, OSError) and _too_many_args(e): + _path_list_too_long.add("gave_up") return None diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 946fddcf..5d891161 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -193,10 +193,11 @@ MAX_STOP_HOOK_FIRINGS = int(os.environ.get("MAX_STOP_HOOK_FIRINGS", "3")) # diff; unbounded diffs burn tokens and risk 400 on context length. MAX_DIFF_FILES = int(os.environ.get("MAX_DIFF_FILES", "30")) -# Changed paths past which the Stop review is skipped before any diff. A set -# this large is a repo at $HOME or an unignored cache, not edits; no platform -# takes that many paths in one git command, and only resolving them takes -# seconds. +# Changed source paths past which the Stop review is skipped before any diff. +# A set this large is a repo at $HOME or an unignored cache, not edits; no +# platform takes that many paths in one git command, and only resolving them +# takes seconds. Paths the review never reads (an unignored node_modules) do +# not count: they must not hide the one edited source file beside them. MAX_REVIEW_SET_PATHS = int(os.environ.get("MAX_REVIEW_SET_PATHS", "100000")) # Appended to all exit(2) guidance so the asyncRewake auto-turn doesn't @@ -2273,7 +2274,9 @@ def handle_stop_hook(input_data): debug_log("Stop hook: empty review set") _skip(9, touched_paths_count=len(touched_paths)) debug_log(f"Stop hook: review_set={len(review_paths)} base={diff_base[:12]} dirty_now={v2_metrics['dirty_now_count']} changed_since={v2_metrics['changed_since_count']}") - if len(review_paths) > MAX_REVIEW_SET_PATHS: + if (len(review_paths) > MAX_REVIEW_SET_PATHS + and sum(_is_reviewable_source(os.path.relpath(p, repo_root)) + for p in review_paths) > MAX_REVIEW_SET_PATHS): debug_log(f"Stop hook: pathological review set (more than " f"{MAX_REVIEW_SET_PATHS} paths), skipping") _skip(8) @@ -2288,7 +2291,8 @@ def handle_stop_hook(input_data): content_base = baseline_sha or diff_base diff_output = get_git_diff(repo_root, content_base, full_context=False, paths=review_paths, untracked_paths=untracked) - if diff_output is None and content_base != diff_base: + if (diff_output is None and content_base != diff_base + and "gave_up" not in gitutil._path_list_too_long): debug_log(f"Stop hook: diff against {content_base[:12]} failed — falling back to {diff_base}") diff_output = get_git_diff(repo_root, diff_base, full_context=False, paths=review_paths, untracked_paths=untracked) @@ -2298,6 +2302,12 @@ def handle_stop_hook(input_data): baseline_sha = "HEAD" if not diff_output or not diff_output.strip(): + if "gave_up" in gitutil._path_list_too_long: + debug_log("Stop hook: changed paths do not fit the git commands, skipping") + _skip(8) + if "none_reviewable" in gitutil._path_list_too_long: + debug_log("Stop hook: no source code files among the changed paths") + _skip(7) debug_log("Stop hook: no changes since baseline") _skip(6) diff --git a/plugins/security-guidance/tests/test_stop_review_paths.py b/plugins/security-guidance/tests/test_stop_review_paths.py index 85c612af..986f7b78 100644 --- a/plugins/security-guidance/tests/test_stop_review_paths.py +++ b/plugins/security-guidance/tests/test_stop_review_paths.py @@ -26,6 +26,7 @@ def git_env(tmp_path, monkeypatch): d = tmp_path / "tmproot" d.mkdir() monkeypatch.setattr(tempfile, "tempdir", str(d)) + monkeypatch.setattr(gitutil, "_path_list_too_long", set()) for k, v in GIT_ENV.items(): monkeypatch.setenv(k, v) @@ -40,8 +41,19 @@ def _more_than_one_command_holds(repo, exts): (deep / f"file_{i:05d}{exts[i % len(exts)]}").write_text("x\n") +def _unusual_argument_limit(): + """The long-path tests are sized for the usual limits: 1 MB (macOS) to + 2 MB (Linux with an 8 MB stack).""" + try: + return not 1024 * 1024 <= os.sysconf("SC_ARG_MAX") <= 2 * 1024 * 1024 + 200000 + except (AttributeError, ValueError, OSError): + return False + + long_paths = pytest.mark.skipif( - os.name == "nt", reason="needs paths longer than Windows allows by default") + os.name == "nt" or _unusual_argument_limit(), + reason="needs paths longer than Windows allows by default, and the usual " + "1 to 2 MB limit on one command's arguments") def _refuse_long_commands(monkeypatch, limit, error): @@ -128,6 +140,70 @@ class TestGetGitDiff: assert cut.count("diff --git ") == 1 assert gitutil.parse_diff_into_files(cut) == gitutil.parse_diff_into_files(whole) + def test_rename_away_from_a_secret_shaped_name_stays_out_after_a_refusal( + self, tmp_path, git_env, monkeypatch): + secret = "".join(f"KEY_{i}=value-{i}\n" for i in range(20)) + repo = make_repo(tmp_path / "repo", {".env": secret, "app.py": "x = 1\n"}) + os.rename(repo / ".env", repo / "settings.py") + (repo / "app.py").write_text("x = 2\n") + (repo / "a_much_longer_module_name.py").write_text("y = 1\n") + for i in range(20): + (repo / f"note{i:02d}.txt").write_text("x\n") + paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {}) + whole = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) + reviewed = ["a_much_longer_module_name.py", "app.py"] + assert sorted(f for f, _ in gitutil.parse_diff_into_files(whole)) == reviewed + # Room for .env beside each batch, and not for the three .py together. + monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 60) + ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 120, OSError(errno.E2BIG, "too long")) + cut = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) + diffs = [c for c in ran if "diff" in c] + assert len(diffs) > 1 and all(".env" in c for c in diffs) + assert sorted(f for f, _ in gitutil.parse_diff_into_files(cut)) == reviewed + assert "KEY_1=" not in "".join(d for _, d in gitutil.parse_diff_into_files(cut)) + + def test_gives_up_when_the_secret_shaped_paths_alone_are_too_many( + self, tmp_path, git_env, monkeypatch): + repo = make_repo(tmp_path / "repo", { + "app.py": "x = 1\n", **{f"dir{i:02d}/.env": "K=v\n" for i in range(20)}}) + (repo / "app.py").write_text("x = 2\n") + for i in range(20): + os.remove(repo / f"dir{i:02d}" / ".env") + paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {}) + monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 200) + ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 100, OSError(errno.E2BIG, "too long")) + assert gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) is None + assert [c for c in ran if "diff" in c] == [] + assert "gave_up" in gitutil._path_list_too_long + + def test_secret_shaped_files_still_in_the_work_tree_do_not_ride_along( + self, tmp_path, git_env, monkeypatch): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + (repo / "app.py").write_text("x = 2\n") + for i in range(20): + (repo / f"dir{i:02d}").mkdir() + (repo / f"dir{i:02d}" / ".env").write_text("K=v\n") + paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {}) + monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 200) + ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 100, OSError(errno.E2BIG, "too long")) + cut = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) + assert [f for f, _ in gitutil.parse_diff_into_files(cut)] == ["app.py"] + assert not any(".env" in a for c in ran for a in c) + assert not gitutil._path_list_too_long + + def test_batches_shrink_to_a_lower_system_limit(self, monkeypatch): + monkeypatch.setattr(os, "sysconf", lambda name: 100000, raising=False) + budget = gitutil._path_args_budget({"A": "b" * 9997}) + assert budget == 45000 + paths = [f"dir/file_{i}.py" for i in range(10000)] + assert all(sum(len(p) + 9 for p in b) <= budget + for b in gitutil._path_batches(paths, budget)) + # Never above the platform figure, never uselessly small. + monkeypatch.setattr(os, "sysconf", lambda name: 10**9, raising=False) + assert gitutil._path_args_budget({}) == gitutil._MAX_PATH_ARGS_BYTES + monkeypatch.setattr(os, "sysconf", lambda name: 100, raising=False) + assert gitutil._path_args_budget({}) == 4096 + def test_gives_up_past_the_batch_limit(self, tmp_path, git_env, monkeypatch): root, base, paths, untracked = self._review_set(tmp_path) monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 60) @@ -191,3 +267,48 @@ class TestWholeHook: # The skip taken after a diff reports how many files the diff held. assert "diff_files_count" not in m assert not stub_api.calls + + def test_cap_counts_only_reviewable_paths(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + for i in range(20): + (repo / f"note{i:02d}.txt").write_text("x\n") + rc, so, se = run_hook(stop_payload(repo), {**hook_env, "MAX_REVIEW_SET_PATHS": "5"}) + m = metrics_of(so) + assert m.get("skip_reason") is None, m + assert m.get("review_set_count") == 21 + assert stub_api.calls + + @long_paths + def test_giving_up_is_reported_as_too_many_paths(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + # 3,000 reviewable names of about 750 bytes: more than four commands. + _more_than_one_command_holds(repo, [".py"]) + rc, so, se = run_hook(stop_payload(repo), hook_env) + m = metrics_of(so) + assert m.get("skip_reason") == 8, m + assert not stub_api.calls + + @long_paths + def test_nothing_reviewable_is_reported_as_no_source_files(self, tmp_path, hook_env, stub_api): + repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"}) + run_hook(ups_payload(repo), hook_env) + _more_than_one_command_holds(repo, [".txt"]) + rc, so, se = run_hook(stop_payload(repo), hook_env) + m = metrics_of(so) + assert m.get("skip_reason") == 7, m + assert not stub_api.calls + + def test_cap_reads_paths_from_the_repo_root(self, tmp_path, hook_env, stub_api): + # A directory above the repo named like a skipped one (build/) must + # not make every path look unreviewable. + repo = make_repo(tmp_path / "build" / "repo", {"app.py": "x = 1\n"}) + run_hook(ups_payload(repo), hook_env) + (repo / "app.py").write_text(VULN_PY) + (repo / "new.py").write_text(VULN_PY) + rc, so, se = run_hook(stop_payload(repo), {**hook_env, "MAX_REVIEW_SET_PATHS": "1"}) + assert metrics_of(so).get("skip_reason") == 8 + assert not stub_api.calls |
