diff options
| author | Mohamed Hegazy <8000722+mhegazy@users.noreply.github.com> | 2026-10-15 15:40:39 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-10-15 15:40:39 -0700 |
| commit | f698d8bca315d40f1771a3a12746bd793f842f07 (patch) | |
| tree | 2460ef8446a42eda1a39aae42dd63fa060773c21 /plugins | |
| parent | 01a70b506ec923118744bccf0b78a30de716a7ad (diff) | |
| parent | e873784d807428e86a3ab7cea202d9812de07718 (diff) | |
Merge pull request #6538 from anthropics/mhegazy/sg-launcher-unreadable-plugin-dir
security-guidance: never run a hook with a Python that cannot read it
Diffstat (limited to 'plugins')
5 files changed, 493 insertions, 14 deletions
diff --git a/plugins/security-guidance/hooks/ensure_agent_sdk.py b/plugins/security-guidance/hooks/ensure_agent_sdk.py index f49e857d..059f3825 100644 --- a/plugins/security-guidance/hooks/ensure_agent_sdk.py +++ b/plugins/security-guidance/hooks/ensure_agent_sdk.py @@ -849,6 +849,10 @@ if __name__ == "__main__": pv = _plugin_version_int() if pv: metrics["pv"] = pv + # See sg-python.sh pass 4: started by real path, the PATH names could + # not read the plugin files. + if os.environ.get("SG_LAUNCHER_FALLBACK") == "1": + metrics["launcher_fallback"] = 1 response: dict[str, object] = {"metrics": metrics} # One-time user-visible notice when the agentic reviewer is dead on # arrival. Uses hookSpecificOutput.additionalContext (SessionStart's diff --git a/plugins/security-guidance/hooks/security_reminder_hook.py b/plugins/security-guidance/hooks/security_reminder_hook.py index 368c2b18..1da44e48 100755 --- a/plugins/security-guidance/hooks/security_reminder_hook.py +++ b/plugins/security-guidance/hooks/security_reminder_hook.py @@ -277,6 +277,10 @@ def emit_metrics( head = {} if _PV and "pv" not in metrics: head["pv"] = _PV + # sg-python.sh could only start this interpreter by its real path: the + # names on PATH were launcher aliases that cannot read the plugin files. + if os.environ.get("SG_LAUNCHER_FALLBACK") == "1": + head["launcher_fallback"] = 1 usage = _usage_metrics() head.update(usage) if head: diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh index 9cf8cc07..f1b9d68c 100755 --- a/plugins/security-guidance/hooks/sg-python.sh +++ b/plugins/security-guidance/hooks/sg-python.sh @@ -33,6 +33,10 @@ set -e # changing it from inside the interpreter has no effect. export PYTHONUTF8=1 +# Set to 1 below only when the interpreter had to be found by its real path +# (pass 4); the hook reports it as the `launcher_fallback` metric. +unset SG_LAUNCHER_FALLBACK + # Git Bash / MSYS on Windows hands script paths to this shim in POSIX form # (`/c/Users/...`). When we exec a Windows `python.exe` (which we do on # Windows since `python3` is the Microsoft Store stub), python interprets the @@ -41,14 +45,30 @@ export PYTHONUTF8=1 # fails with ENOENT, and every Edit/Write/MultiEdit tool use blocks until the # session restarts. See anthropics/claude-plugins-official#2043. # -# Fix: convert absolute path args to native Windows form via `cygpath -w` -# before exec. `cygpath` is a Git Bash builtin; it's absent on macOS/Linux, -# where the `command -v` guard makes this a no-op. `cygpath -w` is idempotent -# for already-Windows paths so the rare mixed-form case is safe. +# Fix: convert absolute path args to native Windows form before exec. +# `cygpath` ships with Git Bash; it's absent on macOS/Linux, where the +# `command -v` guard makes this a no-op. `cygpath -w` is idempotent for +# already-Windows paths so the rare mixed-form case is safe. +# +# Under Git Bash every $(...) is a new Windows process, and this shim runs on +# every hook, so drive paths (`/c/Users/...`, where the plugin lives) are +# converted in-shell. Git Bash and MSYS2 (OSTYPE=msys) mount drives at +# /<letter>; anything else (`/tmp`, `/usr`, Cygwin's /cygdrive) needs cygpath +# to resolve. See #6470. if command -v cygpath >/dev/null 2>&1; then + sg_drive_mounts="" + case "${OSTYPE:-}" in msys*) sg_drive_mounts=1 ;; esac converted=() for a in "$@"; do case "$a" in + /[A-Za-z]/*) + if [ -n "$sg_drive_mounts" ]; then + drive="${a:1:1}" + rest="${a:3}" + converted+=("${drive^^}:\\${rest//\//\\}") + else + converted+=("$(cygpath -w "$a")") + fi ;; /*) converted+=("$(cygpath -w "$a")") ;; *) converted+=("$a") ;; esac @@ -56,10 +76,47 @@ if command -v cygpath >/dev/null 2>&1; then set -- "${converted[@]}" fi +# The hook script the chosen interpreter has to run (already in native form). +SG_TARGET="" +case "${1:-}" in + ""|-*) ;; + *) SG_TARGET="$1" ;; +esac + +# Names whose interpreter runs but cannot see the hook script ("|"-separated). +sg_unreadable="" + probe() { # $1..N: the interpreter command (may be multi-word like `py -3`) - # Writes "<major>.<minor>" to stdout and exits 0 iff at least Python 3. - "$@" -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")' 2>/dev/null + # Writes "<major>.<minor>" to stdout and exits 0 iff it is at least + # Python 3 AND it can read the hook script; exits 3 if it cannot. + # + # The second half matters on Windows: an interpreter started through a + # packaged launcher alias (Microsoft Store Python, Python Install Manager; + # the python/python3/py entries under ...\Microsoft\WindowsApps) runs with + # a different view of %APPDATA% than the process that started it. It + # answers `-c` fine, then fails on the script with "can't open file ... + # [Errno 2]" and exit code 2 -- and exit 2 from an asyncRewake hook wakes + # the model, whose reply runs the Stop hook again: an endless loop that + # never reviewed anything. See #6251, #5781. + # + # Only for `$(probe ...)`: the `exec` replaces that subshell instead of + # forking a second process from it. + [ "${BASH_SUBSHELL:-0}" -gt 0 ] || return 1 + exec "$@" -c 'import os, sys; t = (sys.argv[1:] or [""])[0]; sys.exit(3) if t and not (os.path.isfile(t) and os.access(t, os.R_OK)) else print(f"{sys.version_info[0]}.{sys.version_info[1]}")' "$SG_TARGET" 2>/dev/null +} + +# Use as `v=$(probe ...) || { note_unreadable "<name>"; continue; }`. +note_unreadable() { + [ $? -eq 3 ] && sg_unreadable="$sg_unreadable|$1|" + return 0 +} + +# True iff the command's executable is on PATH ($1 of a possibly multi-word +# command like `py -3`). A builtin lookup: `$(probe ...)` costs a process even +# when the interpreter does not exist, so missing names are skipped first. +on_path() { + command -v "$1" >/dev/null 2>&1 } # True iff arg is a "M.m" version string >= 3.10. claude_agent_sdk requires @@ -80,7 +137,9 @@ is_sdk_compatible() { # so picking one here always upgrades over the system `python3`. Highest # available wins; the user doesn't have to PATH-prefer it. for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do - v=$(probe "$cmd") || continue + on_path "$cmd" || continue + v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; } + v=${v%$'\r'} if is_sdk_compatible "$v"; then exec "$cmd" "$@" fi @@ -89,13 +148,21 @@ done # Pass 2 — bare interpreters, but only if SDK-compatible. Covers Linux distros # that ship 3.10+ as the default `python3`, and Windows where `python` / # `py -3` resolves to the user's python.org install. +sg_older="" # first of these that is a readable Python 3 below 3.10 for cmd in "python3" "python" "py -3"; do # shellcheck disable=SC2086 - v=$(probe $cmd) || continue + on_path $cmd || continue + # shellcheck disable=SC2086 + v=$(probe $cmd) || { note_unreadable "$cmd"; continue; } + v=${v%$'\r'} if is_sdk_compatible "$v"; then # shellcheck disable=SC2086 exec $cmd "$@" fi + # Anything that successfully reported a "M.m" string. + case "$v" in + [0-9]*.[0-9]*) [ -n "$sg_older" ] || sg_older="$cmd" ;; + esac done # Pass 3 — fallback to any Python 3, even <3.10. Pattern-based checks @@ -103,18 +170,72 @@ done # own; the SDK-dependent paths will detect the version mismatch and degrade # inside the Python code. Without this fallback, the entire plugin would # stop working on default macOS, which is a regression vs today. +if [ -n "$sg_older" ]; then + # shellcheck disable=SC2086 + exec $sg_older "$@" +fi + +# Pass 4 — nothing above could run the hook script. If that is because the +# names on PATH resolve to packaged launcher aliases that cannot see the +# plugin directory (see probe), the same interpreter usually works when it is +# started by its real path instead of through the alias. Candidates: +# - every further python3/python on PATH, by full path (a regular install +# often sits behind the alias in PATH order; the first match is the one +# the bare name resolved to above), +# - the real executable each alias reports as sys.executable. +# The list is built before the loop that execs, and from a here-document: a +# redirect around that loop would become the hook's stdin. +sg_candidates=() +for name in "python3" "python"; do + first=1 + while IFS= read -r c; do + if [ -n "$first" ]; then first=""; continue; fi + [ -n "$c" ] && sg_candidates+=("$c") + done <<EOF +$(type -ap "$name" 2>/dev/null) +EOF +done for cmd in "python3" "python" "py -3"; do + case "$sg_unreadable" in *"|$cmd|"*) ;; *) continue ;; esac # shellcheck disable=SC2086 - v=$(probe $cmd) || continue - # Accept anything that successfully reported a "M.m" string. + c=$($cmd -c 'import sys; print(sys.executable)' 2>/dev/null) || continue + c=${c%$'\r'} # native Windows Python prints CRLF + [ -n "$c" ] || continue + if command -v cygpath >/dev/null 2>&1; then + c=$(cygpath -u "$c" 2>/dev/null) || continue + fi + sg_candidates+=("$c") +done +export SG_LAUNCHER_FALLBACK=1 +sg_fallback="" +sg_tried="|" +for cmd in "${sg_candidates[@]}"; do + case "$sg_tried" in *"|$cmd|"*) continue ;; esac + sg_tried="$sg_tried$cmd|" + v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; } + v=${v%$'\r'} + if is_sdk_compatible "$v"; then + exec "$cmd" "$@" + fi case "$v" in - [0-9]*.[0-9]*) - # shellcheck disable=SC2086 - exec $cmd "$@" - ;; + [0-9]*.[0-9]*) [ -n "$sg_fallback" ] || sg_fallback="$cmd" ;; esac done +if [ -n "$sg_fallback" ]; then + exec "$sg_fallback" "$@" +fi +# Exit 1, never 2: on an asyncRewake hook exit 2 means "the review has +# findings, wake the model", and a launcher failure is not a finding. +if [ -n "$sg_unreadable" ]; then + echo "security-guidance: found Python, but it cannot read the hook script (missing, or not visible to Python), so no security checks ran." >&2 + echo " hook script: $SG_TARGET" >&2 + echo " on Windows this happens when python, python3 and py are Microsoft Store or Python Install Manager aliases;" >&2 + echo " install Python from https://python.org and put it ahead of ...\\Microsoft\\WindowsApps in PATH" >&2 + # No Python to report it, so the launcher emits the metric itself. + echo '{"metrics": {"launcher_unreadable": 1}}' + exit 1 +fi echo "security-guidance: no working Python 3 interpreter found." >&2 echo " tried: python3.13, python3.12, python3.11, python3.10, python3, python, py -3" >&2 echo " on Windows, install Python from https://python.org (NOT the Microsoft Store)" >&2 diff --git a/plugins/security-guidance/tests/test_launcher_process_count.py b/plugins/security-guidance/tests/test_launcher_process_count.py new file mode 100644 index 00000000..f22fd680 --- /dev/null +++ b/plugins/security-guidance/tests/test_launcher_process_count.py @@ -0,0 +1,158 @@ +"""sg-python.sh starts as few processes as it can before it runs the hook. + +Under Git Bash every command substitution is a new Windows process, and the +launcher runs on every hook, so probing interpreters that are not installed, +probing the same one twice, or calling cygpath for a plain drive path is paid +on each Edit, prompt and Stop. See #6470. + +Interpreters and cygpath are emulated with shell scripts, so these tests need +a POSIX shell. +""" +import shutil +import subprocess +import sys + +import pytest + +from conftest import HOOKS_DIR + +pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers") + +SHIM = HOOKS_DIR / "sg-python.sh" +BASH = shutil.which("bash") or "/bin/bash" + +# Logs each start; answers the probe with a fixed version, else prints its argv. +PYTHON = """#!{bash} +if [ "${{1:-}}" = "-c" ] || [ "${{1:-}} ${{2:-}}" = "-3 -c" ]; then + echo "${{0##*/}} probe" >> '{log}'; printf '{version}{eol}'; exit 0 +fi +echo "${{0##*/}} $*" >> '{log}' +printf 'ran:%s\\n' "${{0##*/}}"; printf 'arg:%s\\n' "$@" +""" +# ${x^^} in the launcher's Git Bash branch needs bash 4; stock macOS has 3.2. +BASH_MAJOR = int(subprocess.run([BASH, "-c", "echo ${BASH_VERSINFO[0]}"], capture_output=True, + text=True).stdout.strip() or 0) + +# The Microsoft Store placeholder: on PATH, starts, does nothing. +STUB = """#!{bash} +echo "${{0##*/}} probe" >> '{log}' +exit 49 +""" +CYGPATH = """#!{bash} +echo "cygpath $*" >> '{log}' +echo "CYGPATH($2)" +""" + + +@pytest.fixture +def box(tmp_path): + (tmp_path / "bin").mkdir() + (tmp_path / "log").write_text("") + return tmp_path + + +def _add(box, name, template, version="", crlf=False): + p = box / "bin" / name + p.write_text(template.format(bash=BASH, log=box / "log", version=version, + eol="\\r\\n" if crlf else "\\n")) + p.chmod(0o755) + + +def _run(box, *args, ostype="linux-gnu", trace=False): + cmd = [BASH] + (["-x"] if trace else []) + [str(SHIM), *args] + return subprocess.run(cmd, input="", capture_output=True, text=True, timeout=60, + env={"PATH": str(box / "bin"), "HOME": "/", "OSTYPE": ostype}) + + +def _starts(box): + return (box / "log").read_text().splitlines() + + +def test_only_installed_interpreters_are_probed(box): + _add(box, "python", PYTHON, "3.12") + r = _run(box, "hook.py", trace=True) + assert r.stdout.splitlines() == ["ran:python", "arg:hook.py"] + # xtrace marks what runs in a subshell with "++": only the one probe did. + probes = [line for line in r.stderr.splitlines() if line.startswith("++ probe ")] + assert probes == ["++ probe python"] + assert _starts(box) == ["python probe", "python hook.py"] + + +def test_store_placeholder_still_falls_through_to_python(box): + _add(box, "python3", STUB) + _add(box, "python", PYTHON, "3.13") + r = _run(box, "hook.py") + assert r.stdout.splitlines() == ["ran:python", "arg:hook.py"] + assert _starts(box) == ["python3 probe", "python probe", "python hook.py"] + + +def test_python_below_3_10_is_probed_once(box): + _add(box, "python3", PYTHON, "3.9") + r = _run(box, "hook.py") + assert r.stdout.splitlines() == ["ran:python3", "arg:hook.py"] + assert _starts(box) == ["python3 probe", "python3 hook.py"] + + +def test_first_older_python_wins_when_none_is_3_10(box): + _add(box, "python3", PYTHON, "3.8") + _add(box, "python", PYTHON, "3.9") + r = _run(box, "hook.py") + assert r.stdout.splitlines() == ["ran:python3", "arg:hook.py"] + + +def test_newer_python_under_a_later_name_beats_an_older_python3(box): + _add(box, "python3", PYTHON, "3.9") + _add(box, "python", PYTHON, "3.12") + r = _run(box, "hook.py") + assert r.stdout.splitlines() == ["ran:python", "arg:hook.py"] + + +def test_py_launcher_is_still_a_candidate(box): + _add(box, "py", PYTHON, "3.12") + r = _run(box, "hook.py") + assert r.stdout.splitlines() == ["ran:py", "arg:-3", "arg:hook.py"] + assert _starts(box) == ["py probe", "py -3 hook.py"] + + +def test_crlf_version_output_does_not_cost_further_probes(box): + # Native Windows Python may print CRLF; 3.12 must still read as 3.10+. + _add(box, "python", PYTHON, "3.12", crlf=True) + _add(box, "py", PYTHON, "3.12", crlf=True) + r = _run(box, "hook.py") + assert r.stdout.splitlines() == ["ran:python", "arg:hook.py"] + assert _starts(box) == ["python probe", "python hook.py"] + + +@pytest.mark.skipif(BASH_MAJOR < 4, reason="needs bash 4+, as Git Bash has") +@pytest.mark.parametrize("posix, native", [ + ("/c/Users/me/.claude/hooks/hook.py", "C:\\Users\\me\\.claude\\hooks\\hook.py"), + ("/d/a b/hook.py", "D:\\a b\\hook.py"), + ("/c/", "C:\\"), +]) +def test_drive_paths_are_converted_without_cygpath(box, posix, native): + _add(box, "cygpath", CYGPATH) + _add(box, "python", PYTHON, "3.12") + rest = ["--flag", "rel/path", "C:\\already\\native", "C:/d/mixed"] + r = _run(box, posix, *rest, ostype="msys") + assert r.stdout.splitlines() == ["ran:python", "arg:" + native] + ["arg:" + a for a in rest] + assert not [s for s in _starts(box) if s.startswith("cygpath")] + + +@pytest.mark.parametrize("ostype, posix", [ + ("msys", "/tmp/hook.py"), # a mount point, not a drive + ("msys", "/usr/bin"), + ("msys", "/c"), + ("msys", "//server/share/hook.py"), + ("cygwin", "/c/Users/me/hook.py"), # drives live under /cygdrive there +]) +def test_other_absolute_paths_still_go_through_cygpath(box, ostype, posix): + _add(box, "cygpath", CYGPATH) + _add(box, "python", PYTHON, "3.12") + r = _run(box, posix, ostype=ostype) + assert r.stdout.splitlines() == ["ran:python", "arg:CYGPATH(%s)" % posix] + + +def test_paths_are_left_alone_without_cygpath(box): + _add(box, "python3", PYTHON, "3.12") + r = _run(box, "/c/Users/me/hook.py", ostype="msys") + assert r.stdout.splitlines() == ["ran:python3", "arg:/c/Users/me/hook.py"] diff --git a/plugins/security-guidance/tests/test_launcher_unreadable_script.py b/plugins/security-guidance/tests/test_launcher_unreadable_script.py new file mode 100644 index 00000000..d963eaa0 --- /dev/null +++ b/plugins/security-guidance/tests/test_launcher_unreadable_script.py @@ -0,0 +1,192 @@ +"""sg-python.sh never hands the hook script to an interpreter that cannot see it. + +On Windows, python/python3/py can be packaged launcher aliases whose +interpreter answers `-c` but has no view of the plugin directory. Running the +hook with one fails with CPython's "can't open file" and exit code 2, which an +asyncRewake hook reports to the model as review findings, on every Stop. + +The aliases are emulated with shell wrappers around the real interpreter, so +these tests need a POSIX shell. +""" +import json +import os +import shutil +import subprocess +import sys + +import pytest + +from conftest import HOOKS_DIR, metrics_of, run_hook, stop_payload + +pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers") + +SHIM = HOOKS_DIR / "sg-python.sh" +BASH = shutil.which("bash") or "/bin/bash" +REAL = os.path.realpath(sys.executable) + +# Echoes its stdin and exits 2, like a hook that has findings to report. +HOOK = ( + "import os, sys\n" + "print('fallback=' + os.environ.get('SG_LAUNCHER_FALLBACK', ''))\n" + "sys.stderr.write('ran:' + sys.stdin.read())\nsys.exit(2)\n" +) + +ALIAS = """#!{bash} +# A packaged alias: `-c` works, files under HIDE are invisible. +HIDE='{hide}'; REAL='{real}' +if [ "${{1:-}}" = "-c" ]; then + code="$2"; shift 2 + out=$("$REAL" -c "import os as _o, sys as _s +_f = _o.path.isfile +_o.path.isfile = lambda p, _f=_f: False if str(p).startswith('$HIDE') else _f(p) +if '{sealed}': _s.executable = '$0' +$code" "$@"); rc=$? + [ -n "$out" ] && printf '%s{eol}' "$out" + exit $rc +fi +case "${{1:-}}" in + "$HIDE"/*) echo "python: can't open file '$1': [Errno 2] No such file or directory" >&2; exit 2 ;; +esac +exec "$REAL" "$@" +""" + + +def _alias(bindir, name, hide, sealed=False, crlf=False): + bindir.mkdir(parents=True, exist_ok=True) + p = bindir / name + p.write_text(ALIAS.format(bash=BASH, hide=hide, real=REAL, sealed="1" if sealed else "", + eol="\\r\\n" if crlf else "\\n")) + p.chmod(0o755) + + +def _run(path_dirs, script, payload='{"k": 1}'): + return subprocess.run( + [BASH, str(SHIM), str(script)], input=payload, capture_output=True, text=True, timeout=60, + env={"PATH": os.pathsep.join(str(d) for d in path_dirs), "HOME": os.environ.get("HOME", "/")}, + ) + + +@pytest.fixture +def plugin(tmp_path): + d = tmp_path / "plugin" / "hooks" + d.mkdir(parents=True) + (d / "hook.py").write_text(HOOK) + return d + + +def test_alias_is_replaced_by_the_interpreter_it_reports(plugin, tmp_path): + for name in ("python3", "python"): + _alias(tmp_path / "alias", name, plugin) + r = _run([tmp_path / "alias"], plugin / "hook.py") + assert "can't open file" not in r.stderr + # The hook ran, read its payload, and its own exit code came through. + assert r.stderr == 'ran:{"k": 1}' + assert r.returncode == 2 + assert r.stdout.strip() == "fallback=1" + + +def test_regular_interpreter_is_not_marked_as_fallback(plugin, tmp_path): + (tmp_path / "real").mkdir() + os.symlink(REAL, tmp_path / "real" / "python3") + r = subprocess.run( + [BASH, str(SHIM), str(plugin / "hook.py")], input="{}", capture_output=True, text=True, timeout=60, + env={"PATH": str(tmp_path / "real"), "HOME": "/", "SG_LAUNCHER_FALLBACK": "1"}, + ) + assert r.returncode == 2 + assert r.stdout.strip() == "fallback=" + + +def test_regular_install_later_on_path_is_used(plugin, tmp_path): + _alias(tmp_path / "alias", "python3", plugin, sealed=True) + (tmp_path / "real").mkdir() + os.symlink(REAL, tmp_path / "real" / "python3") + r = _run([tmp_path / "alias", tmp_path / "real"], plugin / "hook.py") + assert r.stderr == 'ran:{"k": 1}' + assert r.returncode == 2 + + +def test_regular_install_under_another_name_is_used(plugin, tmp_path): + _alias(tmp_path / "alias", "python3", plugin, sealed=True) + (tmp_path / "real").mkdir() + os.symlink(REAL, tmp_path / "real" / "python") + r = _run([tmp_path / "alias", tmp_path / "real"], plugin / "hook.py") + assert r.stderr == 'ran:{"k": 1}' + assert r.returncode == 2 + + +def test_no_interpreter_can_see_the_script_is_not_reported_as_findings(plugin, tmp_path): + for name in ("python3", "python"): + _alias(tmp_path / "alias", name, plugin, sealed=True) + r = _run([tmp_path / "alias"], plugin / "hook.py") + assert r.returncode == 1 + assert "can't open file" not in r.stderr + assert "cannot read the hook script" in r.stderr + assert str(plugin / "hook.py") in r.stderr + assert metrics_of(r.stdout) == {"launcher_unreadable": 1} + + +def test_missing_script_is_not_reported_as_findings(plugin, tmp_path): + (tmp_path / "real").mkdir() + os.symlink(REAL, tmp_path / "real" / "python3") + r = _run([tmp_path / "real"], plugin / "gone.py") + assert r.returncode == 1 + assert "can't open file" not in r.stderr + + +def test_no_python_keeps_its_own_message(plugin, tmp_path): + (tmp_path / "empty").mkdir() + r = _run([tmp_path / "empty"], plugin / "hook.py") + assert r.returncode == 1 + assert "no working Python 3 interpreter found" in r.stderr + + +def test_unusable_python_keeps_the_no_interpreter_message(plugin, tmp_path): + # Runs, but is not Python 3: nothing says the script is unreadable. + d = tmp_path / "old" + d.mkdir() + (d / "python").write_text("#!%s\nexit 1\n" % BASH) + (d / "python").chmod(0o755) + r = _run([d], plugin / "hook.py") + assert r.returncode == 1 + assert "no working Python 3 interpreter found" in r.stderr + + +def test_alias_with_crlf_output_is_still_resolved(plugin, tmp_path): + # Native Windows Python prints CRLF; the reported path must survive that. + _alias(tmp_path / "alias", "python3", plugin, crlf=True) + r = _run([tmp_path / "alias"], plugin / "hook.py") + assert r.stderr == 'ran:{"k": 1}' + assert r.returncode == 2 + + +@pytest.mark.skipif(shutil.which("git") is None, reason="needs git") +def test_real_hook_runs_through_an_alias_only_path(tmp_path): + for name in ("python3", "python"): + _alias(tmp_path / "alias", name, HOOKS_DIR) + payload = json.dumps({"hook_event_name": "UserPromptSubmit", "session_id": "launcher-test", + "cwd": str(tmp_path), "prompt": "hello"}) + # git only: its directory usually holds a regular python3 as well. + git_dir = tmp_path / "git" + git_dir.mkdir() + os.symlink(shutil.which("git"), git_dir / "git") + r = subprocess.run( + [BASH, str(SHIM), str(HOOKS_DIR / "security_reminder_hook.py")], + input=payload, capture_output=True, text=True, timeout=120, + env={"PATH": os.pathsep.join([str(tmp_path / "alias"), str(git_dir)]), "HOME": str(tmp_path), + "SECURITY_GUIDANCE_DEBUG_LOG": str(tmp_path / "debug.log")}, + ) + assert r.returncode == 0, r.stderr + assert "hook_event=UserPromptSubmit" in (tmp_path / "debug.log").read_text() + + +@pytest.mark.parametrize("flag", ["1", None]) +def test_hook_reports_launcher_fallback(workspace, hook_env, flag): + env = dict(hook_env) + env.pop("SG_LAUNCHER_FALLBACK", None) + if flag: + env["SG_LAUNCHER_FALLBACK"] = flag + rc, out, _ = run_hook(stop_payload(workspace), env) + assert rc == 0 + m = metrics_of(out) + assert m is not None + assert m.get("launcher_fallback") == (1 if flag else None) |
