import { OauthClients } from '../../../../src/db/entities/OauthClients.entity'; import { OauthTokens } from '../../../../src/db/entities/OauthTokens.entity'; import type { OauthClientsRepository } from '../../../../src/db/repositories/OauthClients.repository'; import { dbNow } from '../../../../src/db/types'; import { withRequestContext } from '../../../../src/nest/database/request-context'; import { UnitOfWork } from '../../../../src/nest/database/unit-of-work'; import { createSnapshotTestDb } from '../../../helpers/db-mock'; import { createUser } from '../../../helpers/factories'; import { deleteRows, findRow, insertRow, updateRows } from '../../../helpers/factories/rows'; import { resetTestDb } from '../../../helpers/test-db'; import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; const testDb = createSnapshotTestDb(); let t: TestOrm; let clients: OauthClientsRepository; let uow: UnitOfWork; beforeAll(async () => { t = await createTestOrm(testDb); clients = t.repo(OauthClients); uow = new UnitOfWork(t.em); }); beforeEach(async () => { resetTestDb(testDb); t.clear(); await deleteRows(t, OauthTokens); await deleteRows(t, OauthClients); }); afterAll(async () => { await t.close(); testDb.close(); }); async function seedClient( overrides: Partial<{ id: string; userId: number | null; name: string; clientId: string; secretHash: string; redirectUris: string; allowedScopes: string; isPublic: number; createdVia: string; allowsClientCredentials: number; }> = {}, ): Promise<{ id: string; userId: number | null; clientId: string }> { const id = overrides.id ?? `row-${Math.random().toString(36).slice(2)}`; const clientId = overrides.clientId ?? `proto-${Math.random().toString(36).slice(2)}`; await insertRow(t, OauthClients, { id, user: overrides.userId ?? null, name: overrides.name ?? 'Test Client', client_id: clientId, client_secret_hash: overrides.secretHash ?? 'hash-value', redirect_uris: overrides.redirectUris ?? '["https://example.com/cb"]', allowed_scopes: overrides.allowedScopes ?? '["trips:read"]', is_public: overrides.isPublic ?? 0, created_via: overrides.createdVia ?? 'settings_ui', allows_client_credentials: overrides.allowsClientCredentials ?? 0, }); return { id, userId: overrides.userId ?? null, clientId }; } /** The stored row, client_secret_hash included, which no repository read returns. */ function storedClient(id: string) { return findRow(t, OauthClients, { id }); } describe('OauthClientsRepository', () => { describe('listByUser (OA1)', () => { it("OAUTHCLIENTREPO-001: returns the caller's clients only, newest first, without the secret hash", async () => { const { user } = createUser(testDb); const { user: other } = createUser(testDb); await seedClient({ userId: user.id, name: 'first', createdVia: 'settings_ui' }); testDb.exec("UPDATE oauth_clients SET created_at = '2020-01-01 00:00:00' WHERE name = 'first'"); await seedClient({ userId: user.id, name: 'second' }); testDb.exec("UPDATE oauth_clients SET created_at = '2021-01-01 00:00:00' WHERE name = 'second'"); await seedClient({ userId: other.id, name: 'not-mine' }); const rows = await clients.listByUser(user.id); expect(rows.map((r) => r.name)).toEqual(['second', 'first']); expect(rows[0]).not.toHaveProperty('client_secret_hash'); expect(rows[0].user_id).toBe(user.id); }); it('OAUTHCLIENTREPO-002: empty for a user with no clients', async () => { const { user } = createUser(testDb); expect(await clients.listByUser(user.id)).toEqual([]); }); it('OAUTHCLIENTREPO-002b: created_at NULL comes back null, not undefined (coverage: rule 16)', async () => { const { user } = createUser(testDb); const { id } = await seedClient({ userId: user.id, name: 'null-created' }); await updateRows(t, OauthClients, { id }, { created_at: null }); const rows = await clients.listByUser(user.id); expect(rows[0].created_at).toBeNull(); }); }); describe('countByUser / countAnonymous (OA2/OA3)', () => { it("OAUTHCLIENTREPO-003: countByUser only counts the given user's rows", async () => { const { user } = createUser(testDb); const { user: other } = createUser(testDb); await seedClient({ userId: user.id }); await seedClient({ userId: user.id }); await seedClient({ userId: other.id }); expect(await clients.countByUser(user.id)).toBe(2); expect(await clients.countByUser(other.id)).toBe(1); }); it('OAUTHCLIENTREPO-004: countAnonymous counts only NULL-user rows', async () => { const { user } = createUser(testDb); await seedClient({ userId: user.id }); await seedClient({ userId: null }); await seedClient({ userId: null }); expect(await clients.countAnonymous()).toBe(2); }); }); describe('insertClient / findPublicById (OA4/OA5)', () => { it('OAUTHCLIENTREPO-005: writes exactly the given columns and the re-select matches', async () => { const { user } = createUser(testDb); const row = await clients.insertClient({ id: 'client-row-1', user_id: user.id, name: 'My Client', client_id: 'proto-abc', client_secret_hash: 'secrethash', redirect_uris: '["https://a.example.com/cb"]', allowed_scopes: '["trips:read","trips:write"]', is_public: 0, created_via: 'settings_ui', allows_client_credentials: 0, }); expect(row).toMatchObject({ id: 'client-row-1', user_id: user.id, name: 'My Client', client_id: 'proto-abc', redirect_uris: '["https://a.example.com/cb"]', allowed_scopes: '["trips:read","trips:write"]', is_public: 0, created_via: 'settings_ui', allows_client_credentials: 0, }); const raw = await storedClient('client-row-1'); expect(raw?.client_secret_hash).toBe('secrethash'); }); it('OAUTHCLIENTREPO-005b: findPublicById is null for an unknown id', async () => { expect(await clients.findPublicById('nope')).toBeNull(); }); it('OAUTHCLIENTREPO-005c: findPublicById — created_at NULL comes back null, not undefined (coverage: rule 16)', async () => { const { id } = await seedClient({ name: 'null-created-public' }); await updateRows(t, OauthClients, { id }, { created_at: null }); const row = await clients.findPublicById(id); expect(row?.created_at).toBeNull(); }); it('OAUTHCLIENTREPO-006: insertClient writes a NULL user_id for anonymous DCR clients', async () => { const row = await clients.insertClient({ id: 'client-row-2', user_id: null, name: 'DCR Client', client_id: 'proto-dcr', client_secret_hash: 'x', redirect_uris: '[]', allowed_scopes: '[]', is_public: 1, created_via: 'dcr', allows_client_credentials: 0, }); expect(row.user_id).toBeNull(); }); it('OAUTHCLIENTREPO-006b: throws when the read-back after insert finds no row (coverage: the guard branch)', async () => { const spy = vi.spyOn(clients, 'findPublicById').mockResolvedValueOnce(null); await expect( clients.insertClient({ id: 'client-row-ghost', user_id: null, name: 'Ghost Client', client_id: 'proto-ghost', client_secret_hash: 'x', redirect_uris: '[]', allowed_scopes: '[]', is_public: 1, created_via: 'dcr', allows_client_credentials: 0, }), ).rejects.toThrow('OauthClientsRepository.insertClient: row client-row-ghost not found immediately after insert'); spy.mockRestore(); }); }); describe('findOwned (OA6/OA9)', () => { it('OAUTHCLIENTREPO-007: matches id+user, returns the superset projection', async () => { const { user } = createUser(testDb); const { id, clientId } = await seedClient({ userId: user.id, isPublic: 1 }); const row = await clients.findOwned(id, user.id); expect(row).toEqual({ id, client_id: clientId, is_public: 1 }); }); it("OAUTHCLIENTREPO-008: 404-shape null for another user's client (never 403)", async () => { const { user } = createUser(testDb); const { user: other } = createUser(testDb); const { id } = await seedClient({ userId: other.id }); expect(await clients.findOwned(id, user.id)).toBeNull(); }); }); describe('updateSecretHash (OA7)', () => { it('OAUTHCLIENTREPO-009: writes the new hash, nothing else', async () => { const { id } = await seedClient({ secretHash: 'old' }); await clients.updateSecretHash(id, 'new-hash'); const row = await storedClient(id); expect(row?.client_secret_hash).toBe('new-hash'); }); }); describe('remove (OA10)', () => { it('OAUTHCLIENTREPO-010: deletes the row', async () => { const { id } = await seedClient(); await clients.remove(id); expect(await storedClient(id)).toBeNull(); }); }); describe('findSdkProjection (OA15)', () => { it('OAUTHCLIENTREPO-011: never carries client_secret_hash', async () => { const { clientId } = await seedClient({ secretHash: 'super-secret', name: 'SDK Client' }); const row = await clients.findSdkProjection(clientId); expect(row).toEqual({ client_id: clientId, name: 'SDK Client', redirect_uris: '["https://example.com/cb"]', allowed_scopes: '["trips:read"]', is_public: 0, created_via: 'settings_ui', }); expect(row).not.toHaveProperty('client_secret_hash'); }); it('OAUTHCLIENTREPO-012: null for unknown client_id', async () => { expect(await clients.findSdkProjection('nonexistent')).toBeNull(); }); }); describe('findAuthRow (OA21)', () => { it('OAUTHCLIENTREPO-013: exactly the three auth columns, a distinct projection from OA15', async () => { const { clientId } = await seedClient({ secretHash: 'auth-secret', isPublic: 0 }); const row = await clients.findAuthRow(clientId); expect(row).toEqual({ client_id: clientId, client_secret_hash: 'auth-secret', is_public: 0 }); }); it('OAUTHCLIENTREPO-013b: null for unknown client_id', async () => { expect(await clients.findAuthRow('nope')).toBeNull(); }); }); describe('findByClientIdFull (OA29/OA30)', () => { it('OAUTHCLIENTREPO-014: the full row, including the secret hash', async () => { const { user } = createUser(testDb); const { clientId } = await seedClient({ userId: user.id, secretHash: 'full-row-secret' }); const row = await clients.findByClientIdFull(clientId); expect(row?.client_secret_hash).toBe('full-row-secret'); expect(row?.user_id).toBe(user.id); }); it('OAUTHCLIENTREPO-015: null for unknown client_id', async () => { expect(await clients.findByClientIdFull('nope')).toBeNull(); }); }); describe('identity-map write-back regression (program RULING, D-shape)', () => { // task-4-review.md F1: the D-shape needs the `nativeUpdate`'s target // column in the FIRST, WIDER projection and absent from the SECOND, // narrower one — a stale write-back only reverts a column the second // read's snapshot doesn't already carry fresh. The original ordering // here (`listByUser`, narrow, then `findAuthRow`, wide) had it backwards: // `findAuthRow`'s own re-snapshot of `client_secret_hash` left that // column clean, so the mutation this test exists to catch (reverting // `disableIdentityMap: true` back to `refresh: true`) passed anyway. // `findAuthRow` (wide, carries `client_secret_hash`) now goes FIRST and // `findOwned` (narrow, no `client_secret_hash`) second — mutation-proven // load-bearing in the task report. it('OAUTHCLIENTREPO-016: findAuthRow then findOwned then updateSecretHash inside uow.transactional — the write survives', async () => { const { user } = createUser(testDb); const { id, clientId } = await seedClient({ userId: user.id, secretHash: 'original', name: 'kept-name' }); await withRequestContext(t.orm, async () => { // Projection A — wide, carries client_secret_hash. await clients.findAuthRow(clientId); // Projection B — narrow, a different (smaller) field set on the same row. await clients.findOwned(id, user.id); // The intended write, inside the request's own transaction. await uow.transactional(async () => { await clients.updateSecretHash(id, 'rotated'); }); }); const row = await storedClient(id); expect(row?.client_secret_hash).toBe('rotated'); // the nativeUpdate must stick expect(row?.name).toBe('kept-name'); // untouched by either read }); }); describe('upsertCimdClient', () => { const cimd = (name: string, scopes = '["trips:read"]') => ({ id: 'cimd-row', name, client_id: 'https://claude.ai/oauth/mcp-client.json', client_secret_hash: '', redirect_uris: '["https://claude.ai/api/mcp/auth_callback"]', allowed_scopes: scopes, }); it('OAUTHCLIENTREPO-017: registers a public cimd client, then refreshes it from its document', async () => { await clients.upsertCimdClient(cimd('Claude')); expect(await storedClient('cimd-row')).toMatchObject({ name: 'Claude', is_public: 1, created_via: 'cimd', user_id: null, allows_client_credentials: 0, }); await clients.upsertCimdClient({ ...cimd('Claude (new)', '["trips:read","places:write"]'), id: 'ignored' }); expect(await findRow(t, OauthClients, { id: 'ignored' })).toBeNull(); expect(await storedClient('cimd-row')).toMatchObject({ name: 'Claude (new)', allowed_scopes: '["trips:read","places:write"]', }); }); it('OAUTHCLIENTREPO-018: leaves a client another path registered under that client_id alone', async () => { const { id } = await seedClient({ clientId: 'https://claude.ai/oauth/mcp-client.json', name: 'Registered' }); await clients.upsertCimdClient(cimd('Claude')); expect(await storedClient(id)).toMatchObject({ name: 'Registered', created_via: 'settings_ui' }); }); }); describe('deleteUnusedCimdBefore', () => { const CUTOFF = dbNow(new Date('2026-10-01T00:00:00Z')); const OLD = '2026-09-01 00:00:00'; async function holdToken(clientId: string): Promise { const { user } = createUser(testDb); await insertRow(t, OauthTokens, { client: clientId, user: user.id, access_token_hash: `acc-${clientId}`, refresh_token_hash: `ref-${clientId}`, access_token_expires_at: new Date(Date.now() + 3600_000).toISOString(), refresh_token_expires_at: new Date(Date.now() + 86_400_000).toISOString(), }); } it('OAUTHCLIENTREPO-019: drops old cimd clients nobody holds a token for, and counts them', async () => { const unused = await seedClient({ createdVia: 'cimd' }); const held = await seedClient({ createdVia: 'cimd' }); const recent = await seedClient({ createdVia: 'cimd' }); const registered = await seedClient({ createdVia: 'settings_ui' }); await Promise.all( [unused, held, registered].map((client) => updateRows(t, OauthClients, { id: client.id }, { created_at: OLD })), ); await updateRows(t, OauthClients, { id: recent.id }, { created_at: '2026-10-15 00:00:00' }); await holdToken(held.clientId); expect(await clients.deleteUnusedCimdBefore(CUTOFF)).toBe(1); expect(await storedClient(unused.id)).toBeNull(); const kept = await Promise.all([held, recent, registered].map((client) => storedClient(client.id))); for (const row of kept) expect(row).not.toBeNull(); expect(await clients.deleteUnusedCimdBefore(CUTOFF)).toBe(0); }); }); });