summaryrefslogtreecommitdiff
path: root/plugins/security-guidance/hooks/gitutil.py
AgeCommit message (Collapse)Author
2026-11-07security-guidance: count commits that no commit hook sawmhegazy/sg-unseen-commit-countMohamed Hegazy
A commit review starts from a hook on the Bash tool, so a commit made any other way starts none. The Stop row now carries turn_commits: how many commits the turn made, how many have no review, and how many of those no commit hook saw. Count only; what is reviewed does not change, and no hook entry is added. Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-05Merge main into mhegazy/sg-index-copy-all-gitlinksmhegazy/sg-index-copy-all-gitlinksClaude
Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-05Merge pull request #6835 from anthropics/mhegazy/sg-secret-rename-pairingMohamed Hegazy
security-guidance: keep a renamed file paired with its old name in the Stop review
2026-11-05Merge pull request #6922 from anthropics/mhegazy/sg-prompt-snapshotMohamed Hegazy
security-guidance: take the turn baseline without git stash create
2026-11-05Merge pull request #6919 from anthropics/mhegazy/sg-add-failure-fixMohamed Hegazy
security-guidance: keep new files in the Stop review when git add -N fails
2026-11-05Merge pull request #7002 from anthropics/mhegazy/sg-git-log-signature-offMohamed Hegazy
security-guidance: read git log output without signature checks
2026-11-04security-guidance: name new files the Stop review could not seeMohamed Hegazy
When git add -N fails on both tries or times out, wake Claude once per set of files with their names, so the review no longer ends as "no changes". A timed-out add now keeps the tracked files' diff, so a timeout on every turn cannot stop their reviews. Private object directory cleanup no longer chmods through a link. Fixes #6996 Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-04security-guidance: drop every gitlink from the index copyMohamed Hegazy
Whether git starts something in a gitlink's directory is decided when git runs, so the check for a .git there beforehand can go stale. Remove all of them from the copy. On git older than 2.34 the baseline for a submodule that is not checked out falls back to HEAD. Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-04security-guidance: start git by its full path on Windowsmhegazy/sg-git-program-from-pathMohamed Hegazy
A bare program name on Windows is looked up in the working directory before PATH, and the hooks run in the project. Name the first git.exe on PATH, leaving out relative entries, the working directory and folders inside the project, as the claude lookup already avoids that search. Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-11-04security-guidance: read git log output without signature checksmhegazy/sg-git-log-signature-offMohamed Hegazy
With log.showSignature set, git log and git show verify every signed commit, which adds lines to the output the hooks parse and starts gpg.program. Set it off for the hooks' git and for the commit reviewer's environment. Co-authored-by: mhegazy <mhegazy@anthropic.com>
2026-10-27security-guidance: take the turn baseline without git stash createmhegazy/sg-prompt-snapshotMohamed Hegazy
stash create checks the work tree on one thread. add -u into the throwaway index copy, write-tree and commit-tree produce the same commit and use git's index preload instead, which matters where each file status is slow. See #6854.
2026-10-27security-guidance: keep new files in the Stop review when git add -N failsMohamed Hegazy
Retry the add with a private object directory for users who cannot write the object store. Drop the pathspec settings git refuses alongside literal pathspecs, which hid new files since 2.0.16. When a failure stays and nothing is reviewed, keep the files for a later turn.
2026-10-27Merge remote-tracking branch 'origin/main' into mhegazy/sg-secret-rename-pairingmhegazy/sg-secret-rename-pairingMohamed Hegazy
# Conflicts: # plugins/security-guidance/hooks/diffstate.py
2026-10-26Merge pull request #6861 from anthropics/mhegazy/sg-add-fail-metricMohamed Hegazy
security-guidance: count failed git add -N calls in the Stop review
2026-10-23security-guidance: count failed git add -N calls in the Stop reviewmhegazy/sg-add-fail-metricMohamed Hegazy
A failed add leaves new files out of the diff with no sign of it. Measure only; behaviour is unchanged.
2026-10-22security-guidance: report where a slow prompt's time goesmhegazy/sg-prompt-capture-timeMohamed Hegazy
Prompts that wait a second or more in the UserPromptSubmit hook send one metrics row: total, baseline and untracked listing time, index size, and whether the repository is on a Windows drive under WSL. Measures only; capture is unchanged. See #6854.
2026-10-22Merge remote-tracking branch 'origin/main' into mhegazy/sg-secret-rename-pairingMohamed Hegazy
2026-10-21Merge branch 'main' into mhegazy/sg-index-copy-gitlinksClaude
2026-10-20security-guidance: keep nested repositories out of the index copyClaude
The hooks run `git stash create` (the turn baseline) and `git add --intent-to-add` (untracked files) on a throwaway copy of the index. A nested repository that the index records is a gitlink entry there. `git stash create` takes no --ignore-submodules option and `git add` reads the gitlinks its paths cover, so both started a second git inside that directory. Before anything runs on the copy, remove the gitlink entry of every nested repository from the copy, never from the real index. If that removal fails, do not use the copy at all: the baseline falls back to HEAD and runs no stash create, and the diff reads the real index with --ignore-submodules=all. A gitlink whose directory has no `.git` (a submodule that is not checked out) stays; git starts nothing there. Run the intent-to-add `git add` with literal pathspecs, in that one call's environment only. The index file is scanned for a gitlink's mode bytes first, so a repository without one starts no extra git process.
2026-10-20security-guidance: keep a renamed file paired with its old name in the Stop ↵Mohamed Hegazy
review The Stop review limits its diff to the changed paths. For a rename that git already knows about (git mv, or a rename committed during the turn) that list held only the new name, so the diff showed a new file and the parsers could not apply the rule that leaves out a file renamed away from a secret-shaped name. The old name now goes into the list beside the new one, as it already did for a plain mv. The file listings themselves are unchanged.
2026-10-20Merge branch 'main' into mhegazy/sg-stop-pathspecMohamed Hegazy
The batched path commands now read each diff through the bounded reader that main added, so both changes apply to get_git_diff.
2026-10-20Merge pull request #6808 from anthropics/mhegazy/sg-secret-named-telemetryMohamed Hegazy
security-guidance: count secret-named data files in the Stop review set
2026-10-20Merge pull request #6807 from anthropics/mhegazy/sg-stop-diff-memoryMohamed Hegazy
security-guidance: read the Stop review's git diff without holding it whole
2026-10-20Merge pull request #6721 from anthropics/mhegazy/sg-claude-code-credential-filesMohamed Hegazy
security-guidance: keep Claude Code's own credential files out of reviews
2026-10-20Merge pull request #6810 from anthropics/mhegazy/sg-stop-baseline-checkoutMohamed Hegazy
security-guidance: do not review against a baseline from another checkout
2026-10-20Merge main into mhegazy/sg-stop-diff-memorymhegazy/sg-stop-diff-memoryMohamed Hegazy
Conflict in get_git_diff: main added IGNORE_SUBMODULES to the diff command on the line where this branch resets its read counters. Both are kept.
2026-10-19security-guidance: stay out of repositories nested in the work treemhegazy/sg-nested-reposClaude
A directory with its own .git inside the work tree (a submodule, a vendored checkout, an unpacked archive) was added to the throwaway index as a submodule entry, and git then started a second git inside it to see whether it had changed. Nothing in such a directory is reviewed. git status and work-tree git diff now ignore submodule entries, an untracked nested repository is no longer listed as a changed file or added to the index copy, and a commit that moves a submodule is always shown as its two commit ids.
2026-10-19security-guidance: keep added lines past the cut, hold the diff timeoutMohamed Hegazy
A reviewable file past the per-file cap now keeps as much again of its added lines, so a rewritten large file still shows what is new, and its diff ends with a line saying it was cut. The read runs on a thread so the 30 s limit holds while a process git started keeps the pipe open; a read that breaks is an error instead of a short diff. SG_MAX_FILE_DIFF_BYTES of zero or less means the default. The parser and the reader share one test for which files are reviewed.
2026-10-19security-guidance: do not review against a baseline from another checkoutmhegazy/sg-stop-baseline-checkoutMohamed Hegazy
The turn baseline (stash SHA, HEAD, untracked snapshot) is kept per session, and the Stop review used it in whatever checkout the turn ended in. After the session entered another worktree, that worktree's older commits looked like commits made this turn and its files were diffed against the first checkout's, so code committed long before was reviewed and reported again (anthropics/claude-code#102567). The prompt hook now stores the repo root and the prompt time beside the baseline. When the Stop review runs in a different checkout it leaves the baseline out and uses what that checkout can say for itself: its own HEAD when the turn began (from its reflog) for the commit range, HEAD for file contents, and file times to leave out uncommitted files last written before the turn. A baseline taken after a finding records the checkout it was taken in. A prompt in a folder that is not a repo no longer replaces the untracked snapshot of the kept baseline with an empty one, which made every untracked file in the repo look new at the next Stop. Stop rows carry `bl_origin`: 0 same checkout, 1 another worktree, 2 another repository, 3 a folder that is gone, 4 no baseline; plus 10 or 20 when the baseline is an earlier turn's.
2026-10-19security-guidance: count secret-named data files in the Stop review setmhegazy/sg-secret-named-telemetryMohamed Hegazy
Data files named like secrets.yml or client_secret.json are reviewed like any other file. The Stop hook now reports how many are in its review set, as a count only (secret_named_reviewed, emitted when nonzero), so the share of reviews that include one can be read from telemetry. No change to what is reviewed. Refs anthropics/claude-code#96276
2026-10-19security-guidance: read the Stop review's git diff without holding it wholeMohamed Hegazy
The Stop review captured the whole diff of the turn before its per-file caps applied, so a turn that wrote large text files cost the hook several times their size in memory. The output is now read as it arrives: files the review drops keep only their header line, and one file's diff is cut at 4 MiB (SG_MAX_FILE_DIFF_BYTES). The git command is unchanged. Adds count-only metrics, nonzero only: diff_mb, diff_cut_files, diff_timeout.
2026-10-18security-guidance: keep secret renames out and report the right skip when ↵Mohamed Hegazy
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.
2026-10-18Merge remote-tracking branch 'origin/main' into mhegazy/sg-stop-pathspecMohamed Hegazy
2026-10-16security-guidance: keep Claude Code's own credential files out of reviewsmhegazy/sg-claude-code-credential-filesMohamed Hegazy
When the Claude Code config directory is a git repo, .credentials.json and .claude.json show up as changed files each time Claude Code rewrites them, and their contents (sign-in tokens, a saved API key, MCP server secrets) were sent to the Stop review. Treat both names as secret-shaped, like .netrc and .npmrc. Refs anthropics/claude-code#90010
2026-10-15Merge remote-tracking branch 'origin/main' into mhegazy/sg-diff-prefix-configmhegazy/sg-diff-prefix-configMohamed Hegazy
2026-10-15security-guidance: keep secret-shaped files out of reviews (#6537)Mohamed Hegazy
* security-guidance: keep secret-shaped files out of reviews The Stop review covers every dirty file in the work tree, including ones the user changed and Claude never opened. Key files, credential files and encrypted dotfile sources were sent along with the code. Skip files that are secret stores by naming convention: .env variants, SSH private keys, common credential files, and chezmoi private/encrypted sources. * security-guidance: report how many secret-shaped files were skipped The Stop hook now reports secret_shaped_skipped (a count, never names, only when nonzero) so the skip can be confirmed after release and watched for over-matching.
2026-10-13security-guidance: keep the Stop review working when the changed paths do ↵Mohamed Hegazy
not fit one command The Stop review passed every changed path to `git diff` as arguments. With enough of them (an unignored cache, a repo at $HOME) the OS refused to start git, the diff failed twice, and the turn's real edits were never reviewed. When the OS refuses the argument list, keep only the paths the review can use (reviewable source files) and send them in a few commands under the same time limit. A path list that fits one command is handled exactly as before. Skip review sets of more than 100,000 paths before any diff. Fixes #4824
2026-10-13security-guidance: read diffs the same whatever the user's prefix settingsMohamed Hegazy
With diff.mnemonicPrefix or diff.noprefix set in the user's git config, diff headers no longer read `a/<path> b/<path>`, the parser matched no file, and the review was skipped with nothing shown. mnemonicPrefix switched off the Stop review; noprefix switched off the commit and push reviews as well. Pass the default prefix settings on every git call the hook makes. Fixes #4569
2026-10-12security-guidance: count diff headers the parser could not readmhegazy/sg-diff-parsingMohamed Hegazy
A file whose header cannot be parsed is left out of the review without a trace. The Stop hook now reports diff_hdr_unparsed (a count, only when nonzero) so a header shape the parser misses shows up in metrics.
2026-10-12security-guidance: parse diff sections by header lineMohamed Hegazy
The diff parser split on the text 'diff --git ' anywhere, so a file whose own content contains it was cut short, and the rest of that file was never reviewed. It also dropped files whose names git quotes (a double quote, backslash or control character in the name). Split only where a line starts with the header, and decode quoted names.
2026-10-07security-guidance: remove stash indexes older releases left in the git directorymhegazy/sg-reclaim-after-hook-killMohamed Hegazy
Releases before 2.0.10 ran `git stash create` on the real index. When that git was killed, it left an `index.stash.<pid>` file the size of the index in the git directory, and nothing removes those: a clone can hold hundreds. Before it copies the index, the hook now deletes such files once they are older than 30 minutes. It only touches regular files of the current user whose name is exactly `index.stash.<digits>`, and never `index.lock`. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QR7edfw5HHkxJvJVgZiWpM
2026-10-07security-guidance: stop a killed hook from leaving index copies behind ↵Mohamed Hegazy
(2.0.10 → 2.0.11) In a clone with a very large git index, 2.0.10 could still fill the disk. It copies the index for each git call that might write it, and a hook that Claude Code cancels (SIGTERM, then SIGKILL) never reached its cleanup, so every cancelled hook left index-sized files in the temp directory for up to 30 minutes. With several agents in one clone the live copies alone could take many GB. - A hook told to terminate removes its copies before it exits. - A copy's name records the hook's pid; the next run deletes copies whose hook is gone instead of waiting for the age limit. - Diffs no longer need a copy: diff.autoRefreshIndex is off, so they only read the index. Only `git stash create` and `git add -N` get one. - The copy is a hard link where the filesystem allows it. - Only so many hooks hold a copy at once, fewer as the disk fills. A hook that gets no slot within 5 s goes without: the baseline falls back to HEAD, or new untracked files are left out of that review. Co-Authored-By: Claude <noreply@anthropic.com>
2026-10-05security-guidance: leave nothing behind when git is killed (2.0.9 → 2.0.10)mhegazy/sg-temp-index-cleanupMohamed Hegazy
With a very large git index the hook's git calls hit their time limits and are killed, so git cannot clean up. Each kill could leave an index-sized file in the temp directory, index.stash.<pid> files in .git, and a dead .git/index.lock that fails the user's next git add or commit. - `git stash create` and the work-tree diff run on a throwaway index copy. - Every git the hook spawns gets GIT_OPTIONAL_LOCKS=0. - Copies live in a private per-user folder and are removed together with the files git writes next to them. - Leftovers older than 30 minutes are swept, including existing ones. Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-09Harden git invocation and repository hint handlingsg-resolve-repo-rootOctavian Guzu
:house: Remote-Dev: homespace
2026-09-09Adjust SubagentStop handling and repository precedenceOctavian Guzu
- SubagentStop reviews without consuming or advancing the session's Stop state; an identical diff is not reviewed twice. - SubagentStop from a different working tree than the project is skipped. - An explicit `git -C <dir>` / `cd <dir>` naming another repository takes precedence over the hook cwd. - Narrows the `git -C … commit` matcher; keeps Windows path separators when tokenizing; adds `--no-textconv` to diff/show invocations. - Adds tests. :house: Remote-Dev: homespace
2026-05-30security-guidance: move core.quotePath=false to GIT_CMD globally (#2099 ↵fix-2099-quotepath-globalMohamed Hegazy
followup) Followup to PR #2086 (which added the flag to 4 specific git call sites) and PR #2100 (text=True purge for #2099). The Windows reporter for #2099 noticed more git invocations still lacked the flag — rev-parse path queries (--show-toplevel, --git-dir, --git-common-dir), reflog %gs subjects, and `git show <sha>:<path>` all output paths but the per-site PR #2086 approach missed them. The result: an Arabic-named directory shows up via _git_diff_range but rev-parse-emitted paths get C-quoted, breaking downstream os.path.isabs() checks. Fix: add `-c core.quotePath=false` to GIT_CMD itself as the 4th config-set. Every subprocess.run using the *GIT_CMD splat picks it up automatically — diff feeders, rev-parse path queries, reflog log, ls-files, status, git show. No more per-site flag duplication. This commit: 1. gitutil.py: add -c core.quotePath=false to GIT_CMD. 2. Remove the now-redundant per-site flags at the 7 call sites that previously had inline -c core.quotePath=false (cleanup, since the global setting subsumes them): gitutil.py: _git_diff_range, _git_name_only, _git_status_porcelain, get_git_diff (4 sites) diffstate.py: _list_untracked git ls-files (1 site) security_reminder_hook.py: commit-review git diff + git show (2 sites) Verified locally on latest main (post PR #2100 merge) with macOS Python 3.13: - py_compile clean on all 3 modified files. - Bare main BEFORE my fix: 400/401 pass — 1 failure proves the gap (test_git_cmd_contains_quotepath_false catches the missing flag). - Main + my fix: 401/401 pass. - 23 new tests in test_quotepath_global.py (added to internal test suite at sg-staging/tests/, not in this PR): * 1 GIT_CMD-level: GIT_CMD list contains core.quotePath=false as a (-c, value) pair. Single source of truth — single place a future PR will be caught if the flag gets dropped. * 10 static-shape (one per hooks/*.py): every subprocess.run uses the *GIT_CMD splat (no bare git invocation that would bypass the global flag). * 12 end-to-end (parametrized over Arabic, Hebrew, CJK directory names): real git repo, _git_diff_range emits unquoted diff, extract_file_paths_from_diff and parse_diff_into_files keep the non-ASCII path in their output, _git_toplevel returns the non-ASCII path intact. - 1 staleness fix in test_diff_parser_non_ascii.py (test_no_bare_git_diff_or_show_without_flag): updated to accept EITHER inline core.quotePath=false OR *GIT_CMD splat (which globally provides it). NOT verified end-to-end on Windows with a non-ASCII repo root path. The new global-flag test pins the contract permanently, and the parametrized macOS tests confirm parser behavior on ASCII-control paths in non-ASCII directories. The Windows-specific rev-parse quoting behavior follows from the same git contract our macOS test environment exercises (POSIX git always emits raw UTF-8 regardless of quotePath; on Windows the flag is what makes output raw). Closes the #2099 followup specifically about _git_diff_range / rev-parse --show-toplevel / git log %gs paths slipping past. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-30security-guidance: purge text=True from subprocess.run + bake PYTHONUTF8=1 ↵fix-2099-text-true-pythonutf8Mohamed Hegazy
(#2099) URGENT WINDOWS FIX. Sibling of #2056 / PR #2075 but covering 14 more sites that PR #2075 missed. The bug class: on Windows with cp1252 default encoding (typical en-US locale), `subprocess.run(..., text=True)` decodes child stdout AND stderr via `locale.getpreferredencoding()`. When git emits a UTF-8 byte that's undefined in cp1252 (e.g. `0x81` from ف, present in any path/filename/branch ref/commit message containing Arabic/Hebrew/CJK), Python's internal `_readerthread` raises UnicodeDecodeError. The thread crash is silent in Python 3.13+ (only printed to stderr), but `subprocess.run` returns `stdout=None` and the caller AttributeErrors on `.strip()`. The user sees a misleading "WinError 267" or similar catch-all message instead of the real decode failure. PR #2075 fixed 6 specific helpers in `diffstate.py` / `gitutil.py`. This commit covers the 14 survivors. Plus a defense-in-depth belt: `PYTHONUTF8=1` exported by sg-python.sh. This commit: 1. sg-python.sh: `export PYTHONUTF8=1` (PEP 540). No-op on macOS/Linux (already UTF-8). On Windows, makes Python's `locale.getpreferredencoding()` return UTF-8 instead of cp1252 — so even if a future regression slips in text=True, the decode succeeds. Must be set BEFORE Python starts; changing it from inside the interpreter has no effect. 2. gitutil.py: convert 8 subprocess.run sites from `capture_output=True, text=True` to `capture_output=True` + manual `r.stdout.decode("utf-8", errors="replace")`: - _git_rev_parse_head (stdout = SHA, stderr risk) - _find_git_index (stdout = PATH, primary bug site) - _temp_index git add (returncode only, stderr risk) - _git_toplevel (stdout = PATH, primary bug site) - _git_dir (stdout = PATH, primary bug site) - _git_rev_list_range (stdout = SHAs, stderr risk) - _detect_main_branch (stdout = ref, stderr risk) - merge-base --is-ancestor (returncode only, stderr risk) 3. security_reminder_hook.py: convert 6 subprocess.run sites (rev-parse @{u}/@{u}@{1}/local_ref, merge-base, HEAD lookup, reflog SHA resolution) — same pattern. 4. security_reminder_hook.py: fix the misleading log line in handle_user_prompt_submit. Was: debug_log("Failed to capture git baseline (not a git repo?)") Now includes the cwd in the message so the next reporter doesn't waste an hour grepping for the real WinError, per reporter's secondary finding. Verified locally on macOS Python 3.13: - py_compile clean on all modified files. - bash -n sg-python.sh clean. - sg-python.sh actually propagates PYTHONUTF8=1 to child Python (verified via probe — sys.flags.utf8_mode=1). - Existing 353 tests still pass — 0 regression. - 25 new tests in test_2099_subprocess_text_true.py: * 10 static-shape catchers (one per hooks/*.py file). Any future PR that reintroduces text=True OR encoding= in subprocess.run fails this check at PR time. Single source of truth for the regression class. * 2 sg-python.sh verifiers (literal export + actual propagation to child Python). * 5 macOS end-to-end against a real git repo containing non-cp1252 content (`ف.py` filename): _git_toplevel, _git_dir, _find_git_index, _git_rev_parse_head, _git_rev_list_range all return clean values without AttributeError / UnicodeDecodeError. * 7 round-trip bytes-decode pattern verifiers (parametrized over Arabic ف, Hebrew א, Japanese 案, raw 0x81, multiple cp1252-undefined bytes, real-world git diff headers). * 1 sanity check that cp1252 strict DOES raise on 0x81 (proves the test environment can catch the bug class). - Full suite: 378/378 pass in 5.56s. - End-to-end tmux smoke test driving real claude 2.1.145 CLI: Made a git commit via Bash tool call. All 4 hooks fired through the fixed plugin path: 11:28:16.730 Hook called with args: …/plugin/hooks/security_reminder_hook.py 11:28:16.734 Processing: hook_event=UserPromptSubmit 11:28:16.825 Captured git baseline: 445f7f213256 11:28:19.923 Hook called with args: … 11:28:19.923 Processing: hook_event=PostToolUse, tool=Bash 11:28:19.971 Commit review: detected git commit in command 11:28:20.020 Commit review: 1/1 sha(s) resolved, 1 files 11:28:26.415 Hook called with args: … 11:28:26.416 Processing: hook_event=Stop 11:28:26.550 Stop hook: empty review set Confirms: PYTHONUTF8=1 export doesn't break anything; converted helpers (_git_rev_parse_head, _git_toplevel, _git_dir, _find_git_index) run end-to-end without issue on the happy path. NOT verified end-to-end on Windows with actual non-cp1252 content in path/filename/stderr. The static-shape catcher pins the regression class permanently. Reporter's PYTHONUTF8=1 workaround empirically proves the encoding-mode fix works for the affected scenario; this commit just bakes it in. Closes #2099. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29security-guidance: pass core.quotePath=false to diff feeders (#2082)fix-2082-diff-parser-non-asciiMohamed Hegazy
Fixes anthropics/claude-plugins-official#2082 — diff feeders use git's default quotePath setting, which C-quotes any path with a non-ASCII byte. The downstream parsers in gitutil.parse_diff_into_files / gitutil.extract_file_paths_from_diff match the diff header with `re.match(r'^a/(.+?) b/(.+)$', ...)`, which only sees the raw `a/path b/path` form. The C-quoted `"a/\303\201vila/..."` form slips past the regex, the `continue` fires, and the file is silently dropped from review. Effect: a vulnerable file like `Ávila/payment.py` with `os.system('curl ' + user_input)` never reaches the LLM reviewer. False negative in exactly the direction the plugin exists to catch. Sibling of #2056 / #2075: those fixed the UTF-8 decode of the subprocess output (text=True crashed the reader thread on Windows cp1252). This one fixes the diff-feeder commands themselves — the name-only helpers (_git_name_only, _git_status_porcelain) already pass core.quotePath=false for this exact reason; the diff-text feeders were the holdouts. Fix: add `-c core.quotePath=false` to 4 git invocations: - gitutil._git_diff_range (push-sweep feed) - gitutil.get_git_diff (Stop-hook feed) - security_reminder_hook commit-review `git diff` (amend delta) - security_reminder_hook commit-review `git show` (post-amend) With the flag, git emits raw UTF-8 in the diff header (`a/Ávila/payment.py`), the regex matches, and both files (the non-ASCII vulnerable one + any ASCII control file) flow through to review correctly. Verified locally on macOS Python 3.13: - py_compile clean on both files. - Existing 45 smoke + extensibility tests still pass. - 8 new tests in test_diff_parser_non_ascii.py (added to internal test suite at sg-staging/tests/, not in this PR): * 2 static-shape: gitutil._git_diff_range and get_git_diff both contain `core.quotePath=false` in their source. * 2 commit-review static: every subprocess.run in handle_commit_review_posttooluse that mentions `"diff"` or `"show"` also passes the flag. Catches the regression class where a new diff/show call site is added without plumbing the flag through. * 4 end-to-end with a real git repo containing a `Ávila/payment.py` baseline-and-edit: - WITHOUT flag: header is C-quoted, both parsers drop the non-ASCII file (demonstrates the bug). - WITH flag: header is raw UTF-8, both parsers see the file. - parse_diff_into_files (the other parse path) also keeps the file with the flag. - get_git_diff end-to-end produces unquoted output whose file list includes the non-ASCII path. - 53/53 pass total (45 existing + 8 new) in 3.41s. NOT verified end-to-end with a real CC commit-review fire on a non-ASCII path. The static-shape tests catch the regression and the end-to-end git-repo tests pin parser behavior, but the actual LLM-review-with-vuln-found path requires runtime verification against an Anthropic-API-credentialed CC session. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28security-guidance: lenient UTF-8 decode in 6 git-subprocess helpers (#2056)fix-2056-windows-unicode-decodeMohamed Hegazy
Fixes anthropics/claude-plugins-official#2056 — on Windows, when the worktree contains an untracked file whose name has a character undefined in cp1252 (accented capitals like Á Í Ï Ð Ý, most CJK, emoji), the UserPromptSubmit hook crashes: Exception in thread Thread-5 (_readerthread): UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 Traceback (most recent call last): File diffstate.py, line 338, in _list_untracked for p in r.stdout.split('\\0'): AttributeError: 'NoneType' object has no attribute 'split' Non-blocking (UPS failures still let the prompt through) but the baseline-untracked snapshot is silently lost, so the Stop-hook review mis-handles pre-existing untracked files. Root cause (reporter's diagnosis, verified): 1. core.quotePath=false makes git emit raw UTF-8 for non-ASCII filenames. 2. subprocess.run(..., text=True) decodes via locale.getpreferredencoding(False) in strict mode — on Windows that is cp1252, in which 0x81 / 0x8D / 0x8F / 0x90 / 0x9D are undefined. Those bytes appear in the UTF-8 encodings of Á (C3 81), Í (C3 8D), Ï (C3 8F), Ð (C3 90), Ý (C3 9D), and a large fraction of CJK / emoji codepoints. 3. The decode runs in the subprocess reader thread. The thread raises UnicodeDecodeError, threading prints 'Exception in thread Thread-N', subprocess.run returns with stdout=None. The handler then does None.split('\\0') -> AttributeError, which is NOT in the narrow except (TimeoutExpired, FileNotFoundError, OSError) tuple, so it escapes the helper, propagates out of UserPromptSubmit's ThreadPoolExecutor.result(), and exits the hook non-zero. This is internally inconsistent: gitutil._git_diff_range, security_reminder_hook._reflog_amend_lookup (line ~540), and the commit diff loop (line ~1115) already do bytes + decode utf-8/replace, with comments explicitly noting that text=True would crash. The fix below extends that established pattern to the helpers that were holdouts. Affected helpers (6 total): - diffstate._list_untracked <- reporter, hot path, CRITICAL - diffstate.capture_git_baseline <- reporter, latent - diffstate.get_baseline_file_content <- audit, file content read, HIGH - gitutil._git_name_only <- reporter, latent - gitutil._git_status_porcelain <- reporter, latent - gitutil._git_reflog_recent_commits <- audit, embeds %gs commit msg, HIGH For each one: - Drop text=True from subprocess.run. - Decode r.stdout / r.stderr as .decode('utf-8', errors='replace'). - Add ValueError to the except tuple as defense against any future strict-decode regression (UnicodeDecodeError is a ValueError subclass; including it explicitly degrades the helper to its empty/None return instead of escaping out of the hook). Verified locally on macOS Python 3.13: - py_compile clean on both files. - 45 existing smoke + extensibility tests still pass. - 21 new internal tests (not in this PR — added to the team's local test suite at staging/tests/test_unicode_decode.py): * 18 static-shape parametrized: each of the 6 fixed helpers has no text=True in its subprocess calls, contains errors='replace', and lists ValueError in its except. * Deterministic end-to-end: create real git repo + Ávila_report.txt untracked, call _list_untracked, verify it returns {'Ávila_report.txt': <mtime>} without crashing. * Deterministic end-to-end: same for capture_git_baseline (verifies the latent stderr-warning case stays valid). * Deterministic end-to-end: get_baseline_file_content on a file whose content has 山田太郎 + 🎉; verify the bytes round-trip through the decode. - 66/66 tests pass total (45 existing + 21 new). NOT verified end-to-end on Windows — would need actual cp1252 strict decode to fire. Reporter has the deterministic repro and will re-verify on their Win11 / Python 3.14.x setup before merge. Not in this PR (defense-in-depth, lower risk): - 3 git rev-parse calls returning path output (gitutil._find_git_index, _git_toplevel, _git_dir) could fail on Windows if cwd is in a non-ASCII install directory. Same fix shape but unreported and much lower probability — worth a separate follow-up if anyone actually hits it. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26Update security-guidance pluginsecurity-guidance-updateMohamed Hegazy