summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <8000722+mhegazy@users.noreply.github.com>2026-10-14 04:27:59 -0700
committerGitHub <noreply@github.com>2026-10-14 04:27:59 -0700
commit41f32e407b450055044f167db7ded5e8ff67d203 (patch)
tree8bd6189b236af8356ff445455336936a3ee9ce98 /plugins
parent8bd00f08f0b04705e610cf132fbe2cf5ec44cfe3 (diff)
parented2ae7cd72fb60b4b3e58d622745870072cfd2aa (diff)
Merge pull request #6542 from anthropics/mhegazy/sg-diff-parsing
security-guidance: parse diff sections by header line
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/gitutil.py124
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py7
-rw-r--r--plugins/security-guidance/tests/test_diff_parsing.py99
3 files changed, 197 insertions, 33 deletions
diff --git a/plugins/security-guidance/hooks/gitutil.py b/plugins/security-guidance/hooks/gitutil.py
index 2036b45e..93b7a87e 100644
--- a/plugins/security-guidance/hooks/gitutil.py
+++ b/plugins/security-guidance/hooks/gitutil.py
@@ -962,32 +962,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, 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:]
+ 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, _ in _iter_diff_sections(diff_output)
+ if _is_reviewable_source(file_path)
+ ]
def parse_diff_into_files(diff_output):
@@ -999,20 +1070,7 @@ 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 ''
-
+ for file_path, lines in _iter_diff_sections(diff_output):
# Filter to source code files only
if not _is_reviewable_source(file_path):
continue
@@ -1020,7 +1078,7 @@ def parse_diff_into_files(diff_output):
# 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/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index f36cb475..d280e9e1 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,
@@ -2090,6 +2091,8 @@ 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 {}),
})
sys.exit(0)
@@ -2303,6 +2306,8 @@ 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 {}),
}, rewake_summary=_format_vulns_summary(vulns),
additional_context=(PROVENANCE_BANNER + "\n\n"
+ concrete_guidance + CONTINUATION_SUFFIX + "\n"),
@@ -2336,6 +2341,8 @@ 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 {}),
})
sys.exit(0)
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()