copilot-cli icon indicating copy to clipboard operation
copilot-cli copied to clipboard

preToolUse hooks silently bypassed under parallel tool calls (timeout->allow fallback + serial dispatch)

Open torumakabe opened this issue 7 months ago • 4 comments

Describe the bug

preToolUse hooks are silently bypassed under parallel tool calls because:

  1. timeoutSec does not terminate the hook process — when a hook takes longer than timeoutSec, the CLI stops waiting but the hook subprocess keeps running. The CLI then proceeds with an implicit allow (fail-open). Any permissionDecision: deny that the hook eventually writes to stdout is discarded.
  2. Hook invocations are serialized — when several tools are invoked in parallel (e.g. from the agent), preToolUse hooks are dispatched one-by-one with ~1.5–4 s gaps, even though the tool calls themselves land within a <100 ms window. Combined with (1), the later items in the queue are the ones most likely to exceed timeoutSec and get fail-open'd.

The net effect is that a security-oriented hook (e.g. a local guard that blocks dangerous commands) becomes probabilistically unreliable as soon as the agent fires more than a handful of tools concurrently. The reported "hook race condition" turns out not to be a race inside the hook, but a silent allow-fallback on timeout.

Affected version

1.0.35-2 (Windows_NT)

Likely affects other recent versions; not tested across matrix.

Steps to reproduce the behavior

Minimal reproducer using a Python 3 hook. Save as slow-deny.py:

import json, sys, time
sys.stdin.read()
time.sleep(15)  # longer than timeoutSec
print(json.dumps({"permissionDecision": "deny", "permissionDecisionReason": "should block"}))

And ~/.copilot/hooks/hooks.json:

{
  "version": 1,
  "hooks": {
    "preToolUse": [
      {
        "type": "command",
        "bash":       "python3 \"$HOME/slow-deny.py\"",
        "powershell": "py -3 \"$HOME\\slow-deny.py\"",
        "timeoutSec": 10
      }
    ]
  }
}

Start copilot and ask the agent to run any shell command (e.g. echo hi).

Expected: the command is blocked (the hook wrote deny, even if late). Actual: the command executes. The hook logs permissionDecision: deny after the CLI has already moved on.

A second reproducer shows the serialization behavior: ask the agent to run ~5 shell commands in the same turn. Logging the hook's start time (datetime.now()) shows the hooks firing at +0 s, +1.5 s, +4.6 s, +7.1 s, +11.1 s despite the tool calls all starting within ~100 ms.

Expected behavior

At least one of:

  • timeoutSec should kill the hook process (so subsequent failure modes are visible), and a timed-out hook should fall back to deny (fail-closed) — not to an implicit allow.
  • Provide an explicit configuration knob (e.g. onTimeout: "deny" | "allow") so operators can opt into fail-closed semantics.
  • Document the current behavior clearly; right now the docs describe timeoutSec without specifying the fallback direction.

Ideally also: dispatch preToolUse hooks in parallel rather than serializing them, since each tool call is independent.

Additional context

  • OS: Windows 11, powershell invocation path
  • Reproduced with minimal py -3 hook (no uv, no third-party dependencies), so the latency is CLI-side scheduling rather than hook startup cost
  • Observations:
    • dur_stdout_written - dur_invoked for the slow hook is ~15 s (full sleep), confirming the process is not killed at the 10 s timeout
    • For 5 parallel tool invocations, hook start times were spaced 1.5–4 s apart — consistent with a serial queue on the CLI side
    • The bypass probability grows with parallelism, matching community reports of "preToolUse race condition under high concurrency"
  • Security impact: any user who relies on preToolUse hooks for safety (e.g. blocking writes to sensitive paths, blocking dangerous URLs) silently loses that protection under high concurrency

Happy to share a full minimal repro repo or detailed logs on request.

torumakabe avatar Apr 22 '26 09:04 torumakabe

This behaviour is risky for anyone treating preToolUse as a governance or safety surface.

If a hook times out and the tool call silently proceeds, the operator cannot tell the difference between "approved" and "not checked in time". Under parallel tool use that becomes especially hard to reason about.

An explicit timeout policy would help a lot:

  • onTimeout: "deny" | "allow"
  • timeout outcome included in the event/audit payload
  • no silent fallback where a blocking hook was configured

Even if the default remains permissive for developer convenience, teams need a fail-closed option when hooks are enforcing policy.

AgenticThinkingUK avatar May 10 '26 21:05 AgenticThinkingUK

If a preToolUse hook times out and the CLI silently proceeds with an implicit allow, then the hook is no longer acting as an enforcement mechanism. For security focused use cases, a timeout effectively becomes a bypass. The measurements suggest that protection degrades as concurrency increases because later hook invocations spend more time waiting in the queue. I think the request for an explicit timeout policy is reasonable. A lot of runtime policy systems expose a configurable fail open versus fail closed behavior because different users have very different priorities around safety and availability.

This is also why many runtime guardrail systems focus heavily on PreToolUse enforcement. Projects like https://github.com/FailproofAI/failproofai rely on tool interception to block unsafe actions before execution. For that model to work reliably, timeout handling needs to be deterministic and clearly documented. Otherwise operators may believe a policy is protecting them when it is actually being bypassed under load.

ishita-0301 avatar Jun 19 '26 05:06 ishita-0301

Still reproducible on 1.0.103 (macOS, --allow-all-tools). The hooks reference now documents the timeout fallback as intentional ("always fail-open, even for preToolUse"), so the remaining ask is the policy setting.

The setting should also cover unparseable output, which has the same effect. One case per fresh COPILOT_HOME; the hook guards touch marker, and "call ran" means the marker file exists afterwards:

hook call ran message
prints deny JSON no Denied by preToolUse hook: blocked by test
exit 2 no Denied by preToolUse hook: hook exited with code 2
exit 1 no Denied by preToolUse hook … (hook errored)
echo "checking command..." then deny JSON yes
prints deny (not JSON) yes
sleep 8 then deny JSON, timeoutSec 2 yes

A stray log line on stdout silently turns a deny into an allow. Suggestion: onError: "deny" | "allow" for preToolUse, covering timeouts and unparseable output, and recording the outcome in the event stream.

repro.sh
#!/bin/sh
# Does a preToolUse hook that means "deny" stop the call when it answers late or
# not in JSON? One scratch repo and COPILOT_HOME per case; the prompt asks for
# exactly one shell call, `touch marker`. The marker existing afterwards means
# Copilot ran the call.
#
#   repro.sh <model> [workdir]
#
# Needs copilot and gh (logged in: a fresh COPILOT_HOME logs in through gh).
set -u
model=${1:?usage: repro.sh <model> [workdir]}
work=${2:-$(mktemp -d)}
mkdir -p "$work"
copilot --version | head -1

# case name | hook command | timeoutSec
cases='deny-json|printf %s "{\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"blocked by test\"}"|10
exit-2|echo blocked >&2; exit 2|10
exit-1|exit 1|10
log-line-then-deny|echo "checking command..."; printf %s "{\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"blocked by test\"}"|10
not-json|echo deny|10
slow-deny|sleep 8; printf %s "{\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"blocked by test\"}"|2'

printf '\n| case | hook | marker created (call ran) | denial message |\n|---|---|---|---|\n' >"$work/summary.md"
echo "$cases" | while IFS='|' read -r name cmd timeout; do
  d=$work/$name
  rm -rf "$d"; mkdir -p "$d/repo" "$d/home/hooks"
  git -C "$d/repo" init -q
  printf '%s\n' "$cmd" >"$d/hook.sh"
  cat >"$d/home/hooks/test.json" <<JSON
{"version": 1, "hooks": {"preToolUse": [{"type": "command", "bash": "sh '$d/hook.sh'", "timeoutSec": $timeout}]}}
JSON
  (cd "$d/repo" && COPILOT_HOME=$d/home copilot -p "Run exactly this shell command, once, as one tool call: touch marker. If it is denied, do not retry and do not try another way." \
    --model "$model" --no-ask-user --output-format json --allow-all-tools --disable-builtin-mcps \
    >"$d/out.jsonl" 2>"$d/err.txt")
  ran=no; [ -e "$d/repo/marker" ] && ran=YES
  msg=$(grep -o '"error":{"message":"[^}]*"code":"denied"' "$d/out.jsonl" | head -1 | sed 's/^"error":{"message":"//; s/","code":"denied"$//; s|"[^"]*hooks/test.json\\"|<hooks file>|')
  printf '| %s | `%s` (timeoutSec %s) | %s | %s |\n' "$name" "$cmd" "$timeout" "$ran" "$msg" >>"$work/summary.md"
  echo "$name: ran=$ran"
done
cat "$work/summary.md"

mvelosop avatar Oct 27 '26 09:10 mvelosop

A follow-up on the queueing part, which I couldn't reproduce on 1.0.104 (macOS, --allow-all-tools). The model made 10 shell calls in one batch (all started within 8 ms), with a single preToolUse hook:

hook dispatch result
denies immediately, timeoutSec 5 one at a time, ~25 ms apart all 10 denied
sleep 2 then deny, timeoutSec 5 one at a time, 2 s each (~20 s total) all 10 denied, the last after waiting ~18 s in the queue

So hooks are still serialized, but the timeout now seems to run per hook from its own start, not from the tool call: a queued call is not failed open. The 1.5–4 s gaps between hooks didn't show up either. The fail-open paths that remain are a hook that is slow on its own, or one whose output isn't parseable (previous comment).

Also checked: overwriting or deleting the hooks file mid-session has no effect (the next call is still denied), so the file is read once at session start.

bypass.sh (the par-* cases are the queueing probe, mut-* the hooks-file edit)
#!/bin/sh
# Two ways an agent could get past a preToolUse hook without touching its code:
#
#   par-*  many tool calls in one turn: are hooks run one at a time, and does a
#          queued call time out (fail open) before its hook answers?
#   mut-*  the hooks file edited mid-session: does Copilot re-read it?
#
#   bypass.sh <model> [workdir]
#
# One scratch repo per case, COPILOT_HOME inside it (as vloop puts it under
# .vloop/tmp/). Every hook invocation is logged with its start and end time.
set -u
model=${1:?usage: bypass.sh <model> [workdir]}
work=${2:-$(mktemp -d)}
mkdir -p "$work"
copilot --version | head -1
now='perl -MTime::HiRes=time -e "printf q(%.3f), time"'
deny='{"permissionDecision":"deny","permissionDecisionReason":"blocked by test"}'

# setup <case> <timeoutSec> <hook body>: the hook body runs after the start is logged.
setup() {
  d=$work/$1; rm -rf "$d"; mkdir -p "$d/repo/.vloop/tmp/home/hooks"
  git -C "$d/repo" init -q
  home=$d/repo/.vloop/tmp/home
  cat >"$d/hook.sh" <<EOF
in=\$(cat)
s=\$($now)
echo "start \$s \$\$ \$(printf %s "\$in" | tr -d '\n' | cut -c1-200)" >>'$d/hook.log'
$3
echo "end   \$($now) \$\$" >>'$d/hook.log'
EOF
  printf '{"version": 1, "hooks": {"preToolUse": [{"type": "command", "bash": "sh '\''%s/hook.sh'\''", "timeoutSec": %s}]}}\n' "$d" "$2" >"$home/hooks/test.json"
}

session() {
  (cd "$d/repo" && COPILOT_HOME=$home copilot -p "$1" \
    --model "$model" --no-ask-user --output-format json --allow-all-tools --disable-builtin-mcps \
    >"$d/out.jsonl" 2>"$d/err.txt")
}

# The tool calls Copilot started and how each ended: timestamp, ran/denied, command.
calls() {
  python3 - "$d/out.jsonl" <<'PY'
import json, sys
start, rows = {}, []
for line in open(sys.argv[1]):
    try: e = json.loads(line)
    except ValueError: continue
    t, data = e.get("type"), e.get("data", {})
    if t == "tool.execution_start":
        start[data["toolCallId"]] = (e["timestamp"][11:23], json.dumps(data.get("arguments", {}).get("command", data.get("arguments"))))
    elif t == "tool.execution_complete":
        ts, cmd = start.get(data.get("toolCallId"), ("?", "?"))
        err = data.get("error") or {}
        state = "ran" if data.get("success") else ("denied" if err.get("code") == "denied" else "failed")
        print(f"  {ts} -> {e['timestamp'][11:23]}  {state:6} {cmd[:70]}  {err.get('message','')[:60]}")
PY
}

report() {
  echo "== $1"; calls
  echo "  hook log:"; sed 's/^/    /' "$d/hook.log" 2>/dev/null | cut -c1-140
  echo "  files: $(cd "$d/repo" && ls | tr '\n' ' ')"
}

n10='touch m01; touch m02; touch m03; touch m04; touch m05; touch m06; touch m07; touch m08; touch m09; touch m10'
par="This is a test of parallel tool calls in a scratch repository. Make these ten shell tool calls IN PARALLEL, all in one single batch in the same response, without waiting for any result: $n10 (each one its own tool call). If a call is denied, do not retry it and do not try another way. Then stop."

setup par-fast 5 "printf %s '$deny'"
session "$par"; report par-fast

setup par-slow 5 "sleep 2; printf %s '$deny'"
session "$par"; report par-slow

# The mut hook denies any call that mentions "marker" and allows the rest.
mut_hook="case \"\$in\" in *marker*) printf %s '$deny';; esac"
steps() {
  echo "This is a test of your shell tool in a scratch repository. Make these three shell tool calls, one at a time, in order, each as its own tool call. If one is denied, do not retry it and do not try another way: go on to the next.
1. touch marker1
2. $1
3. touch marker3
Then report which ran."
}

setup mut-empty 10 "$mut_hook"
session "$(steps "printf '{\"version\":1,\"hooks\":{}}' > .vloop/tmp/home/hooks/test.json")"; report mut-empty

setup mut-delete 10 "$mut_hook"
session "$(steps "rm -f .vloop/tmp/home/hooks/test.json")"; report mut-delete

mvelosop avatar Oct 27 '26 10:10 mvelosop