From 1af43da242ea98fa124763aa12bf2a497a0fbdb1 Mon Sep 17 00:00:00 2001 From: Jean-Paul van Ravensberg <14926452+DevSecNinja@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:15:49 +0100 Subject: [PATCH 1/4] feat(hooks): let git-push-approval allow feature-branch pushes The hook asked for every git push, so autopilot sessions stalled on routine pushes of their own PR branch. It now stays silent when every push in the command provably targets a non-default, non-protected branch on origin (including --force-with-lease), resolving implicit targets from the current branch and upstream with read-only git commands. Everything else, and anything it can't parse with certainty, still asks. Closes #228 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- scripts/git-push-approval/README.md | 58 ++++ .../require-push-approval.sh | 258 +++++++++++++++++- tests/test_hook_scripts.py | 131 +++++++++ 3 files changed, 446 insertions(+), 1 deletion(-) create mode 100644 scripts/git-push-approval/README.md diff --git a/scripts/git-push-approval/README.md b/scripts/git-push-approval/README.md new file mode 100644 index 0000000..fc9dabd --- /dev/null +++ b/scripts/git-push-approval/README.md @@ -0,0 +1,58 @@ +# Git push approval hook + +[`require-push-approval.sh`](require-push-approval.sh) is a Copilot `preToolUse` +hook, shipped by [`.apm/hooks/git-push-approval.json`](../../.apm/hooks/git-push-approval.json). +Commits stay local and rewritable until they're pushed, so `git push` is where it +asks for a human checkpoint. + +## What it decides + +For a shell tool call that contains `git push`, the hook either stays silent (the +normal permission flow runs, so autopilot sessions continue) or returns +`permissionDecision: "ask"`. + +It stays silent only when **every** `git push` in the command targets a feature +branch on `origin`: + +- `git push origin my-feature`, `git push -u origin HEAD`, + `git push origin HEAD:refs/heads/my-feature` +- `--force-with-lease`, `--force-with-lease=:` and + `--force-if-includes` +- `git push` or `git push origin` with no refspec, when the current branch, its + upstream and its push remote all resolve to a non-protected branch on `origin` +- compound commands such as + `git fetch && git rebase origin/main && git push --force-with-lease 2>&1 | tail` + +It asks for everything else, including: + +- the default branch (from `refs/remotes/origin/HEAD`), `main`, `master`, + `trunk`, `develop`, `gh-pages`, `release`, `release/*`, `releases/*` and + `release-please--*` +- tags, `--tags`, `--all`, `--mirror`, `--delete`, `:branch` deletions, + `--force`, `-f`, `+refspec` and any other option it doesn't know +- remotes other than `origin`, URLs and `git -C`/`-c` global options +- variables, command substitution, backslashes, globs, brace expansion, comments, + unbalanced quotes, `sudo`/`bash -c` wrappers and anything else it can't parse +- implicit targets (`git push`, `HEAD`) after a `cd`, `checkout`, `switch`, + `branch`, `worktree` or two-argument `rebase` in the same command, and any push + after a `cd` +- a `push.default` other than `simple`, `current` or `upstream`, and + `remote.origin.push` or `remote.origin.mirror` config + +The hook resolves branches with read-only `git` commands in the payload's `cwd` +(or its own working directory). It can't see a directory change made by an +earlier, separate shell command, so prefer explicit refspecs such as +`git push --force-with-lease origin HEAD:refs/heads/` in persistent shells. + +## Approving pushes in autopilot + +Feature-branch pushes need no approval. For a push the hook asks about, switch +the session to interactive mode and approve the prompt, or push it yourself. +`SKIP_PUSH_APPROVAL=true` disables the guardrail for the whole session; agents +must never set it themselves. + +## Tests + +`tests/test_hook_scripts.py` covers each allow and ask case against a throwaway +repository. The **Hook Scripts** workflow runs it with the runner's Bash and +with Bash 3.2, which stock macOS uses for `#!/bin/bash`. diff --git a/scripts/git-push-approval/require-push-approval.sh b/scripts/git-push-approval/require-push-approval.sh index a2b14ba..c04165d 100755 --- a/scripts/git-push-approval/require-push-approval.sh +++ b/scripts/git-push-approval/require-push-approval.sh @@ -12,6 +12,12 @@ # approve. For every other tool call it emits no decision and lets the normal # permission flow proceed. # +# Feature-branch pushes are the exception (#228): when every `git push` in the +# command provably targets a non-default, non-protected branch on `origin` +# (including `--force-with-lease`), the hook stays silent so unattended +# autopilot sessions can update their own PR branches. Anything it can't resolve +# with certainty still asks. See scripts/git-push-approval/README.md. +# # IMPORTANT: `preToolUse` command hooks are fail-closed — a non-zero exit (or a # crash) denies the tool call. This script therefore always exits 0 and only # ever upgrades the decision to "ask"; it never blocks unrelated tools. @@ -35,6 +41,10 @@ INPUT="$(cat)" # (toolName / toolArgs) and the VS Code compatible payload (tool_name / tool_input). TOOL_NAME="" TOOL_ARGS="" +# The exact command text, only when jq could extract it; the feature-branch +# check never parses the raw payload. +COMMAND="" +HOOK_CWD="" if command -v jq &>/dev/null; then TOOL_NAME="$(printf '%s' "${INPUT}" | jq -r '.toolName // .tool_name // empty' 2>/dev/null || printf '')" @@ -43,7 +53,16 @@ if command -v jq &>/dev/null; then | if ($a | type) == "string" then $a elif ($a | type) == "object" then ($a.command // $a.cmd // $a.script // ($a | tojson)) else ($a | tojson) end' 2>/dev/null || printf '')" + # Copilot CLI sends toolArgs as a JSON-encoded string; VS Code sends an object. + COMMAND="$(printf '%s' "${INPUT}" | jq -r ' + (.toolArgs // .tool_input // empty) as $a + | (if ($a | type) == "string" then ($a | try fromjson catch $a) else $a end) as $p + | if ($p | type) == "object" then ($p.command // $p.cmd // $p.script // empty) + elif ($p | type) == "string" then $p + else empty end' 2>/dev/null || printf '')" + HOOK_CWD="$(printf '%s' "${INPUT}" | jq -r '.cwd // empty' 2>/dev/null || printf '')" fi +[[ -n "${HOOK_CWD}" && -d "${HOOK_CWD}" ]] || HOOK_CWD="${PWD}" # Fallback when jq is unavailable or produced nothing: scan the raw payload. if [[ -z "${TOOL_NAME}" ]]; then @@ -76,8 +95,245 @@ is_shell_tool() { # holds when scanning JSON-embedded command text (e.g. `git push"`). GIT_PUSH_REGEX='(^|[^[:alnum:]_])git([[:space:]]+[^[:space:];&|]+)*[[:space:]]+push([^[:alnum:]_]|$)' +# --- Feature-branch pushes (#228) --------------------------------------------- +# Every helper below returns non-zero when it can't prove a push is safe, and the +# caller then asks. Bash 3.2 compatible: no ${var,,}, no empty "${arr[@]}". + +SEP=$'\x1e' # marks a command boundary in WORDS +REPO_DIR="" +DEFAULT_BRANCH="" +DIR_MAY_CHANGE=0 +HEAD_MAY_MOVE=0 +CREATED="" +CURRENT="" +WORDS=() +SEG=() +POS=() + +rgit() { git -C "${REPO_DIR}" "$@" 2>/dev/null; } + +is_protected() { + case "$1" in + "" | HEAD | main | master | trunk | develop | gh-pages | release | release/* | releases/* | release-please--*) return 0 ;; + esac + [[ -n "${DEFAULT_BRANCH}" && "$1" == "${DEFAULT_BRANCH}" ]] +} + +flush_word() { + if [[ ${inword} -eq 1 ]]; then + if [[ ${skip} -eq 1 ]]; then skip=0; else WORDS+=("${word}"); fi + fi + word="" + inword=0 +} + +# Split a command into words (quotes removed), with SEP between commands and +# redirections dropped. Fails on anything whose expansion can't be predicted. +tokenize() { + local s="$1" n=${#1} i=0 c next q="" word="" inword=0 skip=0 + WORDS=() + case "${s}" in *'$'* | *'`'* | *'\'* | *"${SEP}"*) return 1 ;; esac + while [[ ${i} -lt ${n} ]]; do + c="${s:${i}:1}" + i=$((i + 1)) + if [[ -n "${q}" ]]; then + if [[ "${c}" == "${q}" ]]; then q=""; else word="${word}${c}"; fi + continue + fi + case "${c}" in + "'" | '"') q="${c}" && inword=1 ;; + ' ' | $'\t' | $'\r') flush_word ;; + $'\n' | ';' | '|' | '&' | '(' | ')') flush_word && WORDS+=("${SEP}") ;; + '>' | '<') + next="${s:${i}:1}" + [[ "${next}" == '(' || "${c}${next}" == '<<' ]] && return 1 + case "${next}" in '>' | '&' | '|') i=$((i + 1)) ;; esac + case "${word}" in *[!0-9]*) ;; *) word="" && inword=0 ;; esac # fd, as in 2>&1 + flush_word + skip=1 + ;; + '#') + [[ ${inword} -eq 1 ]] || return 1 # a comment + word="${word}${c}" + ;; + *) word="${word}${c}" && inword=1 ;; + esac + done + [[ -z "${q}" ]] || return 1 + flush_word + [[ ${skip} -eq 0 ]] +} + +# Call "$1" with SEG set to the words of each command in WORDS. +for_each_command() { + local i=0 n=${#WORDS[@]} + SEG=() + while [[ ${i} -le ${n} ]]; do + if [[ ${i} -eq ${n} || "${WORDS[${i}]}" == "${SEP}" ]]; then + if [[ ${#SEG[@]} -gt 0 ]]; then "$1" || return 1; fi + SEG=() + else + SEG+=("${WORDS[${i}]}") + fi + i=$((i + 1)) + done +} + +# Set SUB / SUB_AT when SEG is a plain `git [--no-pager] ...`. +git_subcommand() { + local i=1 + SUB="" + SUB_AT=0 + case "${SEG[0]}" in git | */git | git.exe | */git.exe) ;; *) return 1 ;; esac + while [[ ${i} -lt ${#SEG[@]} && ("${SEG[${i}]}" == "--no-pager" || "${SEG[${i}]}" == "-P") ]]; do + i=$((i + 1)) + done + [[ ${i} -lt ${#SEG[@]} ]] || return 1 + SUB="${SEG[${i}]}" + SUB_AT=$((i + 1)) +} + +# First pass: note commands that change directory, move HEAD or create branches. +scan_command() { + local i positional=0 + case "$(printf '%s' "${SEG[0]}" | tr '[:upper:]' '[:lower:]')" in + cd | pushd | popd | chdir | sl | set-location | push-location | pop-location) DIR_MAY_CHANGE=1 ;; + esac + git_subcommand || return 0 + i=${SUB_AT} + case "${SUB}" in + checkout | switch) + HEAD_MAY_MOVE=1 + while [[ ${i} -lt $((${#SEG[@]} - 1)) ]]; do + case "${SEG[${i}]}" in -b | -B | -c | -C) CREATED="${CREATED}${SEP}${SEG[$((i + 1))]}${SEP}" ;; esac + i=$((i + 1)) + done + ;; + branch | worktree) HEAD_MAY_MOVE=1 ;; + rebase) + # `git rebase ` checks out first. + while [[ ${i} -lt ${#SEG[@]} ]]; do + case "${SEG[${i}]}" in -*) ;; *) positional=$((positional + 1)) ;; esac + i=$((i + 1)) + done + [[ ${positional} -le 1 ]] || HEAD_MAY_MOVE=1 + ;; + esac + return 0 +} + +current_branch() { + [[ ${HEAD_MAY_MOVE} -eq 0 ]] || return 1 + CURRENT="$(rgit symbolic-ref --quiet --short HEAD)" && [[ -n "${CURRENT}" ]] +} + +# `git push [origin]`: targets follow from the current branch, its upstream and +# push config; only the default-like push.default modes are resolved. +push_current() { + local remote="$1" merge + current_branch || return 1 + case "$(rgit config --get push.default)" in "" | simple | current | upstream) ;; *) return 1 ;; esac + [[ -z "$(rgit config --get-all remote.origin.push)" ]] || return 1 + if [[ -z "${remote}" ]]; then + remote="$(rgit config --get "branch.${CURRENT}.pushRemote" || + rgit config --get remote.pushDefault || + rgit config --get "branch.${CURRENT}.remote" || printf origin)" + fi + [[ "${remote}" == "origin" ]] || return 1 + merge="$(rgit config --get "branch.${CURRENT}.merge")" + if [[ -n "${merge}" ]]; then + [[ "${merge}" == refs/heads/* ]] || return 1 + is_protected "${merge#refs/heads/}" && return 1 + fi + ! is_protected "${CURRENT}" +} + +check_refspec() { + local src="$1" dst="$1" + if [[ "$1" == *:* ]]; then + src="${1%%:*}" + dst="${1#*:}" + fi + [[ -n "${src}" && -n "${dst}" && "${dst}" != *:* && "${src}" != tag ]] || return 1 + if [[ "${src}" == HEAD ]]; then + current_branch || return 1 + src="${CURRENT}" + [[ "$1" == *:* ]] || dst="${CURRENT}" + fi + src="${src#refs/heads/}" + case "${dst}" in + refs/heads/*) dst="${dst#refs/heads/}" ;; + refs/*) return 1 ;; + *) + # An unqualified destination takes its ref type from the source, which + # must therefore be a branch (existing, or created earlier in the command). + rgit show-ref --verify --quiet "refs/tags/${dst}" && return 1 + rgit show-ref --verify --quiet "refs/heads/${src}" || + [[ "${CREATED}" == *"${SEP}${src}${SEP}"* ]] || return 1 + ;; + esac + ! is_protected "${dst}" +} + +check_push() { + local i=${SUB_AT} a options=1 + [[ ${DIR_MAY_CHANGE} -eq 0 ]] || return 1 + POS=() + while [[ ${i} -lt ${#SEG[@]} ]]; do + a="${SEG[${i}]}" + i=$((i + 1)) + if [[ ${options} -eq 1 ]]; then + case "${a}" in + --) options=0 && continue ;; + -u | --set-upstream | -q | --quiet | -v | --verbose | -n | --dry-run | --progress | --no-progress | \ + --porcelain | --atomic | --force-with-lease | --force-with-lease=* | --force-if-includes) continue ;; + -*) return 1 ;; # --force, --tags, --all, --mirror, --delete, --no-verify, ... + esac + fi + case "${a}" in "" | +* | *[*?{}~,@^]* | *'['* | *']'*) return 1 ;; esac + POS+=("${a}") + done + [[ ${#POS[@]} -gt 0 ]] || { + push_current "" + return + } + [[ "${POS[0]}" == "origin" ]] || return 1 + [[ ${#POS[@]} -gt 1 ]] || { + push_current origin + return + } + i=1 + while [[ ${i} -lt ${#POS[@]} ]]; do + check_refspec "${POS[${i}]}" || return 1 + i=$((i + 1)) + done +} + +# Second pass: every push must be safe, and nothing else may hide a push. +check_command() { + if git_subcommand && [[ "${SUB}" == "push" ]]; then + check_push + return + fi + ! grep -qiE "${GIT_PUSH_REGEX}" <<<"${SEG[*]}" +} + +# push_is_safe DIR COMMAND +push_is_safe() { + REPO_DIR="$1" + rgit rev-parse --git-dir >/dev/null || return 1 + [[ "$(rgit config --get --bool remote.origin.mirror)" != "true" ]] || return 1 + DEFAULT_BRANCH="$(rgit symbolic-ref --quiet --short refs/remotes/origin/HEAD)" + DEFAULT_BRANCH="${DEFAULT_BRANCH#origin/}" + tokenize "$2" || return 1 + for_each_command scan_command && for_each_command check_command +} + if is_shell_tool "${TOOL_NAME}" && printf '%s' "${TOOL_ARGS}" | grep -qiE "${GIT_PUSH_REGEX}"; then - REASON="git push publishes commits to a remote and is irreversible, unlike local commits (which can still be amended, reset, or rebased). This repository's guardrail requires explicit human approval for every push. Set SKIP_PUSH_APPROVAL=true to disable it." + if [[ -n "${COMMAND}" ]] && push_is_safe "${HOOK_CWD}" "${COMMAND}"; then + exit 0 + fi + REASON="git push publishes commits to a remote and is irreversible. Pushes to a feature branch on origin are allowed without a prompt, but this one targets the default or a protected branch, a tag or another remote, forces without a lease, or could not be verified, so it needs explicit human approval. Set SKIP_PUSH_APPROVAL=true to disable the guardrail." # Emit exactly one decision object. jq keeps the reason safely JSON-escaped; # the printf fallback covers environments without jq. if command -v jq &>/dev/null; then diff --git a/tests/test_hook_scripts.py b/tests/test_hook_scripts.py index a1c0af0..68d8cfd 100644 --- a/tests/test_hook_scripts.py +++ b/tests/test_hook_scripts.py @@ -175,5 +175,136 @@ def test_guard_hook_allows_safe_and_blocks_dangerous_commands(self): self.assertIn("destructive_file_ops", dangerous.stdout) +class FeatureBranchPushTest(unittest.TestCase): + """#228: feature-branch pushes to origin pass silently; everything else asks.""" + + ALLOWED = ( + "git push origin feat", + "git push --force-with-lease origin feat", + "git push --force-with-lease=feat:abc123 --force-if-includes origin HEAD", + "git push -u origin HEAD:refs/heads/new-topic", + "git push", + "git --no-pager push origin", + "git fetch origin && git rebase origin/main && git push --force-with-lease 2>&1 | tail -n 5", + "git checkout -b new-topic && git push -u origin new-topic", + "git push origin 'feat' > /dev/null; git status", + ) + ASKED = ( + # Default and protected branches; `stable` is the default via origin/HEAD. + "git push origin main", + "git push origin feat:master", + "git push origin HEAD:refs/heads/main", + "git push origin stable", + "git push origin feat:release-please--branches--main", + # Force without a lease, tags and bulk pushes. + "git push --force origin feat", + "git push -f origin feat", + "git push origin +feat", + "git push --force-with-lease --force origin feat", + "git push --tags", + "git push origin --all", + "git push --mirror origin", + "git push origin v1", + "git push origin tag v1", + "git push origin refs/tags/v1", + # Deletions and other remotes. + "git push --delete origin feat", + "git push origin :feat", + "git push upstream feat", + "git push https://example.invalid/repo.git feat", + # Anything the hook can't resolve with certainty. + "git push origin $BRANCH", + "git push origin $(git branch --show-current)", + "git push origin `whoami`", + "git push origin 'feat", + "git push origin {feat,main}", + "git push origin missing-branch", + "git -C /tmp push origin feat", + "sudo git push origin feat", + "bash -c 'git push origin feat'", + # Compound commands where one push is unsafe or the target may move. + "git push origin feat && git push origin main", + "cd ../other && git push origin feat", + "git checkout main && git push", + "git rebase origin/main main && git push", + ) + + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + gitconfig = Path(cls.tmp.name) / "gitconfig" + gitconfig.write_text("", encoding="utf-8") + cls.env = {"GIT_CONFIG_GLOBAL": str(gitconfig), "GIT_CONFIG_NOSYSTEM": "1"} + cls.repo = str(Path(cls.tmp.name) / "repo") + subprocess.run(["git", "init", "-q", "-b", "main", cls.repo], check=True, + env={**os.environ, **cls.env}) + for args in ( + ["-c", "user.name=t", "-c", "user.email=t@example.com", "commit", "-q", "--allow-empty", "-m", "init"], + ["remote", "add", "origin", "https://example.invalid/repo.git"], + ["branch", "feat"], + ["branch", "wip"], + ["tag", "v1"], + ["update-ref", "refs/remotes/origin/feat", "HEAD"], + ["update-ref", "refs/remotes/origin/stable", "HEAD"], + ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/stable"], + ["config", "branch.feat.remote", "origin"], + ["config", "branch.feat.merge", "refs/heads/feat"], + ["config", "branch.wip.remote", "origin"], + ["config", "branch.wip.merge", "refs/heads/main"], + ): + cls.git(*args) + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + @classmethod + def git(cls, *args): + subprocess.run(["git", "-C", cls.repo, *args], check=True, capture_output=True, + env={**os.environ, **cls.env}) + + def setUp(self): + self.git("checkout", "-q", "feat") + + def push(self, command, vscode=False): + if vscode: + payload = {"tool_name": "Bash", "tool_input": {"command": command}, "cwd": self.repo} + else: + payload = {"toolName": "bash", "toolArgs": json.dumps({"command": command}), "cwd": self.repo} + return run_hook(PUSH_HOOK, payload, **self.env) + + def assert_decision(self, result, expected): + self.assertEqual(result.returncode, 0, result.stderr) + decision = json.loads(result.stdout)["permissionDecision"] if result.stdout.strip() else None + self.assertEqual(decision, expected) + + def test_feature_branch_pushes_are_allowed(self): + for command in self.ALLOWED: + with self.subTest(command=command): + self.assert_decision(self.push(command), None) + self.assert_decision(self.push("git push origin feat", vscode=True), None) + + def test_risky_or_unresolved_pushes_ask(self): + for command in self.ASKED: + with self.subTest(command=command): + self.assert_decision(self.push(command), "ask") + + def test_implicit_push_resolves_current_branch_and_upstream(self): + for checkout in (["main"], ["wip"], ["--detach"]): + with self.subTest(checkout=checkout): + self.git("checkout", "-q", *checkout) + self.assert_decision(self.push("git push --force-with-lease"), "ask") + + def test_implicit_push_asks_for_unresolved_push_config(self): + for key, value in (("push.default", "matching"), ("remote.pushDefault", "upstream"), + ("remote.origin.push", "refs/heads/*:refs/heads/*")): + with self.subTest(key=key): + self.git("config", key, value) + try: + self.assert_decision(self.push("git push"), "ask") + finally: + self.git("config", "--unset", key) + + if __name__ == "__main__": unittest.main() From 0947a480b98a3c6e2a367ff8fb95fa00896f4e8d Mon Sep 17 00:00:00 2001 From: Jean-Paul van Ravensberg <14926452+DevSecNinja@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:25:29 +0100 Subject: [PATCH 2/4] fix(hooks): satisfy shellcheck and SkillSpector for push approval Add default case arms, call the per-command checks directly so shellcheck sees them, avoid masked return values, and move the hook docs to docs/git-push-approval.md so the scanned hook directory only holds the script. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../README.md => docs/git-push-approval.md | 4 +- .../require-push-approval.sh | 37 ++++++++++++------- 2 files changed, 26 insertions(+), 15 deletions(-) rename scripts/git-push-approval/README.md => docs/git-push-approval.md (92%) diff --git a/scripts/git-push-approval/README.md b/docs/git-push-approval.md similarity index 92% rename from scripts/git-push-approval/README.md rename to docs/git-push-approval.md index fc9dabd..a2ebb0b 100644 --- a/scripts/git-push-approval/README.md +++ b/docs/git-push-approval.md @@ -1,7 +1,7 @@ # Git push approval hook -[`require-push-approval.sh`](require-push-approval.sh) is a Copilot `preToolUse` -hook, shipped by [`.apm/hooks/git-push-approval.json`](../../.apm/hooks/git-push-approval.json). +[`require-push-approval.sh`](../scripts/git-push-approval/require-push-approval.sh) is a Copilot `preToolUse` +hook, shipped by [`.apm/hooks/git-push-approval.json`](../.apm/hooks/git-push-approval.json). Commits stay local and rewritable until they're pushed, so `git push` is where it asks for a human checkpoint. diff --git a/scripts/git-push-approval/require-push-approval.sh b/scripts/git-push-approval/require-push-approval.sh index c04165d..5b9f28c 100755 --- a/scripts/git-push-approval/require-push-approval.sh +++ b/scripts/git-push-approval/require-push-approval.sh @@ -16,7 +16,7 @@ # command provably targets a non-default, non-protected branch on `origin` # (including `--force-with-lease`), the hook stays silent so unattended # autopilot sessions can update their own PR branches. Anything it can't resolve -# with certainty still asks. See scripts/git-push-approval/README.md. +# with certainty still asks. See docs/git-push-approval.md. # # IMPORTANT: `preToolUse` command hooks are fail-closed — a non-zero exit (or a # crash) denies the tool call. This script therefore always exits 0 and only @@ -115,6 +115,7 @@ rgit() { git -C "${REPO_DIR}" "$@" 2>/dev/null; } is_protected() { case "$1" in "" | HEAD | main | master | trunk | develop | gh-pages | release | release/* | releases/* | release-please--*) return 0 ;; + *) ;; esac [[ -n "${DEFAULT_BRANCH}" && "$1" == "${DEFAULT_BRANCH}" ]] } @@ -132,7 +133,7 @@ flush_word() { tokenize() { local s="$1" n=${#1} i=0 c next q="" word="" inword=0 skip=0 WORDS=() - case "${s}" in *'$'* | *'`'* | *'\'* | *"${SEP}"*) return 1 ;; esac + case "${s}" in *'$'* | *'`'* | *\\* | *"${SEP}"*) return 1 ;; *) ;; esac while [[ ${i} -lt ${n} ]]; do c="${s:${i}:1}" i=$((i + 1)) @@ -147,7 +148,7 @@ tokenize() { '>' | '<') next="${s:${i}:1}" [[ "${next}" == '(' || "${c}${next}" == '<<' ]] && return 1 - case "${next}" in '>' | '&' | '|') i=$((i + 1)) ;; esac + case "${next}" in '>' | '&' | '|') i=$((i + 1)) ;; *) ;; esac case "${word}" in *[!0-9]*) ;; *) word="" && inword=0 ;; esac # fd, as in 2>&1 flush_word skip=1 @@ -164,13 +165,16 @@ tokenize() { [[ ${skip} -eq 0 ]] } -# Call "$1" with SEG set to the words of each command in WORDS. +# Run scan_command ("$1" = scan) or check_command on each command in WORDS, +# with SEG set to its words. for_each_command() { local i=0 n=${#WORDS[@]} SEG=() while [[ ${i} -le ${n} ]]; do if [[ ${i} -eq ${n} || "${WORDS[${i}]}" == "${SEP}" ]]; then - if [[ ${#SEG[@]} -gt 0 ]]; then "$1" || return 1; fi + if [[ ${#SEG[@]} -gt 0 ]]; then + if [[ "$1" == scan ]]; then scan_command; else check_command || return 1; fi + fi SEG=() else SEG+=("${WORDS[${i}]}") @@ -196,8 +200,9 @@ git_subcommand() { # First pass: note commands that change directory, move HEAD or create branches. scan_command() { local i positional=0 - case "$(printf '%s' "${SEG[0]}" | tr '[:upper:]' '[:lower:]')" in + case "$(tr '[:upper:]' '[:lower:]' <<<"${SEG[0]}")" in cd | pushd | popd | chdir | sl | set-location | push-location | pop-location) DIR_MAY_CHANGE=1 ;; + *) ;; esac git_subcommand || return 0 i=${SUB_AT} @@ -205,7 +210,7 @@ scan_command() { checkout | switch) HEAD_MAY_MOVE=1 while [[ ${i} -lt $((${#SEG[@]} - 1)) ]]; do - case "${SEG[${i}]}" in -b | -B | -c | -C) CREATED="${CREATED}${SEP}${SEG[$((i + 1))]}${SEP}" ;; esac + case "${SEG[${i}]}" in -b | -B | -c | -C) CREATED="${CREATED}${SEP}${SEG[$((i + 1))]}${SEP}" ;; *) ;; esac i=$((i + 1)) done ;; @@ -218,6 +223,7 @@ scan_command() { done [[ ${positional} -le 1 ]] || HEAD_MAY_MOVE=1 ;; + *) ;; esac return 0 } @@ -230,10 +236,12 @@ current_branch() { # `git push [origin]`: targets follow from the current branch, its upstream and # push config; only the default-like push.default modes are resolved. push_current() { - local remote="$1" merge + local remote="$1" merge mode refspecs current_branch || return 1 - case "$(rgit config --get push.default)" in "" | simple | current | upstream) ;; *) return 1 ;; esac - [[ -z "$(rgit config --get-all remote.origin.push)" ]] || return 1 + mode="$(rgit config --get push.default)" + case "${mode}" in "" | simple | current | upstream) ;; *) return 1 ;; esac + refspecs="$(rgit config --get-all remote.origin.push)" + [[ -z "${refspecs}" ]] || return 1 if [[ -z "${remote}" ]]; then remote="$(rgit config --get "branch.${CURRENT}.pushRemote" || rgit config --get remote.pushDefault || @@ -288,9 +296,10 @@ check_push() { -u | --set-upstream | -q | --quiet | -v | --verbose | -n | --dry-run | --progress | --no-progress | \ --porcelain | --atomic | --force-with-lease | --force-with-lease=* | --force-if-includes) continue ;; -*) return 1 ;; # --force, --tags, --all, --mirror, --delete, --no-verify, ... + *) ;; esac fi - case "${a}" in "" | +* | *[*?{}~,@^]* | *'['* | *']'*) return 1 ;; esac + case "${a}" in "" | +* | *[*?{}~,@^]* | *'['* | *']'*) return 1 ;; *) ;; esac POS+=("${a}") done [[ ${#POS[@]} -gt 0 ]] || { @@ -320,13 +329,15 @@ check_command() { # push_is_safe DIR COMMAND push_is_safe() { + local mirror REPO_DIR="$1" rgit rev-parse --git-dir >/dev/null || return 1 - [[ "$(rgit config --get --bool remote.origin.mirror)" != "true" ]] || return 1 + mirror="$(rgit config --get --bool remote.origin.mirror)" + [[ "${mirror}" != "true" ]] || return 1 DEFAULT_BRANCH="$(rgit symbolic-ref --quiet --short refs/remotes/origin/HEAD)" DEFAULT_BRANCH="${DEFAULT_BRANCH#origin/}" tokenize "$2" || return 1 - for_each_command scan_command && for_each_command check_command + for_each_command scan && for_each_command check } if is_shell_tool "${TOOL_NAME}" && printf '%s' "${TOOL_ARGS}" | grep -qiE "${GIT_PUSH_REGEX}"; then From 99f62af4767a765599e2d86a86d49f2ceb5a8d33 Mon Sep 17 00:00:00 2001 From: Jean-Paul van Ravensberg <14926452+DevSecNinja@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:35:57 +0100 Subject: [PATCH 3/4] chore(security): accept SkillSpector TM1 on the push approval hook The hook names --force options only to detect them and ask for approval. Accepted with the owner's approval. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/skillspector-accepted.json | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/skillspector-accepted.json b/.github/skillspector-accepted.json index ee64278..1c374d6 100644 --- a/.github/skillspector-accepted.json +++ b/.github/skillspector-accepted.json @@ -191,6 +191,14 @@ "evidence": "chmod 777:::Use 'chmod 755' for directories or 'chmod 644' for files\"\n \"permission_abuse:::high:::chmod -R 777", "fingerprint": "2df784ea404c1b90428a92adcdca4a3baa68d299c8051bba0d1f995439b20c8d", "reason": "Tool Guardian's deny-list: these destructive commands are the regexes it blocks, never commands it runs." + }, + { + "path": "scripts/git-push-approval/require-push-approval.sh", + "rule": "TM1", + "severity": "HIGH", + "evidence": "Git Push Approval Hook\n# Forces an explicit, interactive human approval before the AI coding agent runs\n# any `git push`. A commit is entirely local and rewritable (amend / reset /\n# rebase) until it ", + "fingerprint": "988147c59b2aaa7d1a16a85b17db5d8b2ce9b5db3a5c6747142ad8e19d3413b6", + "reason": "Push-approval hook: it names --force options only to detect them and ask for approval; it never runs them." } ], "limitations": [ From c625469a972600b32bc44fddab1a3f13773d19b3 Mon Sep 17 00:00:00 2001 From: Jean-Paul van Ravensberg <14926452+DevSecNinja@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:55:55 +0100 Subject: [PATCH 4/4] fix(hooks): allowlist commands around feature-branch pushes Review found fail-open gaps: globbed or aliased git, `git -c`, `git config`, `builtin cd` and `rebase --exec` could change what a later push did. Every command in the line must now be on a short allowlist. Unquoted globs are rejected, `src:dst` needs a refs/heads/ destination, and push.followTags, remote.origin.push or an unknown origin/HEAD make the hook ask. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/git-push-approval.md | 26 +++--- .../require-push-approval.sh | 84 +++++++++++-------- tests/test_hook_scripts.py | 28 ++++++- 3 files changed, 89 insertions(+), 49 deletions(-) diff --git a/docs/git-push-approval.md b/docs/git-push-approval.md index a2ebb0b..23c856f 100644 --- a/docs/git-push-approval.md +++ b/docs/git-push-approval.md @@ -21,23 +21,29 @@ branch on `origin`: - `git push` or `git push origin` with no refspec, when the current branch, its upstream and its push remote all resolve to a non-protected branch on `origin` - compound commands such as - `git fetch && git rebase origin/main && git push --force-with-lease 2>&1 | tail` + `git fetch && git rebase origin/main && git push --force-with-lease 2>&1 | tail`, + as long as every other command is on a short allowlist: `git add`, `branch`, + `checkout`, `commit`, `diff`, `fetch`, `log`, `rebase` (without `--exec`), + `rev-parse`, `show`, `status` and `switch`, plus `echo`, `grep`, `head`, + `tail`, `true` and `wc` It asks for everything else, including: -- the default branch (from `refs/remotes/origin/HEAD`), `main`, `master`, - `trunk`, `develop`, `gh-pages`, `release`, `release/*`, `releases/*` and - `release-please--*` +- the default branch (from `refs/remotes/origin/HEAD`, and always when that + can't be resolved), `main`, `master`, `trunk`, `develop`, `gh-pages`, + `release`, `release/*`, `releases/*` and `release-please--*` - tags, `--tags`, `--all`, `--mirror`, `--delete`, `:branch` deletions, `--force`, `-f`, `+refspec` and any other option it doesn't know +- `src:dst` refspecs whose destination isn't spelled `refs/heads/`, + because Git may resolve a short name to a tag on the remote - remotes other than `origin`, URLs and `git -C`/`-c` global options -- variables, command substitution, backslashes, globs, brace expansion, comments, - unbalanced quotes, `sudo`/`bash -c` wrappers and anything else it can't parse -- implicit targets (`git push`, `HEAD`) after a `cd`, `checkout`, `switch`, - `branch`, `worktree` or two-argument `rebase` in the same command, and any push - after a `cd` +- any other command in the same line (`cd`, `git config`, `sudo`, `bash -c`, + aliases, ...), variables, command substitution, backslashes, unquoted globs, + brace expansion, comments, unbalanced quotes and anything else it can't parse +- implicit targets (`git push`, `HEAD`) after a `checkout`, `switch`, `branch` + or two-argument `rebase` in the same command - a `push.default` other than `simple`, `current` or `upstream`, and - `remote.origin.push` or `remote.origin.mirror` config + `remote.origin.push`, `remote.origin.mirror` or `push.followTags` config The hook resolves branches with read-only `git` commands in the payload's `cwd` (or its own working directory). It can't see a directory change made by an diff --git a/scripts/git-push-approval/require-push-approval.sh b/scripts/git-push-approval/require-push-approval.sh index 5b9f28c..7397f9b 100755 --- a/scripts/git-push-approval/require-push-approval.sh +++ b/scripts/git-push-approval/require-push-approval.sh @@ -102,7 +102,6 @@ GIT_PUSH_REGEX='(^|[^[:alnum:]_])git([[:space:]]+[^[:space:];&|]+)*[[:space:]]+p SEP=$'\x1e' # marks a command boundary in WORDS REPO_DIR="" DEFAULT_BRANCH="" -DIR_MAY_CHANGE=0 HEAD_MAY_MOVE=0 CREATED="" CURRENT="" @@ -153,10 +152,11 @@ tokenize() { flush_word skip=1 ;; - '#') - [[ ${inword} -eq 1 ]] || return 1 # a comment + '#' | '~') + [[ ${inword} -eq 1 ]] || return 1 # a comment or tilde expansion word="${word}${c}" ;; + '*' | '?' | '[' | ']' | '{' | '}') return 1 ;; # unquoted glob or brace expansion *) word="${word}${c}" && inword=1 ;; esac done @@ -173,7 +173,7 @@ for_each_command() { while [[ ${i} -le ${n} ]]; do if [[ ${i} -eq ${n} || "${WORDS[${i}]}" == "${SEP}" ]]; then if [[ ${#SEG[@]} -gt 0 ]]; then - if [[ "$1" == scan ]]; then scan_command; else check_command || return 1; fi + if [[ "$1" == scan ]]; then scan_command || return 1; else check_command || return 1; fi fi SEG=() else @@ -184,6 +184,8 @@ for_each_command() { } # Set SUB / SUB_AT when SEG is a plain `git [--no-pager] ...`. +# Other global options (-c, -C, --git-dir, ...) can change the repository, +# config or aliases, so they don't count as plain. git_subcommand() { local i=1 SUB="" @@ -197,16 +199,29 @@ git_subcommand() { SUB_AT=$((i + 1)) } -# First pass: note commands that change directory, move HEAD or create branches. +# First pass: every command must be on a short allowlist that can't change the +# directory, push config or remotes, nor run other programs. Note commands that +# move HEAD or create branches. scan_command() { local i positional=0 - case "$(tr '[:upper:]' '[:lower:]' <<<"${SEG[0]}")" in - cd | pushd | popd | chdir | sl | set-location | push-location | pop-location) DIR_MAY_CHANGE=1 ;; + case "${SEG[0]}" in + echo | head | tail | grep | wc | true) + ! grep -qiE "${GIT_PUSH_REGEX}" <<<"${SEG[*]}" + return + ;; *) ;; esac - git_subcommand || return 0 + git_subcommand || return 1 i=${SUB_AT} + while [[ ${i} -lt ${#SEG[@]} ]]; do + case "${SEG[${i}]}" in -x | --exec* | --upload-pack* | --receive-pack*) return 1 ;; *) ;; esac + i=$((i + 1)) + done + i=${SUB_AT} + # Built-in names only: git aliases can't shadow them. case "${SUB}" in + push) return 0 ;; + add | commit | diff | fetch | log | rev-parse | show | status) ;; checkout | switch) HEAD_MAY_MOVE=1 while [[ ${i} -lt $((${#SEG[@]} - 1)) ]]; do @@ -214,7 +229,7 @@ scan_command() { i=$((i + 1)) done ;; - branch | worktree) HEAD_MAY_MOVE=1 ;; + branch) HEAD_MAY_MOVE=1 ;; rebase) # `git rebase ` checks out first. while [[ ${i} -lt ${#SEG[@]} ]]; do @@ -223,9 +238,9 @@ scan_command() { done [[ ${positional} -le 1 ]] || HEAD_MAY_MOVE=1 ;; - *) ;; + *) return 1 ;; esac - return 0 + ! grep -qiE "${GIT_PUSH_REGEX}" <<<"${SEG[*]}" } current_branch() { @@ -236,12 +251,10 @@ current_branch() { # `git push [origin]`: targets follow from the current branch, its upstream and # push config; only the default-like push.default modes are resolved. push_current() { - local remote="$1" merge mode refspecs + local remote="$1" merge mode current_branch || return 1 mode="$(rgit config --get push.default)" case "${mode}" in "" | simple | current | upstream) ;; *) return 1 ;; esac - refspecs="$(rgit config --get-all remote.origin.push)" - [[ -z "${refspecs}" ]] || return 1 if [[ -z "${remote}" ]]; then remote="$(rgit config --get "branch.${CURRENT}.pushRemote" || rgit config --get remote.pushDefault || @@ -257,35 +270,30 @@ push_current() { } check_refspec() { - local src="$1" dst="$1" + local src="$1" dst if [[ "$1" == *:* ]]; then - src="${1%%:*}" + # Git resolves an unqualified destination against the remote's refs, + # which may hold a tag of that name, so require refs/heads/. dst="${1#*:}" + [[ -n "${1%%:*}" && "${dst}" == refs/heads/* && "${dst}" != *:* ]] || return 1 + ! is_protected "${dst#refs/heads/}" + return fi - [[ -n "${src}" && -n "${dst}" && "${dst}" != *:* && "${src}" != tag ]] || return 1 + # A source-only refspec pushes to the same ref name, so it must be a branch + # (existing, or created earlier in the command). if [[ "${src}" == HEAD ]]; then current_branch || return 1 src="${CURRENT}" - [[ "$1" == *:* ]] || dst="${CURRENT}" fi src="${src#refs/heads/}" - case "${dst}" in - refs/heads/*) dst="${dst#refs/heads/}" ;; - refs/*) return 1 ;; - *) - # An unqualified destination takes its ref type from the source, which - # must therefore be a branch (existing, or created earlier in the command). - rgit show-ref --verify --quiet "refs/tags/${dst}" && return 1 - rgit show-ref --verify --quiet "refs/heads/${src}" || - [[ "${CREATED}" == *"${SEP}${src}${SEP}"* ]] || return 1 - ;; - esac - ! is_protected "${dst}" + rgit show-ref --verify --quiet "refs/tags/${src}" && return 1 + rgit show-ref --verify --quiet "refs/heads/${src}" || + [[ "${CREATED}" == *"${SEP}${src}${SEP}"* ]] || return 1 + ! is_protected "${src}" } check_push() { local i=${SUB_AT} a options=1 - [[ ${DIR_MAY_CHANGE} -eq 0 ]] || return 1 POS=() while [[ ${i} -lt ${#SEG[@]} ]]; do a="${SEG[${i}]}" @@ -318,24 +326,30 @@ check_push() { done } -# Second pass: every push must be safe, and nothing else may hide a push. +# Second pass: every push must target a feature branch. check_command() { if git_subcommand && [[ "${SUB}" == "push" ]]; then check_push return fi - ! grep -qiE "${GIT_PUSH_REGEX}" <<<"${SEG[*]}" + return 0 } # push_is_safe DIR COMMAND push_is_safe() { - local mirror + local mirror follow refspecs REPO_DIR="$1" rgit rev-parse --git-dir >/dev/null || return 1 + # Config that silently adds or remaps targets: mirroring, tag following and + # remote.origin.push refspecs (which also remap source-only refspecs). mirror="$(rgit config --get --bool remote.origin.mirror)" - [[ "${mirror}" != "true" ]] || return 1 + follow="$(rgit config --get --bool push.followTags)" + refspecs="$(rgit config --get-all remote.origin.push)" + [[ "${mirror}" != true && "${follow}" != true && -z "${refspecs}" ]] || return 1 + # An unknown default branch can't be told apart from a feature branch. DEFAULT_BRANCH="$(rgit symbolic-ref --quiet --short refs/remotes/origin/HEAD)" DEFAULT_BRANCH="${DEFAULT_BRANCH#origin/}" + [[ -n "${DEFAULT_BRANCH}" ]] || return 1 tokenize "$2" || return 1 for_each_command scan && for_each_command check } diff --git a/tests/test_hook_scripts.py b/tests/test_hook_scripts.py index 68d8cfd..c583c74 100644 --- a/tests/test_hook_scripts.py +++ b/tests/test_hook_scripts.py @@ -222,11 +222,20 @@ class FeatureBranchPushTest(unittest.TestCase): "git -C /tmp push origin feat", "sudo git push origin feat", "bash -c 'git push origin feat'", + # Unqualified colon destinations may resolve to a remote tag. + "git push origin feat:topic", # Compound commands where one push is unsafe or the target may move. "git push origin feat && git push origin main", "cd ../other && git push origin feat", "git checkout main && git push", "git rebase origin/main main && git push", + # Commands outside the allowlist can change what a later push does. + "git push origin feat && /usr/bin/[g]it push origin main", + "git config remote.origin.push refs/heads/main:refs/heads/main && git push origin", + "builtin cd /tmp && git push origin HEAD", + "git -c advice.detachedHead=false checkout main && git push origin HEAD", + "git -c alias.p=push p origin main; git push origin feat", + "git rebase -x ./ship.sh origin/main && git push origin feat", ) @classmethod @@ -295,16 +304,27 @@ def test_implicit_push_resolves_current_branch_and_upstream(self): self.git("checkout", "-q", *checkout) self.assert_decision(self.push("git push --force-with-lease"), "ask") - def test_implicit_push_asks_for_unresolved_push_config(self): - for key, value in (("push.default", "matching"), ("remote.pushDefault", "upstream"), - ("remote.origin.push", "refs/heads/*:refs/heads/*")): + def test_asks_for_push_config_that_adds_or_remaps_targets(self): + for key, value, command in ( + ("push.default", "matching", "git push"), + ("remote.pushDefault", "upstream", "git push"), + ("remote.origin.push", "refs/heads/feat:refs/heads/main", "git push origin feat"), + ("push.followTags", "true", "git push origin feat"), + ): with self.subTest(key=key): self.git("config", key, value) try: - self.assert_decision(self.push("git push"), "ask") + self.assert_decision(self.push(command), "ask") finally: self.git("config", "--unset", key) + def test_asks_when_default_branch_is_unknown(self): + self.git("symbolic-ref", "--delete", "refs/remotes/origin/HEAD") + try: + self.assert_decision(self.push("git push origin feat"), "ask") + finally: + self.git("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/stable") + if __name__ == "__main__": unittest.main()