diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-11-05 14:28:26 -0800 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-11-05 14:28:26 -0800 |
| commit | d189be9fc7a63d53d4e2af59accdd70e933e41e9 (patch) | |
| tree | fc78ed871ef817c56805bde79bb50fe9c91944a6 /plugins | |
| parent | eba976de6eed86f916e2c3ccd6f176faf19c3bc7 (diff) | |
| parent | 3654d346b45836e43e013b849be19233ff0efbc3 (diff) | |
Merge pull request #6835 from anthropics/mhegazy/sg-secret-rename-pairing
security-guidance: keep a renamed file paired with its old name in the Stop review
Diffstat (limited to 'plugins')
| -rw-r--r-- | plugins/security-guidance/hooks/diffstate.py | 8 | ||||
| -rw-r--r-- | plugins/security-guidance/hooks/gitutil.py | 29 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/conftest.py | 7 | ||||
| -rw-r--r-- | plugins/security-guidance/tests/test_secret_renames.py | 149 |
4 files changed, 188 insertions, 5 deletions
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py index de9719cf..34655335 100644 --- a/plugins/security-guidance/hooks/diffstate.py +++ b/plugins/security-guidance/hooks/diffstate.py @@ -18,7 +18,7 @@ from gitutil import ( GIT_CMD, _git_dir, _git_toplevel, _git_status_porcelain, _git_rev_parse_head, _is_ancestor, _git_name_only, _temp_index, - index_entry_count, + _secret_rename_origins, index_entry_count, ) from session_state import with_locked_state from extensibility import _same_dir @@ -1165,6 +1165,10 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel # dangling baseline SHA was pruned). Either way, don't intersect with ∅ — # that would silently zero the review set. Fall back to dirty_now. review_set = (dirty_now & changed_since) if changed_since is not None else dirty_now + # Kept beside its new name so that the content diff pairs the two. + secret_origins = { + old for new, old in _secret_rename_origins.items() if new in review_set} + review_set = review_set | secret_origins review_paths = [os.path.join(repo, p) for p in sorted(review_set)] untracked_in_review = sorted(new_untracked & review_set) @@ -1176,4 +1180,6 @@ def compute_v2_review_set(cwd, baseline_sha, head_at_capture, untracked_at_basel # Only emit when nonzero to stay under the 10-key telemetry cap. if preexisting_unchanged: metrics["preexisting_untracked_excluded"] = len(preexisting_unchanged) + if secret_origins: + metrics["secret_renamed"] = len(secret_origins) return review_paths, diff_base, repo, untracked_in_review, metrics diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py index 747b95a8..c80d0600 100644 --- a/plugins/security-guidance/hooks/gitutil.py +++ b/plugins/security-guidance/hooks/gitutil.py @@ -1183,6 +1183,18 @@ def _git_reflog_recent_commits(repo_root, max_age_s=120, max_n=5): return fresh, stale +# New name -> secret-shaped old name, for the renames and copies git reported +# during this hook run. The Stop review limits its diff to a list of paths: +# with only the new name in it, git shows the secret's content as a new file, +# and the diff parsers cannot tell it came from a name they leave out. +_secret_rename_origins = {} + + +def _note_rename(old_path, new_path): + if _is_secret_shaped(old_path): + _secret_rename_origins[new_path] = old_path + + def _git_name_only(cwd, base, include_untracked=False): """Return the set of repo-root-relative paths that differ from `base`, or None if git failed (unresolvable ref, not a repo, timeout). Callers @@ -1202,7 +1214,7 @@ def _git_name_only(cwd, base, include_untracked=False): def _run(env): # core.quotePath=false comes from GIT_CMD globally (see definition). result = subprocess.run( - [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-only", "-z", base], + [*GIT_CMD, "diff", IGNORE_SUBMODULES, "--name-status", "-z", base], cwd=cwd, capture_output=True, timeout=30, env=env, ) @@ -1211,7 +1223,18 @@ def _git_name_only(cwd, base, include_untracked=False): debug_log(f"_git_name_only({base!r}) rc={result.returncode}: {stderr_str[:200]}") return None stdout = (result.stdout or b"").decode("utf-8", errors="replace") - return {p for p in stdout.split("\0") if p} + # Fields are `status\0path\0`, or `R<score>\0old\0new\0` for a rename + # or copy, which is listed by its new name only. + fields = stdout.split("\0") + names = set() + i = 0 + while i + 1 < len(fields): + if fields[i][:1] in ("R", "C") and i + 2 < len(fields): + _note_rename(fields[i + 1], fields[i + 2]) + i += 1 + names.add(fields[i + 1]) + i += 2 + return names try: # The diff only reads the index (diff.autoRefreshIndex is off in @@ -1272,6 +1295,8 @@ def _git_status_porcelain(cwd): # 2-char-status entry. if "R" in xy or "C" in xy: i += 1 + if i < len(entries): + _note_rename(entries[i], path) i += 1 return tracked, untracked except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e: diff --git a/plugins/security-guidance/tests/conftest.py b/plugins/security-guidance/tests/conftest.py index 464f4695..b0df08de 100644 --- a/plugins/security-guidance/tests/conftest.py +++ b/plugins/security-guidance/tests/conftest.py @@ -89,8 +89,10 @@ def workspace(tmp_path): class _Stub(http.server.BaseHTTPRequestHandler): def do_POST(self): n = int(self.headers.get("Content-Length") or 0) - if n: - self.rfile.read(n) + body = self.rfile.read(n).decode("utf-8", "replace") if n else "" + # Only the stub_api fixture keeps the request bodies. + if hasattr(self.server, "bodies"): + self.server.bodies.append(body) self.server.calls.append(self.path) if self.server.delay: time.sleep(self.server.delay) @@ -121,6 +123,7 @@ class _Stub(http.server.BaseHTTPRequestHandler): def stub_api(): srv = http.server.HTTPServer(("127.0.0.1", 0), _Stub) srv.calls = [] + srv.bodies = [] srv.status = 200 srv.delay = 0 srv.vulns = [] diff --git a/plugins/security-guidance/tests/test_secret_renames.py b/plugins/security-guidance/tests/test_secret_renames.py new file mode 100644 index 00000000..7d4e38fb --- /dev/null +++ b/plugins/security-guidance/tests/test_secret_renames.py @@ -0,0 +1,149 @@ +"""A tracked file renamed away from a secret-shaped name stays out of the +Stop review, however the rename reached git.""" +import errno +import os +import subprocess + +import pytest + +from conftest import ( + GIT_ENV, bash_payload, commit_file, git, make_repo, metrics_of, run_hook, + stop_payload, ups_payload, +) + +import diffstate +import gitutil + +SECRET_BODY = "".join(f"KEY_{i}=SECRET_VALUE_{i}\n" for i in range(30)) +EDIT = "import os\nos.system(input())\n" + + +def _repo(tmp_path): + return make_repo(tmp_path / "repo", {"deploy_rsa": SECRET_BODY, "app.py": "x = 1\n"}) + + +def _sent(stub_api): + return "".join(stub_api.bodies) + + +def _rename(repo, how): + if how == "moved": + os.rename(repo / "deploy_rsa", repo / "settings.py") + return + git(repo, "mv", "deploy_rsa", "settings.py") + if how == "committed": + git(repo, "commit", "-qm", "rename") + elif how == "amended": + git(repo, "commit", "-q", "--amend", "-m", "init, renamed") + # Edited after the commit, so the file is still part of the turn. + with open(repo / "settings.py", "a") as f: + f.write("KEY_NEW=SECRET_VALUE_NEW\n") + + +@pytest.mark.parametrize("how", ["moved", "staged", "committed", "amended"]) +def test_stop_review_leaves_the_renamed_file_out(tmp_path, hook_env, stub_api, how): + repo = _repo(tmp_path) + run_hook(ups_payload(repo), hook_env) + _rename(repo, how) + (repo / "app.py").write_text(EDIT) + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + m = metrics_of(stdout) + assert m.get("skip_reason") is None, m + assert m.get("files_reviewed") == 1 + # A plain mv is not a rename to git: the old name is listed as deleted. + assert m.get("secret_renamed") == (None if how == "moved" else 1) + assert "os.system" in _sent(stub_api) + assert "SECRET_VALUE" not in _sent(stub_api) + + +def test_stop_review_with_nothing_but_the_rename_sends_nothing(tmp_path, hook_env, stub_api): + repo = _repo(tmp_path) + run_hook(ups_payload(repo), hook_env) + git(repo, "mv", "deploy_rsa", "settings.py") + _rc, stdout, _err = run_hook(stop_payload(repo), hook_env) + assert metrics_of(stdout).get("skip_reason") == 7 + assert stub_api.bodies == [] + + +def test_commit_review_leaves_the_renamed_file_out(tmp_path, hook_env, stub_api): + repo = _repo(tmp_path) + git(repo, "mv", "deploy_rsa", "settings.py") + _sha, out = commit_file(repo, "app.py", EDIT) + run_hook(bash_payload(repo, "git commit -m change", stdout=out), hook_env) + assert "os.system" in _sent(stub_api) + assert "SECRET_VALUE" not in _sent(stub_api) + + +@pytest.fixture +def git_env(monkeypatch): + """The suite's git settings for calls made in this process.""" + for k, v in GIT_ENV.items(): + monkeypatch.setenv(k, v) + monkeypatch.setattr(gitutil, "_secret_rename_origins", {}) + monkeypatch.setattr(diffstate, "_secret_rename_origins", gitutil._secret_rename_origins) + + +def test_listings_are_unchanged_and_note_the_secret_origin(tmp_path, git_env): + repo = make_repo(tmp_path / "repo", { + "deploy_rsa": SECRET_BODY, "old name.py": SECRET_BODY + "x = 1\n", + "gone.py": "x = 1\n", "edit.py": "x = 1\n"}) + git(repo, "mv", "deploy_rsa", "settings.py") + git(repo, "mv", "old name.py", "new name.py") + git(repo, "rm", "-q", "gone.py") + (repo / "edit.py").write_text("x = 2\n") + names = {"settings.py", "new name.py", "gone.py", "edit.py"} + assert gitutil._git_name_only(str(repo), "HEAD") == names + assert gitutil._secret_rename_origins == {"settings.py": "deploy_rsa"} + gitutil._secret_rename_origins.clear() + assert gitutil._git_status_porcelain(str(repo)) == (names, set()) + assert gitutil._secret_rename_origins == {"settings.py": "deploy_rsa"} + + +def test_review_set_gains_only_the_origin_of_a_reviewed_file(tmp_path, git_env): + repo = make_repo(tmp_path / "repo", { + "deploy_rsa": SECRET_BODY, "old.py": SECRET_BODY + "x = 1\n"}) + git(repo, "mv", "deploy_rsa", "settings.py") + git(repo, "mv", "old.py", "new.py") + paths, _base, root, _untracked, metrics = diffstate.compute_v2_review_set(str(repo), None, None, {}) + assert sorted(os.path.relpath(p, root) for p in paths) == ["deploy_rsa", "new.py", "settings.py"] + assert metrics["dirty_now_count"] == 2 and metrics["review_set_count"] == 3 + assert metrics["secret_renamed"] == 1 + + +def test_origin_still_pairs_beside_a_nested_repo_and_a_split_path_list( + tmp_path, git_env, monkeypatch): + repo = make_repo(tmp_path / "repo", {"deploy_rsa": SECRET_BODY, "app.py": "x = 1\n"}) + make_repo(repo / "nested", {"inner.py": "y = 1\n"}) + git(repo, "mv", "deploy_rsa", "settings.py") + (repo / "app.py").write_text(EDIT) + (repo / "a_much_longer_module_name.py").write_text("y = 1\n") + (repo / "another_quite_long_module_name.py").write_text("y = 2\n") + for i in range(20): + (repo / f"note{i:02d}.txt").write_text("x\n") + paths, base, root, untracked, metrics = diffstate.compute_v2_review_set(str(repo), None, None, {}) + names = [os.path.relpath(p, root) for p in paths] + assert "deploy_rsa" in names and "settings.py" in names + assert not any(n.startswith("nested") for n in names) + assert metrics["secret_renamed"] == 1 + + # The OS refuses the one command that holds every path, so the paths go + # out in several: the old name has to be in the one with the new name. + real_popen = subprocess.Popen + limit = sum(len(a) + 1 for a in gitutil.GIT_CMD) + 220 + diffs = [] + + def popen(cmd, *args, **kwargs): + if sum(len(a) + 1 for a in cmd) > limit: + raise OSError(errno.E2BIG, "Argument list too long") + if "diff" in cmd: + diffs.append(cmd) + return real_popen(cmd, *args, **kwargs) + + monkeypatch.setattr(subprocess, "Popen", popen) + monkeypatch.setattr(gitutil, "_MAX_PATH_ARGS_BYTES", 80) + diff = gitutil.get_git_diff(root, base, paths=paths, untracked_paths=untracked) + assert len(diffs) > 1 and all("deploy_rsa" in c for c in diffs) + reviewed = gitutil.parse_diff_into_files(diff) + assert sorted(f for f, _ in reviewed) == [ + "a_much_longer_module_name.py", "another_quite_long_module_name.py", "app.py"] + assert "SECRET_VALUE" not in "".join(d for _, d in reviewed) |
