Repository navigation
feat(credentials): accept Anthropic OAuth tokens for inference - #658
Conversation
api.anthropic.com also reads OAuth tokens: a Claude Pro/Max subscription token (sk-ant-oat...) travels as Authorization: Bearer with the anthropic-beta: oauth-2025-04-20 header. #368 refused sk-ant-oat at write time because the harness routed per-caller credentials through model.headers, which cannot carry that header or the Claude Code identity pi-ai adds for its own OAuth logins, so the token always 401'd mid-turn. - harness: hand a Bearer-bound sk-ant-oat credential to pi as the API key its own registry resolves -- an in-memory AuthStorage runtime override scoped to the session, never the environment (MI1 S5 R2) -- so pi-ai's native OAuth client path fires end to end. Wired into executeTurn and both run-leaf session sites; unchanged for every other credential. - control plane: allow kind oauth2-token/bearer to the bare api.anthropic.com origin; refuse an OAuth token on an x-api-key binding or aimed at any other host (oauth-token-elsewhere, write time for the binding, turn time for the endpoint); the operator fallback accepts an OAuth token on Bearer to api.anthropic.com; the model catalog sends the oauth beta header when asked with one. - mocactl: mirror the new shapes; the kind hint names oauth2-token. Fixes #595 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Summary
This PR lets a Claude Pro/Max sk-ant-oat OAuth token work end to end as Bearer to api.anthropic.com. The harness hands the token to pi's own OAuth client path through an in-memory AuthStorage override, and the control plane and mocactl checks move from refusing the token outright to refusing it only on x-api-key or when aimed at another host. The code is consistent across control plane, harness and mocactl, the new mismatch is wired into exchange, boot and catalog, tests are thorough, and no secret values leak into messages. Nothing blocks merge on code grounds. The main open question is policy: a third-party harness using subscription tokens under the Claude Code identity, especially as a shared operator fallback (see inline).
Author: pdettori (MEMBER — maintainer)
Areas reviewed: TypeScript (harness, control-plane, mocactl), Tests, Docs
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, all signed-off: yes
CI status: passing (16/16)
| const storage = AuthStorage.inMemory(); | ||
| // Keyed on the provider pi resolves the request key by, so a synthesized model's overridden | ||
| // provider name (SH_MODEL_PROVIDER) resolves the same override. | ||
| storage.setRuntimeApiKey(model.provider, credential.value); |
There was a problem hiding this comment.
suggestion — policy/terms, for a maintainer decision before merge. With an sk-ant-oat key, pi-ai's OAuth path (anthropic-messages.js createClient/buildParams, pi-ai 1.4.0) presents every turn as Claude Code: user-agent: claude-cli/…, x-app: cli, the claude-code-20250219 beta, and a system prompt that begins with "You are Claude Code, Anthropic's official CLI for Claude." Claude Pro/Max subscription tokens are meant for Anthropic's own apps and Claude Code. Sending them from a third-party multi-user harness that uses the Claude Code identity may break the consumer terms, and Anthropic has blocked this pattern before. Please confirm this is an intended, supported use, or gate it behind an explicit opt-in. Either way, document the risk in the docs this PR updates.
There was a problem hiding this comment.
Risk documented in docs/reference/cli-mocactl.md: the token runs the session under the Claude Code identity, consumer tokens are meant for Anthropic's own apps, and storing one is the caller's call about their own account's terms. The clearly-problematic half — the shared operator fallback — is now refused outright (see the main.ts thread). Per-caller use stays ungated; whether it needs an explicit opt-in is a maintainer decision I have not made unilaterally, so flagging it here for the merge call.
| ); | ||
| } | ||
| if (token.startsWith('sk-ant-oat')) { | ||
| // An Anthropic OAuth token is a working fallback shape, but only on Bearer and only to |
There was a problem hiding this comment.
suggestion — the PR makes an sk-ant-oat operator fallback a working shape. Then one person's Claude Pro/Max subscription serves turns for every caller without their own credential, which is account sharing on a personal plan, on top of the concern at run-turn.ts:733. Consider continuing to refuse an OAuth token as SH_OPERATOR_INFERENCE_TOKEN, while still accepting per-caller OAuth credentials (where the caller uses their own subscription). If you keep it, say in deploy/vm/README.md that the fallback token is shared by all callers.
There was a problem hiding this comment.
Implemented in 7f32036: SH_OPERATOR_INFERENCE_TOKEN refuses sk-ant-oat in every mode (placeholder included — policy, not a wire shape), with the account-sharing rationale in the message and the VM README updated. Per-caller OAuth credentials remain a working shape; the boot test now covers all four header/endpoint/mode combinations.
| * | ||
| * Undefined for every other credential, which keeps today's model.headers path unchanged. | ||
| */ | ||
| export function oauthAuthStorage( |
There was a problem hiding this comment.
suggestion — the side effects of choosing pi's OAuth path go beyond the auth header, and they are worth stating here. pi also (a) adds the Claude Code system prompt before ours, (b) renames tools to Claude Code names on the wire (toClaudeCodeName / fromClaudeCodeName), and (c) drops the session-affinity and client identity headers. Also, getBetaFeatures lets an anthropic-beta set in model.headers replace the OAuth betas entirely. So a model or synthesized model that carries its own anthropic-beta would silently lose oauth-2025-04-20 and 401. A short note, plus a guard or test for the anthropic-beta override, would keep that from regressing.
There was a problem hiding this comment.
Docblock now names the full side-effect set: the prepended Claude Code system prompt, the tool renames, and the dropped session-affinity headers. Guard added in applyModelGateway (7f32036): a model-level anthropic-beta keeps its own betas and gets oauth-2025-04-20 appended, so the token can no longer 401 on that path — tests cover append, already-present, and non-OAuth cases. The claude-code beta and pi's per-request betas are still lost to such an override, which the guard's comment states; auth survives, and no harness path sets a model-level anthropic-beta today.
| upstreamCredential: { mode: 'direct', value: OAT }, | ||
| }); | ||
| const auth = await ModelRegistry.inMemory(storage!).getApiKeyAndHeaders(model); | ||
| await complete(model, { messages: [{ role: 'user', content: 'hi', timestamp: Date.now() }] }, { |
There was a problem hiding this comment.
suggestion — this wire test calls complete() directly with a key from ModelRegistry.inMemory(storage). That shows pi-ai's client sends the right headers when given the key. It does not show that createAgentSession({ authStorage }) puts the runtime override ahead of the ANTHROPIC_API_KEY sentinel that applyModelGateway sets, and that link is the one this PR depends on. Consider one test that goes through createAgentSession (or executeTurnCore with a stub base URL) and checks Authorization: Bearer <oat> plus oauth-2025-04-20 on the request.
There was a problem hiding this comment.
Added in 7f32036: a createAgentSession-level test drives a real session (Redis backend, locked loader, local HTTP stand-in) with the sentinel seeded by applyModelGateway in place, and asserts the wire carries Authorization: Bearer <oat> plus oauth-2025-04-20 and no x-api-key. Verified the test discriminates: with the authStorage wiring removed, the same test fails exactly as the mechanism predicts — pi resolves the sentinel, takes the API-key branch, and sends its own beta list with no oauth beta.
| a bearer kind (`bearer` or `oauth2-token`) is rejected, as is an `api.anthropic.com` endpoint with a | ||
| bearer kind holding anything but an Anthropic OAuth token. A Claude Pro/Max `sk-ant-oat…` OAuth token | ||
| works with kind `oauth2-token` (or `bearer`) and endpoint `https://api.anthropic.com` — and only | ||
| there: aimed at a gateway it is rejected before stdin is read. |
There was a problem hiding this comment.
nit — "aimed at a gateway it is rejected before stdin is read" is no longer accurate. The OAuth-elsewhere check lives in inferenceSecretProblem (credential-checks.ts), which needs the secret, so it runs after stdin is read. The endpoint-only half cannot know the value is an OAuth token. Suggest: "aimed at a gateway it is rejected before the credential is sent".
There was a problem hiding this comment.
Fixed in 7f32036 — now reads "rejected before the credential is sent", with a note that the check needs the secret and so runs after stdin.
… guard, wiring test - control plane: an sk-ant-oat operator fallback is refused again, in every mode: the fallback is shared by every caller, and one Claude Pro/Max subscription must not serve them all. A caller's OWN OAuth credential stays a working shape. - harness: applyModelGateway appends oauth-2025-04-20 to a model-level anthropic-beta, which pi's Object.assign merge would otherwise use to replace the OAuth betas entirely and 401 the token; the oauthAuthStorage docblock now names the full side-effect set of pi's OAuth path (Claude Code system prompt, tool renames, dropped session-affinity headers). - tests: a createAgentSession-level test drives a real session through a local stand-in and proves the runtime override beats the ANTHROPIC_API_KEY sentinel on the wire (Bearer + oauth beta, no x-api-key). Verified discriminating: without the authStorage wiring the same test fails with pi's API-key beta list and no oauth beta. - docs: the oat-elsewhere rejection runs after stdin, not before it; the terms risk of subscription tokens under the Claude Code identity is documented in cli-mocactl.md and the VM README's fallback list. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
What
api.anthropic.comalso reads OAuth tokens: a Claude Pro/Max subscription token (sk-ant-oat…) travels asAuthorization: Bearerwith theanthropic-beta: oauth-2025-04-20header. #368 refusedsk-ant-oatat write time because the harness routed per-caller credentials throughmodel.headers, which cannot carry that header or the Claude Code identity pi-ai adds for its own OAuth logins — so the token always 401'd mid-turn, and the refusal moved that failure to PUT with a message naming the fix. This makes the shape actually work end to end, then lifts the refusal.Closes #595.
How
run-turn.ts,run-leaf.ts): a Bearer-boundsk-ant-oatcredential is handed to pi as the API key its own registry resolves — an in-memoryAuthStorageruntime override scoped to the session's registry, never the environment (the MI1 §5 R2 boundary the env sentinel holds). pi-ai's native OAuth client path then fires completely: Bearer auth, the oauth beta header, and the Claude Code identity it sends for its own Claude Pro logins.oauthAuthStorage()returnsundefinedfor every other credential, so those paths are byte-identical.credential-store.ts:oauth2-token/bearerto the bareapi.anthropic.comorigin is accepted; an OAuth token on anx-api-keybinding is refused naming the Bearer header.exchange.ts:bearer-to-anthropicnow applies only to non-OAuth Bearer values; a newoauth-token-elsewheremismatch refuses a subscription token aimed at any other host (misdirected secret, symmetric withraw-key-elsewhere).main.ts: the operator fallback accepts an OAuth token on Bearer toapi.anthropic.com; it still refuses one onx-api-keyor aimed at a gateway, at boot, naming the setting.model-catalog.ts: the catalog fetch sendsanthropic-beta: claude-code-20250219,oauth-2025-04-20when asked with an OAuth token, mirroring pi's client.credential-checks.ts): mirrors the new shapes — the Bearer-to-api.anthropic.comrefusal moved to the secret half (only a non-OAuth Bearer value is refused there), an OAuth token aimed elsewhere is refused, and the kind hint namesoauth2-token.Placeholder mode is unchanged: the injector picks the upstream header, so an OAuth credential there is the injector's concern, as before.
Testing
harness/test/anthropic-oauth-credential.test.ts(unit + a wire test driving pi's real Anthropic client against a local stand-in:Authorization: Bearer <token>,anthropic-betacarryingoauth-2025-04-20, nox-api-key), plus new cases ininference-shape,operator-fallback-config,exchange-auth-header,model-catalog,credential-formandheadless-managetests, all written first and watched fail.go test ./..., plus the other workspace packages;pnpm -r typecheckand Prettier clean.Assisted-By: Claude Code