Skip to content

feat(credentials): accept Anthropic OAuth tokens for inference - #658

Merged
pdettori merged 2 commits into
mainfrom
fix/595-anthropic-oauth-credentials
Oct 29, 2026
Merged

pdettori merged 2 commits into
mainfrom
fix/595-anthropic-oauth-credentials

Conversation

@pdettori

Copy link
Copy Markdown
Member

What

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, 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

  • harness (run-turn.ts, run-leaf.ts): a Bearer-bound sk-ant-oat credential is handed to pi as the API key its own registry resolves — an in-memory AuthStorage runtime 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() returns undefined for every other credential, so those paths are byte-identical.
  • control plane:
    • credential-store.ts: oauth2-token/bearer to the bare api.anthropic.com origin is accepted; an OAuth token on an x-api-key binding is refused naming the Bearer header.
    • exchange.ts: bearer-to-anthropic now applies only to non-OAuth Bearer values; a new oauth-token-elsewhere mismatch refuses a subscription token aimed at any other host (misdirected secret, symmetric with raw-key-elsewhere).
    • main.ts: the operator fallback accepts an OAuth token on Bearer to api.anthropic.com; it still refuses one on x-api-key or aimed at a gateway, at boot, naming the setting.
    • model-catalog.ts: the catalog fetch sends anthropic-beta: claude-code-20250219,oauth-2025-04-20 when asked with an OAuth token, mirroring pi's client.
  • mocactl (credential-checks.ts): mirrors the new shapes — the Bearer-to-api.anthropic.com refusal 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 names oauth2-token.

Placeholder mode is unchanged: the injector picks the upstream header, so an OAuth credential there is the injector's concern, as before.

Testing

  • New: 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-beta carrying oauth-2025-04-20, no x-api-key), plus new cases in inference-shape, operator-fallback-config, exchange-auth-header, model-catalog, credential-form and headless-manage tests, all written first and watched fail.
  • Full suites green locally (with Redis): harness 767 passed, control-plane 1015, knative-server 623, supervisor 232, sandbox-relay 224, remote-worker go test ./..., plus the other workspace packages; pnpm -r typecheck and Prettier clean.
  • Known environmental flakes, unrelated and green when run solo: mocactl's ink TUI timing tests and supervisor's shutdown-grace test under full-parallel runs.

Assisted-By: Claude Code

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]>
@pdettori
pdettori requested a review from cwiklik as a code owner October 28, 2026 22:57
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Oct 28, 2026

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Comment thread harness/src/run-turn.ts Outdated
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread packages/control-plane/src/main.ts Outdated
);
}
if (token.startsWith('sk-ant-oat')) {
// An Anthropic OAuth token is a working fallback shape, but only on Bearer and only to

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread harness/src/run-turn.ts
*
* Undefined for every other credential, which keeps today's model.headers path unchanged.
*/
export function oauthAuthStorage(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() }] }, {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread docs/reference/cli-mocactl.md Outdated
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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@pdettori
pdettori merged commit cd5f633 into main Oct 29, 2026
16 checks passed
@pdettori
pdettori deleted the fix/595-anthropic-oauth-credentials branch October 29, 2026 00:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 api.anthropic.com also reads OAuth tokens

2 participants