import type * as FillPlacementOptInsModule from '#worker/credentials/fill-placement-opt-ins.ts' import type * as CloudflareWorkersModule from 'cloudflare:workers' import { personalOrgId } from '@kody-internal/shared/owner-person-ids.ts' import type { McpCallerContext } from '@kody-internal/shared/chat.ts' import { expect, test, vi } from 'vitest' import { executeGatewayFetch } from '#mcp/fetch-gateway.ts' import { credentialClientHintHeaderName } from '#mcp/credential-client-gateway.ts' import { createCredentialClientKodyTools, createCredentialClientOwnerOnlyMessage, } from '#mcp/credential-client-tools.ts' import { credentialClientToolNames } from '#mcp/execute-modules/credential-client-source.ts' import { createRunCredentialClientToolOptions } from '#mcp/run-kody-registry.ts' import type { CredentialClientToolOptions } from '#mcp/runtime-helper-manifest.ts' import { runWithCurrentSecretAuthority } from '#mcp/secrets/secret-authority.ts' import { createCapabilityProxyCredentialClientTools } from '#worker/open-api/capability-proxy.ts' import type { ApiInvocationContext } from '#worker/open-api/context.ts' import { signLocalExecutePackageBinding } from '#worker/package-runtime/local-execute-package-binding.ts' import { deriveRequestContext } from '#worker/request-context/request-context.ts' import { consoleError } from '#worker/test-support/console-spies.ts' import * as usageModule from '#worker/usage/record-usage.ts' import { credentialClientHeaderName } from './credential-client-header.ts' import { newRunCredentialClientBinding, signCredentialClientHandle, } from './credential-client-handle.ts' import { normalizeCredentialCallMap, type CredentialCallMapInput, } from './credential-call-map.ts' import { applyCredentialClient, loadRunCredentialNeedEntries, openCredentialClient, openCredentialClients, signWithCredentialClient, validateCredentialCallMap, } from './credential-client.ts' import { buildWriteCredentialMappingStatement, type CredentialMappingRowTarget, deleteCredentialMappingsForPackage, runCredentialMappingWrite, } from './credential-mappings.ts' import * as needsClosure from './credential-needs-closure.ts' import type { CredentialNeed, SavedCredentialNeed } from './credential-needs.ts' import { buildWebhookTimestampBodyPayload, buildWebhookUrlFormSortedPayload, verifyWebhookHmacSignature, } from '#worker/webhooks/crypto.ts' import { createCredentialClientFixtures, mockNeeds, now, rejection, resendKey, } from '#worker/test-support/credential-client-fixtures.ts' // These cases cover fills the owner has opted in to; enforcement of the // opt-in itself is covered in fill-placement-enforcement.node.test.ts. vi.mock( '#worker/credentials/fill-placement-opt-ins.ts', async (importOriginal) => ({ ...(await importOriginal()), readFillPlacementOptIn: async () => ({ query: true, path: true, body: true, }), }), ) const scheduledAudits = vi.hoisted(() => [] as Array>) vi.mock('cloudflare:workers', async (importOriginal) => ({ ...(await importOriginal()), waitUntil: (promise: Promise) => { scheduledAudits.push(promise) }, })) vi.mock( '#worker/test-support/apply-all-migrations.ts', async (importOriginal) => (await import('./cached-migrations.test-support.ts')).withCachedMigrations( await importOriginal(), ), ) const { setup } = createCredentialClientFixtures(scheduledAudits) test('credential sign() produces signatures the webhook verifier accepts for structured payloads', async () => { const t = await setup() await t.storeKey({ name: 'webhook-signing', hosts: ['public.example'] }) const ctx = t.contextFor({ request: t.requestAs('bea', 'owner') }) const { handle } = await openCredentialClient(ctx, { name: 'webhook-signing', }) const host = 'public.example' const url = `https://${host}:8443/path?literal=%2f` const form = 'b=z&a=%2B&%62=a&b=%7A' const encode = (text: string) => new TextEncoder().encode(text) for (const [formFields, rawBody] of [ [undefined, form], ['received', form], ['dedupe', form], ['dedupe', ''], ] as const) { const options = { algorithm: 'hmac-sha1', encoding: 'base64' } as const const signed = await signWithCredentialClient(ctx, { handle, host, operation: { type: 'hmac', ...options, payload: { type: 'url.form-sorted', url, body: rawBody, formFields }, }, }) const body = buildWebhookUrlFormSortedPayload({ url, body: encode(rawBody), formFields, }) await expect( verifyWebhookHmacSignature({ ...options, secret: resendKey, body, provided: signed.signature, }), ).resolves.toBe(true) } const timestamp = '1700000000' const rawBody = Uint8Array.of(0xff, 0x0a).buffer const options = { algorithm: 'hmac-sha256', encoding: 'hex', prefix: 'sha256=', } as const const signed = await signWithCredentialClient(ctx, { handle, host, operation: { type: 'hmac', ...options, payload: { type: 'timestamp.body', timestamp, body: { base64: '/wo=' } }, }, }) for (const timestampToken of [timestamp, '1700000001']) { await expect( verifyWebhookHmacSignature({ ...options, secret: resendKey, body: buildWebhookTimestampBodyPayload({ timestampToken, body: rawBody, }), provided: signed.signature, }), ).resolves.toBe(timestampToken === timestamp) } }) test('credential sign() rejects malformed HMAC operations as invalid_request', async () => { const t = await setup() const ctx = t.contextFor({ request: t.requestAs('bea', 'owner') }) const form = { type: 'url.form-sorted', url: 'https://public.example/path', body: '', } for (const [input, message] of [ [{}, /exactly one/], [{ message: '', payload: form }, /exactly one/], [{ message: 3 }, /message must be/], [{ message: '', algorithm: 'sha1' }, /algorithm must be/], [{ message: '', encoding: 'binary' }, /encoding must be/], [{ message: '', prefix: 3 }, /prefix must be/], [{ payload: null }, /payload type must be/], [{ payload: { ...form, body: undefined } }, /payload body must be/], [{ payload: { ...form, body: { base64: '#' } } }, /invalid base64/], [{ payload: { ...form, url: '/path' } }, /payload url must be/], [ { payload: { ...form, formFields: 'unknown' } }, /payload formFields must be/, ], [ { payload: { type: 'timestamp.body', timestamp: 1700000000, body: '' } }, /payload timestamp must be/, ], ] as const) { await expect( signWithCredentialClient(ctx, { host: 'public.example', operation: { type: 'hmac', algorithm: 'hmac-sha1', encoding: 'base64', ...input, }, }), ).rejects.toMatchObject({ body: { code: 'invalid_request', message: expect.stringMatching(message), }, }) } }) test('a client opens by key with no value, and the gateway places the key by its inject on its hosts only', async () => { const t = await setup() await t.storeKey({ name: 'resend-prod', inject: { kind: 'header', name: 'X-Api-Key', format: '{value}' }, }) const request = t.requestAs('bea', 'owner') const opened = await openCredentialClient(t.contextFor({ request }), { key: 'resend', }) expect(opened).toMatchObject({ key: 'resend', name: 'resend-prod', scope: 'org', kind: 'secret', hosts: ['api.resend.com'], }) expect(opened.handle).toMatch(/^kch1\./) expect(JSON.stringify(opened)).not.toContain(resendKey) const apply = (url: string, binding = 'run:test') => applyCredentialClient({ env: t.env, request, baseUrl: 'https://example.com', packageId: null, binding, token: opened.handle, requestUrl: new URL(url), }) const applied = await apply('https://api.resend.com/emails') expect(applied.placement).toEqual({ kind: 'header', name: 'X-Api-Key', value: resendKey, }) expect(applied.substitutedValues).toContain(resendKey) await expect(apply('https://attacker.example/collect')).rejects.toMatchObject( { body: { code: 'host_not_allowed' } }, ) await expect(apply('http://api.resend.com/emails')).rejects.toMatchObject({ body: { code: 'insecure_transport' }, }) // A handle works only in the run that opened it. await expect( apply('https://api.resend.com/emails', newRunCredentialClientBinding()), ).rejects.toMatchObject({ body: { code: 'invalid_request' } }) const rows = await t.audits() expect(rows.map((row) => row.result)).toEqual(['success', 'denied', 'denied']) expect(JSON.stringify(rows)).not.toContain(resendKey) }) test('basic and query injects place the value without exposing it', async () => { const t = await setup() await t.storeKey({ name: 'basic-key', provider: 'basicco', hosts: ['api.basic.example'], inject: { kind: 'basic', valueAs: 'username', other: '' }, }) await t.storeKey({ name: 'query-key', provider: 'queryco', hosts: ['api.query.example'], inject: { kind: 'query', param: 'api_key' }, placement: { query: true }, }) const request = t.requestAs('bea', 'owner') const ctx = t.contextFor({ request }) const applyFor = async (key: string, url: string) => applyCredentialClient({ env: t.env, request, baseUrl: 'https://example.com', packageId: null, binding: 'run:test', token: (await openCredentialClient(ctx, { key })).handle, requestUrl: new URL(url), }) const basic = await applyFor('basicco', 'https://api.basic.example/v1') expect(basic.placement).toEqual({ kind: 'header', name: 'Authorization', value: `Basic ${btoa(`${resendKey}:`)}`, }) const query = await applyFor('queryco', 'https://api.query.example/v1?x=1') expect(query.placement).toEqual({ kind: 'query', param: 'api_key', value: resendKey, }) }) test('open reports unbound and ambiguous picks with ready-to-retry options, listing only usable credentials', async () => { const t = await setup() const bea = t.contextFor({ request: t.requestAs('bea', 'owner') }) await expect( rejection(openCredentialClient(bea, { key: 'resend' })), ).resolves.toMatchObject({ body: { code: 'credential_unbound', retryWith: [] }, }) const firstId = await t.storeKey({ name: 'resend-a' }) const secondId = await t.storeKey({ name: 'resend-b' }) const ambiguous = await rejection( openCredentialClient(bea, { key: 'resend' }), ) expect(ambiguous.body).toMatchObject({ code: 'credential_ambiguous', retryWith: [ { credentials: { resend: { id: firstId } }, named: { name: 'resend-a', scope: 'org' }, }, { credentials: { resend: { id: secondId } }, named: { name: 'resend-b', scope: 'org' }, }, ], options: [ expect.objectContaining({ name: 'resend-a', kind: 'secret' }), expect.objectContaining({ name: 'resend-b', kind: 'secret' }), ], }) // Ann has no Use, so neither credential is a candidate for her. const ann = t.contextFor({ request: t.requestAs('ann', 'member') }) await expect( rejection(openCredentialClient(ann, { key: 'resend' })), ).resolves.toMatchObject({ body: { code: 'credential_unbound' } }) await t.grantUse(firstId, 'ann') await expect( openCredentialClient( t.contextFor({ request: t.requestAs('ann', 'member') }), { key: 'resend' }, ), ).resolves.toMatchObject({ name: 'resend-a' }) }) test('credential.named works in ad hoc code and unshared personal packages only', async () => { const t = await setup() await t.storeKey({ name: 'resend-prod' }) const bea = t.requestAs('bea', 'owner') await expect( openCredentialClient(t.contextFor({ request: bea }), { name: 'resend-prod', scope: 'org', }), ).resolves.toMatchObject({ key: null, name: 'resend-prod' }) await expect( rejection( openCredentialClient(t.contextFor({ request: bea }), { name: 'missing', }), ), ).resolves.toMatchObject({ body: { code: 'credential_not_found' } }) const orgPackageId = await t.savePackage({ ownerId: t.acmeId, name: '@acme/tool', }) await expect( rejection( openCredentialClient( t.contextFor({ request: bea, packageId: orgPackageId }), { name: 'resend-prod' }, ), ), ).resolves.toMatchObject({ body: { code: 'credential_denied' } }) const beaOrgId = personalOrgId(t.people.bea.personId) await t.storeKey({ ownerId: beaOrgId, name: 'my-key' }) const personalPackageId = await t.savePackage({ ownerId: beaOrgId, name: '@bea/tool', }) const inPersonal = t.contextFor({ request: t.requestAs('bea', 'owner', beaOrgId), packageId: personalPackageId, }) await expect( openCredentialClient(inPersonal, { name: 'my-key' }), ).resolves.toMatchObject({ name: 'my-key' }) await t.db .prepare( `INSERT INTO community_listings (id, owner_user_id, package_id, source_id, kody_id, name, description, license, pinned_commit) VALUES (?, ?, ?, ?, 'tool', '@bea/tool', 'tool', 'MIT', 'abc')`, ) .bind( crypto.randomUUID(), beaOrgId, personalPackageId, `source-${personalPackageId}`, ) .run() await expect( rejection(openCredentialClient(inPersonal, { name: 'my-key' })), ).resolves.toMatchObject({ body: { code: 'credential_denied' } }) }) test('a handle is refused when forged, expired, or used by another actor', async () => { const t = await setup() const id = await t.storeKey({ name: 'resend-prod' }) await t.grantUse(id, 'ann') const bea = t.requestAs('bea', 'owner') const ann = t.requestAs('ann', 'member') const opened = await openCredentialClient(t.contextFor({ request: bea }), { key: 'resend', }) const applyAs = (request: typeof bea, token: string) => applyCredentialClient({ env: t.env, request, baseUrl: 'https://example.com', packageId: null, binding: 'run:test', token, requestUrl: new URL('https://api.resend.com/emails'), }) await expect(applyAs(ann, opened.handle)).rejects.toMatchObject({ body: { code: 'invalid_request' }, }) const [prefix, body] = opened.handle.split('.') await expect( applyAs(bea, `${prefix}.${body}.${'A'.repeat(43)}`), ).rejects.toMatchObject({ body: { code: 'invalid_request' } }) const expired = await signCredentialClientHandle({ env: t.env, handle: { id, kind: 'secret', name: 'resend-prod', scope: 'org', org: t.acmeId, actor: t.people.bea.personId, binding: 'run:test', }, now: Date.now() - 13 * 60 * 60 * 1000, }) await expect(applyAs(bea, expired)).rejects.toMatchObject({ body: { code: 'invalid_request' }, }) }) test('the gateway strips the handle, places the key, holds redirects, redacts echoes, and hints the shape on a 401', async () => { const t = await setup() await t.storeKey({ name: 'resend-prod' }) vi.spyOn(usageModule, 'recordUsage').mockResolvedValue(undefined) const request = t.requestAs('bea', 'owner') const opened = await openCredentialClient(t.contextFor({ request }), { key: 'resend', }) const seen: Array = [] const globalFetch = vi.fn(async (outbound: Request) => { seen.push(outbound) return new Response(`echo ${outbound.headers.get('authorization')}`, { status: 401, }) }) const response = await executeGatewayFetch({ env: t.env, props: { baseUrl: 'https://example.com', userId: t.acmeId, email: 'bea@example.com', request, storageContext: null, credentialClientBinding: 'run:test', }, request: new Request('https://api.resend.com/emails', { headers: { [credentialClientHeaderName]: opened.handle, Authorization: 'Bearer code-set-value', }, }), globalFetch: globalFetch as unknown as typeof fetch, }) const [outbound] = seen expect(outbound?.headers.get('authorization')).toBe(`Bearer ${resendKey}`) expect(outbound?.headers.has(credentialClientHeaderName)).toBe(false) expect(outbound?.redirect).toBe('manual') expect(response.status).toBe(401) expect(response.headers.get(credentialClientHintHeaderName)).toBe( 'header Authorization Bearer', ) const text = await response.text() expect(text).not.toContain(resendKey) // Without a binding (no run), a client fetch is refused before any send. seen.length = 0 await expect( executeGatewayFetch({ env: t.env, props: { baseUrl: 'https://example.com', userId: t.acmeId, email: 'bea@example.com', request, storageContext: null, }, request: new Request('https://api.resend.com/emails', { headers: { [credentialClientHeaderName]: opened.handle }, }), globalFetch: globalFetch as unknown as typeof fetch, }), ).rejects.toMatchObject({ body: { code: 'invalid_request' } }) expect(seen).toHaveLength(0) }) test('the gateway sends only the exact composition every credential approved by ID', async () => { const t = await setup() const entryId = await t.storeKey({ name: 'entry' }) const companionId = await t.storeKey({ name: 'companion', value: 'companion-value', provider: 'external', placement: { body: true }, }) const endpoint = 'https://api.resend.com/settings' const packageId = 'approved-package' const profile = { kind: 'composition', packageId, endpoint, method: 'POST', entryCredentialId: entryId, sites: [ { kind: 'header', name: 'Authorization', parts: ['Bearer ', { credentialId: entryId }], }, { kind: 'body', credentialId: companionId, placement: { kind: 'body', packageId, endpoint, method: 'POST', mediaType: 'application/json', fields: [['value']], selectors: [{ path: ['resource'], value: 'approved' }], }, }, ], } const setProfile = (id: string, next: unknown) => t.db .prepare('UPDATE secret_entries SET inject_json = ? WHERE id = ?') .bind(JSON.stringify(next), id) .run() await setProfile(entryId, profile) const request = t.requestAs('bea', 'owner') const opened = await openCredentialClient(t.contextFor({ request }), { key: 'resend', }) const forward = vi.fn(async (wire: Request) => { expect(wire.headers.get('authorization')).toBe(`Bearer ${resendKey}`) expect(wire.headers.has(credentialClientHeaderName)).toBe(false) expect(wire.headers.has('x-http-method-override')).toBe(false) expect(wire.redirect).toBe('manual') expect(await wire.json()).toEqual({ resource: 'approved', value: 'companion-value', }) return new Response('companion-value') }) const send = (input?: { body?: object boundId?: string headers?: HeadersInit redirect?: boolean }) => executeGatewayFetch({ env: t.env, props: { baseUrl: 'https://example.com', userId: t.acmeId, email: null, request, storageContext: { packageId, storageId: packageId, appId: packageId, sessionId: null, }, boundPackageId: input?.boundId ?? packageId, grantedSecretAuthorityPackageIds: [packageId, 'other-package'], credentialClientBinding: 'run:test', }, request: new Request(endpoint, { method: 'POST', headers: { [credentialClientHeaderName]: opened.handle, 'Content-Type': 'application/json', 'X-HTTP-Method-Override': 'DELETE', ...input?.headers, }, body: JSON.stringify(input?.body ?? { resource: 'approved' }), }), globalFetch: (input?.redirect ? async () => Response.redirect('https://other.example/') : forward) as unknown as typeof fetch, }) const refusal = { body: { code: 'invalid_request' } } await expect(send()).rejects.toMatchObject(refusal) await setProfile(companionId, profile) await expect(send({ boundId: 'other-package' })).rejects.toMatchObject( refusal, ) await expect(send({ boundId: '' })).rejects.toMatchObject(refusal) await expect( send({ headers: { Authorization: 'caller auth' } }), ).rejects.toMatchObject(refusal) await expect(send({ body: { resource: 'other' } })).rejects.toMatchObject( refusal, ) await expect( send({ body: { resource: 'approved', value: 'override' } }), ).rejects.toMatchObject(refusal) expect(forward).not.toHaveBeenCalled() const result = await send() expect(await result.text()).not.toContain('companion-value') expect(forward).toHaveBeenCalledTimes(1) await expect(send({ redirect: true })).rejects.toMatchObject(refusal) const otherBucket = 'other-package-bucket' await t.db .prepare( `INSERT INTO secret_buckets (id, user_id, scope, binding_key, created_at, updated_at) VALUES (?, ?, 'package', 'other-package', ?, ?)`, ) .bind(otherBucket, t.acmeId, now, now) .run() await t.db .prepare('UPDATE secret_entries SET bucket_id = ? WHERE id = ?') .bind(otherBucket, companionId) .run() await expect(send()).rejects.toMatchObject(refusal) expect(forward).toHaveBeenCalledTimes(1) }) test('the placed header drops the code value before placeholders expand, so a placeholder there never resolves', async () => { const t = await setup() await t.storeKey({ name: 'resend-prod' }) vi.spyOn(usageModule, 'recordUsage').mockResolvedValue(undefined) const request = t.requestAs('bea', 'owner') const opened = await openCredentialClient(t.contextFor({ request }), { key: 'resend', }) const seen: Array = [] const response = await executeGatewayFetch({ env: t.env, props: { baseUrl: 'https://example.com', userId: t.acmeId, email: 'bea@example.com', request, storageContext: null, credentialClientBinding: 'run:test', }, request: new Request('https://api.resend.com/emails', { headers: { [credentialClientHeaderName]: opened.handle, Authorization: 'Bearer {{secret:no-such-secret}}', }, }), globalFetch: (async (outbound: Request) => { seen.push(outbound) return new Response('ok') }) as unknown as typeof fetch, }) expect(response.status).toBe(200) expect(seen[0]?.headers.get('authorization')).toBe(`Bearer ${resendKey}`) }) test('a need a republish added fails only that call in a trigger run, with an org-scoped creation link', async () => { const t = await setup() await t.storeKey({ name: 'resend-prod' }) const packageId = await t.savePackage({ ownerId: t.acmeId, name: '@acme/digest', }) const beaTrigger = deriveRequestContext({ user: { userId: t.people.bea.personId }, source: { kind: 'schedule', jobId: 'job-1', enablement: { id: 'enablement-bea-daily', enabler: { userId: t.people.bea.personId }, role: 'owner', }, }, orgBinding: { org: { id: t.acmeId, slug: 'acme-clients' }, role: 'owner' }, }) const open = (key: string) => openCredentialClient(t.contextFor({ request: beaTrigger, packageId }), { key, }) mockNeeds([{ key: 'mail', provider: 'resend' }]) await expect(open('mail')).resolves.toMatchObject({ name: 'resend-prod' }) mockNeeds([ { key: 'mail', provider: 'resend' }, { key: 'chat', provider: 'slack' }, ]) const unbound = await rejection(open('chat')) const unboundUrl = new URL((unbound.body as { createUrl: string }).createUrl) expect(unbound.body).toMatchObject({ code: 'credential_unbound' }) expect(unboundUrl.pathname).toBe('/@acme-clients/-/credentials/new') expect(unboundUrl.searchParams.get('need')).toBe('chat') expect(unbound.message).toContain(`Create one at ${unboundUrl.href}`) // The rest of the trigger keeps working. await expect(open('mail')).resolves.toMatchObject({ name: 'resend-prod' }) await t.storeKey({ name: 'slack-a', provider: 'slack' }) await t.storeKey({ name: 'slack-b', provider: 'slack' }) const ambiguous = await rejection(open('chat')) expect(ambiguous.body).toMatchObject({ code: 'credential_ambiguous', options: [ expect.objectContaining({ name: 'slack-a' }), expect.objectContaining({ name: 'slack-b' }), ], }) expect( new URL((ambiguous.body as { createUrl: string }).createUrl).pathname, ).toBe('/@acme-clients/-/credentials/new') await expect(open('mail')).resolves.toMatchObject({ name: 'resend-prod' }) }) test('an execution-context run routed for a trigger reads the same mapping layers as the trigger on cloud', async () => { const t = await setup() const keyA = await t.storeKey({ name: 'resend-a' }) const keyB = await t.storeKey({ name: 'resend-b' }) const keyC = await t.storeKey({ name: 'resend-c' }) const packageId = await t.savePackage({ ownerId: t.acmeId, name: '@acme-clients/relay', }) const enablementId = 'enablement-bea-relay' const map = ( target: CredentialMappingRowTarget, credentialIds: Array | null, ) => runCredentialMappingWrite( t.db, buildWriteCredentialMappingStatement({ db: t.db, orgId: t.acmeId, packageId, needKey: 'resend', target, credentialIds, updatedByUserId: t.people.bea.personId, now, }), ) const orgBinding = { org: { id: t.acmeId, slug: 'acme-clients' }, role: 'owner', } as const const cloudTrigger = deriveRequestContext({ user: { userId: t.people.bea.personId }, source: { kind: 'platform-event', sourceId: 'subscription-1', enablement: { id: enablementId, enabler: { userId: t.people.bea.personId }, role: 'owner', }, }, orgBinding, }) const contextRun = (routedEnablementId: string | null) => deriveRequestContext({ user: { userId: t.people.bea.personId }, source: { kind: 'execution-context-run', ecid: 'ec_1', runId: 'run_1', enablementId: routedEnablementId, }, orgBinding, }) const open = (request: ReturnType) => openCredentialClient(t.contextFor({ request, packageId }), { key: 'resend', }) const both = async (expected: { name: string } | { code: string }) => { for (const request of [cloudTrigger, contextRun(enablementId)]) { if ('name' in expected) { await expect(open(request)).resolves.toMatchObject(expected) } else { await expect(open(request)).rejects.toMatchObject({ body: { code: expected.code }, }) } } } mockNeeds([{ key: 'resend' }]) // Nothing mapped: the same auto-pick refusal on cloud and the context. await both({ code: 'credential_ambiguous' }) await map({ target: 'org' }, [keyC]) await both({ name: 'resend-c' }) await map({ target: 'mine', personId: t.people.bea.personId }, [keyB]) await both({ name: 'resend-b' }) const trigger = { target: 'enablement', enablementId, personId: t.people.bea.personId, } as const await map(trigger, [keyA]) await both({ name: 'resend-a' }) // A context run routed for no enablement reads no trigger layer. await expect(open(contextRun(null))).resolves.toMatchObject({ name: 'resend-b', }) await expect(open(contextRun('enablement-other'))).resolves.toMatchObject({ name: 'resend-b', }) // Mapped to nothing on purpose refuses with the creation link. await map(trigger, []) for (const request of [cloudTrigger, contextRun(enablementId)]) { const unbound = await rejection(open(request)) expect(unbound.body).toMatchObject({ code: 'credential_unbound', createUrl: expect.stringContaining('/@acme-clients/-/credentials/new'), }) expect(unbound.message).toContain('(this trigger)') } // A mapped credential that is gone or revoked refuses; nothing else is // auto-picked. await map(trigger, ['credential-revoked']) await both({ code: 'credential_not_found' }) }) test('a stored mapping stops applying when the need changes or is removed, and a corrupt row reads as unset', async () => { const t = await setup() const keyA = await t.storeKey({ name: 'resend-a' }) await t.db .prepare( `INSERT INTO mcp_server_settings (id, user_id, name, url, provider, enabled) VALUES ('mcp-resend', ?, 'resend-mcp', 'https://mcp.resend.example/sse', 'resend', 1)`, ) .bind(t.acmeId) .run() const packageId = await t.savePackage({ ownerId: t.acmeId, name: '@acme-clients/digest', }) const mapOrg = (credentialIds: Array) => runCredentialMappingWrite( t.db, buildWriteCredentialMappingStatement({ db: t.db, orgId: t.acmeId, packageId, needKey: 'resend', target: { target: 'org' }, credentialIds, updatedByUserId: t.people.bea.personId, now, }), ) const open = () => openCredentialClient( t.contextFor({ request: t.requestAs('bea', 'owner'), packageId }), { key: 'resend' }, ) mockNeeds([{ key: 'resend' }]) await mapOrg([keyA]) await expect(open()).resolves.toMatchObject({ name: 'resend-a' }) mockNeeds([{ key: 'resend', provider: 'postmark' }]) await expect(open()).rejects.toMatchObject({ body: { code: 'credential_unbound' }, }) mockNeeds([{ key: 'resend', kind: undefined }]) await mapOrg(['mcp-resend']) await expect(open()).resolves.toMatchObject({ name: 'resend-a', kind: 'secret', }) await mapOrg([]) await t.db .prepare(`UPDATE credential_mappings SET credential_ids_json = '{bad'`) .run() consoleError.mockImplementation(() => {}) await expect(open()).resolves.toMatchObject({ name: 'resend-a' }) expect(consoleError).toHaveBeenCalledWith( expect.stringContaining('corrupt credential ids'), ) await mapOrg([]) await expect(open()).rejects.toMatchObject({ body: { code: 'credential_unbound' }, }) // Removed need: the leftover row is ignored and the key auto-resolves. mockNeeds([]) await expect(open()).rejects.toMatchObject({ body: { code: 'credential_ambiguous' }, }) expect( await deleteCredentialMappingsForPackage({ db: t.db, orgId: t.acmeId, packageId, }), ).toBe(1) }) test('a call map pick wins over a stored mapping, and credentials() opens every mapped credential', async () => { const t = await setup() const keyA = await t.storeKey({ name: 'resend-a' }) const keyB = await t.storeKey({ name: 'resend-b' }) const packageId = await t.savePackage({ ownerId: t.acmeId, name: '@acme-clients/digest', }) mockNeeds([{ key: 'resend' }]) await runCredentialMappingWrite( t.db, buildWriteCredentialMappingStatement({ db: t.db, orgId: t.acmeId, packageId, needKey: 'resend', target: { target: 'org' }, credentialIds: [keyA, keyB], updatedByUserId: t.people.bea.personId, now, }), ) const request = t.requestAs('bea', 'owner') await expect( openCredentialClient(t.contextFor({ request, packageId }), { key: 'resend', }), ).resolves.toMatchObject({ name: 'resend-a' }) await expect( openCredentialClient( t.contextFor({ request, packageId, credentials: { resend: 'resend-b' } }), { key: 'resend' }, ), ).resolves.toMatchObject({ name: 'resend-b' }) const all = await openCredentialClients( t.contextFor({ request, packageId }), { key: 'resend', }, ) expect(all.map((client) => client.name)).toEqual(['resend-a', 'resend-b']) }) test('a call map picks by name among several matches, and credentials() opens every pick', async () => { const t = await setup() await t.storeKey({ name: 'resend-a' }) await t.storeKey({ name: 'resend-b' }) const request = t.requestAs('bea', 'owner') await expect( rejection( openCredentialClient(t.contextFor({ request }), { key: 'resend' }), ), ).resolves.toMatchObject({ body: { code: 'credential_ambiguous' } }) const picked = await openCredentialClient( t.contextFor({ request, credentials: { resend: 'resend-b' } }), { key: 'resend' }, ) expect(picked).toMatchObject({ name: 'resend-b', scope: 'org', key: 'resend', }) expect(picked.hint).toBeUndefined() const both = t.contextFor({ request, credentials: { resend: ['resend-a', { name: 'resend-b', scope: 'org' }] }, }) const many = await openCredentialClients(both, { key: 'resend' }) expect(many.map((client) => client.name)).toEqual(['resend-a', 'resend-b']) await expect( rejection(openCredentialClient(both, { key: 'resend' })), ).resolves.toMatchObject({ body: { code: 'invalid_request', message: 'The credentials map picks 2 credentials for "resend": "resend-a" (org), "resend-b" (org). Pick one of them for credential("resend"), or call credentials("resend") to get all of them.', retryWith: [ expect.objectContaining({ credentials: { resend: { id: expect.any(String) } }, }), expect.objectContaining({ credentials: { resend: { id: expect.any(String) } }, }), ], options: [ expect.objectContaining({ name: 'resend-a', scope: 'org' }), expect.objectContaining({ name: 'resend-b', scope: 'org' }), ], }, }) const none = t.contextFor({ request, credentials: { resend: [] } }) expect(await openCredentialClients(none, { key: 'resend' })).toEqual([]) await expect( rejection(openCredentialClient(none, { key: 'resend' })), ).resolves.toMatchObject({ body: { code: 'credential_unbound' } }) // No map entry: a multiple need still gets only the one match. await t.storeKey({ name: 'solo', provider: 'solo' }) const solo = await openCredentialClients(t.contextFor({ request }), { key: 'solo', }) expect(solo.map((client) => client.name)).toEqual(['solo']) }) test('a call map is validated before code runs: unknown keys fail an invoke and warn ad hoc code', async () => { const t = await setup() const id = await t.storeKey({ name: 'resend-prod' }) const request = t.requestAs('bea', 'owner') const packageId = await t.savePackage({ ownerId: t.acmeId, name: '@acme/m' }) mockNeeds([{ key: 'MAIL', provider: 'resend' }]) const validate = ( credentials: CredentialCallMapInput, strict: boolean, packageIds: Array = [packageId], ) => validateCredentialCallMap({ env: t.env, request, map: normalizeCredentialCallMap(credentials)!, packageIds, strict, baseUrl: 'https://example.com', }) await expect(validate({ MAIL: 'resend-prod' }, true)).resolves.toEqual({ warnings: [], map: new Map([['MAIL', [{ id }]]]), }) await expect(validate({ MAIL: { id } }, true)).resolves.toEqual({ warnings: [], map: new Map([['MAIL', [{ id }]]]), }) await expect( rejection(validate({ MAIL: 'resend-prod', OTHER: 'resend-prod' }, true)), ).resolves.toMatchObject({ body: { code: 'credential_need_unknown', retryWith: [] }, }) const adHoc = await validate({ resend: 'resend-prod' }, false, []) expect(adHoc.warnings).toEqual([ expect.stringContaining('credentials.resend is not a need of this code'), ]) const missing = await rejection(validate({ MAIL: 'missing' }, true)) expect(missing.body).toMatchObject({ code: 'credential_not_found' }) expect( Object.fromEntries( new URL((missing.body as { createUrl: string }).createUrl).searchParams, ), ).toEqual({ kind: 'secret', kindMode: 'required', name: 'missing', }) const emptyPick = await rejection( openCredentialClient( t.contextFor({ request, packageId, credentials: { MAIL: [] } }), { key: 'MAIL' }, ), ) expect(emptyPick.body).toMatchObject({ code: 'credential_unbound', createUrl: expect.stringContaining('need=MAIL'), }) await expect( rejection( validateCredentialCallMap({ env: t.env, request: null, map: normalizeCredentialCallMap({ MAIL: 'resend-prod' })!, packageIds: [], strict: false, baseUrl: 'https://example.com', }), ), ).resolves.toMatchObject({ body: { code: 'credential_denied' } }) }) async function setupEntryAndDependency() { const t = await setup() const keyA = await t.storeKey({ name: 'resend-a' }) const keyB = await t.storeKey({ name: 'resend-b' }) const entryId = await t.savePackage({ ownerId: t.acmeId, name: '@acme-clients/storefront', }) const depId = await t.savePackage({ ownerId: t.acmeId, name: '@acme-clients/mail-kit', }) const mail: CredentialNeed = { key: 'MAIL', kind: 'secret', provider: 'resend', description: '', multiple: false, } const needsBySource = new Map>([ [`source-${entryId}`, [{ ...mail, from: '@acme-clients/mail-kit' }]], [`source-${depId}`, [mail]], ]) vi.spyOn(needsClosure, 'loadPublishedCredentialNeeds').mockImplementation( async ({ sourceId }) => needsBySource.get(sourceId) ?? [], ) const map = ( packageId: string, target: CredentialMappingRowTarget, credentialIds: Array | null, ) => runCredentialMappingWrite( t.db, buildWriteCredentialMappingStatement({ db: t.db, orgId: t.acmeId, packageId, needKey: 'MAIL', target, credentialIds, updatedByUserId: t.people.bea.personId, now, }), ) const callerContextFor = (request: ReturnType) => ({ baseUrl: 'https://example.com', request, user: { userId: request.actor!.userId }, }) as unknown as McpCallerContext const open = async ( options: CredentialClientToolOptions, request: ReturnType, args: Record = {}, ) => (await createCredentialClientKodyTools({ env: t.env, callerContext: callerContextFor(request), options, })[credentialClientToolNames.open]!({ key: 'MAIL', ...args })) as { ok: boolean value?: { name: string } error?: { code: string; message: string; createUrl?: string } } return { ...t, keyA, keyB, entryId, depId, mail, needsBySource, map, callerContextFor, open, } } test('a dependency credential() reads stored mappings and the creation link from the run entry package', async () => { const t = await setupEntryAndDependency() const bea = t.requestAs('bea', 'owner') const { needs, entries } = await loadRunCredentialNeedEntries({ env: t.env, orgId: t.acmeId, packageIds: [t.entryId], }) expect(entries.entryByKey.get('MAIL')).toBe(t.entryId) const dependency = (request: ReturnType) => ({ ...t.contextFor({ request, packageId: t.depId }), runNeeds: async () => needs, runEntries: async () => entries, }) const open = (request = bea) => openCredentialClient(dependency(request), { key: 'MAIL' }) await expect(open()).rejects.toMatchObject({ body: { code: 'credential_ambiguous' }, }) await t.map(t.entryId, { target: 'org' }, [t.keyB]) await expect(open()).resolves.toMatchObject({ key: 'MAIL', name: 'resend-b' }) // The dependency's own scope has no mapping, so without the run's entries // the same call stays ambiguous. await expect( openCredentialClient( { ...dependency(bea), runEntries: undefined }, { key: 'MAIL' }, ), ).rejects.toMatchObject({ body: { code: 'credential_ambiguous' } }) // A mapping stored on the dependency itself never applies to its entry's run. await t.map(t.depId, { target: 'org' }, [t.keyA]) await expect(open()).resolves.toMatchObject({ name: 'resend-b' }) await t.map(t.entryId, { target: 'mine', personId: t.people.bea.personId }, [ t.keyA, ]) await expect(open()).resolves.toMatchObject({ name: 'resend-a' }) await t.map( t.entryId, { target: 'mine', personId: t.people.bea.personId }, [], ) const unbound = await rejection(open()) expect(unbound.body).toMatchObject({ code: 'credential_unbound' }) const createUrl = new URL((unbound.body as { createUrl: string }).createUrl) expect(createUrl.searchParams.get('forPackage')).toBe('storefront') expect(createUrl.searchParams.get('need')).toBe('MAIL') // A trigger run reads the entry package's enablement mapping too. await t.grantUse(t.keyA, 'ann') await t.grantUse(t.keyB, 'ann') const enablementId = 'enablement-ann-nightly' const annTrigger = deriveRequestContext({ user: { userId: t.people.ann.personId }, source: { kind: 'schedule', jobId: 'job-1', enablement: { id: enablementId, enabler: { userId: t.people.ann.personId }, role: 'member', }, }, orgBinding: { org: { id: t.acmeId, slug: 'acme-clients' }, role: null }, }) const trigger = { target: 'enablement', enablementId, personId: t.people.ann.personId, } as const await t.map(t.depId, trigger, [t.keyB]) await t.map(t.entryId, trigger, [t.keyA]) await expect(open(annTrigger)).resolves.toMatchObject({ name: 'resend-a' }) }) test('hosted execute and invoke read the entry mapping for a bound dependency, and its code cannot name another package', async () => { const t = await setupEntryAndDependency() const bea = t.requestAs('bea', 'owner') await t.map(t.entryId, { target: 'org' }, [t.keyB]) const hosted = (runPackageId: string | null) => createRunCredentialClientToolOptions({ env: t.env, callerContext: t.callerContextFor(bea), binding: 'run:test', runPackageId, entryPackageIds: [t.entryId], callMap: null, })! // Invoke runs the entry package; ad hoc execute imports it, so it is the // run's entry either way. for (const options of [hosted(t.entryId), hosted(null)]) { await expect( runWithCurrentSecretAuthority(t.depId, () => t.open(options, bea)), ).resolves.toMatchObject({ ok: true, value: { name: 'resend-b' } }) await expect( runWithCurrentSecretAuthority(t.depId, () => t.open(options, bea, { packageId: t.entryId }), ), ).resolves.toMatchObject({ ok: false, error: { code: 'credential_denied', message: createCredentialClientOwnerOnlyMessage(t.entryId), }, }) } // The entry's own code reads its mapping; ad hoc code reads none. await expect(t.open(hosted(t.entryId), bea)).resolves.toMatchObject({ ok: true, value: { name: 'resend-b' }, }) await expect(t.open(hosted(null), bea)).resolves.toMatchObject({ ok: false, error: { code: 'credential_ambiguous' }, }) }) test('local CapabilityProxy reads the entry mapping from the signed binding, never a claimed id', async () => { const t = await setupEntryAndDependency() const bea = t.requestAs('bea', 'owner') await t.map(t.entryId, { target: 'org' }, [t.keyB]) const subject = { org: t.acmeId, actor: bea.actor!.userId } const options = createCapabilityProxyCredentialClientTools( { env: t.env, callerContext: t.callerContextFor(bea), } as unknown as ApiInvocationContext, null, )! const depBinding = await signLocalExecutePackageBinding({ env: t.env, packageId: t.depId, subject, entryPackageIds: [t.entryId], }) await expect( t.open(options, bea, { packageId: depBinding }), ).resolves.toMatchObject({ ok: true, value: { name: 'resend-b' } }) // A binding minted without entries keeps the dependency's own scope. const legacyBinding = await signLocalExecutePackageBinding({ env: t.env, packageId: t.depId, subject, }) await expect( t.open(options, bea, { packageId: legacyBinding }), ).resolves.toMatchObject({ ok: false, error: { code: 'credential_ambiguous' }, }) // Bare ids are refused, the entry's included. for (const packageId of [t.depId, t.entryId]) { await expect(t.open(options, bea, { packageId })).resolves.toMatchObject({ ok: false, error: { code: 'credential_denied' }, }) } }) test('ownerCredentialForVisitors on a need grants no owner authority; the caller still resolves the credential', async () => { const t = await setup() await t.storeKey({ name: 'rooms-db', provider: 'database', hosts: ['db.example.com'], }) const request = t.requestAs('bea', 'owner') const packageId = await t.savePackage({ ownerId: t.acmeId, name: '@acme-clients/rooms', }) const runNeeds = Promise.resolve( new Map([ [ 'database', { key: 'database', kind: 'secret', provider: 'database', description: 'Rooms.', multiple: false, ownerCredentialForVisitors: true, }, ], ]), ) const asOwner = { ...t.contextFor({ request, packageId }), runNeeds: () => runNeeds, } await expect( openCredentialClient(asOwner, { key: 'database' }), ).resolves.toMatchObject({ key: 'database', name: 'rooms-db' }) const anonymous = { ...t.contextFor({ request, packageId }), callerContext: { baseUrl: 'https://example.com', request: null, user: null, } as unknown as (typeof asOwner)['callerContext'], runNeeds: () => runNeeds, } await expect( rejection(openCredentialClient(anonymous, { key: 'database' })), ).resolves.toMatchObject({ body: { code: 'credential_denied' }, message: expect.stringContaining('no acting person'), }) }) test('an unbound need error names a same-named Key that did not match, with the fix', async () => { const t = await setup() const packageId = await t.savePackage({ ownerId: t.acmeId, name: '@acme/memo', }) const bea = t.contextFor({ request: t.requestAs('bea', 'owner'), packageId }) mockNeeds([{ key: 'memo-bearer', provider: 'memo-bearer' }]) const id = await t.storeKey({ name: 'memo-bearer', provider: null }) const unbound = await rejection( openCredentialClient(bea, { key: 'memo-bearer' }), ) expect(unbound.body).toMatchObject({ code: 'credential_unbound' }) expect(unbound.message).toContain( `Credential "memo-bearer" (id ${id}) is named like this need but has no provider, and only a Key stored for this package (package scope) matches a need by name. To fill it, set its provider with credentialUpdate { credential_id: "${id}", provider: "memo-bearer" }`, ) expect(unbound.message).not.toContain(resendKey) })