Skip to content
pi-c Artifact [fd7b08b8ee]
Login

Artifact [fd7b08b8ee]

Artifact fd7b08b8ee8952785e7e8879a8f9d5c1f993b69af30a3dcc1cb26ed68148db92:


#!/bin/sh
# A required PostToolUse hook fails closed: when it redacts, only the redacted
# text reaches a request; when it times out, exits non-zero, prints something
# that is not JSON or is cut off by a crash, the model sees a notice and never
# the output. The same holds for a command the user runs (pic bash, the
# terminal's !). A required PreToolUse hook that fails blocks the call. The
# live event stream may carry the raw output (display only); the journal, the
# requests and the hook's transcript_path rows never do. --no-faults skips the
# crash cases (release has no crash points).
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
SQL="$(dirname "$SERVER")/sqlite3"
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
S=$(cd "$(dirname "$0")/streams" && pwd)
T=$(cd "$(mktemp -d "${TMPDIR:-/tmp}/pic-guard.XXXXXX")" && pwd -P)
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null || :; [ -n "${KEEP:-}" ] && { echo "kept $T" >&2; return; }; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
export HOME="$T/home" ANTHROPIC_API_KEY=pic-guard-test-key PIC_PI_EXPORT=0 PIC_MODEL_CATALOG=offline
unset PIC_HOOK PIC_HOOK_OWNER 2>/dev/null || :
mkdir -p "$HOME/.pic" "$T/ws" "$T/h"
WS="$T/ws"
DB="$T/j"
SECRET=sk-guard-SECRET-4242
printf 'the key is %s\n' "$SECRET" > "$WS/key.txt"
pic() { "$PIC" --db "$DB" --workspace "$WS" --model fake/m "$@"; }

# serve SPEC...: a fresh fake server, its requests in $T/log.
serve() {
    [ -n "$spid" ] && kill "$spid" 2>/dev/null && wait "$spid" 2>/dev/null || :
    rm -rf "$T/log" "$T/port"
    mkdir "$T/log"
    "$SERVER" "$T/port" "$T/log" 120 "$@" &
    spid=$!
    i=0
    while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 100 ] || fail "server"; sleep 0.05; done
    printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$ANTHROPIC_API_KEY","models":[{"id":"m","input":["text","image"]}]}}}' \
        "$(cat "$T/port")" > "$T/models.json"
}
export PIC_MODELS_FILE="$T/models.json"
tool_sse() { # tool_sse FILE ID NAME ESCAPED_JSON
    cat > "$1" <<EOF
event: message_start
data: {"type":"message_start","message":{"id":"msg_$2","type":"message","role":"assistant","model":"m","content":[],"stop_reason":null,"usage":{"input_tokens":5,"output_tokens":1}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_$2","name":"$3","input":{}}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"$4"}}

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":9}}

event: message_stop
data: {"type":"message_stop"}

EOF
}
text="sse:$S/text.sse"
tool_sse "$T/leak.sse" leak bash '{\"command\": \"cat key.txt\"}'
tool_sse "$T/plain.sse" plain bash '{\"command\": \"echo plain-output-77\"}'
tool_sse "$T/touch.sse" touch bash '{\"command\": \"touch ran\"}'

# The fake guard: what $T/h/behave says, on its input.
cat > "$T/h/hook.sh" <<'SH'
d=$(dirname "$0")
cat > "$d/in.$$"
echo x >> "$d/fired"
case "$(cat "$d/behave" 2>/dev/null || :)" in
redact) if grep -q 'sk-guard-SECRET' "$d/in.$$"; then
        sed 's/.*"content":"\(.*\)","is_error".*/\1/; s/sk-guard-SECRET-[0-9]*/[REDACTED]/g' "$d/in.$$" > "$d/text.$$"
        printf '{"hookSpecificOutput":{"hookEventName":"PostToolUse","updatedToolOutput":{"content":[{"type":"text","text":"%s"}]}}}\n' \
            "$(cat "$d/text.$$")"
    fi ;;
replace) printf '{"hookSpecificOutput":{"hookEventName":"PostToolUse","updatedToolOutput":{"content":[{"type":"text","text":"replaced-text"}]}}}\n' ;;
sleep) sleep 30 ;;
fail) echo broken >&2; exit 1 ;;
garbage) echo 'this is not json' ;;
quiet) : ;;
esac
rm -f "$d/in.$$" "$d/text.$$"
exit 0
SH
behave() { printf '%s\n' "$1" > "$T/h/behave"; rm -f "$T/h/fired"; }
fired() { [ -e "$T/h/fired" ] && wc -l < "$T/h/fired" | tr -d ' ' || echo 0; }
# hooks EVENT REQUIRED [SECONDS]: one hook on Bash for EVENT, timeout SECONDS (1 s when not given).
hooks() {
    printf '{"hooks": {"%s": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "sh %s/h/hook.sh", "timeout": %s%s}]}]}}\n' \
        "$1" "$T" "${3:-1}" "${2:+, \"required\": $2}" > "$HOME/.pic/hooks.json"
}
# no_secret WHAT: no request, the journal, nor the hooks' transcript rows hold it.
no_secret() {
    if grep -l "$SECRET" "$T"/log/*.req > /dev/null 2>&1; then fail "$1: the output reached a request"; fi
    if "$PIC" --db "$DB" --workspace "$WS" dump | grep -q "$SECRET"; then fail "$1: the output is journaled"; fi
    if [ -e "$HOME/.pic/pic.sqlite" ] && "$SQL" "$HOME/.pic/pic.sqlite" \
        "SELECT CAST(sqlar_uncompress(line, sz) AS TEXT) FROM picu_pi_session_line" | grep -q "$SECRET"; then
        fail "$1: the output is in ~/.pic/pic.sqlite"
    fi
}
last_req() { printf '%s/log/%s' "$T" "$(ls "$T/log" | grep '\.req$' | sort -n | tail -1)"; }
withheld='\[output withheld: the required hook sh '

# ---- the normal case: a required hook redacts ----------------------------
hooks PostToolUse true
behave redact
serve "sse:$T/leak.sse" "$text"
pic --json ask 'show the key' > "$T/ev" 2> "$T/err" || fail "redact: $(cat "$T/err")"
grep -qF 'the key is [REDACTED]' "$T/log/2.req" || fail "redact: the model saw $(tail -c 400 "$T/log/2.req")"
no_secret redact
[ "$(fired)" = 1 ] || fail "redact: the hook ran $(fired) times"
pic check > /dev/null || fail "redact: check"
printf 'PASS: a required PostToolUse hook that redacts: only the redacted text reaches the model\n'

# Display only: the live tool_execution_end carries what the tool printed,
# as the terminal, pic attach and a phone may show it while the call runs.
grep '"type":"tool_execution_end"' "$T/ev" | grep -q "$SECRET" ||
    fail "live: the event stream lacks the raw output: $(grep tool_execution_end "$T/ev")"
printf 'PASS: the live event stream shows the raw output; requests and the journal never do\n'

# A required hook that finishes and says nothing keeps the output.
behave quiet
serve "sse:$T/plain.sse" "$text"
pic ask 'echo' > /dev/null 2> "$T/err" || fail "quiet: $(cat "$T/err")"
grep -q 'plain-output-77' "$T/log/2.req" || fail "quiet: the output was lost: $(tail -c 400 "$T/log/2.req")"
grep -q 'output withheld' "$T/log/2.req" && fail "quiet: withheld though the hook finished"
pic dump | grep -q '^effect .*| plain-output-77' || fail "quiet: journal $(pic dump | grep '^effect')"
pic check > /dev/null || fail "quiet: check"
printf 'PASS: a required hook that finishes without output leaves the result as it was\n'

# ---- failing hooks withhold the output -----------------------------------
for how in sleep fail garbage; do
    behave $how
    serve "sse:$T/leak.sse" "$text"
    pic ask 'show the key' > /dev/null 2> "$T/err" || fail "$how: $(cat "$T/err")"
    grep -q "$withheld" "$T/log/2.req" || fail "$how: no notice: $(tail -c 400 "$T/log/2.req")"
    no_secret "$how"
    pic check > /dev/null || fail "$how: check"
done
printf 'PASS: a required hook that times out, exits 1 or prints what is not JSON withholds the output\n'

# ---- a withheld result's images are withheld too --------------------------
# A read that returns an image, under a required hook on Read: a hook that times out leaves the
# notice and no image part; one that finishes quietly keeps text and image; one that replaces the
# text drops the image the replacement does not carry.
PNG_B64='iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=='
printf '%s' "$PNG_B64" | base64 -d > "$WS/dot.png" 2> /dev/null || printf '%s' "$PNG_B64" | base64 -D > "$WS/dot.png"
printf '{"hooks": {"PostToolUse": [{"matcher": "Read", "hooks": [{"type": "command", "command": "sh %s/h/hook.sh", "timeout": 1, "required": true}]}]}}\n' \
    "$T" > "$HOME/.pic/hooks.json"
img_run() { # BEHAVE: a read of dot.png under the hook, then the final reply
    behave "$1"
    serve "sse:$S/../image-streams/read_png.sse" "$text"
    pic ask 'look' > /dev/null 2> "$T/err" || fail "images $1: $(cat "$T/err")"
}
img_run sleep
grep -q "$withheld" "$T/log/2.req" || fail "images: no notice: $(tail -c 400 "$T/log/2.req")"
grep -q '"type":"image"' "$T/log/2.req" && fail "images: a withheld result still carried its image"
pic check > /dev/null || fail "images: check"
img_run quiet
grep -q '"type":"image"' "$T/log/2.req" || fail "images: a result the hook passed lost its image: $(tail -c 400 "$T/log/2.req")"
img_run replace
grep -q 'replaced-text' "$T/log/2.req" || fail "images: no replacement: $(tail -c 400 "$T/log/2.req")"
grep -q '"type":"image"' "$T/log/2.req" && fail "images: a replaced result still carried its image"
pic check > /dev/null || fail "images: check after replace"
printf 'PASS: a withheld or replaced result carries no image; a result a required hook passed keeps its image\n'

# Not required: a failing hook is ignored, as before.
hooks PostToolUse
behave fail
serve "sse:$T/leak.sse" "$text"
pic ask 'show the key' > /dev/null 2> "$T/err" || fail "optional: $(cat "$T/err")"
grep -q "$SECRET" "$T/log/2.req" || fail "optional: the output was withheld: $(tail -c 400 "$T/log/2.req")"
printf 'PASS: a hook that is not required and fails is ignored\n'

# ---- a required PreToolUse hook that fails blocks the call ---------------
hooks PreToolUse true
behave fail
rm -f "$WS/ran"
serve "sse:$T/touch.sse" "$text"
pic ask 'touch it' > /dev/null 2> "$T/err" || fail "pre: $(cat "$T/err")"
[ ! -e "$WS/ran" ] || fail "pre: the call ran"
grep -q 'the required hook sh .* did not finish' "$T/log/2.req" || fail "pre: $(tail -c 400 "$T/log/2.req")"
behave quiet
serve "sse:$T/touch.sse" "$text"
pic ask 'touch it' > /dev/null 2> "$T/err" || fail "pre ok: $(cat "$T/err")"
[ -e "$WS/ran" ] || fail "pre: a finished hook kept the call from running"
pic check > /dev/null || fail "pre: check"
printf 'PASS: a required PreToolUse hook that fails blocks the call; one that finishes lets it run\n'

# ---- pic bash (and the terminal's !) -------------------------------------
hooks PostToolUse true
rm -f "$DB" "$DB-wal" "$DB-shm" "$HOME/.pic/pic.sqlite"
behave redact
out=$(pic bash 'cat key.txt' 2> "$T/err") || fail "bash: $(cat "$T/err")"
[ "$(fired)" = 1 ] || fail "bash: the hook ran $(fired) times"
printf '%s\n' "$out" | grep -qF 'the key is [REDACTED]' || fail "bash: printed $out"
pic --json bash -c 'cat key.txt' > "$T/bev" 2> "$T/err" || fail "bash --json: $(cat "$T/err")"
grep '"type":"response"' "$T/bev" | grep -qF 'the key is [REDACTED]' || fail "bash --json: $(cat "$T/bev")"
# A long output keeps its whole text for read (pic:bash/N): not once redacted.
pic bash -c "seq 1 4000; cat key.txt" > /dev/null 2> "$T/err" || fail "bash long: $(cat "$T/err")"
[ "$("$SQL" "$DB" 'SELECT count(*) FROM pic_bash WHERE full IS NOT NULL')" = 0 ] || fail "bash long: the whole output was kept"
behave fail
pic bash -c 'cat key.txt' > /dev/null 2> "$T/err" || fail "bash fail: $(cat "$T/err")"
serve "$text"
pic ask -c 'what did I run' > /dev/null 2> "$T/err" || fail "bash ask: $(cat "$T/err")"
grep -qF 'the key is [REDACTED]' "$T/log/1.req" || fail "bash: the model saw $(tail -c 600 "$T/log/1.req")"
grep -q "$withheld" "$T/log/1.req" || fail "bash fail: no notice: $(tail -c 600 "$T/log/1.req")"
no_secret bash
pic check > /dev/null || fail "bash: check"
printf 'PASS: a required PostToolUse hook runs on pic bash output (tool_name Bash) and fails closed\n'

# ---- crashes (development builds) -----------------------------------------
if [ "$FAULTS" = yes ]; then
    # crash_case NAME POINT BEHAVIOUR WANT RUNS: the job crashes at POINT, the
    # recovery finishes it; the last request holds WANT and never the secret.
    crash_case() {
        hooks PostToolUse true 15 # these test crashes, not the timeout: 1 s can pass under a loaded suite
        behave "$3"
        rm -f "$DB" "$DB-wal" "$DB-shm" "$HOME/.pic/pic.sqlite"
        serve "sse:$T/leak.sse" "$text"
        pic submit job 'show the key' > /dev/null
        if PIC_CRASH_AT="$2:1" "$PIC" --db "$DB" --workspace "$WS" --model fake/m run > /dev/null 2>&1; then
            fail "$1: no crash at $2"
        fi
        pic run > /dev/null 2> "$T/err" || fail "$1: recovery: $(cat "$T/err")"
        grep -q "$4" "$(last_req)" || fail "$1: the model saw $(tail -c 400 "$(last_req)")"
        no_secret "$1"
        [ "$(fired)" = "$5" ] || fail "$1: the hook ran $(fired) times"
        pic check > /dev/null || fail "$1: check"
    }
    # The tool finished, its hook not yet started: the recovery runs it.
    crash_case before-hook after-result redact 'the key is \[REDACTED\]' 1
    # Cut off with the output held back: the recovery's hook sees the notice.
    crash_case withheld after-withhold redact "$withheld" 1
    # Killed mid-run: never run again, and the output stays withheld.
    crash_case mid-hook after-hook-run redact "$withheld" 1
    # The hook finished, pic died before writing its answer.
    crash_case after-hook after-hook-row redact "$withheld" 1
    printf 'PASS: a crash before, during or after a required hook never lets the output into a request\n'
fi