Skip to content

refactor(ai): provider-owned auth and self-censoring Secret - #68586

Merged
rekram1-node merged 3 commits into
devfrom
ai-provider-auth
Dec 6, 2026
Merged

rekram1-node merged 3 commits into
devfrom
ai-provider-auth

Conversation

@rekram1-node

@rekram1-node rekram1-node commented Dec 6, 2026 •

Copy link
Copy Markdown
Member

Issue for this PR

Closes #

Follows #68585 (plain Model record), now merged; this branch is rebased onto dev.

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

Credentials now belong to the provider. openai({ apiKey }) makes one credential value, and every model from that provider call shares it by reference as model.auth. The model's API still decides how a key is sent (header and prefix), as today.

// AuthSource: where a provider's credential comes from, as plain data
| { type: "env"; vars: string[] }   // read when each request is sent
| { type: "key"; key: Secret }
| { type: "none" }                  // apiKey: false
| { type: "custom" }                // Bedrock SigV4, Vertex access token / OAuth, authToken bearer; the handler sits under a private symbol
  // provider.ts, per model
- auth: token === undefined ? Auth.fromAuthentication(api.auth ?? input.auth, apiKey) : Auth.bearer(token)
+ auth: api.auth ?? input.auth          // how the API sends a key
+ model.auth = credential(api.auth)     // one value per provider call, shared by its models

  // route/client.ts, media and compaction: when a request is sent
- auth: Auth.fromAuthentication(api.auth)
+ auth: resolve(internal(api).auth, request.model.auth, request.apiKey)   // route/credential.ts, package-private

How resolve picks the auth:

request.apiKey set           → that key, in the API's header and prefix (Authorization: Bearer when the API names none)
model.auth is custom         → its private handler (signing, OAuth, bearer authToken)
model.auth is none           → no credential
model.auth is key            → the key; the "<redacted>" placeholder fails with an AuthenticationError
model.auth is env            → the first of vars that is set, read now

Secret (src/secret.ts) holds its value in a private field. String, JSON.stringify and console.log/inspect all give "<redacted>", and Secret.value is the only reader. sanitizeSurrogates passes it through untouched, like media assets.

Settings inputs don't change (apiKey, authToken, accessToken, auth: "sigv4", apiKey: false). An empty key still falls back to the environment. A key from Effect Config is still read when a request is sent. An API whose auth is a definition keeps it and ignores apiKey, as before. LanguageModel.make fills auth from the API's own auth when it's omitted. LanguageModel.update with an API that brings different auth takes that auth, so update(model, { api: model.api.with({ auth }) }) behaves as before.

Net for this PR: +356 / −92 (+264). Together with #68585 the change is −244.

Public changes

Accepted direction: credentials live on the provider, as plain data. Everything else that changes for callers:

  • New field: model.auth: AuthSource on every model (env / key / none / custom), required on hand-written records. LanguageModel.make fills it from the API's own auth when it's omitted. No internal Auth.Definition appears in public types; a custom source keeps its handler under a private symbol.
  • New request field: apiKey?: string | Secret on every request (text, media, decision, embedding). It wins over the provider's credential.
  • Job calls by ID: status(model, id, { apiKey }), result(model, id, { apiKey }) and cancel(model, id, { apiKey }) for image, video and transcription jobs, in both the Promise and Effect APIs (new JobOptions type). Same precedence as start. generate/stream already poll with the start call's key, because the poll reuses the route start built.
  • New exports: Secret, and the AuthSource and JobOptions types.
  • Behavior: a key equal to "<redacted>" fails at request time with AuthenticationError ("The API key is the "" placeholder a printed key leaves") instead of being sent.
  • @opencode/ai/internal is unchanged; the resolver (route/credential.ts) and auth-source.ts helpers are package-private, and tests import them from src.

Unchanged: wire bytes, provider settings (apiKey, authToken, accessToken, auth: "sigv4", apiKey: false), packages/plugin types, and core behavior.

How did you verify your code works?

  • Local request snapshot of every ./providers/* entrypoint (not committed): unchanged, 130/130. It masks credential header values, so the existing provider auth tests cover the values. They now resolve through the package-private resolve and pass.
  • One existing job test (image-job.test.ts) gains an assertion that status(model, id, { apiKey }) sends the call's key while a plain status sends the provider's.
  • One new test: Secret prints as <redacted> from String, JSON and Bun.inspect. The existing "reads the API key from the environment when a request is sent" test covers env reads.
  • packages/ai: bun run typecheck, typecheck:tsc, bun test: 2561 pass. The emitted model.d.ts/auth-source.d.ts public types reference no Auth.Definition or AuthInput.
  • packages/core: typecheck:tsc; model-resolver (auth asserted on the sent request), aisdk, session-native-compaction, session-model-request and generate tests: 138 pass.
  • Root bun run check.

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The refactor works as described, and I found nothing that blocks it. With a temporary test I checked that models from one provider call share the same credential object, and that the API's header and prefix are kept (Bearer for OpenAI, x-api-key for Anthropic). I also checked that a request's own apiKey wins: a string and a Secret both reached the wire through ai.generate. The environment is read when a request is sent, apiKey: false sends nothing, a "<redacted>" key fails with AuthenticationError, and update(..., { api: api.with({ baseURL }) }) keeps the credential. packages/ai tests (2431) and typecheck:tsc pass. Core tsc and the model-resolver / session-model-request tests pass.

Public API of @opencode/ai:

  • Added: model.auth: Auth.Source on every model, required on hand-written model records (LanguageModel.make fills it in when omitted).
  • Added: apiKey?: string | Secret on text, media, decision and embedding requests.
  • Added: the Secret export.
  • Added: Auth.Source and Auth.resolve in @opencode/ai/internal.
  • Changed: model.api.auth now holds how the API sends a key, not the resolved credential. Code that called model.api.auth.apply(...) must switch to Auth.resolve(model.api.auth, model.auth).
  • Changed: a literal "<redacted>" key is now rejected instead of sent.

Provider settings, the config, plugin and server APIs, and wire bytes are unchanged. So this is backwards compatible for settings-based callers, but not for code that builds model records by hand or reads api.auth directly.

One gap worth closing: nothing tests the two new behaviours, a request-level apiKey overriding the provider's credential and the "<redacted>" placeholder being rejected. Two small Auth.resolve cases in test/auth.test.ts would cover them.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The update still works as described. In packages/ai, bun test passes (2431) and typecheck:tsc is clean. In packages/core, tsc is clean and the model-resolver, session-model-request and native-compaction tests pass. I re-ran an end-to-end check through ai.generate: the provider key, a request string key, a request Secret and the environment key each produced the right header, and a request key of Secret.make("<redacted>") fails with AuthenticationError. Custom sources keep their handler out of JSON and survive object spread.

Public API of @opencode/ai:

  • Added: model.auth: AuthSource (env / key / none / custom), required on hand-written model records (LanguageModel.make fills it in when omitted).
  • Added: apiKey?: string | Secret on every request.
  • Added: the Secret export and the AuthSource type.
  • Changed: a "<redacted>" key is now rejected at request time instead of sent.
  • Changed: model.api.auth no longer carries the resolved credential.

Provider settings, config, the plugin and server APIs, and wire bytes are unchanged.

One new problem: the placeholder guard crashes when a model's auth has been through JSON (see the inline comment).

Comment thread packages/ai/src/route/credential.ts Outdated
}

const keyed = (format: Auth.ApiKey, key: Secret) =>
Secret.isPlaceholder(key)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The placeholder check is meant to catch the key a printed model leaves behind. But a model whose auth went through JSON comes back as { type: "key", key: "<redacted>" }, with a plain string where a Secret should be. Secret.isPlaceholder then reads #value on a non-Secret and throws TypeError: Cannot access invalid private field, so the request dies with a defect instead of the AuthenticationError. I hit this by spreading a model with auth: JSON.parse(JSON.stringify(model.auth)) and calling ai.generate. Checking key instanceof Secret first, and treating anything else as the placeholder, would give the intended error.

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 0fec582: a key that isn't a Secret (as after a JSON round trip) is treated as the placeholder and fails with AuthenticationError. Checked with { ...model, auth: JSON.parse(JSON.stringify(model.auth)) } through ai.generate.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The new commit fixes the crash I reported: a model whose auth went through JSON now fails with the intended AuthenticationError instead of a TypeError. I checked it end to end through ai.generate. Provider keys and per-request keys still send the right header, the auth and provider tests pass, and typecheck:tsc is clean. Nothing new to raise. The public API impact is the same as in my last review: it adds model.auth (AuthSource), request apiKey, and the Secret and AuthSource exports, and hand-built models must set auth.

@opencodejr opencodejr Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The new commit is fine. Job calls by ID (status, result, cancel) now take an optional { apiKey } and pass it to the route lookup, so they follow the same rule as start. The updated image-job test checks that a plain call sends the provider's key and a call with its own key sends that one. bun test passes in packages/ai and typecheck:tsc is clean. The "<redacted>" crash from my earlier comment was fixed in the previous push.

Public API changes in this push: an optional third argument { apiKey } on status/result/cancel for image, video and transcription (Effect and Promise APIs), and the new JobOptions type. Both are backwards compatible. The rest of the PR's impact is unchanged: model.auth, request apiKey, and the Secret and AuthSource exports.

@rekram1-node
rekram1-node merged commit e065beb into dev Dec 6, 2026
12 checks passed
@rekram1-node
rekram1-node deleted the ai-provider-auth branch December 6, 2026 03:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant