#!/bin/sh
# Named keys and what pic remembers of each, against a fake server, with a
# private HOME: a provider's extra keys (--as), the active one (auth use),
# one run's (--key), a variable sealed once (auth import), logout of one key;
# each refusal read into its class (refused, out of credit, limited until a
# time, transient) with no blind retry of the first three and never another
# key on its own; the state recorded per key and shown by auth status before
# the next run; a variable's state reset when its value changes; the key each
# reply used in the journal; the RPC commands; and no key text anywhere but
# the requests. --no-faults (the release build): skipped whole, since the
# passphrase comes from PIC_TEST_PASSPHRASE, which only the dev build reads.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SERVER=${SERVER:?set SERVER to the fake_server binary}
SQLITE3=${SQLITE3:-sqlite3}
if [ "${1:-}" = --no-faults ]; then
    printf 'SKIP: keys needs the dev build (PIC_TEST_PASSPHRASE)\n'
    exit 0
fi
S=$(cd "$(dirname "$0")/streams" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-keys.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/out"
# No real key from the shell running the suite reaches this test.
for v in $(env | sed -nE 's/^([A-Za-z0-9_]*_(API_KEY|TOKEN))=.*/\1/p'); do unset "$v"; done
unset FAKE_API_KEY FAKE_API_KEY_2
PASS="pic-keys-passphrase-$$"
export HOME="$T/home" PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0 PIC_MODELS_FILE="$T/models.json" PIC_TEST_PASSPHRASE="$PASS"
K1="pic-keys-one-$$-a1"
K2="pic-keys-two-$$-b2"
K3="pic-keys-three-$$-c3"
K4="pic-keys-four-$$-f6"
E1="pic-keys-env-$$-d4"
E2="pic-keys-env-$$-e5"

round=0
serve() { # SPEC...: a fresh server for the next requests, its log in $T/log
    [ -n "$spid" ] && kill "$spid" 2>/dev/null || :
    [ -n "$spid" ] && wait "$spid" 2>/dev/null || :
    round=$((round + 1))
    rm -rf "$T/log" "$T/port"
    mkdir "$T/log"
    "$SERVER" "$T/port" "$T/log" 60 "$@" &
    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,"cost":{"input":3,"output":15}}]},"anthropic":{"baseUrl":"http://127.0.0.1:%s"}}}' \
        "$(cat "$T/port")" "$(cat "$T/port")" > "$T/models.json"
}
pic() { # NAME ARGS...: stdout and stderr in $T/out/NAME.{out,err}
    name=$1
    shift
    "$PIC" --db "$T/j" --workspace "$T/ws" --model fake/m "$@" > "$T/out/$name.out" 2> "$T/out/$name.err" < /dev/null
}
requests() { ls "$T/log" | wc -l | tr -d ' '; }
sent_key() { sed -n 's/^x-api-key: //p' "$T/log/$1.req" | tr -d '\r'; }
last_credential() { "$SQLITE3" "$T/j" "SELECT coalesce(credential, '-') FROM pic_generation ORDER BY id DESC LIMIT 1"; }
status() { pic "$1" auth status || fail "status $1: $(cat "$T/out/$1.err")"; }

printf '{"type":"error","error":{"type":"billing_error","message":"Your credit balance is too low to access the Anthropic API."}}' > "$T/billing.json"
printf '{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}' > "$T/auth.json"
printf '{"error":{"message":"You exceeded your current quota","type":"insufficient_quota","code":"insufficient_quota"}}' > "$T/quota.json"
printf '{"type":"error","error":{"type":"invalid_request_error","message":"Your credit balance is too low to access the Anthropic API. Please go to Plans & Billing."}}' > "$T/low.json"
printf '{"type":"error","error":{"type":"rate_limit_error","message":"Number of request tokens has exceeded your per-minute rate limit"}}' > "$T/rate.json"

serve "sse:$S/text.sse"
# The provider's own key and a named one, piped.
printf "%s\n" "$K1" | "$PIC" --db "$T/j" --workspace "$T/ws" login fake > "$T/out/login1.out" 2> "$T/out/login1.err" || fail "login: $(cat "$T/out/login1.err")"
printf '%s\n' "$K2" | "$PIC" --db "$T/j" --workspace "$T/ws" auth login fake --api-key --as second > "$T/out/login2.out" 2> "$T/out/login2.err" ||
    fail "login --as: $(cat "$T/out/login2.err")"
grep -q 'Saved the API key "second" for fake' "$T/out/login2.out" || fail "login --as: $(cat "$T/out/login2.out")"
grep -q 'Requests use "default"; pic auth use fake second makes this one active' "$T/out/login2.out" ||
    fail "login --as: $(cat "$T/out/login2.out")"
pic badlabel auth login fake --api-key --as 'No Good' && fail "a bad label was taken"
grep -q "label is 1-32" "$T/out/badlabel.err" || fail "badlabel: $(cat "$T/out/badlabel.err")"
status st1
grep -q '^fake  *default\*  *API key  *not checked yet' "$T/out/st1.out" || fail "st1: $(cat "$T/out/st1.out")"
grep -q '^fake  *second  *API key  *not checked yet' "$T/out/st1.out" || fail "st1: $(cat "$T/out/st1.out")"
printf 'PASS: login --as stores a named key beside the default; auth status lists both\n'

# Out of credit (Anthropic's billing error as a 402): one request, never
# retried, never another key; the plain message; recorded and shown.
serve "status:402:$T/billing.json"
pic credit -p hello && fail "credit: the request succeeded"
[ "$(requests)" = 1 ] || fail "credit: $(requests) requests (retried?)"
[ "$(sent_key 1)" = "$K1" ] || fail "credit: sent another key"
grep -q 'The key "default" for fake is out of credit (HTTP 402: Your credit balance is too low' "$T/out/credit.err" ||
    fail "credit: $(cat "$T/out/credit.err")"
[ "$(last_credential)" = fake ] || fail "credit: journal credential $(last_credential)"
status st2
grep -q '^fake  *default\*  *API key  *out of credit since [0-9:]* (HTTP 402)' "$T/out/st2.out" || fail "st2: $(cat "$T/out/st2.out")"
printf 'PASS: out of credit is one request, a plain message, remembered before the next run\n'

# auth use: the next request goes with the named key, and the journal says so.
pic use1 auth use fake third && fail "use: a key nobody stored was taken"
grep -q 'fake has no key named "third"' "$T/out/use1.err" || fail "use1: $(cat "$T/out/use1.err")"
pic use2 auth use fake second || fail "use2: $(cat "$T/out/use2.err")"
[ "$("$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT value FROM picu_setting WHERE key = 'activeKey:fake'")" = second ] || fail "use2: setting"
serve "sse:$S/text.sse"
pic second -p again || fail "second: $(cat "$T/out/second.err")"
[ "$(sent_key 1)" = "$K2" ] || fail "second: sent another key"
[ "$(last_credential)" = fake:second ] || fail "second: journal credential $(last_credential)"
status st3
grep -q '^fake  *second\*  *API key  *valid, checked just now' "$T/out/st3.out" || fail "st3: $(cat "$T/out/st3.out")"
grep -q '^fake  *default  *API key  *out of credit since' "$T/out/st3.out" || fail "st3: $(cat "$T/out/st3.out")"
printf 'PASS: auth use swaps the key; the journal records which one each reply used\n'

# --key for one run: the default again, the setting unchanged.
serve "sse:$S/text.sse"
pic once --key default -p 'one run' || fail "once: $(cat "$T/out/once.err")"
[ "$(sent_key 1)" = "$K1" ] || fail "once: --key was not used"
[ "$(last_credential)" = fake ] || fail "once: journal credential $(last_credential)"
[ "$("$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT value FROM picu_setting WHERE key = 'activeKey:fake'")" = second ] ||
    fail "once: the setting changed"
pic nokey --key nosuch -p 'x' && fail "nokey: a request ran with a key nobody stored"
grep -q 'no key "nosuch" for fake' "$T/out/nokey.err" || fail "nokey: $(cat "$T/out/nokey.err")"
printf 'PASS: --key picks a key for one run only\n'

# --key names the provider the model resolves to, a bare claude- id included,
# and a key that provider lacks is an error, never another key.
printf '%s\n' "$K1" | "$PIC" --db "$T/j" --workspace "$T/ws" login anthropic > /dev/null 2> "$T/out/login4.err" ||
    fail "login anthropic: $(cat "$T/out/login4.err")"
printf '%s\n' "$K4" | "$PIC" --db "$T/j" --workspace "$T/ws" auth login anthropic --api-key --as work > /dev/null 2> "$T/out/login4.err" ||
    fail "login anthropic: $(cat "$T/out/login4.err")"
serve "sse:$S/text.sse"
"$PIC" --db "$T/j" --workspace "$T/ws" --model claude-sonnet-4-5 --key work -p bare > "$T/out/bare.out" 2> "$T/out/bare.err" < /dev/null ||
    fail "bare: $(cat "$T/out/bare.err")"
[ "$(sent_key 1)" = "$K4" ] || fail "bare: --key was not used for a bare claude- id"
"$PIC" --db "$T/j" --workspace "$T/ws" --model claude-sonnet-4-5 --key nosuch -p bare > /dev/null 2> "$T/out/bare2.err" < /dev/null &&
    fail "bare2: ran with a key anthropic does not have"
grep -q 'no key "nosuch" for anthropic' "$T/out/bare2.err" || fail "bare2: $(cat "$T/out/bare2.err")"
[ "$(requests)" = 1 ] || fail "bare2: a request went out"
# A provider name with ':' (the separator of a key's name) is refused where it enters.
sed 's/"fake":{/"fa:ke":{/' "$T/models.json" > "$T/colon.json"
(PIC_MODELS_FILE="$T/colon.json" && export PIC_MODELS_FILE && pic colon --model fa:ke/m -p x) && fail "colon: a provider named with ':' ran"
grep -q "fa:ke.*':'" "$T/out/colon.err" || fail "colon: $(cat "$T/out/colon.err")"
printf 'PASS: --key goes to the provider the model resolves to; a key it lacks, or a provider named with ':', is an error\n'

# Each class: refused (401), quota as a 429 (credit), credit as a 400, a long
# 429 by Retry-After and by Anthropic's reset header (limited), a short 429
# (retried as before).
serve "status:401:$T/auth.json"
pic invalid -p x && fail "invalid: succeeded"
[ "$(requests)" = 1 ] || fail "invalid: $(requests) requests"
grep -q 'fake refused the key "second" (HTTP 401: invalid x-api-key)' "$T/out/invalid.err" || fail "invalid: $(cat "$T/out/invalid.err")"
status st4
grep -q '^fake  *second\*  *API key  *refused since [0-9:]* (HTTP 401)' "$T/out/st4.out" || fail "st4: $(cat "$T/out/st4.out")"
# A refusal that quotes part of the key (as OpenAI's does, masked) keeps none of it.
head6=$(printf %s "$K2" | cut -c1-6)
tail4=$(printf %s "$K2" | rev | cut -c1-4 | rev)
printf '{"error":{"message":"Incorrect API key provided: %s****%s. You can find your API key at x.","code":"invalid_api_key"}}' \
    "$head6" "$tail4" > "$T/quoted.json"
serve "status:401:$T/quoted.json"
pic quoted -p x && fail "quoted: succeeded"
grep -q 'Incorrect API key provided: \[key\]. You can find' "$T/out/quoted.err" || fail "quoted: $(cat "$T/out/quoted.err")"
! grep -qF -- "$head6****" "$T/out/quoted.err" || fail "quoted: part of the key in the error"
[ "$("$SQLITE3" "$T/j" "SELECT count(*) FROM pic_generation WHERE instr(error, '$tail4') > 0")" = 0 ] || fail "quoted: in the journal"
[ "$("$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT count(*) FROM picu_credential_health WHERE instr(reason, '$tail4') > 0")" = 0 ] ||
    fail "quoted: in the health table"
serve "status:429:$T/quota.json"
pic quota -p x && fail "quota: succeeded"
[ "$(requests)" = 1 ] || fail "quota: $(requests) requests (an insufficient_quota 429 was retried)"
grep -q 'is out of credit (HTTP 429: You exceeded your current quota)' "$T/out/quota.err" || fail "quota: $(cat "$T/out/quota.err")"
serve "status:400:$T/low.json"
pic low -p x && fail "low: succeeded"
grep -q 'is out of credit (HTTP 400: Your credit balance is too low' "$T/out/low.err" || fail "low: $(cat "$T/out/low.err")"
serve "head:429:$T/rate.json:retry-after: 900"
pic limited -p x && fail "limited: succeeded"
[ "$(requests)" = 1 ] || fail "limited: $(requests) requests (a long limit was retried)"
grep -Eq 'The key "second" for fake is limited until ([0-9]{4}-[0-9]{2}-[0-9]{2} )?[0-9:]+ \(15 min\) \(HTTP 429' "$T/out/limited.err" ||
    fail "limited: $(cat "$T/out/limited.err")"
status st5
grep -Eq '^fake  *second\*  *API key  *limited until ([0-9]{4}-[0-9]{2}-[0-9]{2} )?[0-9:]+ \(15 min\)' "$T/out/st5.out" || fail "st5: $(cat "$T/out/st5.out")"
reset=$(perl -MPOSIX=strftime -e 'print strftime("%Y-%m-%dT%H:%M:%SZ", gmtime(time + 3600))')
serve "head:429:$T/rate.json:anthropic-ratelimit-tokens-reset: $reset|anthropic-ratelimit-tokens-remaining: 0"
pic header -p x && fail "header: succeeded"
[ "$(requests)" = 1 ] || fail "header: $(requests) requests"
grep -Eq 'is limited until ([0-9]{4}-[0-9]{2}-[0-9]{2} )?[0-9:]+ \(60 min\)' "$T/out/header.err" || fail "header: $(cat "$T/out/header.err")"
serve "head:429:$T/rate.json:retry-after: 0" "sse:$S/text.sse"
pic short -p x || fail "short: $(cat "$T/out/short.err")"
[ "$(requests)" = 2 ] || fail "short: $(requests) requests (a short 429 is retried as before)"
status st6
grep -q '^fake  *second\*  *API key  *valid, checked just now' "$T/out/st6.out" || fail "st6: $(cat "$T/out/st6.out")"
printf 'PASS: refused, out of credit (402, quota 429, 400) and limited are not retried; a short 429 is\n'

# Spent keys as the providers word it (seen 2026-11-24): Anthropic's spend limit, a 400 naming the
# day access comes back (limited until then), and OpenAI's spent prepaid credit, a 429 with a short
# Retry-After (out of credit). Neither is retried. A free check that says valid since keeps both.
regain=$(perl -MPOSIX=strftime -e 'print strftime("%Y-%m-%d", gmtime(time + 9 * 86400))')
day=$(LC_ALL=C perl -MPOSIX=strftime -e '@t = gmtime(time + 9 * 86400); print strftime("%b ", @t), $t[3]')
printf '{"type":"error","error":{"type":"invalid_request_error","message":"You have reached your specified API usage limits. You will regain access on %s at 00:00 UTC."},"request_id":"req_011"}' \
    "$regain" > "$T/usage.json"
printf '{"error":{"message":"You have no credits remaining. Add credits to continue using the API.","type":"invalid_request_error","param":null,"code":"credit_balance_exhausted"}}' \
    > "$T/nocredit.json"
printf '{"data":[{"id":"m1","type":"model"}],"has_more":false}' > "$T/list.json"
anthropic() { # NAME ARGS...: a request to anthropic, in UTC
    name=$1
    shift
    TZ=UTC "$PIC" --db "$T/j" --workspace "$T/ws" --model claude-sonnet-4-5 "$@" > "$T/out/$name.out" 2> "$T/out/$name.err" < /dev/null
}
pic usework auth use anthropic work || fail "usework: $(cat "$T/out/usework.err")"
serve "status:400:$T/usage.json"
anthropic usage -p x && fail "usage: succeeded"
[ "$(requests)" = 1 ] || fail "usage: $(requests) requests (a usage limit was retried)"
grep -Eq "The key \"work\" for anthropic is limited until $regain 00:00 \([0-9]+ h\) \(HTTP 400: You have reached your specified API usage limits" \
    "$T/out/usage.err" || fail "usage: $(cat "$T/out/usage.err")"
TZ=UTC status st11
grep -Eq "^anthropic  *work\*  *API key  *limited until $regain 00:00" "$T/out/st11.out" || fail "st11: $(cat "$T/out/st11.out")"
serve "status:200:$T/list.json"
TZ=UTC pic check11 auth status --check --active anthropic || fail "check11: $(cat "$T/out/check11.err")"
[ "$(requests)" = 1 ] || fail "check11: $(requests) requests"
grep -Eq "^anthropic  *work\*  *API key  *valid · last request failed [0-9:]+ \(usage limit until $day\)" "$T/out/check11.out" ||
    fail "check11: $(cat "$T/out/check11.out")"
serve "head:429:$T/nocredit.json:retry-after: 1" "sse:$S/text.sse"
anthropic nocredit --key default -p x && fail "nocredit: succeeded"
[ "$(requests)" = 1 ] || fail "nocredit: $(requests) requests (no credit was retried)"
grep -q 'The key "default" for anthropic is out of credit (HTTP 429: You have no credits remaining' "$T/out/nocredit.err" ||
    fail "nocredit: $(cat "$T/out/nocredit.err")"
status st12
grep -Eq '^anthropic  *default  *API key  *out of credit since [0-9:]+ \(HTTP 429\)' "$T/out/st12.out" || fail "st12: $(cat "$T/out/st12.out")"
printf 'PASS: a usage limit is limited until the day it names, spent credit is out of credit; neither retried\n'

# offline: no key check and no model catalog fetch; PIC_MODEL_CATALOG=offline works as before.
pic offon settings offline true || fail "offon: $(cat "$T/out/offon.err")"
serve "status:200:$T/list.json"
pic offchk auth status --check || fail "offchk: $(cat "$T/out/offchk.err")"
[ "$(requests)" = 0 ] || fail "offchk: $(requests) checks went out while offline"
grep -q 'offline' "$T/out/offchk.err" || fail "offchk: $(cat "$T/out/offchk.err")"
(unset PIC_MODEL_CATALOG && pic offcat models --refresh) || fail "offcat: $(cat "$T/out/offcat.err")"
[ ! -s "$T/out/offcat.err" ] || fail "offcat: $(cat "$T/out/offcat.err")"
[ "$("$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT count(*) FROM picu_catalog")" = 0 ] || fail "offcat: the catalog was fetched"
pic offoff settings --unset offline || fail "offoff: $(cat "$T/out/offoff.err")"
printf 'PASS: offline makes no key check and fetches no model catalog\n'

# The variable: chosen by name, its state under its variable and a salted
# hash of the value, so a new value starts fresh.
serve "status:401:$T/auth.json"
pic useenv auth use fake env && fail "useenv: env chosen while unset"
(FAKE_API_KEY="$E1" && export FAKE_API_KEY && pic useenv2 auth use fake env) || fail "useenv2: $(cat "$T/out/useenv2.err")"
(FAKE_API_KEY="$E1" && export FAKE_API_KEY && pic env1 -p x) && fail "env1: succeeded"
[ "$(sent_key 1)" = "$E1" ] || fail "env1: did not send the variable"
case $(last_credential) in env:FAKE_API_KEY:[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]) ;;
*) fail "env1: journal credential $(last_credential)" ;; esac
(FAKE_API_KEY="$E1" && export FAKE_API_KEY && status st7)
grep -q '^fake  *env\*  *FAKE_API_KEY  *refused since' "$T/out/st7.out" || fail "st7: $(cat "$T/out/st7.out")"
(FAKE_API_KEY="$E2" && export FAKE_API_KEY && status st8)
grep -q '^fake  *env\*  *FAKE_API_KEY  *not checked yet' "$T/out/st8.out" || fail "st8: $(cat "$T/out/st8.out")"
pic back auth use fake second || fail "back: $(cat "$T/out/back.err")"
(FAKE_API_KEY="$E2" && export FAKE_API_KEY && status st9)
grep -q '^fake  *env  *FAKE_API_KEY  *not used: a stored key wins' "$T/out/st9.out" || fail "st9: $(cat "$T/out/st9.out")"
printf 'PASS: a variable chosen by name; a changed value resets its state\n'

# auth import: the variable's value sealed once, its provider found from the name.
(FAKE_API_KEY_2="$K3" && export FAKE_API_KEY_2 && pic import auth import FAKE_API_KEY_2 --as third) ||
    fail "import: $(cat "$T/out/import.err")"
grep -q 'Sealed FAKE_API_KEY_2 as the key "third" for fake' "$T/out/import.out" || fail "import: $(cat "$T/out/import.out")"
(FAKE_API_KEY_2="$K3" && export FAKE_API_KEY_2 && pic import2 auth import FAKE_API_KEY_2 --as third) && fail "import2: replaced a key"
pic import3 auth import NOT_A_PROVIDER_VAR && fail "import3: guessed a provider"
pic import4 auth import PATH fake --as path && fail "import4: sealed PATH without --force"
grep -q 'PATH is not the variable fake reads (FAKE_API_KEY).*--force' "$T/out/import4.err" || fail "import4: $(cat "$T/out/import4.err")"
serve "sse:$S/text.sse"
pic third --key third -p x || fail "third: $(cat "$T/out/third.err")"
[ "$(sent_key 1)" = "$K3" ] || fail "third: the imported key was not sent"
pic out3 auth logout fake:third || fail "logout: $(cat "$T/out/out3.err")"
grep -q 'Removed the API key "third" for fake' "$T/out/out3.out" || fail "logout: $(cat "$T/out/out3.out")"
status st10
! grep -q third "$T/out/st10.out" || fail "st10: $(cat "$T/out/st10.out")"
printf 'PASS: auth import seals a variable once; logout PROVIDER:LABEL removes one key\n'

# RPC: get_credentials lists the keys with their state; set_credential picks one.
printf '%s\n' '{"id":"1","type":"get_credentials"}' '{"id":"2","type":"set_credential","provider":"fake","label":"default"}' \
    '{"id":"3","type":"set_credential","provider":"fake","label":"nosuch"}' '{"id":"4","type":"get_credentials","provider":"fake"}' |
    "$PIC" --db "$T/j" --workspace "$T/ws" --model fake/m --mode rpc > "$T/out/rpc.out" 2> "$T/out/rpc.err" || fail "rpc: $(cat "$T/out/rpc.err")"
grep '"id":"1"' "$T/out/rpc.out" | grep -q '"provider":"fake","label":"second","kind":"api_key","active":true,"state":"ok"' ||
    fail "rpc get: $(cat "$T/out/rpc.out")"
grep '"id":"1"' "$T/out/rpc.out" | grep -q '"label":"default","kind":"api_key","active":false,"state":"ok","status":200' ||
    fail "rpc get: $(cat "$T/out/rpc.out")"
grep '"id":"2"' "$T/out/rpc.out" | grep -q '"success":true' || fail "rpc set: $(cat "$T/out/rpc.out")"
grep '"id":"3"' "$T/out/rpc.out" | grep -q '"success":false.*no key named' || fail "rpc set bad: $(cat "$T/out/rpc.out")"
grep '"id":"4"' "$T/out/rpc.out" | grep -q '"label":"default","kind":"api_key","active":true' || fail "rpc get after: $(cat "$T/out/rpc.out")"
[ "$("$SQLITE3" "$HOME/.pic/pic.sqlite" "SELECT value FROM picu_setting WHERE key = 'activeKey:fake'")" = second ] ||
    fail "rpc: set_credential changed the saved choice, not only this process's"
printf 'PASS: RPC get_credentials and set_credential\n'

# No key text anywhere but the requests: the user database, the journal, outputs, an export.
pic export export || fail "export: $(cat "$T/out/export.err")"
pic dump dump || fail "dump"
find "$HOME" "$T"/j* "$T/ws" "$T/out" -type f > "$T/files"
while IFS= read -r f; do
    for k in "$K1" "$K2" "$K3" "$K4" "$E1" "$E2"; do
        if grep -aqF -- "$k" "$f"; then fail "leak: a key is in $f"; fi
    done
done < "$T/files"
printf 'PASS: no key text in the user database, the journal, any output or an export\n'
