import { describe, expect, test } from 'bun:test'; import type { PoolConfig } from 'pg'; import { RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, RESEARCH_COPILOT_PG_POOL_MAX, RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, ResearchCopilotExecutorError, type ResearchCopilotExecutorPool, openResearchCopilotExecutor, } from '../src/index'; const SECRET_USER = 'copilot_secret_user'; const SECRET_PASS = 'Sup3rS3cretP@ssw0rd!'; const SECRET_HOST = 'pg-internal-secret.example.test'; const VALID_URL = `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`; interface FakePoolState { readonly queries: Array<{ readonly text: string; readonly values?: unknown[] }>; readonly errorListeners: Array<(error: Error) => void>; endCalls: number; readonly pool: ResearchCopilotExecutorPool; } function createFakePool(options?: { onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>; onEnd?: () => Promise; }): FakePoolState { const queries: Array<{ readonly text: string; readonly values?: unknown[] }> = []; const errorListeners: Array<(error: Error) => void> = []; const state: FakePoolState = { queries, errorListeners, endCalls: 0, pool: { async query(text: string, values?: unknown[]) { queries.push(values === undefined ? { text } : { text, values }); if (options?.onQuery) { return options.onQuery(text, values); } return { rows: [] }; }, async end() { state.endCalls += 1; if (options?.onEnd) { return options.onEnd(); } }, on(event: 'error', listener: (error: Error) => void) { if (event === 'error') { errorListeners.push(listener); } return state.pool; }, }, }; return state; } function assertNoSecretsLeaked(error: unknown): void { expect(error).toBeInstanceOf(ResearchCopilotExecutorError); const typed = error as ResearchCopilotExecutorError; expect((typed as { cause?: unknown }).cause).toBeUndefined(); const message = typed.message; for (const needle of [ VALID_URL, SECRET_USER, SECRET_PASS, encodeURIComponent(SECRET_PASS), SECRET_HOST, 'raw-pg-secret', ]) { expect(message).not.toContain(needle); } } describe('openResearchCopilotExecutor', () => { test('opens a bounded pg pool, probes once with SELECT 1, and attaches an error listener', async () => { const capturedConfigs: PoolConfig[] = []; const fake = createFakePool({ async onQuery(text) { if (text === 'SELECT 1') { return { rows: [{ '?column?': 1 }] }; } return { rows: [{ id: 42 }] }; }, }); const handle = await openResearchCopilotExecutor( { postgresUrl: VALID_URL }, { createPool(poolConfig) { capturedConfigs.push(poolConfig); return fake.pool; }, } ); expect(capturedConfigs).toHaveLength(1); expect(capturedConfigs[0]).toEqual({ connectionString: VALID_URL, max: RESEARCH_COPILOT_PG_POOL_MAX, connectionTimeoutMillis: RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, statement_timeout: RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, query_timeout: RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, lock_timeout: RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, options: `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`, }); expect(RESEARCH_COPILOT_PG_POOL_MAX).toBe(4); expect(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS).toBe(5_000); expect(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS).toBe(10_000); expect(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS).toBe(15_000); expect(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS).toBe(2_000); expect(fake.errorListeners).toHaveLength(1); expect(fake.queries).toEqual([{ text: 'SELECT 1' }]); const res = await handle.executor.query<{ id: number }>('SELECT $1::int AS id', [42]); expect(res.rows).toEqual([{ id: 42 }]); expect(fake.queries).toEqual([ { text: 'SELECT 1' }, { text: 'SELECT $1::int AS id', values: [42] }, ]); await handle.close(); expect(fake.endCalls).toBe(1); }); test('accepts postgresql:// scheme as well as postgres://', async () => { const fake = createFakePool(); const handle = await openResearchCopilotExecutor( { postgresUrl: 'postgresql://127.0.0.1:5432/research_db' }, { createPool: () => fake.pool } ); expect(fake.queries).toEqual([{ text: 'SELECT 1' }]); await handle.close(); }); test('rejects invalid URLs with INVALID_CONFIG before constructing a pool', async () => { const invalidUrls = [ '', ' ', ` ${VALID_URL} `, `${VALID_URL}\n`, 'not-a-url', `http://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`, `mysql://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:3306/research_db`, 'postgres:///research_db', `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432`, `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/`, `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%20%20`, `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/db/extra`, `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:0/research_db`, `postgres://%ZZ:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`, `postgres://${SECRET_USER}:%ZZ@${SECRET_HOST}:5432/research_db`, `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%ZZ`, ]; let createPoolCalls = 0; for (const postgresUrl of invalidUrls) { let caught: unknown; try { await openResearchCopilotExecutor( { postgresUrl }, { createPool() { createPoolCalls += 1; return createFakePool().pool; }, } ); } catch (err) { caught = err; } assertNoSecretsLeaked(caught); expect((caught as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG'); } expect(createPoolCalls).toBe(0); }); test('rejects malformed config or deps with INVALID_CONFIG', async () => { await expect( openResearchCopilotExecutor(null as unknown as { postgresUrl: string }) ).rejects.toMatchObject({ name: 'ResearchCopilotExecutorError', code: 'INVALID_CONFIG', }); await expect( openResearchCopilotExecutor( { postgresUrl: VALID_URL }, { createPool: 'not-a-fn' as unknown as () => ResearchCopilotExecutorPool } ) ).rejects.toMatchObject({ name: 'ResearchCopilotExecutorError', code: 'INVALID_CONFIG', }); }); test('ends pool and throws sanitized OPEN_FAILED when startup probe fails', async () => { const fake = createFakePool({ async onQuery() { throw new Error(`password authentication failed for ${SECRET_USER} at ${SECRET_HOST} raw-pg-secret`); }, }); let caught: unknown; try { await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool }); } catch (err) { caught = err; } assertNoSecretsLeaked(caught); expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED'); expect(fake.endCalls).toBe(1); }); test('still throws OPEN_FAILED when both probe and cleanup end() fail', async () => { const fake = createFakePool({ async onQuery() { throw new Error(`connect ECONNREFUSED ${SECRET_HOST} raw-pg-secret`); }, async onEnd() { throw new Error(`pool end failed ${VALID_URL}`); }, }); let caught: unknown; try { await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool }); } catch (err) { caught = err; } assertNoSecretsLeaked(caught); expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED'); expect(fake.endCalls).toBe(1); }); test('forwards parameters defensively without mutating caller arrays', async () => { const fake = createFakePool({ async onQuery(text, values) { if (values) { values.push('mutated-by-driver'); } return { rows: [{ text }] }; }, }); const handle = await openResearchCopilotExecutor( { postgresUrl: VALID_URL }, { createPool: () => fake.pool } ); const callerParams = Object.freeze(['alpha', 7]); const res = await handle.executor.query('SELECT $1, $2', callerParams); expect(res.rows).toEqual([{ text: 'SELECT $1, $2' }]); expect(callerParams).toEqual(['alpha', 7]); await handle.executor.query('SELECT 2'); expect(fake.queries[2]).toEqual({ text: 'SELECT 2' }); expect('values' in fake.queries[2]!).toBe(false); await handle.close(); }); test('preserves SQLSTATE 23505 on sanitized unique-violation query errors', async () => { let callCount = 0; const fake = createFakePool({ async onQuery() { callCount += 1; if (callCount === 1) { return { rows: [{ '?column?': 1 }] }; } const pgErr = Object.assign( new Error(`duplicate key value violates unique constraint on ${SECRET_HOST} raw-pg-secret`), { code: '23505', detail: `Key (id)=(dup-1) already exists (${SECRET_PASS})` } ); throw pgErr; }, }); const handle = await openResearchCopilotExecutor( { postgresUrl: VALID_URL }, { createPool: () => fake.pool } ); let caught: unknown; try { await handle.executor.query('INSERT INTO findings (id) VALUES ($1)', ['dup-1']); } catch (err) { caught = err; } assertNoSecretsLeaked(caught); expect((caught as ResearchCopilotExecutorError).code).toBe('23505'); await handle.close(); }); test('sanitizes generic query errors to QUERY_FAILED with no cause or raw text', async () => { let callCount = 0; const fake = createFakePool({ async onQuery() { callCount += 1; if (callCount === 1) { return { rows: [{ '?column?': 1 }] }; } throw Object.assign( new Error(`relation "missing" does not exist on ${VALID_URL} raw-pg-secret`), { code: '42P01' } ); }, }); const handle = await openResearchCopilotExecutor( { postgresUrl: VALID_URL }, { createPool: () => fake.pool } ); let caught: unknown; try { await handle.executor.query('SELECT * FROM missing'); } catch (err) { caught = err; } assertNoSecretsLeaked(caught); expect((caught as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED'); await handle.close(); }); test('close() is idempotent and subsequent queries fail with EXECUTOR_CLOSED', async () => { const fake = createFakePool(); const handle = await openResearchCopilotExecutor( { postgresUrl: VALID_URL }, { createPool: () => fake.pool } ); await handle.close(); await handle.close(); expect(fake.endCalls).toBe(1); let caught: unknown; try { await handle.executor.query('SELECT 1'); } catch (err) { caught = err; } assertNoSecretsLeaked(caught); expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED'); expect(fake.queries).toHaveLength(1); // Only the initial SELECT 1 probe ran. }); test('sanitizes pool.end() failures to CLOSE_FAILED with no cause or secret leakage', async () => { const fake = createFakePool({ async onEnd() { throw new Error(`failed closing pool for ${VALID_URL} raw-pg-secret`); }, }); const handle = await openResearchCopilotExecutor( { postgresUrl: VALID_URL }, { createPool: () => fake.pool } ); let caught: unknown; try { await handle.close(); } catch (err) { caught = err; } assertNoSecretsLeaked(caught); expect((caught as ResearchCopilotExecutorError).code).toBe('CLOSE_FAILED'); expect(fake.endCalls).toBe(1); }); });