Files
junction/tests/oauth.sh
T
lotherk e86c52b074 oauth: make Claude subscription tokens usable as endpoint keys
An Anthropic OAuth token (sk-ant-oat01…, e.g. CLAUDE_CODE_OAUTH_TOKEN) is
not an API key. Sent with an ordinary body, a current model answers
429 rate_limit_error "Error" — the same status and shape as an exhausted
quota, so the endpoint looks broken at random instead of misconfigured.

`oauth on` per endpoint puts Claude Code's system prompt in place, and only
for endpoints that ask for it. The client's own system prompt is kept:
on /v1/messages as further blocks after the marker (cache_control intact),
on /v1/chat/completions as its own user message before the first turn —
there the system content must be the marker alone.

Measured against api.anthropic.com, each case repeated:

  body                                  /v1/messages  /v1/chat/completions
  no system                                    429           429
  system = <marker>                            200           200
  system = [<marker>, <text>]                  200           429
  system = [<text>, <marker>]                  429           429

The gating is model-dependent: retired names such as
claude-haiku-4-5-20251001 answer without the marker and prove nothing.
claude-sonnet-5-5, claude-haiku-5-5, claude-opus-5 and claude-opus-4-8 are
gated. The marker matches byte for byte — a missing final period or a
trailing newline is worth the same as no marker at all.

Verified: full suite PASS, 574 OK, 0 failures. Against the live API through
junction with a real subscription token: 200 on claude-sonnet-5-5 for
/v1/messages (client system prompt applied, answer "Paris") and for
/v1/chat/completions; streaming with a tool call works; the same request
with `oauth off` still gets 429 upstream, which is the counter-proof that
the option is what changes the outcome. Token B in ~/toktok is dead
independently of this (403 oauth_not_allowed_for_organization).

The stub's new STUB_BODY_FILE writes request bodies verbatim; a structural
check (is the marker the first block) cannot be done from a header.
2026-11-24 10:56:16 +00:00

202 lines
8.9 KiB
Bash

#!/bin/bash
# Wird von tests/run.sh eingebunden: wird der Claude-Code-Systemprompt gesetzt, wenn
# der Endpunkt einen OAuth-Token trägt — und nur dann?
#
# Warum das ein eigener Test ist: ein OAuth-Token ohne diesen Prompt beantwortet
# Anthropic mit 429 rate_limit_error. Das sieht aus wie ein aufgebrauchtes Kontingent,
# nicht wie ein fehlender Prompt — der Fehler wurde deshalb lange für ein Limit
# gehalten. Der Test prüft die Bytes, die upstream ankommen, nicht nur dass "200" zurück
# kommt: ein zufriedener Proxy mit falschem Rumpf ist der eigentliche Fehlerfall.
echo "== OAuth-Token: Claude-Code-Systemprompt =="
OEP=$((PORT+310))
OSP=$((PORT+311))
MARKER="You are a Claude agent, built on Anthropic's Claude Agent SDK."
# --- 1. Das Modul allein, ohne junction. Der Rewrite muss die JSON-Struktur erhalten,
# nicht bloß die Marke irgendwo einfügen.
PROBE=tests/oauth_probe
if [ ! -x "$PROBE" ] || [ tests/oauth_probe.c -nt "$PROBE" ] || [ src/oauth.c -nt "$PROBE" ]; then
cc -std=c99 -O2 -Wall -Wextra -Isrc -o "$PROBE" tests/oauth_probe.c src/oauth.c || \
bad "the oauth probe did not build"
fi
# Ein Muss-Fall: natives Format, kein system-Feld. Die Marke muss als erster Block
# entstehen, alles andere unangetastet bleiben.
IN='{"model":"m","max_tokens":8,"messages":[{"role":"user","content":"hi"}]}'
OUT=$(printf '%s' "$IN" | "$PROBE" native)
if python3 - "$OUT" "$MARKER" <<'PY'
import json, sys
d = json.loads(sys.argv[1])
assert d["system"][0]["text"] == sys.argv[2], d["system"]
assert len(d["system"]) == 1, d["system"]
assert d["messages"] == [{"role": "user", "content": "hi"}]
assert d["max_tokens"] == 8
PY
then ok "native body without system gets the marker as its only block"
else bad "native body without system was not rewritten correctly: $OUT"
fi
# Der Systemprompt des Clients muss als folgender Block erhalten bleiben — ihn zu
# ersetzen würde die Anweisungen des Operators stillschweigend löschen.
IN='{"model":"m","system":"Sei knapp.","messages":[]}'
OUT=$(printf '%s' "$IN" | "$PROBE" native)
if python3 - "$OUT" "$MARKER" <<'PY'
import json, sys
d = json.loads(sys.argv[1])
assert [b["text"] for b in d["system"]] == [sys.argv[2], "Sei knapp."], d["system"]
PY
then ok "the client's system prompt survives as the following block"
else bad "the client's system prompt was lost: $OUT"
fi
# cache_control gehört zum Prompt-Caching des Clients und darf nicht verloren gehen.
IN='{"model":"m","system":[{"type":"text","text":"A","cache_control":{"type":"ephemeral"}}],"messages":[]}'
OUT=$(printf '%s' "$IN" | "$PROBE" native)
if python3 - "$OUT" <<'PY'
import json, sys
d = json.loads(sys.argv[1])
assert d["system"][0]["type"] == "text"
assert d["system"][1]["cache_control"] == {"type": "ephemeral"}, d["system"]
PY
then ok "cache_control on the client's system block is preserved"
else bad "cache_control was dropped: $OUT"
fi
# Ein Rumpf, der schon stimmt, darf nicht ein zweites Mal umschrieben werden: die Marke
# zweimal im Prompt ist ein doppelter Prompt, kein doppelter Schutz.
printf '%s' '{"model":"m","system":[{"type":"text","text":"'"$MARKER"'"}],"messages":[]}' \
| "$PROBE" native > /dev/null
[ $? -eq 3 ] && ok "an already marked body is left alone" \
|| bad "an already marked body was rewritten again"
# Die Marke muss exakt sein. Fast richtig ist falsch — das ist der Unterschied zwischen
# 200 und 429, und ein Test, der "enthält Claude agent" prüft, würde ihn nicht sehen.
printf '%s' '{"model":"m","system":"'"${MARKER%.}"'","messages":[]}' \
| "$PROBE" native > /dev/null
[ $? -eq 0 ] && ok "a marker missing its final period is still corrected" \
|| bad "a body with an almost-marker was not corrected"
# OpenAI-kompatibler Pfad: dort darf der Systeminhalt NUR die Marke sein. Der Prompt des
# Clients wird deshalb zur eigenen user-Nachricht — erhalten, nicht gelöscht.
IN='{"model":"m","messages":[{"role":"system","content":"Sei knapp."},{"role":"user","content":"hallo"}]}'
OUT=$(printf '%s' "$IN" | "$PROBE" compat)
if python3 - "$OUT" "$MARKER" <<'PY'
import json, sys
d = json.loads(sys.argv[1])
msgs = d["messages"]
assert msgs[0] == {"role": "system", "content": sys.argv[2]}, msgs
assert msgs[1] == {"role": "user", "content": "Sei knapp."}, msgs
assert msgs[2] == {"role": "user", "content": "hallo"}, msgs
assert len(msgs) == 3, msgs
PY
then ok "on the compat path the client's system text becomes its own user message"
else bad "the compat path did not carry the system prompt over: $OUT"
fi
# Kaputte oder fremde Rümpfe werden nicht angefasst: ein Proxy, der bei unerwartetem
# JSON einen leeren Rumpf schickt, bricht jede Anfrage. Ein Rumpf ohne messages ist
# keine Chat-Anfrage (Token-Zählung, Batch-Eintrag) und darf keinen Prompt bekommen.
for BAD_BODY in 'not json' '{"model":"m"}' '{"model":"m","system":7,"messages":[]}' ''; do
printf '%s' "$BAD_BODY" | "$PROBE" native > /dev/null
rc=$?
[ "$rc" -eq 4 ] || bad "a body that is not ours was mishandled (rc=$rc): $BAD_BODY"
done
ok "foreign or malformed bodies are left to the provider"
# --- 2. Durch junction hindurch: kommt der umgeschriebene Rumpf beim Endpunkt an, und
# bleibt ein Endpunkt ohne oauth on unberührt?
# Beide Endpunkte schreiben mit. Der zweite ist die wichtigere Hälfte: ein Marker, der
# bei jedem Konto gesetzt wird, wäre schlimmer als keiner.
BODYFILE="$TMP/oauth-bodies"
PLAINFILE="$TMP/plain-bodies"
: > "$BODYFILE"
: > "$PLAINFILE"
STUB_BODY_FILE="$BODYFILE" tests/stub $OSP "OAUTH" & PIDS+=($!)
wait_port $OSP 10 || bad "the oauth stub did not come up"
STUB_BODY_FILE="$PLAINFILE" tests/stub $((OSP+1)) "OAUTH2" & PIDS+=($!)
wait_port $((OSP+1)) 10 || bad "the second oauth stub did not come up"
cat > "$TMP/oauth.conf" <<CFG
listen 127.0.0.1:$OEP
endpoint marked {
base http://127.0.0.1:$OSP/v1
kind anthropic
oauth on
context 200000
timeout 10
idle_timeout 5
}
endpoint plain {
base http://127.0.0.1:$((OSP+1))/v1
kind anthropic
context 200000
timeout 10
idle_timeout 5
}
req for "claude-plain*" check none pass plain
req for "*" check none pass marked
CFG
./junction --config "$TMP/oauth.conf" > "$TMP/oauth.log" 2>&1 &
PIDS+=($!)
wait_port $OEP 10 || bad "junction did not come up for the oauth test"
# Der Stub schreibt den Rumpf mit, weil er in einem Header nicht zu prüfen ist.
R=$(curl -s -m 10 -D- -o /dev/null -X POST -H 'Content-Type: application/json' \
-d '{"model":"claude-x","max_tokens":16,"system":"Sei knapp.","messages":[{"role":"user","content":"hi"}]}' \
"http://127.0.0.1:$OEP/v1/messages")
contains "$R" "200 OK" "the request to the oauth endpoint is accepted"
if [ -s "$BODYFILE" ] && python3 - "$BODYFILE" "$MARKER" <<'PY'
import json, sys
lines = [l for l in open(sys.argv[1]) if l.strip()]
assert lines, "no body reached the stub"
d = json.loads(lines[-1])
assert d["system"][0]["text"] == sys.argv[2], d["system"]
assert d["system"][1]["text"] == "Sei knapp.", d["system"]
PY
then ok "junction put the marker upstream, keeping the client's system prompt"
else bad "the body that reached the endpoint is wrong: $(tail -1 "$BODYFILE" 2>/dev/null)"
fi
# Gegenprobe: derselbe Rumpf an einen Endpunkt ohne "oauth on" muss unverändert bleiben.
curl -s -m 10 -o /dev/null -X POST -H 'Content-Type: application/json' \
-d '{"model":"claude-plain-y","max_tokens":16,"system":"Sei knapp.","messages":[{"role":"user","content":"hi"}]}' \
"http://127.0.0.1:$OEP/v1/messages"
if [ -s "$PLAINFILE" ] && python3 - "$PLAINFILE" "$MARKER" <<'PY'
import json, sys
bodies = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
assert bodies, "no body reached the plain endpoint"
with_marker = [b for b in bodies if sys.argv[2] in json.dumps(b)]
assert not with_marker, with_marker
assert bodies[-1]["system"] == "Sei knapp.", bodies[-1].get("system")
PY
then ok "an endpoint without oauth on is not rewritten"
else bad "an endpoint without oauth on got the marker anyway: $(cat "$PLAINFILE" 2>/dev/null)"
fi
# /v1/chat/completions durch den markierten Endpunkt: der Compat-Pfad muss auch dort
# greifen, nicht nur auf dem nativen Pfad.
curl -s -m 10 -o /dev/null -X POST -H 'Content-Type: application/json' \
-d '{"model":"claude-z","messages":[{"role":"system","content":"Sei knapp."},{"role":"user","content":"hi"}]}' \
"http://127.0.0.1:$OEP/v1/chat/completions"
if python3 - "$BODYFILE" "$MARKER" <<'PY'
import json, sys
# The compat bodies are the ones without a top-level "system" key; a plain
# substring test would match the role value {"role":"system",...}.
bodies = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
compat = [b for b in bodies if "system" not in b and "messages" in b]
assert compat, [list(b) for b in bodies]
d = compat[-1]
msgs = d["messages"]
assert msgs[0] == {"role": "system", "content": sys.argv[2]}, msgs
assert msgs[1]["role"] == "user" and msgs[1]["content"] == "Sei knapp.", msgs
PY
then ok "the compat path through junction keeps the system prompt as a user message"
else bad "/v1/chat/completions was not rewritten: $(tail -1 "$BODYFILE" 2>/dev/null)"
fi