Skip to content
pi-c Artifact [c7bc485fa9]
Login

Artifact [c7bc485fa9]

Artifact c7bc485fa9f163e3fc32eab99d781f404cc9a812e5ef64f225048ce0c4a515f6:


#!/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 || :
    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"
export PIC_TEST_OPENAI_API="$URL/v1/" # where the sign-in's token may go (https://api.openai.com/ without the seam)

# 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  *default\*  *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 sign-in beats the provider's environment variable (Pi's order), and auth status says so.
(OPENAI_API_KEY=pic-oauth-env-key && export OPENAI_API_KEY && pic envwin -p hello < /dev/null) || fail "envwin: $(cat "$T/out/envwin.err")"
grep -a -q 'Authorization: Bearer acc-1-oauth-sentinel' "$T/log/requests" || fail "envwin: no bearer token"
! grep -a -q 'pic-oauth-env-key' "$T/log/requests" || fail "envwin: the variable was sent"
(OPENAI_API_KEY=pic-oauth-env-key && export OPENAI_API_KEY && pic envstatus auth status < /dev/null) || fail "envstatus"
grep -q '^openai  *default\*  *Sign in with ChatGPT' "$T/out/envstatus.out" || fail "envstatus: $(cat "$T/out/envstatus.out")"
grep -q '^openai  *env  *OPENAI_API_KEY  *not used: a stored key wins' "$T/out/envstatus.out" || fail "envstatus: $(cat "$T/out/envstatus.out")"
! grep -q 'pic-oauth-env-key' "$T/out/envstatus.out" || fail "envstatus: printed the variable"
printf 'PASS: a sign-in beats the environment variable, and auth status names the source\n'

# The token goes only where the sign-in was granted: with the models file pointing openai at another
# address (here, the fake server is no longer the allowed one), the request is refused before any
# token is read or sent.
before=$(grep -c '^POST /v1/responses ' "$T/log/requests")
(PIC_TEST_OPENAI_API=https://api.openai.com/ && export PIC_TEST_OPENAI_API && pic elsewhere -p hello < /dev/null) &&
    fail "elsewhere: the request ran"
grep -q "the openai sign-in is sent only to https://api.openai.com/, and this request goes to $URL/v1/responses" \
    "$T/out/elsewhere.err" || fail "elsewhere: $(cat "$T/out/elsewhere.err")"
[ "$(grep -c '^POST /v1/responses ' "$T/log/requests")" = "$before" ] || fail "elsewhere: a request reached the server"
printf 'PASS: a subscription token is refused for an endpoint other than its own\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)" = 3 ] || 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)" = 7 ] || 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"
code=$(printf '%s' "$redirect" | sed 's/.*[?&]code=\([^&]*\).*/\1/')
! grep -a -q -- "$code" "$T/out/paste.tx" || fail "paste: the pasted code was echoed"
grep -a -q 'Pasted address received.' "$T/out/paste.tx" || fail "paste: no acknowledgement"
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'

# OpenRouter: the PKCE sign-in on a free port and a random path hands back a key, stored as a key.
export PIC_TEST_OPENROUTER_SITE="$URL"
drive orlogin auth login openrouter <<EOF || fail "openrouter: $(screen "$T/out/orlogin.tx")"
expect Signed in to openrouter (Sign in with OpenRouter)
EOF
[ "$(count keys)" = 1 ] || fail "openrouter: $(count keys) key exchanges"
grep -a -q '"code_challenge_method":"S256"' "$T/log/requests" || fail "openrouter: the key request"
pic status3 auth status || fail "status3"
grep -q '^openrouter  *default\*  *API key' "$T/out/status3.out" || fail "status3: $(cat "$T/out/status3.out")"
pic orlogout auth logout openrouter || fail "orlogout"
grep -q 'Removed the stored API key for openrouter' "$T/out/orlogout.out" || fail "orlogout: $(cat "$T/out/orlogout.out")"
printf 'PASS: OpenRouter sign-in stores the key it hands back\n'

# RPC: login signs in with the browser (its messages on stderr, stdout stays JSON), get_auth_status
# lists it without a value, logout removes it.
printf '%s\n' '{"id":"a","type":"login","provider":"openai"}' '{"id":"b","type":"get_auth_status"}' \
    '{"id":"c","type":"logout","provider":"openai"}' '{"id":"d","type":"login","provider":"fake-none"}' |
    notty "$PIC" --db "$T/j" --workspace "$T/ws" --model openai/test-model --mode rpc > "$T/out/rpc.out" 2> "$T/out/rpc.err" ||
    fail "rpc: $(cat "$T/out/rpc.err")"
grep -q '^{"id":"a","type":"response","command":"login","success":true,"data":{"provider":"openai","type":"oauth"}}$' \
    "$T/out/rpc.out" || fail "rpc login: $(cat "$T/out/rpc.out") $(cat "$T/out/rpc.err")"
grep -q '"command":"get_auth_status","success":true,"data":{"credentials":\[{"provider":"openai","type":"oauth","label":"Sign in with ChatGPT","createdAt":' \
    "$T/out/rpc.out" || fail "rpc status: $(cat "$T/out/rpc.out")"
grep -q '^{"id":"c","type":"response","command":"logout","success":true,"data":{"removed":true}}$' "$T/out/rpc.out" ||
    fail "rpc logout: $(cat "$T/out/rpc.out")"
grep -q '"id":"d".*"success":false' "$T/out/rpc.out" || fail "rpc unknown provider: $(cat "$T/out/rpc.out")"
grep -q 'Open this URL to sign in' "$T/out/rpc.err" && ! grep -q 'Open this URL' "$T/out/rpc.out" || fail "rpc: the URL went to stdout"
[ "$(count exchanges)" = 3 ] || fail "rpc: $(count exchanges) exchanges"
printf 'PASS: RPC login, get_auth_status and logout\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
expect Paste an API key
send \r
expect Passphrase for pic's credential store:
send $PASS\r
expect Stop asking for this passphrase?
send n
expect Signed in to openai
send \r
expect Hello,
send \x04\x04
expect pic: conversation
EOF
[ "$(count exchanges)" = 4 ] || fail "tui: $(count exchanges) exchanges"
[ "$(count responses)" = 8 ] || 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'