#!/bin/sh
# Subscription sign-in end to end against fake_oauth (an OAuth server and a
# Responses API stand-in), with a private HOME; nothing reaches a real
# provider. With nothing stored, a request names pic auth login and pic auth
# status says so. Then (dev build: its test seams point the flow at the fake
# server, pick a free callback port, run a scripted browser and feed the
# passphrase): pic auth login runs the PKCE round trip through the loopback
# callback; requests carry the access token; a 401 refreshes it once; a token
# near expiry is refreshed before use; two processes refreshing at once spend
# a rotating refresh token once; --no-browser takes the pasted redirect after
# refusing a forged one; logout removes the sign-in; the terminal interface's
# first message offers the choice and signs in; and no token appears in any
# output, transcript, ~/.pic or the journal. --no-faults (the release build):
# the cases without seams.
set -eu
PIC=${PIC:?set PIC to the pic binary}
OAUTH=${OAUTH:?set OAUTH to the fake_oauth binary}
DRIVE=${DRIVE:?set DRIVE to the pty_drive binary}
FAULTS=yes
[ "${1:-}" = --no-faults ] && FAULTS=no
here=$(cd "$(dirname "$0")" && pwd)
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-oauth.XXXXXX")
T=$(cd "$T" && pwd -P)
spid=
dpid=
cleanup() {
[ -n "$dpid" ] && kill "$dpid" 2>/dev/null || :
[ -n "$spid" ] && kill "$spid" 2>/dev/null || :
[ -n "${KEEP:-}" ] || 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" "$T/bin"
unset OPENAI_API_KEY PIC_TEST_PASSPHRASE PIC_TEST_OPENAI_AUTH PIC_TEST_OAUTH_PORT PIC_TEST_BROWSER
export HOME="$T/home" PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0 PIC_MODELS_FILE="$T/models.json" PIC_NO_NATIVE_CLIPBOARD=1
"$OAUTH" "$T/port" "$T/log" 300 "$here/responses-streams/reasoning_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
URL="http://127.0.0.1:$(cat "$T/port")"
printf '{"providers":{"openai":{"baseUrl":"%s/v1"}}}' "$URL" > "$T/models.json"
notty() { perl -MPOSIX=setsid -e 'setsid() or die "setsid"; exec @ARGV or die "exec"' "$@"; }
pic() { # NAME ARGS...: pic with no terminal; stdout and stderr in $T/out/NAME.{out,err}
name=$1
shift
notty "$PIC" --db "$T/j" --workspace "$T/ws" --model openai/test-model "$@" > "$T/out/$name.out" 2> "$T/out/$name.err"
}
drive() { # NAME ARGS...: pic on a pseudo-terminal, the script on stdin
name=$1
shift
"$DRIVE" "$T/out/$name.tx" 100 30 "$PIC" --db "$T/j" --workspace "$T/ws" --model openai/test-model "$@"
}
screen() { perl -pe 's/\e\[[0-9;?]*[A-Za-z]//g; s/\r//g' "$1" | grep -v '^\s*$' | tail -12; }
count() { if [ -f "$T/log/$1" ]; then tr -d ' \n' < "$T/log/$1"; else printf 0; fi; }
refused() { # requests the Responses stand-in answered 401
total=$(grep -c '^POST /v1/responses ' "$T/log/requests" 2>/dev/null || :)
echo $((${total:-0} - $(count responses)))
}
admin() { curl -s --max-time 10 "$URL/admin/$1" > /dev/null || fail "admin $1"; }
# Nothing stored: auth status says so, a request names the sign-in, and a sign-in needs a terminal.
pic status0 auth status || fail "status: $(cat "$T/out/status0.err")"
grep -q 'No stored credentials' "$T/out/status0.out" || fail "status: $(cat "$T/out/status0.out")"
pic nokey -p hello < /dev/null && fail "nokey: a request ran"
grep -q 'nothing is stored for openai: run `pic auth login openai` (Sign in with ChatGPT), or `pic login openai`' \
"$T/out/nokey.err" || fail "nokey: $(cat "$T/out/nokey.err")"
pic notty auth login openai < /dev/null && fail "notty: signed in without a terminal"
grep -q 'needs a terminal' "$T/out/notty.err" || fail "notty: $(cat "$T/out/notty.err")"
pic usage auth login && fail "usage: no provider accepted"
pic both auth login openai --api-key --no-browser < /dev/null && fail "both: accepted"
grep -q -- '--no-browser only applies to signing in' "$T/out/both.err" || fail "both: $(cat "$T/out/both.err")"
printf 'PASS: with nothing stored, auth status and the request error name the sign-in\n'
if [ "$FAULTS" = no ]; then
exit 0
fi
PASS="pic-oauth-passphrase-$$"
cat > "$T/bin/browser" <<EOF
#!/bin/sh
# The scripted browser: follows the authorize page's redirect to pic's callback.
curl -s -L --max-time 20 "\$1" >> "$T/log/browser.out" 2>&1
EOF
chmod +x "$T/bin/browser"
export PIC_TEST_OPENAI_AUTH="$URL" PIC_TEST_OAUTH_PORT=0 PIC_TEST_PASSPHRASE="$PASS" PIC_TEST_BROWSER="$T/bin/browser"
# The browser sign-in: PKCE through the loopback callback, the issued client id kept.
drive login auth login openai <<EOF || fail "login: $(screen "$T/out/login.tx")"
expect Open this URL to sign in
expect Signed in to openai (Sign in with ChatGPT)
EOF
[ "$(count exchanges)" = 1 ] || fail "login: $(count exchanges) code exchanges"
auth=$(grep -a '^GET /api/accounts/authorize?' "$T/log/requests" | head -1)
for want in client_id=dynamic_agent_client agent_name_hint=pic 'ext_agent_host_id=urn%3Auuid%3A' \
'resource=https%3A%2F%2Fapi.openai.com%2Fv1' code_challenge_method=S256 'chatgpt.tokens.use.direct' nonce=; do
case "$auth" in *"$want"*) ;; *) fail "login: the authorize request lacks $want" ;; esac
done
grep -a -q 'grant_type=authorization_code&client_id=issued-client-7&code=' "$T/log/requests" || fail "login: the exchange"
pic status1 auth status || fail "status1"
grep -q '^openai *Sign in with ChatGPT' "$T/out/status1.out" || fail "status1: $(cat "$T/out/status1.out")"
printf 'PASS: pic auth login: the PKCE round trip through the loopback callback with a scripted browser\n'
# Requests carry the access token.
pic first -p hello < /dev/null || fail "first: $(cat "$T/out/first.err")"
grep -q 'Hello, "world"' "$T/out/first.out" || fail "first: $(cat "$T/out/first.out")"
grep -a -q 'Authorization: Bearer acc-1-oauth-sentinel' "$T/log/requests" || fail "first: no bearer token"
[ "$(count responses)" = 1 ] || fail "first: $(count responses) answered"
printf 'PASS: a request is sent with the access token\n'
# The server stops taking the token: one 401, one refresh, the request sent again.
admin expire
pic again -p again < /dev/null || fail "again: $(cat "$T/out/again.err")"
[ "$(count refreshes)" = 1 ] || fail "again: $(count refreshes) refreshes"
[ "$(count responses)" = 2 ] || fail "again: $(count responses) answered"
[ "$(refused)" = 1 ] || fail "again: $(refused) refused"
grep -a -q 'grant_type=refresh_token&client_id=issued-client-7&refresh_token=ref-1-oauth-sentinel' "$T/log/requests" ||
fail "again: the refresh request"
printf 'PASS: a 401 refreshes the token once and sends again\n'
# A token near its expiry is refreshed before it is sent: no 401.
admin 'lifetime?s=200' # expires within the 3-minute margin plus pic's minute
admin expire
pic short -p short < /dev/null || fail "short: $(cat "$T/out/short.err")"
[ "$(count refreshes)" = 2 ] && [ "$(refused)" = 2 ] || fail "short: $(count refreshes) refreshes, $(refused) refused"
admin 'lifetime?s=3600'
pic early -p early < /dev/null || fail "early: $(cat "$T/out/early.err")"
[ "$(count refreshes)" = 3 ] || fail "early: $(count refreshes) refreshes"
[ "$(refused)" = 2 ] || fail "early: a request was refused ($(refused))"
printf 'PASS: a token near expiry is refreshed before the request\n'
# Two processes refused at once: the rotating refresh token is spent once, both requests answered.
admin 'slow?ms=800'
admin expire
pic race1 -p one < /dev/null &
r1=$!
pic race2 -p two < /dev/null &
r2=$!
wait "$r1" || fail "race1: $(cat "$T/out/race1.err")"
wait "$r2" || fail "race2: $(cat "$T/out/race2.err")"
admin 'slow?ms=0'
[ "$(count refreshes)" = 4 ] || fail "race: $(count refreshes) refreshes (want 4)"
[ "$(count reuse)" = 0 ] || fail "race: a spent refresh token was offered $(count reuse) times"
[ "$(count responses)" = 6 ] || fail "race: $(count responses) answered"
printf 'PASS: two processes refreshing at once spend a rotating refresh token once\n'
# --no-browser: the URL is printed, a forged redirect to the callback is refused, the pasted one is taken.
mkfifo "$T/fifo"
drive paste auth login openai --no-browser < "$T/fifo" > "$T/out/paste.drive" 2>&1 &
dpid=$!
exec 3> "$T/fifo"
printf 'expect press Enter.\n' >&3
i=0
until grep -a -q 'press Enter.' "$T/out/paste.tx" 2> /dev/null; do i=$((i + 1)); [ "$i" -lt 400 ] || fail "paste: no URL"; sleep 0.05; done
authorize=$(perl -ne 'print "$1\n" if m{(http://127\.0\.0\.1:\d+/api/accounts/authorize\?\S+)}' "$T/out/paste.tx" | head -1)
[ -n "$authorize" ] || fail "paste: no authorize URL: $(screen "$T/out/paste.tx")"
redirect=$(curl -s -o /dev/null --max-time 10 -w '%{redirect_url}' "$authorize")
case "$redirect" in http://127.0.0.1:*/auth/callback\?code=*) ;; *) fail "paste: redirect $redirect" ;; esac
forged=$(curl -s -o /dev/null --max-time 10 -w '%{http_code}' "${redirect%%\?*}?code=forged&state=forged&client_id=x")
[ "$forged" = 400 ] || fail "paste: a forged state got $forged"
printf 'send %s\\r\nexpect Signed in to openai\n' "$redirect" >&3
exec 3>&-
wait "$dpid" || fail "paste: $(screen "$T/out/paste.tx")"
dpid=
[ "$(count exchanges)" = 2 ] || fail "paste: $(count exchanges) exchanges"
printf 'PASS: --no-browser takes the pasted redirect and refuses a forged one\n'
# Logout removes the sign-in; a request names the sign-in again.
pic logout auth logout openai || fail "logout: $(cat "$T/out/logout.err")"
grep -q 'Removed the sign-in for openai' "$T/out/logout.out" || fail "logout: $(cat "$T/out/logout.out")"
pic status2 auth status || fail "status2"
grep -q 'No stored credentials' "$T/out/status2.out" || fail "status2: $(cat "$T/out/status2.out")"
pic gone -p hello < /dev/null && fail "gone: a request ran"
grep -q 'pic auth login openai' "$T/out/gone.err" || fail "gone: $(cat "$T/out/gone.err")"
printf 'PASS: logout removes the sign-in\n'
# The terminal interface: the first message with no credential offers the choice; signing in sends it.
drive tui --tui-mode regular <<EOF || fail "tui: $(screen "$T/out/tui.tx")"
expect openai/test-model
send hello\r
expect Log in to openai
expect Sign in with ChatGPT (use your subscription)
expect Paste an API key
send \r
expect Signed in to openai
send \r
expect Hello,
send \x04\x04
expect pic: conversation
EOF
[ "$(count exchanges)" = 3 ] || fail "tui: $(count exchanges) exchanges"
[ "$(count responses)" = 7 ] || fail "tui: $(count responses) answered"
printf 'PASS: the terminal interface offers the choice on the first message and signs in\n'
# No token anywhere pic writes: outputs, transcripts, ~/.pic (the database and its WAL) or the journal.
if grep -a -r -l 'oauth-sentinel' "$T/out" "$T/home" "$T/ws" "$T"/j* 2> /dev/null; then
fail "a token reached the files above"
fi
printf 'PASS: no token in any output, transcript, ~/.pic or the journal\n'