summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
Diffstat (limited to 'plugins')
-rw-r--r--plugins/security-guidance/hooks/hooks.json3
-rwxr-xr-xplugins/security-guidance/hooks/sg-python.sh57
-rw-r--r--plugins/security-guidance/tests/test_launcher_redirector.py215
3 files changed, 266 insertions, 9 deletions
diff --git a/plugins/security-guidance/hooks/hooks.json b/plugins/security-guidance/hooks/hooks.json
index 138dae00..d066726c 100644
--- a/plugins/security-guidance/hooks/hooks.json
+++ b/plugins/security-guidance/hooks/hooks.json
@@ -27,7 +27,8 @@
"hooks": [
{
"type": "command",
- "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\""
+ "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/sg-python.sh\" \"${CLAUDE_PLUGIN_ROOT}/hooks/security_reminder_hook.py\"",
+ "timeout": 60
}
],
"matcher": "Edit|Write|MultiEdit|NotebookEdit"
diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh
index f2d5bd8a..74927965 100755
--- a/plugins/security-guidance/hooks/sg-python.sh
+++ b/plugins/security-guidance/hooks/sg-python.sh
@@ -3,14 +3,13 @@
#
# On Windows + Git Bash, `python3` typically resolves to the Microsoft Store
# stub at C:\Users\<user>\AppData\Local\Microsoft\WindowsApps\python3, which
-# exits 49 silently in non-TTY subprocess context (a known Microsoft Store
-# stub behavior). This shim
-# probes each candidate with `-c ""` and skips any that fails, so the Store
-# stub falls through to the real python.org install (`python` in Git Bash) or
+# is not a Python; it is told by its link and not started (sg_is_redirector).
+# This shim probes each other candidate with `-c ""` and skips any that fails,
+# so the search reaches the real python.org install (`python` in Git Bash) or
# the `py -3` launcher.
#
# Order:
-# 1. python3 — canonical on macOS/Linux; the Store stub fails the probe.
+# 1. python3 — canonical on macOS/Linux; the Store stub is skipped.
# 2. python — python.org installs on Windows; some Linux distros (RHEL 7
# EOL'd 2024-06) point this at Python 2, but `-c ""` succeeds
# on Python 2 too — guard with a version check.
@@ -117,11 +116,50 @@ note_unreadable() {
return 0
}
+# Where packaged aliases exist (and bash has what telling them apart needs).
+sg_windows=""
+case "${OSTYPE:-}" in
+ msys*|cygwin*) [ "${BASH_VERSINFO[0]:-0}" -lt 4 ] || sg_windows=1 ;;
+esac
+
# 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.
+# when the interpreter does not exist, so missing names are skipped first. On
+# Windows a python or python3 that is only App Installer's alias counts as
+# missing; that check takes one process, in place of starting the alias.
+sg_skipped=""
on_path() {
- command -v "$1" >/dev/null 2>&1
+ case "$sg_windows:$1" in
+ 1:python|1:python3)
+ hash "$1" 2>/dev/null || return 1
+ if sg_is_redirector "${BASH_CMDS[$1]:-}"; then
+ sg_skipped="${sg_skipped:+$sg_skipped, }$1"
+ return 1
+ fi ;;
+ *) command -v "$1" >/dev/null 2>&1 ;;
+ esac
+}
+
+# True iff $1 is the path of App Installer's python or python3, which Windows
+# puts under ...\Microsoft\WindowsApps when no packaged Python is installed.
+# It is not a Python, it points the user to the Store, so nothing is lost by
+# telling it by where its link leads instead of starting it. Starting it is a
+# packaged app activation on every hook, and waits for Windows' package
+# services: normally a fraction of a second, but until they answer again when
+# they are stuck, in every session on the machine at once. See #3870, #6348.
+# Git Bash shows these aliases as symbolic links; where the link cannot be
+# read, the name is probed like any other. Aliases of a packaged Python are
+# interpreters and are probed too.
+sg_is_redirector() {
+ local to
+ [ -n "$sg_windows" ] && sg_is_alias_path "$1" || return 1
+ # Full path: another readlink on PATH may not know these links.
+ to=$(/usr/bin/readlink -- "$1" 2>/dev/null </dev/null) || return 1
+ # Not lowercased: the result would depend on the locale.
+ case "$to" in
+ *[/\\]Microsoft.DesktopAppInstaller_*) return 0 ;;
+ esac
+ return 1
}
# How long the probes took, for the launcher_probe_max_ms / launcher_probe_ms
@@ -404,7 +442,7 @@ 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")
+ [ -n "$c" ] && ! sg_is_redirector "$c" && sg_candidates+=("$c")
done <<EOF
$(type -ap "$name" 2>/dev/null)
EOF
@@ -452,6 +490,9 @@ if [ -n "$sg_unreadable" ]; then
fi
echo "security-guidance: no working Python 3 interpreter found." >&2
echo " tried: python3.13 to python3.10, python3, python, py -3, python3.14 to python3.19" >&2
+if [ -n "$sg_skipped" ]; then
+ echo " not started: $sg_skipped (App Installer's alias, which is not a Python)" >&2
+fi
echo " on Windows, install Python from https://python.org (NOT the Microsoft Store)" >&2
echo " on macOS, install Python 3.10+ via Homebrew (\`brew install python\`)" >&2
exit 1
diff --git a/plugins/security-guidance/tests/test_launcher_redirector.py b/plugins/security-guidance/tests/test_launcher_redirector.py
new file mode 100644
index 00000000..26800a72
--- /dev/null
+++ b/plugins/security-guidance/tests/test_launcher_redirector.py
@@ -0,0 +1,215 @@
+"""sg-python.sh does not start the python/python3 that App Installer provides.
+
+On Windows without a packaged Python, `python3` under ...\\Microsoft\\WindowsApps
+is a link to AppInstallerPythonRedirector.exe, which is not a Python. Starting
+it on every hook makes the hook wait for Windows' package services, and hang
+while they do not answer. See #3870, #6348.
+
+Aliases are shell scripts behind a symbolic link, so these tests need a POSIX
+shell; the launcher's Windows branch is switched on with OSTYPE.
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+from conftest import HOOKS_DIR
+
+SHIM = HOOKS_DIR / "sg-python.sh"
+BASH = shutil.which("bash") or "/bin/bash"
+REAL = os.path.realpath(sys.executable)
+try:
+ BASH_MAJOR = int(subprocess.run([BASH, "-c", "echo ${BASH_VERSINFO[0]}"], capture_output=True,
+ text=True, timeout=30).stdout.strip() or 0)
+except (OSError, ValueError, subprocess.SubprocessError):
+ BASH_MAJOR = 0
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers")
+needs_bash4 = pytest.mark.skipif(BASH_MAJOR < 4, reason="the Windows branch needs bash 4")
+
+HOOK = "import os, sys\nprint('name=' + os.environ.get('SG_NAME', ''))\nprint('stdin=' + sys.stdin.read())\n"
+
+
+class Box:
+ def __init__(self, root):
+ self.apps = root / "AppData" / "Local" / "Microsoft" / "WindowsApps"
+ self.pkg = root / "Program Files" / "WindowsApps" / "Microsoft.DesktopAppInstaller_1.29.379.0_x64__8wekyb3d8bbwe"
+ self.bin = root / "bin"
+ self.late = root / "late"
+ self.log = root / "log"
+ for d in (self.apps, self.pkg, self.bin, self.late):
+ d.mkdir(parents=True)
+ self.log.write_text("")
+ self.script = root / "hook.py"
+ self.script.write_text(HOOK)
+ # Names the launcher tries that this machine may really have.
+ for name in ("python3.13", "python3.12", "python3.11", "python3.10", "python3.14", "py"):
+ self.broken(self.bin / name)
+
+ def write(self, path, text):
+ path.write_text(text)
+ path.chmod(0o755)
+
+ def broken(self, path):
+ self.write(path, f"#!{BASH}\nexit 49\n")
+
+ def python(self, path):
+ self.write(path, f"#!{BASH}\necho {path.name} >> '{self.log}'\nSG_NAME={path.name} exec '{REAL}' \"$@\"\n")
+
+ def alias(self, name, target="AppInstallerPythonRedirector.exe", hangs=False):
+ """An entry under WindowsApps that leads to `target`, and logs its starts."""
+ exe = self.pkg / target
+ body = "sleep 300" if hangs else "exit 49"
+ self.write(exe, f"#!{BASH}\necho redirector >> '{self.log}'\n{body}\n")
+ (self.apps / name).symlink_to(exe)
+
+ def path(self, *first):
+ return os.pathsep.join([*(str(p) for p in first), str(self.bin), "/usr/bin", "/bin"])
+
+ def run(self, path, ostype="msys", timeout=60):
+ env = {"PATH": path, "HOME": os.environ.get("HOME", "/"), "OSTYPE": ostype,
+ "SECURITY_WARNINGS_STATE_DIR": str(self.log.parent / "state")}
+ return subprocess.run([BASH, str(SHIM), str(self.script)], input="payload", capture_output=True,
+ text=True, timeout=timeout, env=env)
+
+ @property
+ def starts(self):
+ return self.log.read_text().split()
+
+
+def _tools(box):
+ """A PATH entry with readlink and no Python of the machine's own."""
+ d = box.log.parent / "tools"
+ d.mkdir(exist_ok=True)
+ for name in ("readlink", "sleep"):
+ if not (d / name).exists():
+ (d / name).symlink_to(shutil.which(name))
+ return str(d)
+
+
+@pytest.fixture
+def box(tmp_path):
+ return Box(tmp_path)
+
+
+@needs_bash4
+def test_redirector_is_not_started(box):
+ box.alias("python3")
+ box.python(box.bin / "python")
+ r = box.run(box.path(box.apps))
+ assert r.returncode == 0, r.stderr
+ assert r.stdout.splitlines() == ["name=python", "stdin=payload"]
+ assert "redirector" not in box.starts
+
+
+@needs_bash4
+def test_redirector_that_never_answers_does_not_hold_the_hook(box):
+ box.alias("python3", hangs=True)
+ box.python(box.bin / "python")
+ r = box.run(box.path(box.apps), timeout=30)
+ assert r.returncode == 0 and "name=python" in r.stdout
+
+
+@needs_bash4
+def test_both_names_lead_to_the_redirector(box):
+ # python and python3 both first on PATH as redirectors, a real python
+ # further down: found by its full path, as before.
+ box.alias("python3")
+ box.alias("python")
+ box.python(box.late / "python")
+ r = box.run(os.pathsep.join([str(box.apps), str(box.late), str(box.bin), "/nowhere"])
+ + os.pathsep + _tools(box))
+ assert r.returncode == 0, r.stderr
+ assert "name=python" in r.stdout
+ assert "redirector" not in box.starts
+
+
+@needs_bash4
+def test_only_redirectors_is_reported_as_no_python(box):
+ box.alias("python3")
+ box.alias("python")
+ r = box.run(os.pathsep.join([str(box.apps), str(box.bin), _tools(box)]))
+ assert r.returncode == 1
+ assert "no working Python 3 interpreter found" in r.stderr
+ assert "not started: python3, python (App Installer's alias" in r.stderr
+ assert box.starts == []
+
+
+@needs_bash4
+@pytest.mark.parametrize("ostype", ["msys", "cygwin"])
+def test_redirector_behind_a_broken_python_is_not_started(box, ostype):
+ # Pass 4 collects every further python3 on PATH by its full path.
+ box.alias("python3")
+ box.broken(box.bin / "python3")
+ box.broken(box.bin / "python")
+ r = box.run(os.pathsep.join([str(box.bin), str(box.apps), _tools(box)]), ostype=ostype)
+ assert r.returncode == 1
+ assert box.starts == []
+
+
+@needs_bash4
+def test_link_outside_windowsapps_is_not_looked_at(box):
+ # Only aliases are told by their link; any other python3 is asked.
+ box.alias("python3")
+ (box.apps / "python3").rename(box.late / "python3")
+ box.python(box.bin / "python")
+ r = box.run(box.path(box.late))
+ assert r.returncode == 0 and "name=python" in r.stdout
+ assert "redirector" in box.starts
+
+
+@needs_bash4
+def test_readlink_on_path_is_not_relied_on(box):
+ box.alias("python3")
+ box.python(box.bin / "python")
+ box.broken(box.bin / "readlink")
+ r = box.run(box.path(box.apps))
+ assert r.returncode == 0 and "redirector" not in box.starts
+
+
+
+@needs_bash4
+def test_packaged_python_alias_is_still_used(box):
+ # An alias of a packaged Python leads to that Python, not to the redirector.
+ pkg = box.pkg.parent / "PythonSoftwareFoundation.Python.3.12_3.12.2800.0_x64__qbz5n2kfra8p0"
+ pkg.mkdir()
+ box.python(pkg / "python3.12.exe")
+ (box.apps / "python3").symlink_to(pkg / "python3.12.exe")
+ box.broken(box.bin / "python")
+ r = box.run(box.path(box.apps))
+ assert r.returncode == 0, r.stderr
+ assert "stdin=payload" in r.stdout
+ assert "python3.12.exe" in box.starts
+
+
+@needs_bash4
+def test_unreadable_link_is_probed_as_before(box):
+ # Not a link at all (or readlink missing): the name is started and fails.
+ box.write(box.apps / "python3", f"#!{BASH}\necho redirector >> '{box.log}'\nexit 49\n")
+ box.python(box.bin / "python")
+ r = box.run(box.path(box.apps))
+ assert r.returncode == 0 and "name=python" in r.stdout
+ assert "redirector" in box.starts
+
+
+def test_other_systems_do_not_look_at_links(box):
+ box.alias("python3")
+ box.python(box.bin / "python")
+ r = box.run(box.path(box.apps), ostype="linux-gnu")
+ assert r.returncode == 0 and "name=python" in r.stdout
+ assert "redirector" in box.starts
+
+
+def test_edit_hook_has_a_time_limit():
+ """The edit hook holds the tool call; without a limit of its own a stuck
+ one holds it for the host's 600 s default. See #6348."""
+ groups = json.loads((HOOKS_DIR / "hooks.json").read_text())["hooks"]["PostToolUse"]
+ (edit,) = [g for g in groups if "Edit" in g["matcher"]]
+ assert [h.get("timeout") for h in edit["hooks"]] == [60]
+ # The background reviews keep the host's limit: they run past a minute.
+ for g in groups:
+ if g is not edit:
+ assert all("timeout" not in h for h in g["hooks"])