summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/gitutil.py119
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py10
-rw-r--r--plugins/security-guidance/tests/test_stop_review_paths.py193
3 files changed, 303 insertions, 19 deletions
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index 2036b45e..5ef8a8db 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -15,9 +15,12 @@ Functions that DO compose patched leaves (``compute_v2_review_set``,
``security_reminder_hook.py`` for that reason.
"""
import contextlib
+import errno
import os
import re
import subprocess
+import sys
+import time
from _base import debug_log
@@ -143,6 +146,78 @@ def _diff_pathspec(cwd, paths):
return ["--"] + rel if rel else []
+# Bytes of file paths per git call once a path list has proved too long for
+# one command. Windows caps a whole command line at 32,767 characters;
+# elsewhere the limit is about 1 MB (macOS) or 2 MB (Linux), environment
+# included.
+_MAX_PATH_ARGS_BYTES = (
+ 20000 if sys.platform in ("win32", "cygwin", "msys") else 500000)
+# More commands than this and the path list is not worth diffing: each one
+# matches its paths against the whole index, and a set that large is thrown
+# away as pathological after the diff anyway.
+_MAX_PATH_BATCHES = 4
+
+
+def _path_batches(paths):
+ 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:
+ yield batch
+ batch, size = [], 0
+ batch.append(p)
+ size += n
+ if batch:
+ yield batch
+
+
+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
+ a FileNotFoundError."""
+ return e.errno == errno.E2BIG or getattr(e, "winerror", None) == 206
+
+
+def _run_git_on_review_paths(args, paths, timeout, **kwargs):
+ """Run `git <args> -- <paths>` for the Stop review; return the results.
+
+ One command with every path whenever the OS takes it. When the OS refuses
+ the argument list as too long, only reviewable source paths are kept (the
+ review drops the rest from the diff anyway) and they go out in as few
+ commands as they need, all within `timeout` seconds together. If even
+ 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.
+ """
+ cmd = [*GIT_CMD, *args, "--"]
+ paths = list(paths)
+ deadline = time.monotonic() + timeout
+ try:
+ return [subprocess.run(cmd + paths, capture_output=True,
+ timeout=timeout, **kwargs)]
+ except OSError as e:
+ if not _too_many_args(e):
+ raise
+ too_long = e
+ batches = list(_path_batches([p for p in paths if _is_reviewable_source(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:
+ raise too_long
+ results = []
+ for batch in batches:
+ left = deadline - time.monotonic()
+ if left <= 0:
+ raise subprocess.TimeoutExpired(cmd, timeout)
+ results.append(subprocess.run(cmd + batch, capture_output=True,
+ timeout=left, **kwargs))
+ return results
+
+
_TEMP_INDEX_PREFIX = "security_hook_idx_"
# A copy is named <prefix>pid<hook pid>_<8 random chars>, so a later run can
# tell that the hook which made it is gone. Names from earlier releases have
@@ -443,7 +518,7 @@ def _copied_index(cwd, real_index, tmpdir, untracked_paths):
# filter to surviving paths (lexists so dangling symlinks count).
surviving = [p for p in untracked_paths
if os.path.lexists(os.path.join(cwd, p))]
- add_args = ["--"] + surviving if surviving else None
+ add_args = surviving or None
else:
add_args = None
if add_args:
@@ -451,11 +526,8 @@ def _copied_index(cwd, real_index, tmpdir, untracked_paths):
# still spawns reader threads that decode stderr — git error
# messages can reference non-ASCII filenames and crash on
# cp1252. See #2099. Drop text=True so bytes stay raw.
- subprocess.run(
- [*GIT_CMD, "add", "--intent-to-add"] + add_args,
- cwd=cwd, capture_output=True, timeout=10,
- env=env,
- )
+ _run_git_on_review_paths(["add", "--intent-to-add"], add_args,
+ timeout=10, cwd=cwd, env=env)
yield env
finally:
_remove_copy(tmp_index)
@@ -772,6 +844,8 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
If `paths` is given, the diff is restricted to those paths (relative to
cwd; absolute paths are converted, paths outside cwd are dropped).
+ A path list too long for one command is cut down to reviewable source
+ files: see _run_git_on_review_paths.
`untracked_paths` (repo-root-relative) is forwarded to _temp_index so it
can add only those files instead of scanning the whole worktree.
"""
@@ -784,22 +858,29 @@ def get_git_diff(cwd, baseline_sha, full_context=False, paths=None, untracked_pa
return ""
# core.quotePath=false comes from GIT_CMD globally (see definition).
- cmd = [*GIT_CMD, "diff", "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else []) + pathspec
+ args = ["diff", "--no-color", "--no-ext-diff", "--no-textconv", baseline_sha] + (["--unified=99999"] if full_context else [])
+
+ def _run(env):
+ if pathspec:
+ 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)]
+ for result in results:
+ if result.returncode != 0:
+ debug_log(f"git diff failed: {result.stderr[:200].decode('utf-8', errors='replace')}")
+ return None
+ # Decode with errors='replace' so binary diffs don't crash
+ return b"".join(r.stdout for r in results).decode("utf-8", errors="replace")
+
try:
if untracked_paths is not None and not untracked_paths:
# Nothing to `add -N`, and the diff only reads the index.
- result = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=30)
- else:
- with _temp_index(cwd, untracked_paths) as env:
- # env is None when there is no index (bare repo / not a repo)
- # or no copy slot — diff still runs, just without
- # untracked-file support.
- result = subprocess.run(cmd, cwd=cwd, capture_output=True, timeout=30, env=env)
- if result.returncode != 0:
- debug_log(f"git diff failed: {result.stderr[:200].decode('utf-8', errors='replace')}")
- return None
- # Decode with errors='replace' so binary diffs don't crash
- return result.stdout.decode("utf-8", errors="replace")
+ return _run(None)
+ with _temp_index(cwd, untracked_paths) as env:
+ # env is None when there is no index (bare repo / not a repo)
+ # or no copy slot — diff still runs, just without
+ # untracked-file support.
+ return _run(env)
except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
debug_log(f"git diff error: {e}")
return None
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index e8df7a1c..6b885e64 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -189,6 +189,12 @@ 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.
+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
# cause the model to abandon the user's original request.
CONTINUATION_SUFFIX = (
@@ -2016,6 +2022,10 @@ 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:
+ debug_log(f"Stop hook: pathological review set (more than "
+ f"{MAX_REVIEW_SET_PATHS} paths), skipping")
+ _skip(8)
# Run from repo_root so the toplevel-relative review_paths resolve.
# Diff CONTENT against the turn-start stash (baseline_sha) so the LLM
# sees only this-turn edits — diffing against HEAD includes the user's
diff --git a/plugins/security-guidance/tests/test_stop_review_paths.py b/plugins/security-guidance/tests/test_stop_review_paths.py
new file mode 100644
index 00000000..85c612af
--- /dev/null
+++ b/plugins/security-guidance/tests/test_stop_review_paths.py
@@ -0,0 +1,193 @@
+"""The Stop review still runs when the changed paths of a turn do not fit in
+one git command."""
+import errno
+import os
+import subprocess
+import tempfile
+import types
+
+import pytest
+
+from conftest import (
+ GIT_ENV, VULN_PY, make_repo, metrics_of, run_hook, stop_payload,
+ ups_payload,
+)
+
+import diffstate
+import gitutil
+
+GIT_CMD_CHARS = sum(len(a) + 1 for a in gitutil.GIT_CMD)
+
+
+@pytest.fixture
+def git_env(tmp_path, monkeypatch):
+ """Git identity for in-process calls, and a temp dir of our own for the
+ index copies."""
+ d = tmp_path / "tmproot"
+ d.mkdir()
+ monkeypatch.setattr(tempfile, "tempdir", str(d))
+ for k, v in GIT_ENV.items():
+ monkeypatch.setenv(k, v)
+
+
+def _more_than_one_command_holds(repo, exts):
+ """3,000 untracked files, cycling through `exts`, whose names add up to
+ more than a single command can carry on any platform (the largest limit
+ is about 2 MB, on Linux)."""
+ deep = repo / ("d" * 180) / ("e" * 180) / ("f" * 180) / ("g" * 180)
+ deep.mkdir(parents=True)
+ for i in range(3000):
+ (deep / f"file_{i:05d}{exts[i % len(exts)]}").write_text("x\n")
+
+
+long_paths = pytest.mark.skipif(
+ os.name == "nt", reason="needs paths longer than Windows allows by default")
+
+
+def _refuse_long_commands(monkeypatch, limit, error):
+ """Make subprocess.run fail like the OS does for a command whose
+ arguments exceed `limit` characters. Returns the list of commands run."""
+ real_run = subprocess.run
+ ran = []
+
+ def run(cmd, *args, **kwargs):
+ if sum(len(a) + 1 for a in cmd) > limit:
+ raise error
+ ran.append(cmd)
+ return real_run(cmd, *args, **kwargs)
+
+ monkeypatch.setattr(subprocess, "run", run)
+ return ran
+
+
+class TestPathBatches:
+ def test_every_path_once_and_each_batch_bounded(self):
+ paths = [f"dir/file_{i}.py" for i in range(100000)]
+ batches = list(gitutil._path_batches(paths))
+ assert [p for b in batches for p in b] == paths
+ assert len(batches) > 1
+ assert all(sum(len(p) for p in b) <= gitutil._MAX_PATH_ARGS_BYTES
+ for b in batches)
+
+ def test_budget_is_in_bytes(self, monkeypatch):
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 100)
+ assert len(list(gitutil._path_batches(["\u6f22" * 20 + ".py"] * 3))) == 3
+
+ def test_one_overlong_path_still_goes_out(self):
+ long = "x" * (gitutil._MAX_PATH_ARGS_BYTES + 10)
+ assert list(gitutil._path_batches(["a", long, "b"])) == [["a"], [long], ["b"]]
+
+ def test_no_paths_no_batches(self):
+ assert list(gitutil._path_batches([])) == []
+
+
+class TestGetGitDiff:
+ def _review_set(self, tmp_path):
+ repo = make_repo(tmp_path / "repo", {f"t{i}.py": "x = 1\n" for i in range(6)})
+ for i in range(6):
+ (repo / f"t{i}.py").write_text("x = 2\n")
+ (repo / f"new{i}.py").write_text("y = 1\n")
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ assert len(paths) == 12 and len(untracked) == 6
+ return root, base, paths, untracked
+
+ def test_one_command_when_the_paths_fit(self, tmp_path, git_env, monkeypatch):
+ root, base, paths, untracked = self._review_set(tmp_path)
+ ran = _refuse_long_commands(monkeypatch, 10**9, OSError(errno.E2BIG, "too long"))
+ diff = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert len(gitutil.parse_diff_into_files(diff)) == 12
+ assert len([c for c in ran if "diff" in c]) == 1
+ assert len([c for c in ran if "add" in c]) == 1
+
+ @pytest.mark.parametrize("error", [
+ OSError(errno.E2BIG, "Argument list too long"),
+ # What Python raises on Windows for ERROR_FILENAME_EXCED_RANGE.
+ type("WinTooLong", (FileNotFoundError,), {"winerror": 206})(errno.ENOENT, "too long"),
+ ], ids=["posix", "windows"])
+ def test_batches_when_one_command_is_refused(self, tmp_path, git_env, monkeypatch, error):
+ root, base, paths, untracked = self._review_set(tmp_path)
+ whole = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 60)
+ limit = GIT_CMD_CHARS + 100 # the six-path add fits, the twelve-path diff does not
+ ran = _refuse_long_commands(monkeypatch, limit, error)
+ batched = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert sorted(gitutil.parse_diff_into_files(batched)) == \
+ sorted(gitutil.parse_diff_into_files(whole))
+ assert len([c for c in ran if "diff" in c]) > 1
+
+ def test_only_reviewable_paths_after_a_refusal(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"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)
+ assert whole.count("diff --git ") == 21
+ _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 cut.count("diff --git ") == 1
+ assert gitutil.parse_diff_into_files(cut) == gitutil.parse_diff_into_files(whole)
+
+ 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)
+ monkeypatch.setattr(gitutil, "_MAX_PATH_BATCHES", 2)
+ 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] == []
+
+ def test_other_start_failures_are_not_retried(self, tmp_path, git_env, monkeypatch):
+ root, base, paths, untracked = self._review_set(tmp_path)
+ ran = _refuse_long_commands(monkeypatch, 0, FileNotFoundError(errno.ENOENT, "git"))
+ assert gitutil.get_git_diff(root, base, paths=paths, untracked_paths=[]) is None
+ assert ran == []
+
+ def test_batches_share_one_time_limit(self, tmp_path, git_env, monkeypatch):
+ repo = make_repo(tmp_path / "repo")
+ clock = iter([0, 0, 31])
+ monkeypatch.setattr(gitutil, "time", types.SimpleNamespace(monotonic=lambda: next(clock)))
+ monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 30)
+ ran = _refuse_long_commands(monkeypatch, GIT_CMD_CHARS + 60, OSError(errno.E2BIG, "too long"))
+ with pytest.raises(subprocess.TimeoutExpired):
+ gitutil._run_git_on_review_paths(
+ ["status"], ["a" * 40, "b" * 40, "c" * 40], timeout=30, cwd=str(repo))
+ assert len(ran) == 1
+
+ @long_paths
+ def test_more_paths_than_one_command_holds(self, tmp_path, git_env):
+ repo = make_repo(tmp_path / "repo", {"app.py": "x = 1\n"})
+ (repo / "app.py").write_text("x = 2\n")
+ _more_than_one_command_holds(repo, [".py", ".txt"])
+ paths, base, root, untracked, _ = diffstate.compute_v2_review_set(str(repo), None, None, {})
+ assert sum(len(p) for p in untracked) > 2 * 1024 * 1024
+ diff = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked)
+ assert diff is not None
+ # app.py and the 1,500 .py files, from more than one command.
+ assert len(gitutil.parse_diff_into_files(diff)) == 1501
+ assert diff.count("diff --git ") == 1501
+
+
+class TestWholeHook:
+ @long_paths
+ def test_edit_reviewed_beside_more_paths_than_one_command_holds(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)
+ _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") is None, m
+ assert m.get("review_set_count") == 3001
+ assert stub_api.calls
+
+ def test_review_set_past_the_cap_skips_without_a_diff(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)
+ (repo / "new.py").write_text(VULN_PY)
+ rc, so, se = run_hook(stop_payload(repo), {**hook_env, "MAX_REVIEW_SET_PATHS": "1"})
+ m = metrics_of(so)
+ assert m.get("skip_reason") == 8, m
+ # 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