diff --git a/libs/data/postgres/src/research-copilot-executor.ts b/libs/data/postgres/src/research-copilot-executor.ts index 42ff2698..dc875139 100644 --- a/libs/data/postgres/src/research-copilot-executor.ts +++ b/libs/data/postgres/src/research-copilot-executor.ts @@ -133,7 +133,29 @@ function parseAndNormalizePoolConfig(config: ResearchCopilotExecutorConfig): Poo throw invalidConfigError(); } - if (parsed.hostname.length === 0) { + const hostQueryParams = parsed.searchParams.getAll('host'); + if (hostQueryParams.length > 1) { + throw invalidConfigError(); + } + const queryHost = hostQueryParams.length === 1 ? (hostQueryParams[0] as string).trim() : ''; + if (hostQueryParams.length === 1 && queryHost.length === 0) { + throw invalidConfigError(); + } + + const hasAuthorityHost = parsed.hostname.length > 0; + if (hasAuthorityHost) { + let decodedHost: string; + try { + decodedHost = decodeURIComponent(parsed.hostname); + } catch { + throw invalidConfigError(); + } + if (decodedHost.trim().length === 0) { + throw invalidConfigError(); + } + } + + if (!hasAuthorityHost && queryHost.length === 0) { throw invalidConfigError(); } @@ -190,21 +212,23 @@ function parseAndNormalizePoolConfig(config: ResearchCopilotExecutorConfig): Poo parsed.searchParams.delete(keysToDelete[i] as string); } - const enforcedOptions = `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`; - const options = - existingOptions.length > 0 - ? `${existingOptions.join(' ')} ${enforcedOptions}` - : enforcedOptions; + const envOptions = typeof process.env.PGOPTIONS === 'string' ? process.env.PGOPTIONS.trim() : ''; + const baseOptions = existingOptions.length > 0 ? existingOptions.join(' ') : envOptions; - return { + const poolConfig: PoolConfig = { connectionString: parsed.toString(), 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, }; + + if (baseOptions.length > 0) { + poolConfig.options = `${baseOptions} -c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`; + } + + return poolConfig; } function resolveCreatePool( diff --git a/libs/data/postgres/test/research-copilot-executor-edge.test.ts b/libs/data/postgres/test/research-copilot-executor-edge.test.ts index 5b4c329a..f126bd50 100644 --- a/libs/data/postgres/test/research-copilot-executor-edge.test.ts +++ b/libs/data/postgres/test/research-copilot-executor-edge.test.ts @@ -97,6 +97,199 @@ describe('openResearchCopilotExecutor edge cases', () => { await handle.close(); }); + test('accepts Unix-domain socket host query parameter and resolves domain-socket parameters in pg', async () => { + const capturedConfigs: PoolConfig[] = []; + const fakePool: ResearchCopilotExecutorPool = { + async query() { + return { rows: [{ '?column?': 1 }] }; + }, + async end() {}, + on() { + return fakePool; + }, + }; + + const handle = await openResearchCopilotExecutor( + { + postgresUrl: + 'postgres:///research_db?host=/var/run/postgresql&statement_timeout=99999&lock_timeout=88888', + }, + { + createPool(poolConfig) { + capturedConfigs.push(poolConfig); + return fakePool; + }, + } + ); + + expect(capturedConfigs).toHaveLength(1); + const client = new Client(capturedConfigs[0]); + const params = ( + client as unknown as { + connectionParameters: { + host?: string; + database?: string; + isDomainSocket?: boolean; + statement_timeout?: unknown; + lock_timeout?: unknown; + query_timeout?: unknown; + }; + } + ).connectionParameters; + + expect(params.host).toBe('/var/run/postgresql'); + expect(params.database).toBe('research_db'); + expect(params.isDomainSocket).toBe(true); + expect(params.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); + expect(params.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); + expect(params.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS); + + await handle.close(); + }); + + test('rejects URLs missing host or database even when PGHOST and PGDATABASE are set', async () => { + const previousPgHost = process.env.PGHOST; + const previousPgDatabase = process.env.PGDATABASE; + process.env.PGHOST = '127.0.0.1'; + process.env.PGDATABASE = 'fallback_db'; + cleanup.push(() => { + if (previousPgHost === undefined) { + delete process.env.PGHOST; + } else { + process.env.PGHOST = previousPgHost; + } + if (previousPgDatabase === undefined) { + delete process.env.PGDATABASE; + } else { + process.env.PGDATABASE = previousPgDatabase; + } + }); + + let createPoolCalls = 0; + for (const postgresUrl of [ + 'postgres:///research_db', + 'postgres://127.0.0.1:5432/', + 'postgres://127.0.0.1:5432', + ]) { + await expect( + openResearchCopilotExecutor( + { postgresUrl }, + { + createPool() { + createPoolCalls += 1; + return { + async query() { + return { rows: [] }; + }, + async end() {}, + on() { + return undefined; + }, + }; + }, + } + ) + ).rejects.toMatchObject({ + name: 'ResearchCopilotExecutorError', + code: 'INVALID_CONFIG', + }); + } + expect(createPoolCalls).toBe(0); + }); + + test('preserves PGOPTIONS startup precedence while enforcing executor timeouts', async () => { + const previousPgOptions = process.env.PGOPTIONS; + cleanup.push(() => { + if (previousPgOptions === undefined) { + delete process.env.PGOPTIONS; + } else { + process.env.PGOPTIONS = previousPgOptions; + } + }); + + const fakePool: ResearchCopilotExecutorPool = { + async query() { + return { rows: [{ '?column?': 1 }] }; + }, + async end() {}, + on() { + return fakePool; + }, + }; + + // 1. No URL options and no PGOPTIONS -> PoolConfig.options omitted. + delete process.env.PGOPTIONS; + let captured: PoolConfig | undefined; + const h1 = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, + { + createPool(poolConfig) { + captured = poolConfig; + return fakePool; + }, + } + ); + expect(captured?.options).toBeUndefined(); + const c1 = new Client(captured); + const p1 = ( + c1 as unknown as { + connectionParameters: { + options?: string; + statement_timeout?: unknown; + lock_timeout?: unknown; + }; + } + ).connectionParameters; + expect(p1.options).toBeUndefined(); + expect(p1.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); + expect(p1.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); + await h1.close(); + + // 2. PGOPTIONS set with no URL options -> PGOPTIONS preserved + executor timeouts appended. + process.env.PGOPTIONS = '-c search_path=research -c statement_timeout=99999 -c lock_timeout=88888'; + captured = undefined; + const h2 = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, + { + createPool(poolConfig) { + captured = poolConfig; + return fakePool; + }, + } + ); + expect(captured?.options).toBe( + `-c search_path=research -c statement_timeout=99999 -c lock_timeout=88888 ` + + `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` + ); + const c2 = new Client(captured); + const p2 = ( + c2 as unknown as { connectionParameters: { options?: string } } + ).connectionParameters; + expect(p2.options).toBe(captured?.options); + await h2.close(); + + // 3. Both URL options and PGOPTIONS set -> URL options wins over PGOPTIONS, timeouts still appended. + process.env.PGOPTIONS = '-c search_path=env_schema'; + captured = undefined; + const h3 = await openResearchCopilotExecutor( + { + postgresUrl: + 'postgres://127.0.0.1:5432/research_db?options=-c%20search_path%3Durl_schema', + }, + { + createPool(poolConfig) { + captured = poolConfig; + return fakePool; + }, + } + ); + expect(captured?.options).toBe( + `-c search_path=url_schema ` + + `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` + ); + await h3.close(); + }); + test('absorbs idle-client pool error events without crashing the process', async () => { const errorListeners: Array<(error: Error) => void> = []; const fakePool: ResearchCopilotExecutorPool = { diff --git a/libs/data/postgres/test/research-copilot-executor.test.ts b/libs/data/postgres/test/research-copilot-executor.test.ts index 6dd75102..1ecf9f83 100644 --- a/libs/data/postgres/test/research-copilot-executor.test.ts +++ b/libs/data/postgres/test/research-copilot-executor.test.ts @@ -77,64 +77,80 @@ function assertNoSecretsLeaked(error: unknown): void { 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; + const previousPgOptions = process.env.PGOPTIONS; + delete process.env.PGOPTIONS; + try { + 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, + }); + expect(capturedConfigs[0]?.options).toBeUndefined(); + 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); + } finally { + if (previousPgOptions === undefined) { + delete process.env.PGOPTIONS; + } else { + process.env.PGOPTIONS = previousPgOptions; } - ); - - 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('accepts postgresql:// scheme and Unix-domain socket host query parameters', async () => { + for (const postgresUrl of [ + 'postgresql://127.0.0.1:5432/research_db', + 'postgres:///research_db?host=/var/run/postgresql', + 'postgresql:///research_db?host=/var/run/postgresql', + ]) { + const fake = createFakePool(); + const handle = await openResearchCopilotExecutor( + { postgresUrl }, + { 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 () => { @@ -147,6 +163,12 @@ describe('openResearchCopilotExecutor', () => { `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:///research_db?host=', + 'postgres:///research_db?host=%20%20', + 'postgres:///research_db?host=/var/run/postgresql&host=/tmp', + 'postgres:///research_db?HOST=/var/run/postgresql', + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=/a&host=/b`, `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`, diff --git a/test/postgres/mcp-copilot-executor.test.ts b/test/postgres/mcp-copilot-executor.test.ts index e80f9240..021ede01 100644 --- a/test/postgres/mcp-copilot-executor.test.ts +++ b/test/postgres/mcp-copilot-executor.test.ts @@ -212,6 +212,65 @@ describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () => expect(lockRows[0]?.lock_timeout).toBe('2s'); }); + test('preserves PGOPTIONS search_path when URL omits options while enforcing 10s/2s timeouts', async () => { + const f = await createIsolatedFixture(); + const appName = `copilot_pgoptions_${randomUUID().slice(0, 8)}`; + + // Build a URL with NO options query parameter so pg must honor PGOPTIONS. + const parsed = new URL(f.safeUrl); + parsed.searchParams.delete('options'); + parsed.searchParams.set('application_name', appName); + + const previousPgOptions = process.env.PGOPTIONS; + process.env.PGOPTIONS = `-c search_path=${f.schema} -c statement_timeout=99999 -c lock_timeout=88888`; + cleanup.push(() => { + if (previousPgOptions === undefined) { + delete process.env.PGOPTIONS; + } else { + process.env.PGOPTIONS = previousPgOptions; + } + }); + + const handle = await openResearchCopilotExecutor({ postgresUrl: parsed.toString() }); + cleanup.push(() => handle.close()); + + const { rows: schemaRows } = await handle.executor.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>( + 'SHOW statement_timeout' + ); + const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>( + 'SHOW lock_timeout' + ); + + expect(schemaRows[0]?.current_schema).toBe(f.schema); + expect(stmtRows[0]?.statement_timeout).toBe('10s'); + expect(lockRows[0]?.lock_timeout).toBe('2s'); + + // Verify unqualified findings writes and reads resolve against the PGOPTIONS search_path. + const writePort = createPostgresFindingWritePort({ executor: handle.executor }); + const readers = createPostgresKnowledgeReaders({ executor: handle.executor }); + const created = await writePort.appendFinding( + { + id: 'finding-pgoptions-0001', + kind: 'finding', + title: 'PGOPTIONS search_path finding', + summary: 'Resolved via PGOPTIONS search_path without explicit schema option.', + status: 'pending_review', + createdAt: FIXED_TS, + trialRefs: [], + evidenceRefs: [], + }, + 'idem-pgoptions-0001' + ); + expect(created.status).toBe('created'); + + const listed = await readers.listFindings({ query: 'PGOPTIONS search_path' }); + expect(listed).toHaveLength(1); + expect(listed[0]?.id).toBe('finding-pgoptions-0001'); + }); + test('supports migrated findings writes, reads, and idempotent same-ID 23505 replay', async () => { const f = await createIsolatedFixture(); const appName = `copilot_findings_${randomUUID().slice(0, 8)}`;