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
8 changes: 8 additions & 0 deletions .github/skillspector-accepted.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down
64 changes: 64 additions & 0 deletions docs/git-push-approval.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Git push approval hook
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed

[`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.

## 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=<ref>:<expect>` 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`,
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`, 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/<branch>`,
because Git may resolve a short name to a tag on the remote
- remotes other than `origin`, URLs and `git -C`/`-c` global options
- 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`, `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
earlier, separate shell command, so prefer explicit refspecs such as
`git push --force-with-lease origin HEAD:refs/heads/<branch>` in persistent shells.
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed

## Approving pushes in autopilot

Feature-branch pushes need no approval. For a push the hook asks about, switch
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
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`.
283 changes: 282 additions & 1 deletion scripts/git-push-approval/require-push-approval.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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 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
# ever upgrades the decision to "ask"; it never blocks unrelated tools.
Expand All @@ -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 '')"
Expand All @@ -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
Expand Down Expand Up @@ -76,8 +95,270 @@ 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=""
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 or tilde expansion
word="${word}${c}"
;;
'*' | '?' | '[' | ']' | '{' | '}') return 1 ;; # unquoted glob or brace expansion
*) word="${word}${c}" && inword=1 ;;
esac
done
[[ -z "${q}" ]] || return 1
flush_word
[[ ${skip} -eq 0 ]]
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

# 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
if [[ "$1" == scan ]]; then scan_command || return 1; else check_command || return 1; fi
fi
SEG=()
else
SEG+=("${WORDS[${i}]}")
fi
i=$((i + 1))
done
}

# Set SUB / SUB_AT when SEG is a plain `git [--no-pager] <subcommand> ...`.
# 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=""
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: 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 "${SEG[0]}" in
echo | head | tail | grep | wc | true)
! grep -qiE "${GIT_PUSH_REGEX}" <<<"${SEG[*]}"
return
;;
*) ;;
esac
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
case "${SEG[${i}]}" in -b | -B | -c | -C) CREATED="${CREATED}${SEP}${SEG[$((i + 1))]}${SEP}" ;; *) ;; esac
i=$((i + 1))
done
;;
branch) HEAD_MAY_MOVE=1 ;;
rebase)
# `git rebase <upstream> <branch>` checks out <branch> 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
;;
*) return 1 ;;
esac
! grep -qiE "${GIT_PUSH_REGEX}" <<<"${SEG[*]}"
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

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 mode
current_branch || return 1
mode="$(rgit config --get push.default)"
case "${mode}" in "" | simple | current | upstream) ;; *) return 1 ;; esac
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
if [[ "$1" == *:* ]]; then
# 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
# 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}"
fi
src="${src#refs/heads/}"
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
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
Comment thread
DevSecNinja marked this conversation as resolved.
Resolved
[[ ${#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 target a feature branch.
check_command() {
if git_subcommand && [[ "${SUB}" == "push" ]]; then
check_push
return
fi
return 0
}

# push_is_safe DIR COMMAND
push_is_safe() {
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)"
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
}

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
Expand Down
Loading
Loading