summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorClaude <noreply@anthropic.com>2026-11-18 10:33:51 +0000
committerClaude <noreply@anthropic.com>2026-11-18 10:33:51 +0000
commitffcf8ac799a2a2a80e3d9cdb608ae7de4608498c (patch)
treec48108d0ff4c1173f04ba584fd53959f5f611283
parente6143c9807a001832badb63e89d58ffe25d542ec (diff)
security-guidance: follow Git Bash drive paths in commandsmhegazy/sg-git-bash-drive-paths
On Windows, Git Bash writes C:\x as /c/x. The hooks read that as a folder c at the root of the current drive, found no repository there, and fell back to the session's own, so a commit or push made with `cd /c/...` or `git -C /c/...` in another repository was not reviewed. Map /x/ to x: for Bash commands on Windows. PowerShell reads such a path as a folder, so its commands are left as they are. Compare folders without regard to drive letter case, so the session's own repository is still recognized. Fixes #7161 Co-authored-by: mhegazy <mhegazy@anthropic.com>
-rw-r--r--plugins/security-guidance/hooks/reporesolve.py43
-rwxr-xr-xplugins/security-guidance/hooks/security_reminder_hook.py15
-rw-r--r--plugins/security-guidance/tests/test_bash_drive_paths.py153
3 files changed, 194 insertions, 17 deletions
diff --git a/plugins/security-guidance/hooks/reporesolve.py b/plugins/security-guidance/hooks/reporesolve.py
index c00a752c..b21ece9e 100644
--- a/plugins/security-guidance/hooks/reporesolve.py
+++ b/plugins/security-guidance/hooks/reporesolve.py
@@ -35,6 +35,15 @@ _PUSH_DIR_WORDS = frozenset(("pushd", "push-location"))
_POP_DIR_WORDS = frozenset(("popd", "pop-location"))
+# Git Bash writes `C:\x` as `/c/x`, which Windows reads as a folder `c` at
+# the root of the current drive, as PowerShell does too.
+_BASH_DRIVE_RE = re.compile(r"/([A-Za-z])(?=/)")
+
+
+def _drive_path(p):
+ return _BASH_DRIVE_RE.sub(r"\1:", p, count=1) if _BASH_DRIVE_RE.match(p) else p
+
+
def _abs(base, p):
try:
p = os.path.expanduser(p)
@@ -45,6 +54,10 @@ def _abs(base, p):
return None
+def _same_path(a, b):
+ return bool(a and b) and os.path.normcase(a) == os.path.normcase(b)
+
+
def _is_sep(tok):
return bool(tok) and set(tok) <= _SEPARATORS
@@ -67,10 +80,14 @@ def _tokenize(command):
return []
-def dirs_from_command(command, cwd, subcommands=None):
+def dirs_from_command(command, cwd, subcommands=None, bash=True):
if not isinstance(command, str) or not command.strip():
return []
tokens = _tokenize(command)
+
+ def resolve(base, p):
+ return _abs(base, _drive_path(p) if bash and os.name == "nt" else p)
+
out = []
cur = cwd or ""
pushed = []
@@ -100,7 +117,7 @@ def dirs_from_command(command, cwd, subcommands=None):
i += 1
if i + 1 < n and not _is_sep(tokens[i + 1]) and tokens[i + 1] not in ("-",) \
and not tokens[i + 1].startswith("-"):
- nxt = _abs(cur, tokens[i + 1])
+ nxt = resolve(cur, tokens[i + 1])
if nxt:
cur = nxt
i += 2
@@ -120,26 +137,26 @@ def dirs_from_command(command, cwd, subcommands=None):
while j < n and not _is_sep(tokens[j]):
a = tokens[j]
if a == "-C" and j + 1 < n:
- cdir = _abs(cdir, tokens[j + 1]) or cdir
+ cdir = resolve(cdir, tokens[j + 1]) or cdir
j += 2
continue
if a == "-c" and j + 1 < n:
j += 2
continue
if a.startswith("--git-dir="):
- gdir = _abs(cdir, a.split("=", 1)[1])
+ gdir = resolve(cdir, a.split("=", 1)[1])
j += 1
continue
if a == "--git-dir" and j + 1 < n:
- gdir = _abs(cdir, tokens[j + 1])
+ gdir = resolve(cdir, tokens[j + 1])
j += 2
continue
if a.startswith("--work-tree="):
- wtree = _abs(cdir, a.split("=", 1)[1])
+ wtree = resolve(cdir, a.split("=", 1)[1])
j += 1
continue
if a == "--work-tree" and j + 1 < n:
- wtree = _abs(cdir, tokens[j + 1])
+ wtree = resolve(cdir, tokens[j + 1])
j += 2
continue
if a.startswith("-"):
@@ -163,10 +180,10 @@ def dirs_from_command(command, cwd, subcommands=None):
return list(dict.fromkeys(d for d in out if d))
-def toplevel_from_command(command, cwd, subcommands=None, cwd_root=None):
+def toplevel_from_command(command, cwd, subcommands=None, cwd_root=None, bash=True):
cwd_abs = _abs(None, cwd) if cwd else None
- for d in dirs_from_command(command, cwd, subcommands):
- if cwd_root and d == cwd_abs:
+ for d in dirs_from_command(command, cwd, subcommands, bash):
+ if cwd_root and _same_path(d, cwd_abs):
return cwd_root
try:
if os.path.isdir(d):
@@ -304,12 +321,12 @@ _UNSET = object()
def resolve_repo_root(cwd, command=None, subcommands=None, sha=None,
- touched_paths=None, session_id=None, cwd_root=_UNSET):
+ touched_paths=None, session_id=None, cwd_root=_UNSET, bash=True):
if cwd_root is _UNSET:
cwd_root = _git_toplevel(cwd) if cwd else None
if command:
- top = toplevel_from_command(command, cwd, subcommands, cwd_root)
- if top and top != cwd_root:
+ top = toplevel_from_command(command, cwd, subcommands, cwd_root, bash)
+ if top and not _same_path(top, cwd_root):
return top, RES_COMMAND
if cwd_root:
return cwd_root, RES_CWD
diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py
index d31307de..c71a390e 100755
--- a/plugins/security-guidance/hooks/security_reminder_hook.py
+++ b/plugins/security-guidance/hooks/security_reminder_hook.py
@@ -138,7 +138,7 @@ from diffstate import ( # noqa: E402,F401
from reporesolve import ( # noqa: E402,F401
RES_NONE, RES_CWD, RES_COMMAND, RES_SHA_SCAN, RES_TOUCHED_PATHS, RES_HINT,
COMMIT_SUBCOMMANDS, PUSH_SUBCOMMANDS,
- toplevel_from_command, repo_containing_commit, scan_roots,
+ toplevel_from_command, repo_containing_commit, scan_roots, _same_path,
resolve_repo_root, save_repo_hint, load_repo_hint,
)
import diffstate # noqa: E402 module ref for last_baseline_fail
@@ -1245,6 +1245,10 @@ def _unmatched_bash_sampled(input_data):
_bash_hook_git_dir = {}
+def _from_bash(input_data):
+ return input_data.get("tool_name") != "PowerShell"
+
+
def _bash_hook_sentinel(input_data, route="once"):
"""The file one spawn of this Bash call's hook creates to claim `route`,
or None when there is nothing to tell the spawns apart by."""
@@ -1257,7 +1261,8 @@ def _bash_hook_sentinel(input_data, route="once"):
if call not in _bash_hook_git_dir:
_bash_hook_git_dir[call] = _git_dir(
_git_toplevel(cwd)
- or toplevel_from_command(command, cwd, COMMIT_SUBCOMMANDS | PUSH_SUBCOMMANDS)
+ or toplevel_from_command(command, cwd, COMMIT_SUBCOMMANDS | PUSH_SUBCOMMANDS,
+ bash=_from_bash(input_data))
or cwd
)
gd = _bash_hook_git_dir[call]
@@ -1985,8 +1990,9 @@ def handle_commit_review_posttooluse(input_data):
repo_root = cwd_root
repo_res = RES_CWD if cwd_root else RES_NONE
if cwd:
- _cmd_root = toplevel_from_command(command, cwd, COMMIT_SUBCOMMANDS, cwd_root)
- if _cmd_root and _cmd_root != cwd_root:
+ _cmd_root = toplevel_from_command(command, cwd, COMMIT_SUBCOMMANDS, cwd_root,
+ bash=_from_bash(input_data))
+ if _cmd_root and not _same_path(_cmd_root, cwd_root):
repo_root, repo_res = _cmd_root, RES_COMMAND
if not cwd_root:
_base["cwd_is_repo"] = False
@@ -2580,6 +2586,7 @@ def handle_push_sweep_posttooluse(input_data):
cwd, command, PUSH_SUBCOMMANDS,
sha=_tip_m.group(2) if _tip_m else None,
session_id=session_id, cwd_root=cwd_root,
+ bash=_from_bash(input_data),
)
if not cwd_root:
_base["cwd_is_repo"] = False
diff --git a/plugins/security-guidance/tests/test_bash_drive_paths.py b/plugins/security-guidance/tests/test_bash_drive_paths.py
new file mode 100644
index 00000000..fc132e81
--- /dev/null
+++ b/plugins/security-guidance/tests/test_bash_drive_paths.py
@@ -0,0 +1,153 @@
+"""Git Bash spells `C:\\x` as `/c/x` (#7161)."""
+import ntpath
+import os
+import types
+
+import pytest
+
+import reporesolve as rr
+from conftest import (
+ VULN_PY, bash_payload, commit_file, git, make_repo, metrics_of, run_hook,
+)
+
+windows_only = pytest.mark.skipif(os.name != "nt", reason="drive paths exist on Windows only")
+
+
+@pytest.mark.parametrize("path,expected", [
+ ("/c/Users/me/repo", "c:/Users/me/repo"),
+ ("/D/work", "D:/work"),
+ ("/c/", "c:/"),
+ ("/c", "/c"),
+ ("/cc/x", "/cc/x"),
+ ("/tmp/x", "/tmp/x"),
+ ("/1/x", "/1/x"),
+ ("//c/share", "//c/share"),
+ ("c/x", "c/x"),
+ ("C:/x", "C:/x"),
+ ("~/x", "~/x"),
+ ("", ""),
+])
+def test_drive_path(path, expected):
+ assert rr._drive_path(path) == expected
+
+
+@pytest.mark.skipif(os.name == "nt", reason="a one-letter folder at the root is a drive there")
+def test_one_letter_folder_stays_a_folder_elsewhere():
+ assert rr.dirs_from_command("cd /c/repo && git commit -m x", "/w") == ["/c/repo"]
+
+
+@pytest.fixture
+def as_windows(monkeypatch):
+ monkeypatch.setattr(rr, "os", types.SimpleNamespace(
+ name="nt", sep="\\", path=ntpath, getcwd=lambda: "C:\\w", environ=os.environ))
+
+
+SHAPES = [
+ "cd /c/a/repo && git commit -m x",
+ "pushd /c/a/repo && git commit -m x",
+ "cd /c/a && cd repo && git commit -m x",
+ "git -C /c/a/repo commit -m x",
+ "git --git-dir=/c/a/repo/.git commit -m x",
+ "git --git-dir /c/a/repo/.git commit -m x",
+ "git --work-tree=/c/a/repo commit -m x",
+ "git --work-tree /c/a/repo commit -m x",
+]
+
+
+@pytest.mark.parametrize("command", SHAPES)
+def test_bash_command(as_windows, command):
+ assert rr.dirs_from_command(command, "D:\\s") == ["c:\\a\\repo"]
+
+
+@pytest.mark.parametrize("command", SHAPES)
+def test_powershell_command_is_left_as_it_is(as_windows, command):
+ assert all(not d.startswith("c:\\a") for d in rr.dirs_from_command(command, "D:\\s", bash=False))
+
+
+@pytest.mark.parametrize("command", [
+ "cd /d && git commit -m x", "cd /tmp/repo && git commit -m x", "cd sub && git commit -m x",
+])
+def test_other_paths_stay(as_windows, command):
+ assert rr.dirs_from_command(command, "D:\\s") == rr.dirs_from_command(command, "D:\\s", bash=False)
+
+
+def test_drive_letter_case_is_not_another_folder(as_windows, monkeypatch):
+ monkeypatch.setattr(rr, "_git_toplevel", lambda d: pytest.fail("git was started"))
+ assert rr.toplevel_from_command("cd /c/ws && git commit -m x", "C:\\ws", None, "C:/ws") == "C:/ws"
+
+
+def _bash(path):
+ drive, rest = os.path.splitdrive(str(path))
+ return "/" + drive[0].lower() + rest.replace("\\", "/")
+
+
+@windows_only
+@pytest.mark.parametrize("shape", [
+ 'cd "{p}" && git commit -m x',
+ 'pushd "{p}" && git commit -m x',
+ 'git -C "{p}" commit -m x',
+ 'git --git-dir="{p}/.git" --work-tree="{p}" commit -m x',
+ '(cd "{p}"; git commit -m x)',
+])
+def test_command_in_another_repo(tmp_path, shape):
+ session, other = tmp_path / "session", tmp_path / "other repo"
+ for d in (session, other):
+ d.mkdir()
+ make_repo(d)
+ top, how = rr.resolve_repo_root(str(session), shape.format(p=_bash(other)), rr.COMMIT_SUBCOMMANDS)
+ assert how == rr.RES_COMMAND and os.path.samefile(top, other)
+
+
+@windows_only
+def test_powershell_reads_it_as_a_folder_of_the_current_drive(tmp_path):
+ session, other = tmp_path / "session", tmp_path / "other"
+ for d in (session, other):
+ d.mkdir()
+ make_repo(d)
+ cmd = f'cd "{_bash(other)}"; git commit -m x'
+ assert rr.resolve_repo_root(str(session), cmd, bash=False)[1] == rr.RES_CWD
+
+
+@pytest.fixture
+def two_repos(tmp_path):
+ session, other = tmp_path / "session", tmp_path / "other"
+ for d in (session, other):
+ d.mkdir()
+ make_repo(d)
+ return session, other
+
+
+@windows_only
+@pytest.mark.parametrize("shown", [True, False])
+def test_commit_in_another_repo_is_reviewed(two_repos, hook_env, stub_api, shown):
+ session, other = two_repos
+ _, out = commit_file(other, "app.py", VULN_PY)
+ payload = bash_payload(session, f'cd "{_bash(other)}" && git commit -m x', out if shown else "")
+ m = metrics_of(run_hook(payload, hook_env)[1])
+ assert m.get("skip_reason") is None and m["repo_resolution"] == rr.RES_COMMAND, m
+ assert "shell=True" in "".join(stub_api.bodies)
+
+
+@windows_only
+def test_push_in_another_repo_is_reviewed(two_repos, hook_env, stub_api, tmp_path):
+ session, other = two_repos
+ remote = tmp_path / "remote.git"
+ git(tmp_path, "init", "-q", "--bare", str(remote))
+ git(other, "remote", "add", "origin", str(remote))
+ git(other, "push", "-q", "-u", "origin", "main")
+ base = git(other, "rev-parse", "--short", "HEAD").strip()
+ sha, _ = commit_file(other, "app.py", VULN_PY)
+ git(other, "push", "-q")
+ out = f"To {remote}\n {base}..{sha[:7]} main -> main\n"
+ payload = bash_payload(session, f'cd "{_bash(other)}" && git push', out)
+ m = metrics_of(run_hook(payload, hook_env)[1])
+ assert m.get("skip_reason") is None and m["repo_resolution"] == rr.RES_COMMAND, m
+
+
+@windows_only
+def test_powershell_call_is_not_mapped(two_repos, hook_env, stub_api):
+ session, other = two_repos
+ _, out = commit_file(other, "app.py", VULN_PY)
+ payload = {**bash_payload(session, f'cd "{_bash(other)}"; git commit -m x', out), "tool_name": "PowerShell"}
+ assert metrics_of(run_hook(payload, hook_env)[1]).get("skip_reason") == 28
+ assert not any("messages" in c for c in stub_api.calls)