#!/bin/sh
# The credential store end to end against a fake server, with a private HOME:
# pic login seals a sentinel key (typed on a terminal with echo off, or piped
# on stdin), a request sends exactly that key, the terminal interface asks for
# the passphrase once and hands the key to its request child, a wrong
# passphrase fails cleanly, /login in the interface serves its requests, the
# environment overrides the store, pic keys
# shows names only, logout removes the key, and the sentinel's bytes appear
# nowhere else: not in ~/.pic/pic.sqlite (or its WAL), the journal, any
# output, a terminal transcript, or pic export. --no-faults (the release
# build): the cases that feed the passphrase through PIC_TEST_PASSPHRASE,
# which only the dev build reads, are skipped; the terminal cases run.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
DRIVE=${DRIVE:?set DRIVE to the pty_drive binary}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
S=$(cd "$(dirname "$0")/streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-creds.XXXXXX")
T=$(cd "$T" && pwd -P)
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
mkdir "$T/home" "$T/ws" "$T/log" "$T/out"
unset FAKE_API_KEY PIC_TEST_PASSPHRASE ANTHROPIC_API_KEY
export HOME="$T/home" PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0 PIC_MODELS_FILE="$T/models.json" T
export PIC_NO_NATIVE_CLIPBOARD=1
SENTINEL="pic-creds-sentinel-$$-5e1f0c"
PASS="pic-creds-passphrase-$$"
OTHER="pic-creds-env-key-$$"

"$SERVER" "$T/port" "$T/log" 120 "sse:$S/text.sse" &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 600 ] || fail "server did not start"; sleep 0.05; done
printf '{"providers":{"fake":{"baseUrl":"http://127.0.0.1:%s","api":"anthropic-messages","apiKey":"$FAKE_API_KEY","models":[{"id":"m","contextWindow":200000}]}}}' \
    "$(cat "$T/port")" > "$T/models.json"

# (A variable set in front of a shell function stays set after it in some
# shells, so those cases set theirs in a subshell.)
# Without a terminal of its own (its own session): a stray passphrase prompt
# fails at once instead of waiting on whatever terminal runs the suite.
notty() { perl -MPOSIX=setsid -e 'setsid() or die "setsid"; exec @ARGV or die "exec"' "$@"; }
n=0
pic() { # NAME ARGS...: pic with no terminal; stdout and stderr kept in $T/out/NAME.{out,err}
    name=$1
    shift
    notty "$PIC" --db "$T/j" --workspace "$T/ws" --model fake/m "$@" > "$T/out/$name.out" 2> "$T/out/$name.err"
}
drive() { # NAME ARGS...: pic on a pseudo-terminal, the script on stdin; the transcript in $T/out/NAME.tx
    name=$1
    shift
    "$DRIVE" "$T/out/$name.tx" 80 24 "$PIC" --db "$T/j" --workspace "$T/ws" --model fake/m "$@"
}
screen() { perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$1" | grep -v '^\s*$' | tail -8; }
requests() { ls "$T/log" | wc -l | tr -d ' '; }
sent_key() { sed -n 's/^x-api-key: //p' "$T/log/$1.req" | tr -d '\r'; }

# Nothing stored: pic keys says so, and a request names pic login.
pic keys0 keys || fail "keys: $(cat "$T/out/keys0.err")"
grep -q 'No stored keys' "$T/out/keys0.out" || fail "keys: $(cat "$T/out/keys0.out")"
pic nokey -p hello < /dev/null && fail "nokey: a request ran without a key"
grep -q 'FAKE_API_KEY is not set and no key is stored for fake: run `pic login fake`' "$T/out/nokey.err" ||
    fail "nokey: $(cat "$T/out/nokey.err")"
[ "$(requests)" = 0 ] || fail "nokey: a request reached the server"
printf 'PASS: with nothing stored, a request names pic login\n'

# pic login on a terminal: the key and the new passphrase (twice) are typed
# with echo off, so none of them is in the transcript.
drive login login fake <<EOF || fail "login: $(screen "$T/out/login.tx")"
expect API key for fake:
send $SENTINEL\r
expect New passphrase for pic's credential store:
send $PASS\r
expect Same passphrase again:
send $PASS\r
expect Saved the API key for fake
EOF
printf 'PASS: pic login on a terminal, key and passphrase typed with echo off\n'

# The terminal interface: the first message asks for the passphrase (on the
# terminal, before the request child starts); the child has no terminal and
# no passphrase in its environment, so the key reaches the server only by
# the inherited pipe.
drive tui --tui-mode regular <<EOF || fail "tui: $(screen "$T/out/tui.tx")"
expect pic fake/m
send hello\r
expect Passphrase for pic's credential store:
send $PASS\r
expect Hello, "world"
send \x04
expect pic: conversation
EOF
[ "$(requests)" = 1 ] || fail "tui: $(requests) requests"
[ "$(sent_key 1)" = "$SENTINEL" ] || fail "tui: the server got another key"
printf 'PASS: the terminal interface asks once and hands the key to its request child\n'

# A wrong passphrase fails cleanly: no request, an error naming it.
drive wrong -p again <<EOF && fail "wrong: the request ran"
expect Passphrase for pic's credential store:
send not-$PASS\r
expect wrong passphrase for the credential store
EOF
grep -q 'wrong passphrase for the credential store' "$T/out/wrong.tx" || fail "wrong: $(screen "$T/out/wrong.tx")"
[ "$(requests)" = 1 ] || fail "wrong: a request reached the server"
printf 'PASS: a wrong passphrase fails cleanly\n'

# The environment overrides the store, and the store is not even opened.
(FAKE_API_KEY="$OTHER" && export FAKE_API_KEY && pic env -p again < /dev/null) || fail "env: $(cat "$T/out/env.err")"
[ "$(requests)" = 2 ] || fail "env: $(requests) requests"
[ "$(sent_key 2)" = "$OTHER" ] || fail "env: the variable did not win"
printf 'PASS: the environment variable overrides the store\n'

if [ "$FAULTS" = yes ]; then
    # Piped: the key on stdin, the passphrase from the dev build's test hook.
    printf '%s\n' "$SENTINEL" | PIC_TEST_PASSPHRASE="$PASS" notty "$PIC" login fake > "$T/out/pipe.out" 2> "$T/out/pipe.err" ||
        fail "pipe login: $(cat "$T/out/pipe.err")"
    (PIC_TEST_PASSPHRASE="$PASS" && export PIC_TEST_PASSPHRASE && pic print -p 'once more' < /dev/null) || fail "print: $(cat "$T/out/print.err")"
    [ "$(requests)" = 3 ] || fail "print: $(requests) requests"
    [ "$(sent_key 3)" = "$SENTINEL" ] || fail "print: the server got another key"
    (PIC_TEST_PASSPHRASE="wrong-$PASS" && export PIC_TEST_PASSPHRASE && pic wrong2 -p 'no' < /dev/null) && fail "wrong2: the request ran"
    grep -q 'wrong passphrase for the credential store' "$T/out/wrong2.err" || fail "wrong2: $(cat "$T/out/wrong2.err")"
    [ "$(requests)" = 3 ] || fail "wrong2: a request reached the server"
    printf 'PASS: a piped key, a request with it, a wrong passphrase (test hook)\n'
fi

# /login in the terminal interface: the key and the passphrase on its
# terminal, in its own process, so the message after it asks for nothing.
before=$(requests)
drive tuilogin --tui-mode regular <<EOF || fail "tui /login: $(screen "$T/out/tuilogin.tx")"
expect pic fake/m
send /login\r
expect API key for fake:
send $SENTINEL\r
expect Passphrase for pic's credential store:
send $PASS\r
expect Saved the API key for fake
send hi\r
expect Hello, "world"
send \x04
expect pic: conversation
EOF
[ "$(grep -c "Passphrase for pic's credential store" "$T/out/tuilogin.tx")" = 1 ] || fail "tui /login: asked twice"
[ "$(requests)" = $((before + 1)) ] || fail "tui /login: $(requests) requests"
[ "$(sent_key "$(requests)")" = "$SENTINEL" ] || fail "tui /login: the server got another key"
printf 'PASS: /login in the terminal interface, then a request without a second prompt\n'

# pic keys: the name and dates, never the value.
pic keys1 keys || fail "keys1: $(cat "$T/out/keys1.err")"
grep -q '^fake  *added [0-9-]* [0-9:]*  last used ' "$T/out/keys1.out" || fail "keys1: $(cat "$T/out/keys1.out")"
printf 'PASS: pic keys lists names and dates\n'

# Everything that could hold a copy, before logout removes the row.
pic export export < /dev/null || fail "export: $(cat "$T/out/export.err")"
pic exportpi export --pi - < /dev/null || fail "export --pi: $(cat "$T/out/exportpi.err")"
pic dump dump < /dev/null || fail "dump: $(cat "$T/out/dump.err")"
[ -s "$T/out/export.out" ] || fail "export: empty"

pic logout logout fake || fail "logout: $(cat "$T/out/logout.err")"
grep -q 'Removed the stored API key for fake' "$T/out/logout.out" || fail "logout: $(cat "$T/out/logout.out")"
pic keys2 keys || fail "keys2"
grep -q 'No stored keys' "$T/out/keys2.out" || fail "keys2: $(cat "$T/out/keys2.out")"
pic gone -p 'after logout' < /dev/null && fail "gone: a request ran after logout"
grep -q 'run `pic login fake`' "$T/out/gone.err" || fail "gone: $(cat "$T/out/gone.err")"
printf 'PASS: logout removes the key\n'

# The sentinel was sent (the test is live) and is nowhere but the server's log.
grep -rqF -- "$SENTINEL" "$T/log" || fail "leak: the sentinel never reached the server (test is broken)"
for f in "$HOME"/.pic/* "$T"/j* "$T"/ws/.pic/* "$T"/out/*; do
    [ -f "$f" ] || continue
    if grep -aqF -- "$SENTINEL" "$f"; then fail "leak: the key is in $f"; fi
    if grep -aqF -- "$PASS" "$f"; then fail "leak: the passphrase is in $f"; fi
done
ls "$HOME"/.pic/pic.sqlite > /dev/null || fail "leak check: no pic.sqlite"
printf 'PASS: the key appears nowhere but the request\n'
