refactor(schema): store key credential form answers in metadata (#56934)

This commit is contained in:
Aiden Cline 2026-10-18 23:48:44 -05:00 • committed by GitHub
parent e1d8a45641
commit 816bce70c8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 181 additions and 113 deletions

View file

@ -1,6 +1,6 @@
import { EOL } from "node:os"
import { isConflictError, type CredentialCreateInput } from "@opencode/client"
import { Credential } from "@opencode/schema/credential"
import { CredentialLegacy } from "@opencode/schema/credential-legacy"
import { Effect, Option, Schema } from "effect"
import { Commands } from "../../commands"
import { Runtime } from "../../../framework/runtime"
@ -16,7 +16,9 @@ export default Runtime.handler(
if (!file && process.stdin.isTTY)
return yield* Effect.fail(new Error("Pipe auth export output into stdin or pass a file to import"))
const text = yield* request(() => (file ? Bun.file(file).text() : readStdin()))
const credentials = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Credential.Entry)))(text)
const credentials = yield* Schema.decodeUnknownEffect(
Schema.fromJsonString(Schema.Array(CredentialLegacy.Entry)),
)(text)
const client = yield* createClient({ server: Option.getOrUndefined(input.server), standalone: input.standalone })
const existing = yield* request((signal) => client.credential.list({ signal }))
const ids = new Set(existing.map((credential) => credential.id))

View file

@ -261,6 +261,42 @@ describe("auth command", () => {
expect(result.stdout).not.toContain("\n at ")
})
test("imports credentials exported before v2.1 with their form answers as metadata", async () => {
const created: unknown[] = []
using server = authServer(async (request, url) => {
if (url.pathname === "/api/credential" && request.method === "GET") return Response.json({ data: [] })
if (url.pathname === "/api/credential" && request.method === "POST") {
const body = await request.json()
created.push(body)
return Response.json({ data: { ...body, active: true } })
}
return new Response("Not found", { status: 404 })
})
const value = { type: "key", key: "secret", configuration: { resourceName: "answered" } }
const exported = [{ id: "cred_legacy", integrationID: "azure", label: "Work", active: true, value }]
const child = Bun.spawn(
[process.execPath, "run", "src/index.ts", "auth", "import", "--server", server.url.toString()],
{
cwd: path.join(import.meta.dir, ".."),
stdin: new Blob([JSON.stringify(exported)]),
stdout: "pipe",
stderr: "pipe",
},
)
const [stderr, exitCode] = await Promise.all([new Response(child.stderr).text(), child.exited])
expect({ exitCode, stderr: stderr.trim() }).toEqual({ exitCode: 0, stderr: "Imported 1 credential" })
expect(created).toEqual([
{
id: "cred_legacy",
integrationID: "azure",
label: "Work",
value: { type: "key", key: "secret", metadata: { resourceName: "answered" } },
activate: true,
},
])
})
test("removes a selected stored credential", async () => {
const removed: string[] = []
using server = authServer((request, url) => {

View file

@ -236,6 +236,8 @@ export type McpResourceTemplate = {
mimeType?: string
}
export type CredentialKey = { type: "key"; key: string; metadata?: { [x: string]: JsonValue } }
export type ProjectVcs = string
export type ProjectIcon = { url?: string; override?: string; color?: string }
@ -848,7 +850,7 @@ export type FormMultiselectField1 = {
default?: Array<string>
}
export type FormAnswer2 = { [x: string]: FormValue1 }
export type FormAnswer1 = { [x: string]: FormValue1 }
export type VcsInfo = { provider?: string; branch: VcsBranch }
@ -1922,13 +1924,6 @@ export type FormState =
| { status: "answered"; answer: FormAnswer }
| { status: "cancelled"; message?: string }
export type CredentialKey = {
type: "key"
key: string
metadata?: { [x: string]: JsonValue }
configuration?: FormAnswer
}
export type ProviderInfo = {
id: ProviderID
canonical?: ProviderID
@ -1944,6 +1939,8 @@ export type ProviderInfo = {
export type VoiceSessionResponse = { data: { transport: VoiceTransport } }
export type CredentialValue = CredentialOAuth | CredentialKey | CredentialExternal
export type ConnectionInfo = ConnectionCredentialInfo | ConnectionEnvInfo
export type PtyCreated = {
@ -1994,7 +1991,7 @@ export type FormReplied = {
metadata?: { [x: string]: any }
type: "form.replied"
location?: LocationRef
data: { id: FormID; sessionID: string; answer: FormAnswer2 }
data: { id: FormID; sessionID: string; answer: FormAnswer1 }
}
export type SessionInboxMove = {
@ -2379,7 +2376,13 @@ export type SessionMessageAssistantTool1 = {
export type FormFields = [FormField, ...Array<FormField>]
export type CredentialValue = CredentialOAuth | CredentialKey | CredentialExternal
export type CredentialEntry = {
id: CredentialID
integrationID: IntegrationID
label: string
active: boolean
value: CredentialValue
}
export type FormFields2 = [FormField1, ...Array<FormField1>]
@ -2445,14 +2448,6 @@ export type IntegrationKeyMethod = { type: "key"; label?: string; form?: FormFie
export type IntegrationExternalMethod = { id: IntegrationMethodID; type: "external"; label: string; form?: FormFields }
export type CredentialEntry = {
id: CredentialID
integrationID: IntegrationID
label: string
active: boolean
value: CredentialValue
}
export type FormInfo1 = { id: FormID; sessionID: string; title: string; metadata?: FormMetadata1; fields: FormFields2 }
export type SessionMessageInfo =
@ -5180,14 +5175,7 @@ export type CredentialCreateInput = {
readonly expires: number
readonly metadata?: { readonly [x: string]: JsonValue }
}
| {
readonly type: "key"
readonly key: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly configuration?: {
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
}
}
| { readonly type: "key"; readonly key: string; readonly metadata?: { readonly [x: string]: JsonValue } }
| {
readonly type: "external"
readonly methodID: string
@ -5208,14 +5196,7 @@ export type CredentialCreateInput = {
readonly expires: number
readonly metadata?: { readonly [x: string]: JsonValue }
}
| {
readonly type: "key"
readonly key: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly configuration?: {
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
}
}
| { readonly type: "key"; readonly key: string; readonly metadata?: { readonly [x: string]: JsonValue } }
| {
readonly type: "external"
readonly methodID: string
@ -5236,14 +5217,7 @@ export type CredentialCreateInput = {
readonly expires: number
readonly metadata?: { readonly [x: string]: JsonValue }
}
| {
readonly type: "key"
readonly key: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly configuration?: {
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
}
}
| { readonly type: "key"; readonly key: string; readonly metadata?: { readonly [x: string]: JsonValue } }
| {
readonly type: "external"
readonly methodID: string
@ -5264,14 +5238,7 @@ export type CredentialCreateInput = {
readonly expires: number
readonly metadata?: { readonly [x: string]: JsonValue }
}
| {
readonly type: "key"
readonly key: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly configuration?: {
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
}
}
| { readonly type: "key"; readonly key: string; readonly metadata?: { readonly [x: string]: JsonValue } }
| {
readonly type: "external"
readonly methodID: string
@ -5292,14 +5259,7 @@ export type CredentialCreateInput = {
readonly expires: number
readonly metadata?: { readonly [x: string]: JsonValue }
}
| {
readonly type: "key"
readonly key: string
readonly metadata?: { readonly [x: string]: JsonValue }
readonly configuration?: {
readonly [x: string]: string | number | "Infinity" | "-Infinity" | "NaN" | boolean | ReadonlyArray<string>
}
}
| { readonly type: "key"; readonly key: string; readonly metadata?: { readonly [x: string]: JsonValue } }
| {
readonly type: "external"
readonly methodID: string

View file

@ -3,6 +3,7 @@ export * as Credential from "./credential.js"
import { asc, desc, eq } from "drizzle-orm"
import { Cause, Context, Effect, Layer, Schema } from "effect"
import { Credential } from "@opencode/schema/credential"
import { CredentialLegacy } from "@opencode/schema/credential-legacy"
import { Integration } from "@opencode/schema/integration"
import { Database } from "./database/database.js"
import { Bus } from "./bus.js"
@ -67,7 +68,8 @@ const layer = Layer.effect(
Effect.gen(function* () {
const db = (yield* Database.Service).db
const bus = yield* Bus.Service
const decode = Schema.decodeUnknownSync(Value)
// Rows written before v2.1 may carry the old key credential shape.
const decode = Schema.decodeUnknownSync(CredentialLegacy.Value)
const stored = (row: typeof CredentialTable.$inferSelect) => {
if (!row.integration_id) return
return new Info({

View file

@ -759,7 +759,7 @@ const layer = Layer.effect(
value: Credential.Key.make({
type: "key",
key: input.key,
...(Object.keys(answer).length > 0 ? { configuration: answer } : {}),
...(Object.keys(answer).length > 0 ? { metadata: answer } : {}),
}),
})
}),

View file

@ -199,8 +199,7 @@ const resolveCatalogModel = Effect.fn("ModelResolver.resolveCatalogModel")(funct
dependencies?: Dependencies,
) {
const resolved = prepareRuntimeModel(model)
const configuration = credential?.type === "key" ? credential.configuration : undefined
const configured = { ...resolved.settings, ...credential?.metadata, ...configuration }
const configured = { ...resolved.settings, ...credential?.metadata }
if (Provider.isAISDK(resolved.package)) {
const loadAISDK = dependencies?.loadAISDK
if (!loadAISDK) return yield* unsupported(resolved)
@ -209,7 +208,6 @@ const resolveCatalogModel = Effect.fn("ModelResolver.resolveCatalogModel")(funct
Provider.mergeOverlay(resolved.settings, {
...nativeCredentialSettings(resolved, resolved.package ?? "", credential),
...credential?.metadata,
...configuration,
}) ?? {},
)
return yield* loadAISDK({ ...resolved, settings }).pipe(

View file

@ -479,15 +479,12 @@ function expandResourceName(baseURL: string, resourceName: string) {
.replaceAll("${AZURE_COGNITIVE_SERVICES_RESOURCE_NAME}", resourceName)
}
// The Azure CLI method stores the resource as credential metadata, the API key method as its form answer. API keys
// imported from V1 keep their connect-form answer as metadata.
// Both the API key and Azure CLI methods store their resource form answer as credential metadata.
function credentialResource(credential: Credential.Value | undefined) {
const resource =
credential?.type === "key"
? (credential.configuration?.resourceName ?? credential.metadata?.resourceName)
: credential?.type === "external" && credential.methodID === methodID
? credential.metadata?.resourceName
: undefined
credential?.type === "key" || (credential?.type === "external" && credential.methodID === methodID)
? credential.metadata?.resourceName
: undefined
return typeof resource === "string" && resource.trim() !== "" ? resource : undefined
}

View file

@ -172,13 +172,7 @@ export const SnowflakeCortexPlugin = define({
const load = Effect.gen(function* () {
const value = (yield* saved)?.value
account.value = normalizeAccount(
process.env.SNOWFLAKE_ACCOUNT ??
(value?.type === "key"
? (value.configuration?.account ?? value.metadata?.account)
: value?.metadata?.account) ??
configured?.account,
)
account.value = normalizeAccount(process.env.SNOWFLAKE_ACCOUNT ?? value?.metadata?.account ?? configured?.account)
})
yield* load
yield* ctx.provider.transform((providers) => {

View file

@ -1,5 +1,5 @@
import { describe, expect } from "bun:test"
import { eq } from "drizzle-orm"
import { eq, sql } from "drizzle-orm"
import { Effect } from "effect"
import { Bus } from "@opencode/core/bus"
import { Credential } from "@opencode/core/credential"
@ -48,6 +48,30 @@ describe("Credential", () => {
}),
)
it.effect("reads key form answers stored in configuration before v2.1 as metadata", () =>
Effect.gen(function* () {
const credentials = yield* Credential.Service
const db = (yield* Database.Service).db
const integrationID = Integration.ID.make("azure")
// A row from an earlier release, which the current schema would otherwise strip.
const legacy = {
type: "key",
key: "secret",
metadata: { imported: true, resourceName: "older" },
configuration: { resourceName: "answered" },
}
yield* db.run(
sql`INSERT INTO credential (id, integration_id, label, value, active, time_created, time_updated) VALUES ('cred_legacy', ${integrationID}, 'Legacy', ${JSON.stringify(legacy)}, 1, 0, 0)`,
)
expect((yield* credentials.get(Credential.ID.make("cred_legacy")))?.value).toEqual({
type: "key",
key: "secret",
metadata: { imported: true, resourceName: "answered" },
})
}),
)
it.effect("publishes global events only for observable credential mutations", () =>
Effect.gen(function* () {
const credentials = yield* Credential.Service

View file

@ -187,7 +187,7 @@ describe("Integration", () => {
expect.objectContaining({
integrationID,
label: "Work",
value: Credential.Key.make({ type: "key", key: "secret", configuration: { accountId: "account" } }),
value: Credential.Key.make({ type: "key", key: "secret", metadata: { accountId: "account" } }),
}),
])
expect((yield* Fiber.join(created)).map((event) => ({ type: event.type, data: event.data }))).toEqual([

View file

@ -1336,7 +1336,7 @@ describe("ModelResolver", () => {
Credential.Key.make({
type: "key",
key: "workers-secret",
configuration: { accountId: "account" },
metadata: { accountId: "account" },
}),
)
@ -1397,7 +1397,7 @@ describe("ModelResolver", () => {
Credential.Key.make({
type: "key",
key: "fallback-secret",
configuration: { accountId: "account" },
metadata: { accountId: "account" },
}),
{
loadAISDK: (runtime) =>

View file

@ -162,7 +162,7 @@ const cliCredential = () =>
})
const keyCredential = (key = "secret", resourceName = "test-resource") =>
Credential.Key.make({ type: "key", key, configuration: { resourceName } })
Credential.Key.make({ type: "key", key, metadata: { resourceName } })
const connect = Effect.fn(function* (value: Credential.Value) {
const credentials = yield* Credential.Service

View file

@ -14869,9 +14869,6 @@
},
"metadata": {
"type": "object"
},
"configuration": {
"$ref": "#/components/schemas/Form.Answer_1"
}
},
"required": ["type", "key"],
@ -15006,12 +15003,6 @@
"$ref": "#/components/schemas/Form.Value"
}
},
"Form.Answer_1": {
"type": "object",
"additionalProperties": {
"$ref": "#/components/schemas/Form.Value"
}
},
"Form.BooleanField": {
"type": "object",
"properties": {

View file

@ -0,0 +1,29 @@
export * as CredentialLegacy from "./credential-legacy.js"
import { Schema, SchemaTransformation } from "effect"
import { Credential } from "./credential.js"
import { Form } from "./form.js"
import { optional } from "./schema.js"
/**
* Storage and import compatibility for credentials written before v2.1 (not V1 contracts). Key credentials then kept
* their setup-form answers in `configuration`; they now live in `metadata`. Only decoders for stored rows and
* `auth export` files use these schemas, so the public credential contract never sees the old field.
*/
const Key = Schema.Struct({ ...Credential.Key.fields, configuration: optional(Form.Answer) }).pipe(
Schema.decodeTo(
Credential.Key,
SchemaTransformation.transform({
// Form answers overrode metadata when both reached provider settings, so they keep precedence.
decode: ({ configuration, ...key }) =>
configuration === undefined ? key : { ...key, metadata: { ...key.metadata, ...configuration } },
encode: (key) => key,
}),
),
)
/** Decodes a stored or exported credential value of either shape into the current `Credential.Value`. */
export const Value = Schema.Union([Credential.OAuth, Key, Credential.External])
/** Decodes an `auth export` entry of either shape into the current `Credential.Entry`. */
export const Entry = Schema.Struct({ ...Credential.Entry.fields, value: Value })

View file

@ -6,7 +6,6 @@ import { ephemeral, inventory } from "./event.js"
import { IntegrationID, IntegrationMethodID } from "./integration-id.js"
import { ascending } from "./identifier.js"
import { NonNegativeInt, statics } from "./schema.js"
import { Form } from "./form.js"
export const ID = Schema.String.pipe(
Schema.brand("Credential.ID"),
@ -44,7 +43,6 @@ export const Key = Schema.Struct({
type: Schema.Literal("key"),
key: Schema.String,
metadata: optional(Schema.Record(Schema.String, Schema.Unknown)),
configuration: optional(Form.Answer),
}).annotate({ identifier: "Credential.Key" })
/** References a credential source whose secrets and renewal are managed outside the credential store. */

View file

@ -0,0 +1,55 @@
import { describe, expect, test } from "bun:test"
import { Schema } from "effect"
import { Credential } from "../src/credential.js"
import { CredentialLegacy } from "../src/credential-legacy.js"
const decode = Schema.decodeUnknownSync(CredentialLegacy.Value)
const legacy = {
type: "key",
key: "secret",
metadata: { imported: true, resourceName: "older" },
configuration: { resourceName: "answered", accountId: "account" },
}
describe("CredentialLegacy", () => {
test("decodes key form answers written to configuration before v2.1 into metadata, keeping answers first", () => {
expect(decode(legacy)).toEqual({
type: "key",
key: "secret",
metadata: { imported: true, resourceName: "answered", accountId: "account" },
})
expect(decode({ type: "key", key: "secret", configuration: { resourceName: "answered" } })).toEqual({
type: "key",
key: "secret",
metadata: { resourceName: "answered" },
})
})
test("decodes current values and exported entries unchanged", () => {
const current = { type: "key", key: "secret", metadata: { resourceName: "answered" } } as const
expect(decode(current)).toEqual(current)
const external = { type: "external", methodID: "azure-cli", metadata: { resourceName: "answered" } } as const
expect(Schema.encodeSync(Credential.Value)(decode(external))).toEqual(external)
expect(
Schema.decodeUnknownSync(CredentialLegacy.Entry)({
id: "cred_legacy",
integrationID: "azure",
label: "Work",
active: true,
value: legacy,
}).value,
).toEqual(decode(legacy))
})
test("rejects invalid legacy configuration", () => {
expect(() => decode({ type: "key", key: "secret", configuration: "answered" })).toThrow()
})
test("the public credential schema does not know configuration", () => {
expect(Schema.decodeUnknownSync(Credential.Value)(legacy)).toEqual({
type: "key",
key: "secret",
metadata: { imported: true, resourceName: "older" },
})
})
})

View file

@ -14869,9 +14869,6 @@
},
"metadata": {
"type": "object"
},
"configuration": {
"$ref": "#/components/schemas/Form.Answer_1"
}
},
"required": ["type", "key"],
@ -15006,12 +15003,6 @@
"$ref": "#/components/schemas/Form.Value"
}
},
"Form.Answer_1": {
"type": "object",
"additionalProperties": {
"$ref": "#/components/schemas/Form.Value"
}
},
"Form.BooleanField": {
"type": "object",
"properties": {

View file

@ -14869,9 +14869,6 @@
},
"metadata": {
"type": "object"
},
"configuration": {
"$ref": "#/components/schemas/Form.Answer_1"
}
},
"required": ["type", "key"],
@ -15006,12 +15003,6 @@
"$ref": "#/components/schemas/Form.Value"
}
},
"Form.Answer_1": {
"type": "object",
"additionalProperties": {
"$ref": "#/components/schemas/Form.Value"
}
},
"Form.BooleanField": {
"type": "object",
"properties": {