summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-15 22:21:47 +0000
committerClaude <noreply@anthropic.com>2026-10-15 22:21:47 +0000
commitf014d4623b59ffc4212ffd43f274ec81dffa35d6 (patch)
treeb273e273bb42a9ae00395ba4c72c19d4bfde7020
parent8876c9951efd618ef5a889dd1a6479bdb73b70bd (diff)
parent83e004a98e1fc268a94cc6a74b1b054630542696 (diff)
Merge remote-tracking branch 'origin/main' into mhegazy/sg-skip-untracked-listingmhegazy/sg-skip-untracked-listing
-rw-r--r--.claude-plugin/marketplace.json2
-rw-r--r--plugins/security-guidance/hooks/diffstate.py28
-rw-r--r--plugins/security-guidance/hooks/gitutil.py88
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py6
-rw-r--r--plugins/security-guidance/tests/test_secret_shaped_paths.py95
-rw-r--r--plugins/security-guidance/tests/test_untracked_cap.py85
6 files changed, 293 insertions, 11 deletions
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index bf5482ef..cf677bbc 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -3502,7 +3502,7 @@
"source": "git-subdir",
"url": "https://github.com/semgrep/mcp-marketplace.git",
"path": "plugin",
- "sha": "f97e1ce43533ffde2eae9af2a80f95a7250c365f"
+ "sha": "b58f407c6ac0f5fe47dee8301602f2e290a8ecfb"
},
"homepage": "https://github.com/semgrep/mcp-marketplace.git"
},
diff --git a/plugins/security-guidance/hooks/diffstate.py b/plugins/security-guidance/hooks/diffstate.py
index f50382e6..af8f2a78 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 (
@@ -352,6 +353,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):
@@ -378,6 +385,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"],
@@ -398,6 +406,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:
@@ -443,14 +455,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 93b7a87e..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()
@@ -1037,12 +1110,12 @@ _unparsed_diff_headers = set()
def _iter_diff_sections(diff_output):
- """Yield (new_path, lines after the header line) per file section."""
+ """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], lines[1:]
+ yield paths[1] or paths[0], paths[0], lines[1:]
else:
_unparsed_diff_headers.add(lines[0])
@@ -1056,8 +1129,8 @@ def extract_file_paths_from_diff(diff_output):
return []
return [
- file_path for file_path, _ in _iter_diff_sections(diff_output)
- if _is_reviewable_source(file_path)
+ 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)
]
@@ -1070,9 +1143,10 @@ def parse_diff_into_files(diff_output):
return []
files = []
- for file_path, lines in _iter_diff_sections(diff_output):
- # 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 --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index 97ad466e..e29f515e 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -2135,6 +2135,8 @@ def handle_stop_hook(input_data):
**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)
@@ -2350,6 +2352,8 @@ def handle_stop_hook(input_data):
**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"),
@@ -2385,6 +2389,8 @@ def handle_stop_hook(input_data):
**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_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