import { ownerIdFromStored } from '@kody-internal/shared/owner-person-ids.ts' import { DatabaseSync } from 'node:sqlite' import { expect, test, vi } from 'vitest' import { decryptUserOauthAccessToken, decryptUserOauthRefreshToken, encryptUserOauthAccessToken, encryptUserOauthRefreshToken, userIntegrationCredentialContext, } from '#mcp/secrets/crypto.ts' import { applyAllMigrations } from '#worker/test-support/apply-all-migrations.ts' import { createAuditTestDb, createTestOrgAuditWriter, } from '#worker/test-support/create-audit-db.ts' import { createD1FromSqlite } from '#worker/test-support/create-d1-from-sqlite.ts' import { getOrgCredential, type OrgCredential } from './credential-ids.ts' import { renameOrgCredential, vaultBindingRenameRefusal, } from './credential-rename.ts' const hub = vi.hoisted(() => ({ renameServer: vi.fn(async () => {}) })) vi.mock('#worker/mcp-client/hub-client.ts', () => ({ createMcpClientHubClient: () => hub, })) const migrationsDirectory = new URL('../../migrations/', import.meta.url) const orgId = ownerIdFromStored('org-1') function createEnv() { const sqlite = new DatabaseSync(':memory:') applyAllMigrations(sqlite, migrationsDirectory) const env = { APP_DB: createD1FromSqlite(sqlite), SECRET_STORE_KEY: 'test-secret-store-key-32-chars-minimum', } as unknown as Env return { sqlite, env } } async function insertConnection( env: Env, name: string, tokens = { access: 'access-token', refresh: 'refresh-token' }, ) { const context = userIntegrationCredentialContext(orgId, name) await env.APP_DB.prepare( `INSERT OR IGNORE INTO user_oauth_apps (user_id, slug, provider, client_id, token_url, flow) VALUES (?, 'google', 'google', 'client-id', 'https://oauth2.example.com/token', 'pkce')`, ) .bind(orgId) .run() await env.APP_DB.prepare( `INSERT INTO user_integrations (user_id, name, app_slug, access_token_encrypted, refresh_token_encrypted) VALUES (?, ?, 'google', ?, ?)`, ) .bind( orgId, name, await encryptUserOauthAccessToken(env, tokens.access, context), await encryptUserOauthRefreshToken(env, tokens.refresh, context), ) .run() const row = await env.APP_DB.prepare( `SELECT id FROM user_integrations WHERE user_id = ? AND name = ?`, ) .bind(orgId, name) .first<{ id: string }>() return row!.id } async function credential(env: Env, id: string): Promise { const found = await getOrgCredential(env.APP_DB, orgId, id) if (!found) throw new Error(`missing credential ${id}`) return found } test('renaming an OAuth connection keeps its id, id-keyed mappings, and usable tokens', async () => { const { env } = createEnv() const id = await insertConnection(env, 'old-google') const now = new Date().toISOString() await env.APP_DB.prepare( `INSERT INTO credential_mappings (id, org_id, package_id, need_key, target, credential_ids_json, created_at, updated_at) VALUES ('mapping-1', ?, 'package-1', 'google', 'org', ?, ?, ?)`, ) .bind(orgId, JSON.stringify([id]), now, now) .run() const auditDb = createAuditTestDb() const audit = createTestOrgAuditWriter({ appDb: env.APP_DB, db: auditDb, actorUserId: 'person-1', }) const result = await renameOrgCredential({ env, orgId, credential: await credential(env, id), name: 'new-google', audit, }) expect(result).toMatchObject({ name: 'new-google', previousName: 'old-google', }) expect(result.note).toContain('id:') await expect(credential(env, id)).resolves.toMatchObject({ id, kind: 'integration', name: 'new-google', live: true, }) const events = await auditDb .prepare(`SELECT action, resource_id, details_json FROM org_audit_events`) .all<{ action: string; resource_id: string; details_json: string }>() expect( events.results.map((row) => ({ action: row.action, resourceId: row.resource_id, details: JSON.parse(row.details_json), })), ).toContainEqual({ action: 'credential.renamed', resourceId: id, details: expect.objectContaining({ previousName: 'old-google', fields: ['name'], }), }) const mapping = await env.APP_DB.prepare( `SELECT credential_ids_json FROM credential_mappings WHERE id = 'mapping-1'`, ).first<{ credential_ids_json: string }>() expect(JSON.parse(mapping!.credential_ids_json)).toEqual([id]) const sealed = await env.APP_DB.prepare( `SELECT access_token_encrypted, refresh_token_encrypted FROM user_integrations WHERE id = ?`, ) .bind(id) .first<{ access_token_encrypted: string refresh_token_encrypted: string }>() const newContext = userIntegrationCredentialContext(orgId, 'new-google') await expect( decryptUserOauthAccessToken( env, sealed!.access_token_encrypted, newContext, ), ).resolves.toBe('access-token') await expect( decryptUserOauthRefreshToken( env, sealed!.refresh_token_encrypted, newContext, ), ).resolves.toBe('refresh-token') await expect( decryptUserOauthAccessToken( env, sealed!.access_token_encrypted, userIntegrationCredentialContext(orgId, 'old-google'), ), ).rejects.toThrow('Unable to decrypt integration access token.') }) test('renaming refuses a name another connection or MCP server already uses', async () => { const { env } = createEnv() const id = await insertConnection(env, 'first') await insertConnection(env, 'second') await env.APP_DB.prepare( `INSERT INTO mcp_server_settings (id, user_id, name, url) VALUES ('mcp-1', ?, 'linear-mcp', 'https://mcp.example.com/sse')`, ) .bind(orgId) .run() for (const name of ['second', 'linear-mcp']) { await expect( renameOrgCredential({ env, orgId, credential: await credential(env, id), name, audit: null, }), ).rejects.toThrow(`named "${name}" already exists in this org`) } await expect( renameOrgCredential({ env, orgId, credential: await credential(env, id), name: 'has spaces', audit: null, }), ).rejects.toThrow('is not a valid connection name') await expect( renameOrgCredential({ env, orgId, credential: await credential(env, id), name: 'Work-Google', audit: null, }), ).rejects.toThrow('is not a valid connection name') await expect( renameOrgCredential({ env, orgId, credential: await credential(env, id), name: 'kody-sealed.abc', audit: null, }), ).rejects.toThrow('reserves for sealed tokens') await expect(credential(env, id)).resolves.toMatchObject({ name: 'first' }) }) test('renaming an OAuth connection waits out a held token refresh lease', async () => { const { env } = createEnv() const id = await insertConnection(env, 'leased') await env.APP_DB.prepare( `UPDATE user_integrations SET token_refresh_lease_id = 'lease-1', token_refresh_lease_expires_at = ? WHERE id = ?`, ) .bind(new Date(Date.now() + 60_000).toISOString(), id) .run() await expect( renameOrgCredential({ env, orgId, credential: await credential(env, id), name: 'renamed', audit: null, }), ).rejects.toThrow('changed while renaming') await expect(credential(env, id)).resolves.toMatchObject({ name: 'leased' }) }) test('renaming an MCP server keeps its id and relabels the hub registration', async () => { const { env } = createEnv() await env.APP_DB.prepare( `INSERT INTO mcp_server_settings (id, user_id, name, url) VALUES ('mcp-1', ?, 'old-mcp', 'https://mcp.example.com/sse')`, ) .bind(orgId) .run() const result = await renameOrgCredential({ env, orgId, credential: await credential(env, 'mcp-1'), name: 'new-mcp', audit: null, }) expect(result).toMatchObject({ name: 'new-mcp', previousName: 'old-mcp' }) await expect(credential(env, 'mcp-1')).resolves.toMatchObject({ kind: 'mcp-server', name: 'new-mcp', }) expect(hub.renameServer).toHaveBeenCalledWith({ serverId: 'mcp-1', name: 'new-mcp', }) await expect( renameOrgCredential({ env, orgId, credential: await credential(env, 'mcp-1'), name: 'Not_Valid', audit: null, }), ).rejects.toThrow('Server name must use lowercase letters') }) test('vault bindings explain why they cannot be renamed', async () => { const { env } = createEnv() await expect( renameOrgCredential({ env, orgId, credential: { id: 'vault-1', kind: 'vault', name: 'vault', live: true }, name: 'other', audit: null, }), ).rejects.toThrow(vaultBindingRenameRefusal) })