Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions .github/workflows/hook-scripts.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
name: Hook Scripts

on:
push:
branches:
- main
paths:
- '.apm/hooks/**'
- 'scripts/git-push-approval/**'
- 'scripts/tool-guardian/**'
- 'tests/test_hook_scripts.py'
- 'tests/build-bash32.sh'
- '.github/workflows/hook-scripts.yml'
pull_request:
paths:
- '.apm/hooks/**'
- 'scripts/git-push-approval/**'
- 'scripts/tool-guardian/**'
- 'tests/test_hook_scripts.py'
- 'tests/build-bash32.sh'
- '.github/workflows/hook-scripts.yml'

permissions:
contents: read

jobs:
test:
name: Test Hook Scripts
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false

- name: Test hooks with the runner's Bash
run: PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -p 'test_hook_scripts.py' -v

# Stock macOS runs `#!/bin/bash` hooks under Bash 3.2 (#217).
- name: Build Bash 3.2
run: |
hook_bash="$(bash tests/build-bash32.sh "${RUNNER_TEMP}/bash32")"
echo "HOOK_BASH=${hook_bash}" >> "${GITHUB_ENV}"

- name: Test hooks with Bash 3.2
env:
EXPECT_BASH_VERSION: "3.2"
run: PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests -p 'test_hook_scripts.py' -v
5 changes: 4 additions & 1 deletion scripts/git-push-approval/require-push-approval.sh
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,11 @@ fi
# Only shell-execution tools can run `git push`. Gate on the tool name so that,
# for example, editing a document that merely mentions "git push" is unaffected.
# An empty/unknown tool name falls through to scanning, erring toward asking.
# Lowercase with `tr`, not `${1,,}`: stock macOS runs this under Bash 3.2.
is_shell_tool() {
case "${1,,}" in
local name
name="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"
case "${name}" in
bash | powershell | shell | "") return 0 ;;
*) return 1 ;;
esac
Expand Down
55 changes: 55 additions & 0 deletions tests/build-bash32.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
# Build Bash 3.2.57, the version stock macOS still runs for `#!/bin/bash`, so CI
# can run the hook scripts under it (see tests/test_hook_scripts.py).
#
# Usage: tests/build-bash32.sh [DEST_DIR]
# Prints the path of the built `bash`. Needs curl, a C compiler, make and bison.

set -euo pipefail

VERSION="3.2.57"
SHA256="3fa9daf85ebf35068f090ce51283ddeeb3c75eb5bc70b1a4a7cb05868bfe06a4"
DEST="${1:-${HOME}/.cache/bash-${VERSION}}"
# Anchor a relative DEST to the caller's directory; the build `cd`s away below.
case "${DEST}" in
/*) ;;
*) DEST="${PWD}/${DEST}" ;;
esac

if [[ -x "${DEST}/bash" ]]; then
printf '%s\n' "${DEST}/bash"
exit 0
fi

for tool in curl make bison; do
command -v "${tool}" >/dev/null || {
echo "build-bash32: ${tool} is required" >&2
exit 1
}
done

work="$(mktemp -d)"
trap 'rm -rf "${work}"' EXIT

curl -fsSL --retry 3 "https://ftpmirror.gnu.org/bash/bash-${VERSION}.tar.gz" -o "${work}/bash.tar.gz"
printf '%s %s\n' "${SHA256}" "${work}/bash.tar.gz" | sha256sum -c - >/dev/null
tar -xzf "${work}/bash.tar.gz" -C "${work}"
cd "${work}/bash-${VERSION}"

# Bash 3.2 predates C99 and ships a stale y.tab.c: relax modern GCC's errors
# (via CC, so build-host helpers get them too) and regenerate the parser.
export CC="${CC:-gcc} -std=gnu89 -Wno-implicit-function-declaration -Wno-implicit-int -Wno-int-conversion -Wno-incompatible-pointer-types"
export YACC="bison -y"
./configure --quiet --without-bash-malloc >"${work}/configure.log" 2>&1 || {
tail -n 40 "${work}/configure.log" >&2
exit 1
}
jobs="$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 2)"
make -j"${jobs}" >"${work}/make.log" 2>&1 || {
tail -n 40 "${work}/make.log" >&2
exit 1
}

mkdir -p "${DEST}"
cp bash "${DEST}/bash"
printf '%s\n' "${DEST}/bash"
179 changes: 179 additions & 0 deletions tests/test_hook_scripts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
"""Keep the shipped hook scripts compatible with Bash 3.2.

Regression test for #217: `${1,,}` in require-push-approval.sh is a "bad
substitution" under the Bash 3.2 that stock macOS runs for `#!/bin/bash`, and a
crashing `preToolUse` hook is fail-closed, so every tool call was denied.

Two layers:
- a static scan of every script referenced by `.apm/hooks/*.json` for Bash 4+
syntax, which runs anywhere;
- behaviour checks that run the hooks with `$HOOK_BASH` (default: `bash`).
CI runs them a second time with a Bash 3.2 build (see tests/build-bash32.sh).
Set `EXPECT_BASH_VERSION` (e.g. `3.2`) to assert which interpreter ran.

Standard library only.
"""

import json
import os
from pathlib import Path
import re
import subprocess
import tempfile
import unittest


ROOT = Path(__file__).resolve().parents[1]
HOOK_BASH = os.environ.get("HOOK_BASH", "bash")
PUSH_HOOK = ROOT / "scripts" / "git-push-approval" / "require-push-approval.sh"
GUARD_HOOK = ROOT / "scripts" / "tool-guardian" / "guard-tool.sh"

# (regex, what it is). Applied per line, after dropping full-line comments.
BASH4_SYNTAX = [
(r"\$\{[A-Za-z0-9_]+(\[[^]]*\])?(\^|,)", "case modification ${var,,} / ${var^^} (Bash 4.0)"),
(r"\$\{[^}]*@[QEPAaUuLKk]\}", "parameter transformation ${var@Q} (Bash 4.4)"),
(r"\$\{[A-Za-z_][A-Za-z0-9_]*\[-[0-9]", "negative array index ${arr[-1]} (Bash 4.3)"),
(r"\b(declare|typeset|local)\s+(-[A-Za-z]+\s+)*-[A-Za-z]*[Anlu]", "declare -A/-n/-l/-u (Bash 4.0/4.3)"),
(r"\b(mapfile|readarray|coproc)\b", "mapfile/readarray/coproc (Bash 4.0)"),
(r"\|&", "|& pipe (Bash 4.0)"),
(r"&>>", "&>> redirect (Bash 4.0)"),
(r";;&|\s;&\s*$", "case fall-through ;& / ;;& (Bash 4.0)"),
(r"(\[\[|\[|\btest)\s+-v\s", "-v variable test (Bash 4.2)"),
(r"\bwait\s+-n\b", "wait -n (Bash 4.3)"),
(r"\bshopt\s+-s\s+(globstar|lastpipe|autocd|direxpand|checkjobs)\b", "Bash 4+ shopt option"),
(r"\$\{?(EPOCHSECONDS|EPOCHREALTIME|BASH_ARGV0)\b", "Bash 5.0 variable"),
(r"\{-?[0-9]+\.\.-?[0-9]+\.\.-?[0-9]+\}", "brace expansion step {1..9..2} (Bash 4.0)"),
(r"%\([^)]*\)T", "printf %(...)T (Bash 4.2)"),
]


def bash4_findings(text):
findings = []
for number, line in enumerate(text.splitlines(), start=1):
if line.lstrip().startswith("#"):
continue
for pattern, label in BASH4_SYNTAX:
if re.search(pattern, line):
findings.append(f"line {number}: {label}: {line.strip()}")
return findings


def hook_scripts():
"""Scripts that `.apm/hooks/*.json` runs via the `bash` key."""
scripts = set()
for manifest in sorted((ROOT / ".apm" / "hooks").glob("*.json")):
hooks = json.loads(manifest.read_text(encoding="utf-8")).get("hooks", {})
for entries in hooks.values():
for entry in entries:
command = entry.get("bash")
if command:
scripts.add(ROOT / command.replace("${PLUGIN_ROOT}/", "", 1))
return sorted(scripts)


def run_hook(script, payload, **env):
merged = {**os.environ, "SKIP_PUSH_APPROVAL": "", "SKIP_TOOL_GUARD": "", **env}
return subprocess.run(
[HOOK_BASH, str(script)],
input=json.dumps(payload),
capture_output=True,
text=True,
env=merged,
timeout=30,
check=False,
)


class Bash4SyntaxScanTest(unittest.TestCase):
def test_hook_scripts_are_found(self):
scripts = hook_scripts()
self.assertIn(PUSH_HOOK, scripts)
self.assertIn(GUARD_HOOK, scripts)
for script in scripts:
self.assertTrue(script.is_file(), f"{script} is referenced by a hook but missing")

def test_hook_scripts_have_no_bash4_syntax(self):
for script in hook_scripts():
with self.subTest(script=script.relative_to(ROOT).as_posix()):
self.assertEqual(bash4_findings(script.read_text(encoding="utf-8")), [])

def test_scan_flags_bash4_syntax(self):
for snippet in (
'case "${1,,}" in',
'echo "${name^^}"',
"declare -A seen=()",
"local -n ref=$1",
"mapfile -t lines < file",
"cmd |& tee log",
'if [[ -v FOO ]]; then',
):
with self.subTest(snippet=snippet):
self.assertNotEqual(bash4_findings(snippet), [])

def test_scan_ignores_bash32_syntax(self):
for snippet in (
'if [[ ${#ALLOWLIST[@]} -gt 0 ]]; then',
'echo "${1:-}" "${match:0:35}"',
"GIT_PUSH_REGEX='git([[:space:]]+[^[:space:];&|]+)*'",
"# ${1,,} in a comment is fine",
"local name",
):
with self.subTest(snippet=snippet):
self.assertEqual(bash4_findings(snippet), [])


class HookBehaviourTest(unittest.TestCase):
def test_interpreter_version(self):
expected = os.environ.get("EXPECT_BASH_VERSION")
if not expected:
self.skipTest("EXPECT_BASH_VERSION not set")
result = subprocess.run(
[HOOK_BASH, "-c", "printf %s \"$BASH_VERSION\""],
capture_output=True, text=True, check=True,
)
self.assertTrue(result.stdout.startswith(expected), result.stdout)

def assert_asks(self, result):
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(json.loads(result.stdout)["permissionDecision"], "ask")

def assert_silent(self, result):
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.strip(), "")

def test_push_hook_asks_for_git_push_with_any_tool_name_case(self):
for tool in ("bash", "Bash", "PowerShell", "SHELL"):
with self.subTest(tool=tool):
self.assert_asks(run_hook(
PUSH_HOOK, {"toolName": tool, "toolArgs": {"command": "git push origin main"}}))

def test_push_hook_accepts_vscode_payload(self):
self.assert_asks(run_hook(
PUSH_HOOK, {"tool_name": "Bash", "tool_input": {"command": "git -C /repo push"}}))

def test_push_hook_ignores_other_commands_and_tools(self):
for payload in (
{"toolName": "Bash", "toolArgs": {"command": "git status && npm run push"}},
{"toolName": "edit", "toolArgs": {"path": "README.md", "text": "run git push"}},
):
with self.subTest(payload=payload):
self.assert_silent(run_hook(PUSH_HOOK, payload))

def test_push_hook_can_be_skipped(self):
self.assert_silent(run_hook(
PUSH_HOOK, {"toolName": "bash", "toolArgs": {"command": "git push"}},
SKIP_PUSH_APPROVAL="true"))

def test_guard_hook_allows_safe_and_blocks_dangerous_commands(self):
with tempfile.TemporaryDirectory() as log_dir:
safe = run_hook(GUARD_HOOK, {"toolName": "bash", "toolInput": "ls -la"},
TOOL_GUARD_LOG_DIR=log_dir, GUARD_MODE="block")
self.assertEqual(safe.returncode, 0, safe.stderr)
dangerous = run_hook(GUARD_HOOK, {"toolName": "bash", "toolInput": "rm -rf /"},
TOOL_GUARD_LOG_DIR=log_dir, GUARD_MODE="block")
self.assertEqual(dangerous.returncode, 1, dangerous.stderr)
self.assertIn("destructive_file_ops", dangerous.stdout)


if __name__ == "__main__":
unittest.main()
Loading