fix(776): a signal must not become consent
Round 3, from two independent re-reviews of the round-2 fix commit. The fix for the lost-output-on-SIGTERM defect introduced a worse one than the defect. The signal handler ended in `exit "$?"`, and `$?` at signal time is the status of whatever command was running — normally 0 for a guard still gathering evidence. Measured on the real guard, `prepush-donewhen.sh` SIGTERMed mid-curl with an unticked Done-when box: uninstrumented rc=-15 git ABORTS the push instrumented rc=0 git PUSHES to main That converts a killed guard into consent, in the permissive direction, in the hook that protects `main`. The handler now flushes, restores the default disposition and re-raises the signal, so the process dies the way it would have died. test_output_survives_a_SIGTERM could not see it: it asserts stdout content, never reads the return code, and drives a capture-mode hook so no exit-code guard is ever signalled. Also from this round: - The flush ran TWICE on the signal path (signal handler, then EXIT trap), writing two contradictory exit records for one invocation — a real decision then a phantom no-op — so the report mis-histogrammed the very case the trap was added for. It is idempotent now. - `exec 4<&- 2>/dev/null`: the round-1 blocker pattern again, eight lines below the comment forbidding it. Rather than fix the third instance and wait for a fourth, test_no_exec_in_the_sink_carries_a_STDERR_REDIRECT now enforces it. - The log write leaked `Operation not permitted` to stderr on an unwritable log, because `>> "$file" 2>/dev/null` opens the file BEFORE redirecting stderr. The fail-open test used a path that dies at mkdir and never reached this. - Classification: an unrecognised value is no longer lowercased into a valid decision, exit 2 now dominates a printed `allow` (it is the harness's block channel, and reporting a permit for a refused call is the one direction this log must never be wrong in), and a non-zero exit no longer annotates a real decision with an invented `+error`. - Classification and replay read the same bytes; they disagreed when a hook used fd 4, so the harness saw `deny` while the log recorded `no-op`. - The stderr normaliser rewrote `line N:` globally, collapsing genuinely different diagnostics; it is anchored to the script-path prefix now. - docs 5.4 claimed the two zero rows were "trigger did not fire", justified by unit tests that invoke the scripts directly and therefore prove nothing about harness dispatch. It now separates what is established from what is not, and stops contradicting its own decision record. Refs: #776 Decisions-Edit: yes Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -527,14 +527,23 @@ headless session exercising the four tool paths above, then a `git commit` and a
|
||||
`git push --dry-run`, and read `scripts/hook-fire-log.sh report --all --dir <that directory>`.
|
||||
|
||||
**A zero is two findings wearing one number** — a hook that is broken, and a hook whose trigger did
|
||||
not occur — and the report says so rather than presenting a zero as a verdict. Both zeroes here are
|
||||
the second kind, and that is established rather than assumed: `pretooluse-nav-guard` and
|
||||
`pretooluse-merge-consent` are each driven to their deciding branch in
|
||||
`scripts/tests/test_hook_fire_log.py` (a `deny` on an `/iptv/` URL and an `ask` on a merge call
|
||||
respectively), emitting the correct decision with instrumentation in place. So both hooks are
|
||||
demonstrably healthy; what did not happen in this window is their trigger. Neither can be exercised
|
||||
end-to-end without a live browser session or a real merge attempt, and manufacturing a merge to
|
||||
observe the merge guard is a worse idea than the gap it would close.
|
||||
not occur — and the report says so rather than presenting a zero as a verdict.
|
||||
|
||||
For the two zeroes here, what is established and what is not, kept apart deliberately.
|
||||
**Established:** both script bodies work. `pretooluse-nav-guard` and `pretooluse-merge-consent` are
|
||||
each driven to their deciding branch in `scripts/tests/test_hook_fire_log.py` — a `deny` on an
|
||||
`/iptv/` URL and an `ask` on a merge call — emitting the correct decision with the instrumentation
|
||||
in place. **Not established:** that the harness would dispatch to them. Those tests invoke the
|
||||
scripts directly, so they bypass registration and matcher dispatch entirely; a typo in
|
||||
`.claude/settings.json`, a settings file that never loaded, or a matcher that does not match would
|
||||
leave both tests green while the production zero still meant broken wiring. A working script is a
|
||||
necessary condition, not the finding.
|
||||
|
||||
So these two zeroes remain genuinely ambiguous, and neither can be resolved without the thing that
|
||||
resolves it: a live browser session, or a real merge attempt. Manufacturing a merge to observe the
|
||||
merge guard is a worse idea than the gap it would close. Distinguishing the two meanings of zero
|
||||
stays a human judgement — `testing.hook-reports-its-own-execution` says so, and an earlier draft of
|
||||
this paragraph quietly contradicted it by treating "the script works" as "the wiring works".
|
||||
|
||||
**The measurement earned its keep on its first run.** `pretooluse-agent-model` was recorded deciding
|
||||
`no-op` on an `Agent` dispatch where `ask` was expected. Previously that would have been an
|
||||
|
||||
+84
-36
@@ -107,7 +107,12 @@ etv_hook_fire_record() {
|
||||
"$(etv_hook_fire_scrub "${6:-}")" \
|
||||
"$(etv_hook_fire_scrub "${7:-}")" 2>/dev/null) || return 0
|
||||
|
||||
printf '%s\n' "$line" >> "$file" 2>/dev/null || true
|
||||
# ORDER MATTERS: `2>` BEFORE `>>`. Redirections are applied left to right, so
|
||||
# `printf ... >> "$file" 2>/dev/null` opens the file FIRST and bash reports a failure to open it
|
||||
# on the stderr still in force — the hook prints `Operation not permitted` at the harness. An
|
||||
# existing-but-unwritable log file is the reachable case; the fail-open test missed it by using a
|
||||
# path that dies at `mkdir` instead. Redirecting stderr first covers the open failure too.
|
||||
printf '%s\n' "$line" 2>/dev/null >> "$file" || true
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -131,12 +136,17 @@ etv_hook_fire_classify() {
|
||||
fi
|
||||
|
||||
if [ -n "$out" ]; then
|
||||
# `[A-Za-z]` then lowercased, not `[a-z]`: a hook printing `"permissionDecision":"Deny"` fell
|
||||
# through the lowercase-only class and was recorded as `output` — a real decision filed as
|
||||
# unclassified prose.
|
||||
d=$(printf '%s' "$out" | sed -n 's/.*"permissionDecision"[[:space:]]*:[[:space:]]*"\([A-Za-z-]*\)".*/\1/p' | head -n1)
|
||||
[ -z "$d" ] && d=$(printf '%s' "$out" | sed -n 's/.*"decision"[[:space:]]*:[[:space:]]*"\([A-Za-z-]*\)".*/\1/p' | head -n1)
|
||||
d=$(printf '%s' "$d" | tr 'A-Z' 'a-z')
|
||||
|
||||
# A NON-CANONICAL VALUE IS RECORDED AS SUCH, not normalised into a valid one. An earlier version
|
||||
# lowercased whatever it found, so `"permissionDecision":"Deny"` was filed as a clean `deny` —
|
||||
# manufacturing a decision the harness may never have honoured. The documented values are
|
||||
# lowercase; anything else is a hook bug, and the log should say so rather than launder it.
|
||||
case "$d" in
|
||||
allow|deny|ask|block|"") ;;
|
||||
*) d="unrecognized" ;;
|
||||
esac
|
||||
# `additionalContext` with no decision (design-sync-reminder's `start` path) informs, it does
|
||||
# not gate. Naming it distinctly keeps it out of the allow/deny counts. Matched WITH its quotes
|
||||
# and colon — a bare substring test also fired on human prose that merely used the word.
|
||||
@@ -144,21 +154,19 @@ etv_hook_fire_classify() {
|
||||
[ -z "$d" ] && d="output"
|
||||
fi
|
||||
|
||||
# Exit 2 is the harness's non-JSON block channel. No hook here uses it today; it is classified
|
||||
# anyway so that a hook which starts using it is not silently recorded as a no-op.
|
||||
if [ "$code" = "2" ] && [ -z "$d" ]; then d="deny-exit2"; fi
|
||||
# Exit 2 is the harness's block channel and it DOMINATES: the call is blocked whatever the JSON
|
||||
# said. Recording a printed `allow` here would report a permit for an invocation that was refused,
|
||||
# which is the one direction a log of security decisions must never be wrong in.
|
||||
if [ "$code" = "2" ]; then printf 'deny-exit2'; return 0; fi
|
||||
|
||||
[ -z "$d" ] && d="no-op"
|
||||
|
||||
# A non-zero status NO LONGER OVERWRITES a parsed decision. It used to, so a hook that printed a
|
||||
# real `deny` and then exited 1 was recorded as `error` — the status erasing the decision, when
|
||||
# the status already has its own field in the record. `error` now means only "it failed and said
|
||||
# nothing classifiable".
|
||||
if [ "$code" != "0" ] && [ "$code" != "2" ]; then
|
||||
case "$d" in
|
||||
no-op|output) d="error" ;;
|
||||
*) d="${d}+error" ;;
|
||||
esac
|
||||
fi
|
||||
# A non-zero status does NOT annotate a parsed decision. It used to overwrite one (`deny` + exit 1
|
||||
# recorded as `error`), and the first correction over-swung the other way and appended `+error` —
|
||||
# inventing a composite state the harness does not report. The status already has its own field in
|
||||
# the record, so the decision field states the decision and nothing else. `error` means only "it
|
||||
# failed and said nothing classifiable".
|
||||
if [ "$code" != "0" ] && [ "$d" = "no-op" ]; then d="error"; fi
|
||||
|
||||
printf '%s' "$d"
|
||||
}
|
||||
@@ -258,16 +266,33 @@ etv_hook_fire_begin() {
|
||||
|
||||
# SIGNALS, not just EXIT. Bash runs no EXIT trap for an untrapped fatal signal, so a hook killed
|
||||
# by the harness timeout would have its already-printed decision discarded along with the temp
|
||||
# file: measured at 52 bytes delivered before instrumentation and 0 after. Trapping the signals
|
||||
# makes bash run the handler and then the EXIT trap, which replays. Every `capture`-mode hook
|
||||
# today prints and exits immediately, so the window is sub-millisecond — but the constraint is
|
||||
# invisible to a future editor, so it is enforced here rather than relied upon.
|
||||
trap 'etv_hook_fire_end "$?"' EXIT INT TERM HUP
|
||||
# file: measured at 52 bytes delivered before instrumentation and 0 after.
|
||||
#
|
||||
# THE SIGNAL HANDLER MUST NOT `exit`, AND THIS IS THE IMPORTANT PART. A handler that ends in
|
||||
# `exit "$?"` re-raises whatever status the interrupted command happened to have — normally 0 for
|
||||
# a guard still gathering evidence. Measured on `prepush-donewhen.sh` mid-`curl`, with an unticked
|
||||
# Done-when box: uninstrumented, SIGTERM kills it and git ABORTS the push; with an `exit`-based
|
||||
# handler the hook returned 0 and git PUSHED TO MAIN. That converts a signal into consent, in the
|
||||
# permissive direction, in the guard that protects `main` — worse than the lost log line it was
|
||||
# added to fix. So the handler flushes, then restores the default disposition and re-raises the
|
||||
# signal, letting the process die the way it would have died. Pinned by
|
||||
# `test_a_SIGNALLED_stream_hook_still_FAILS`.
|
||||
trap 'etv_hook_fire_signal INT' INT
|
||||
trap 'etv_hook_fire_signal TERM' TERM
|
||||
trap 'etv_hook_fire_signal HUP' HUP
|
||||
trap 'etv_hook_fire_end "$?"' EXIT
|
||||
return 0
|
||||
}
|
||||
|
||||
etv_hook_fire_end() {
|
||||
# Flush and record, WITHOUT deciding how the process ends. Both the EXIT trap and the signal handler
|
||||
# call this; `ETV_HOOK_FIRE_FLUSHED` makes it idempotent, because on the signal path bash runs the
|
||||
# signal handler AND then the EXIT trap. Without the guard that wrote two contradictory `exit`
|
||||
# records for one invocation — a real `deny` followed by a phantom `no-op` — so the report
|
||||
# mis-histogrammed exactly the case the signal trap was added for.
|
||||
etv_hook_fire_flush() {
|
||||
local code="${1:-0}" out=""
|
||||
[ "${ETV_HOOK_FIRE_FLUSHED:-0}" = "1" ] && return 0
|
||||
ETV_HOOK_FIRE_FLUSHED=1
|
||||
|
||||
# RESTORE FIRST, UNCONDITIONALLY — then replay if there is anything to replay.
|
||||
#
|
||||
@@ -288,19 +313,26 @@ etv_hook_fire_end() {
|
||||
exec 1>&3 3>&- || true
|
||||
fi
|
||||
if [ -n "${ETV_HOOK_FIRE_STDOUT_TMP:-}" ]; then
|
||||
# Read through the FD, not the path — see the `exec 4<` comment in begin. `cat <&4` also avoids
|
||||
# the other trap: `out=$(cat ...)` strips trailing newlines, so replaying through a variable
|
||||
# delivers the hook's JSON one byte short of what it wrote, which every JSON parser downstream
|
||||
# accepts without complaint. Pinned by `test_stdout_is_replayed_BYTE_EXACT`.
|
||||
out=$(cat <&4 2>/dev/null || true) # for CLASSIFICATION; losing a trailing newline is harmless
|
||||
exec 4<&- 2>/dev/null || true
|
||||
# Replay the exact bytes from the file if the name still resolves, else from what the fd gave
|
||||
# us. The first path is byte-exact; the second is the rescue.
|
||||
if [ -r "${ETV_HOOK_FIRE_STDOUT_TMP:-}" ] && [ -s "${ETV_HOOK_FIRE_STDOUT_TMP:-}" ]; then
|
||||
cat "$ETV_HOOK_FIRE_STDOUT_TMP" 2>/dev/null || true
|
||||
elif [ -n "$out" ]; then
|
||||
printf '%s' "$out"
|
||||
# ONE read, used for BOTH the replay and the classification, so the two cannot disagree. They
|
||||
# did: the classifier read fd 4 while the replay preferred the file, so a hook that used fd 4
|
||||
# itself replayed its `deny` correctly to the harness and filed it in the log as `no-op` — the
|
||||
# log quietly contradicting the decision it exists to record.
|
||||
#
|
||||
# The `printf X` / `%X` dance preserves trailing newlines, which `$(...)` strips. Without it the
|
||||
# rescue path delivered 52 bytes where the hook wrote 53, and every JSON parser downstream
|
||||
# accepts the short form without complaint. Pinned by `test_stdout_is_replayed_BYTE_EXACT`.
|
||||
#
|
||||
# NO `2>/dev/null` ON THE `exec` — see the stdin comment. An earlier version of THIS line had
|
||||
# it, eight lines below the comment forbidding it, which is why the rule is now restated at
|
||||
# every `exec` rather than once.
|
||||
if [ -r "${ETV_HOOK_FIRE_STDOUT_TMP:-}" ]; then
|
||||
out=$( { cat "$ETV_HOOK_FIRE_STDOUT_TMP" 2>/dev/null; printf 'X'; } )
|
||||
else
|
||||
out=$( { cat <&4 2>/dev/null; printf 'X'; } ) # the file was unlinked; the fd still reads it
|
||||
fi
|
||||
out="${out%X}"
|
||||
exec 4<&- || true
|
||||
[ -n "$out" ] && printf '%s' "$out"
|
||||
fi
|
||||
|
||||
etv_hook_fire_record \
|
||||
@@ -309,12 +341,28 @@ etv_hook_fire_end() {
|
||||
"exit" "$code" "$(etv_hook_fire_classify "$out" "$code" "${ETV_HOOK_FIRE_MODE:-capture}")" || true
|
||||
|
||||
rm -f "${ETV_HOOK_FIRE_STDIN_TMP:-}" "${ETV_HOOK_FIRE_STDOUT_TMP:-}" 2>/dev/null || true
|
||||
ETV_HOOK_FIRE_STDOUT_TMP=""
|
||||
return 0
|
||||
}
|
||||
|
||||
etv_hook_fire_end() {
|
||||
local code="${1:-0}"
|
||||
etv_hook_fire_flush "$code"
|
||||
# Re-raise the hook's own status explicitly rather than relying on the trap preserving it. Bash
|
||||
# does not re-enter an EXIT trap, so this is not recursive.
|
||||
exit "$code"
|
||||
}
|
||||
|
||||
# The signal path. Flush, then DIE THE WAY THE PROCESS WOULD HAVE DIED: restore the default
|
||||
# disposition and re-raise, so the parent still sees "killed by signal N" rather than a status this
|
||||
# handler invented. `git` reads that distinction, and reporting 0 here let a push through.
|
||||
etv_hook_fire_signal() {
|
||||
local sig="${1:-TERM}"
|
||||
etv_hook_fire_flush "$?"
|
||||
trap - INT TERM HUP EXIT
|
||||
kill -s "$sig" "$$"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
# Read side: the report
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
|
||||
@@ -528,9 +528,12 @@ def _normalise_stderr(err: bytes) -> bytes:
|
||||
transparency. Only the script path and `line N:` are normalised — narrowly, so that a genuine
|
||||
difference in the message body still fails.
|
||||
"""
|
||||
err = re.sub(rb"[^\s:]*/[^\s:]*\.sh:", b"<script>:", err)
|
||||
err = re.sub(rb"line \d+:", b"line <n>:", err)
|
||||
return err
|
||||
# The two fields are normalised TOGETHER, as one anchored prefix, not independently. A global
|
||||
# `line \d+:` substitution also rewrites application text that happens to contain that phrase,
|
||||
# and cold review demonstrated it collapsing two genuinely different diagnostics ("highest
|
||||
# private fd line 0" vs "line 4") into one — hiding exactly the kind of fd-state difference this
|
||||
# comparison exists to catch.
|
||||
return re.sub(rb"[^\s:]*/[^\s:]*\.sh: line \d+:", b"<script>: line <n>:", err)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hook", hook_scripts(), ids=lambda h: h.stem)
|
||||
@@ -966,13 +969,19 @@ def test_output_survives_a_SIGTERM(sandbox):
|
||||
@pytest.mark.parametrize(
|
||||
"emit,code,expected",
|
||||
[
|
||||
# Uppercase: a real decision was filed as unclassified prose because the class was [a-z] only.
|
||||
(r'{\"permissionDecision\":\"Deny\"}', 0, "deny"),
|
||||
# A non-zero status must not ERASE a decision the hook actually printed; the status has its
|
||||
# own field in the record.
|
||||
(r'{\"permissionDecision\":\"deny\"}', 1, "deny+error"),
|
||||
# ...but a failure with nothing classifiable is still an error.
|
||||
# A NON-CANONICAL value is recorded as non-canonical, not laundered into a valid decision.
|
||||
# This case went both ways before settling: first filed as unclassified prose, then
|
||||
# lowercased into a clean `deny` (manufacturing a decision the harness may never honour).
|
||||
(r'{\"permissionDecision\":\"Deny\"}', 0, "unrecognized"),
|
||||
# A non-zero status neither ERASES a printed decision nor annotates it. The status has its
|
||||
# own field; the decision field states the decision and nothing else.
|
||||
(r'{\"permissionDecision\":\"deny\"}', 1, "deny"),
|
||||
# A failure with nothing classifiable IS an error.
|
||||
("", 1, "error"),
|
||||
# Exit 2 is the harness's block channel and DOMINATES the printed JSON. Recording the
|
||||
# printed `allow` would report a permit for a call that was actually refused — the one
|
||||
# direction a log of security decisions must never be wrong in.
|
||||
(r'{\"permissionDecision\":\"allow\"}', 2, "deny-exit2"),
|
||||
],
|
||||
)
|
||||
def test_the_classifier_does_not_MISREPORT(sandbox, emit, code, expected):
|
||||
@@ -1082,9 +1091,13 @@ def test_DELETING_the_replay_makes_the_differential_go_RED(sandbox, positives, t
|
||||
root, env = sandbox
|
||||
mutated = tmp_path / "hook-fire-log.sh"
|
||||
text = SINK.read_text()
|
||||
marker = ' cat "$ETV_HOOK_FIRE_STDOUT_TMP" 2>/dev/null || true'
|
||||
assert marker in text, "the replay line has moved; this mutation no longer targets it"
|
||||
mutated.write_text(text.replace(marker, " : # MUTATED: replay removed", 1))
|
||||
marker = ''' [ -n "$out" ] && printf '%s' "$out"'''
|
||||
assert marker in text, (
|
||||
"the replay line has moved; this mutation no longer targets it. Retarget it rather than "
|
||||
"loosening the match — a mutation that silently stops mutating proves nothing, which is "
|
||||
"the whole failure class this file exists to catch."
|
||||
)
|
||||
mutated.write_text(text.replace(marker, " : # MUTATED: replay removed", 1))
|
||||
|
||||
hook = tmp_path / "victim.sh"
|
||||
hook.write_text(
|
||||
@@ -1100,3 +1113,171 @@ def test_DELETING_the_replay_makes_the_differential_go_RED(sandbox, positives, t
|
||||
"the mutation did not actually disarm the replay, so this proof establishes nothing: "
|
||||
f"stdout={p.stdout!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_a_SIGNALLED_stream_hook_still_FAILS(sandbox):
|
||||
"""A signal must not become consent. THE regression from the round-2 signal trap.
|
||||
|
||||
Measured on the real guard: `prepush-donewhen.sh` SIGTERMed mid-`curl` exits -15 without
|
||||
instrumentation, so git aborts the push; with an `exit "$?"`-based signal handler it returned 0
|
||||
and git PUSHED TO MAIN, because `$?` at signal time was the status of whatever command was
|
||||
running — 0 for a guard still gathering evidence.
|
||||
|
||||
`test_output_survives_a_SIGTERM` could not see it: that test asserts stdout CONTENT and never
|
||||
reads the return code, and it drives a capture-mode hook, so no exit-code guard is ever
|
||||
signalled. This one asserts the only thing git looks at.
|
||||
"""
|
||||
import signal
|
||||
import time
|
||||
|
||||
root, env = sandbox
|
||||
for sig, name in ((signal.SIGTERM, "TERM"), (signal.SIGINT, "INT"), (signal.SIGHUP, "HUP")):
|
||||
hook = root / f"sig-{name}.sh"
|
||||
hook.write_text(
|
||||
"#!/usr/bin/env bash\nset -uo pipefail\n"
|
||||
f'. "{SINK}"\n'
|
||||
f'etv_hook_fire_begin sig{name} "" stream || true\n'
|
||||
"input=$(cat)\n"
|
||||
"sleep 30\n"
|
||||
"exit 1\n"
|
||||
)
|
||||
payload = root / f"sig-{name}.json"
|
||||
payload.write_bytes(b'{"tool_name":"Bash"}')
|
||||
with open(payload, "rb") as fh:
|
||||
p = subprocess.Popen(["bash", str(hook)], stdin=fh, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, cwd=str(root), env=env)
|
||||
time.sleep(1.5)
|
||||
p.send_signal(sig)
|
||||
p.communicate(timeout=30)
|
||||
|
||||
assert p.returncode != 0, (
|
||||
f"a hook killed by SIG{name} reported SUCCESS ({p.returncode}). git reads this status: "
|
||||
"for a pre-push guard that is the difference between aborting the push and letting it "
|
||||
"through, so the instrumentation would have turned a killed guard into consent."
|
||||
)
|
||||
assert p.returncode == -sig, (
|
||||
f"SIG{name}: expected death by signal ({-sig}), got {p.returncode}. The handler is "
|
||||
"inventing an exit status instead of re-raising."
|
||||
)
|
||||
|
||||
|
||||
def test_the_exit_record_is_written_ONCE_on_the_signal_path(sandbox):
|
||||
"""Bash runs the signal handler AND then the EXIT trap, so the flush must be idempotent.
|
||||
|
||||
Without the guard this wrote two contradictory `exit` records for one invocation — a real
|
||||
decision followed by a phantom `no-op` — and the report histograms exit records, so the product
|
||||
mis-reported precisely the case the signal trap was added to capture.
|
||||
"""
|
||||
import signal
|
||||
import time
|
||||
|
||||
root, env = sandbox
|
||||
logdir = root / "log-signal-once"
|
||||
hook = root / "sigonce.sh"
|
||||
hook.write_text(
|
||||
"#!/usr/bin/env bash\nset -uo pipefail\n"
|
||||
f'. "{SINK}"\n'
|
||||
'etv_hook_fire_begin sigonce "" capture || true\n'
|
||||
"input=$(cat)\n"
|
||||
r'printf "{\"hookSpecificOutput\":{\"permissionDecision\":\"deny\"}}"' + "\n"
|
||||
"sleep 30\n"
|
||||
)
|
||||
payload = root / "sigonce.json"
|
||||
payload.write_bytes(b'{"session_id":"s1","tool_name":"Bash"}')
|
||||
with open(payload, "rb") as fh:
|
||||
p = subprocess.Popen(["bash", str(hook)], stdin=fh, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, cwd=str(root),
|
||||
env={**env, "ETV_HOOK_FIRE_LOG_DIR": str(logdir)})
|
||||
time.sleep(1.5)
|
||||
p.send_signal(signal.SIGTERM)
|
||||
out, _ = p.communicate(timeout=30)
|
||||
|
||||
records = (logdir / "s1.jsonl").read_text().splitlines()
|
||||
exits = [r for r in records if '"phase":"exit"' in r]
|
||||
assert len(exits) == 1, f"expected exactly one exit record, got {len(exits)}:\n" + "\n".join(records)
|
||||
assert '"decision":"deny"' in exits[0], f"the surviving record lost the decision: {exits[0]}"
|
||||
assert b'"permissionDecision":"deny"' in out, "the decision was not replayed to the harness"
|
||||
|
||||
|
||||
def test_no_exec_in_the_sink_carries_a_STDERR_REDIRECT():
|
||||
"""The rule that has now been broken twice, enforced instead of restated.
|
||||
|
||||
`exec` with redirections and no command applies them to the SHELL, permanently. `exec ... 2>/dev/null`
|
||||
therefore silences the hook's whole stderr rather than suppressing an error from that one
|
||||
redirection. It shipped once in the stdin replay (silencing every husky guard's user-facing
|
||||
output), was fixed, and was then reintroduced eight lines below the comment forbidding it.
|
||||
A grep is a weak detector in general; here the pattern is exact and the cost of missing it is a
|
||||
guard that blocks while explaining nothing.
|
||||
"""
|
||||
offenders = [
|
||||
f"{SINK.name}:{i}: {ln.strip()}"
|
||||
for i, ln in enumerate(SINK.read_text().splitlines(), 1)
|
||||
if re.match(r"\s*exec\s[^|&;#]*2>", ln) and not ln.lstrip().startswith("#")
|
||||
]
|
||||
assert not offenders, (
|
||||
"these `exec` lines carry a stderr redirection, which applies to the whole shell and "
|
||||
"silences the hook:\n " + "\n ".join(offenders)
|
||||
)
|
||||
|
||||
|
||||
def test_the_log_and_the_REPLAY_agree_when_the_hook_uses_fd_4(sandbox):
|
||||
"""Classification and replay must read the same bytes.
|
||||
|
||||
They did not: the classifier read fd 4 while the replay preferred the file, so a hook that used
|
||||
fd 4 for its own purposes replayed its `deny` correctly to the harness and filed it in the log
|
||||
as `no-op` — the record contradicting the decision it exists to record.
|
||||
"""
|
||||
root, env = sandbox
|
||||
logdir = root / "log-fd4"
|
||||
hook = root / "fd4.sh"
|
||||
hook.write_text(
|
||||
"#!/usr/bin/env bash\nset -uo pipefail\n"
|
||||
f'. "{SINK}"\n'
|
||||
'etv_hook_fire_begin fd4 "" capture || true\n'
|
||||
"input=$(cat)\n"
|
||||
'exec 4</dev/null\n' # the hook takes fd 4 for itself
|
||||
r'printf "{\"hookSpecificOutput\":{\"permissionDecision\":\"deny\"}}"' + "\n"
|
||||
)
|
||||
p = subprocess.run(["bash", str(hook)], input=b'{"session_id":"s1","tool_name":"Bash"}',
|
||||
capture_output=True, cwd=str(root),
|
||||
env={**env, "ETV_HOOK_FIRE_LOG_DIR": str(logdir)}, timeout=60)
|
||||
assert b'"permissionDecision":"deny"' in p.stdout, f"replay lost the decision: {p.stdout!r}"
|
||||
exits = [r for r in (logdir / "s1.jsonl").read_text().splitlines() if '"phase":"exit"' in r]
|
||||
assert '"decision":"deny"' in exits[0], (
|
||||
f"the harness saw a deny but the log recorded something else: {exits[0]}"
|
||||
)
|
||||
|
||||
|
||||
def test_an_UNWRITABLE_log_file_is_still_stderr_transparent(sandbox, tmp_path):
|
||||
"""Fail-open must be SILENT, not merely non-fatal.
|
||||
|
||||
`printf ... >> "$file" 2>/dev/null` looks like it suppresses a failure to open the log. It does
|
||||
not: redirections apply left to right, so bash opens the file first and reports the failure on
|
||||
the stderr still in force — the hook prints `Operation not permitted` straight at the harness.
|
||||
`test_logging_failure_does_not_break_the_hook` could not see it because its path dies at `mkdir`
|
||||
and never reaches an existing-but-unwritable destination.
|
||||
"""
|
||||
_root, env = sandbox
|
||||
logdir = tmp_path / "ro-log"
|
||||
logdir.mkdir()
|
||||
victim = logdir / "s1.jsonl"
|
||||
victim.write_text("")
|
||||
victim.chmod(0o400)
|
||||
|
||||
hook = tmp_path / "ro.sh"
|
||||
hook.write_text(
|
||||
"#!/usr/bin/env bash\nset -uo pipefail\n"
|
||||
f'. "{SINK}"\n'
|
||||
'etv_hook_fire_begin ro "" capture || true\n'
|
||||
"input=$(cat)\n"
|
||||
r'printf "{\"hookSpecificOutput\":{\"permissionDecision\":\"deny\"}}"' + "\n"
|
||||
)
|
||||
p = subprocess.run(["bash", str(hook)], input=b'{"session_id":"s1","tool_name":"Bash"}',
|
||||
capture_output=True, cwd=str(tmp_path),
|
||||
env={**env, "ETV_HOOK_FIRE_LOG_DIR": str(logdir)}, timeout=60)
|
||||
assert p.returncode == 0
|
||||
assert p.stdout == b'{"hookSpecificOutput":{"permissionDecision":"deny"}}'
|
||||
assert p.stderr == b"", (
|
||||
"an unwritable log leaked a diagnostic to the harness. Observability that cannot write must "
|
||||
f"be silent, not chatty: {p.stderr!r}"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user