From e720c879df6b32f9c31959521551a9356ecfc060 Mon Sep 17 00:00:00 2001 From: Studio Date: Thu, 3 Dec 2026 15:19:01 -0500 Subject: [PATCH] T-200: edits made in the worktree --- .../postgres/src/research-copilot-executor.ts | 213 +++++------------- .../research-copilot-executor-edge.test.ts | 18 +- .../test/research-copilot-executor.test.ts | 86 +++++-- test/postgres/mcp-copilot-executor.test.ts | 20 +- 4 files changed, 158 insertions(+), 179 deletions(-) diff --git a/libs/data/postgres/src/research-copilot-executor.ts b/libs/data/postgres/src/research-copilot-executor.ts index 5f0ba467..66fed43b 100644 --- a/libs/data/postgres/src/research-copilot-executor.ts +++ b/libs/data/postgres/src/research-copilot-executor.ts @@ -30,7 +30,8 @@ export const RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS = 2_000; const POSTGRES_URL_PREFIX_RE = /^postgres(?:ql)?:\/\//i; const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; -const SQLSTATE_RE = /^[0-9A-Z]{5}$/; +const PORT_DIGITS_RE = /^\d+$/; +const FINDING_REPLAY_SQLSTATE = '23505'; function hasControlChar(value: string): boolean { for (let i = 0; i < value.length; i += 1) { @@ -127,131 +128,38 @@ export interface OpenResearchCopilotExecutorOptions { readonly env?: Readonly>; } -interface NormalizedPoolSetup { - readonly poolConfig: PoolConfig; - readonly secretNeedles: readonly string[]; -} - -function addRawAndDecodedNeedle(needles: Set, raw: string): void { - if (raw.length === 0) { - return; - } - needles.add(raw); - try { - const decoded = decodeURIComponent(raw); - if (decoded.length > 0) { - needles.add(decoded); - } - } catch { - // Malformed percent-encoding: raw needle is already registered. - } -} - -function collectSecretNeedles(rawUrl: string, parsed: URL): readonly string[] { - const needles = new Set(); - if (rawUrl.length > 0) { - needles.add(rawUrl); - } - if (parsed.href.length > 0) { - needles.add(parsed.href); - } - addRawAndDecodedNeedle(needles, parsed.password); - for (const [key, value] of parsed.searchParams.entries()) { - if (key.toLowerCase() === 'password' && value.length > 0) { - needles.add(value); - } - } - if (parsed.search.length > 1) { - const pairs = parsed.search.slice(1).split('&'); - for (let i = 0; i < pairs.length; i += 1) { - const pair = pairs[i] as string; - const eqIdx = pair.indexOf('='); - if (eqIdx <= 0) { - continue; - } - const rawKey = pair.slice(0, eqIdx); - let decodedKey = rawKey; - try { - decodedKey = decodeURIComponent(rawKey); - } catch { - // Keep rawKey if percent-decoding fails. - } - if (decodedKey.toLowerCase() === 'password') { - addRawAndDecodedNeedle(needles, pair.slice(eqIdx + 1)); - } - } - } - return Array.from(needles); -} - -function containsAnyNeedle(text: string, needles: readonly string[]): boolean { - for (let i = 0; i < needles.length; i += 1) { - if (text.includes(needles[i] as string)) { - return true; - } - } - return false; -} - -function isErrorSafeToSurface( - error: unknown, - needles: readonly string[], - visited: Set = new Set(), - depth = 0 -): error is Error { - if (!(error instanceof Error) || depth > 8) { - return false; - } - if (visited.has(error)) { - return true; - } - visited.add(error); - - try { - if (typeof error.message !== 'string' || containsAnyNeedle(error.message, needles)) { - return false; - } - if (typeof error.stack === 'string' && containsAnyNeedle(error.stack, needles)) { - return false; - } - const record = error as unknown as Record; - for (const field of ['detail', 'hint', 'where', 'internalQuery', 'routine']) { - const value = record[field]; - if (typeof value === 'string' && containsAnyNeedle(value, needles)) { - return false; - } - } - if (record.cause !== undefined && !isErrorSafeToSurface(record.cause, needles, visited, depth + 1)) { - return false; - } - if (error instanceof AggregateError || 'errors' in error) { - const nested = record.errors; - if (nested !== undefined) { - if (!Array.isArray(nested)) { - return false; - } - for (let i = 0; i < nested.length; i += 1) { - if (!isErrorSafeToSurface(nested[i], needles, visited, depth + 1)) { - return false; - } - } - } - } - return true; - } catch { - return false; - } -} - -function extractSqlState(error: unknown): string | undefined { +function extractFindingReplaySqlState(error: unknown): '23505' | undefined { if (typeof error !== 'object' || error === null) { return undefined; } const code = (error as { readonly code?: unknown }).code; - if (typeof code === 'string' && SQLSTATE_RE.test(code)) { - return code; + return code === FINDING_REPLAY_SQLSTATE ? FINDING_REPLAY_SQLSTATE : undefined; +} + +function getLastExactQueryParam(parsed: URL, name: string): string | undefined { + let value: string | undefined; + for (const [key, entry] of parsed.searchParams.entries()) { + if (key === name) { + value = entry; + } + } + return value; +} + +function assertValidPort(rawPort: string): void { + if (!PORT_DIGITS_RE.test(rawPort)) { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: URL port must be an integer between 1 and 65535.' + ); + } + const portNum = Number(rawPort); + if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: URL port must be an integer between 1 and 65535.' + ); } - return undefined; } function parsePostgresUrlStrict(raw: string): { readonly url: URL; readonly usedDummyHost: boolean } { @@ -352,7 +260,7 @@ function normalizePgOptions( function parseAndNormalizePoolConfig( config: ResearchCopilotExecutorConfig, env: Readonly> -): NormalizedPoolSetup { +): PoolConfig { if (typeof config !== 'object' || config === null) { throw new ResearchCopilotExecutorError( 'INVALID_CONFIG', @@ -376,6 +284,7 @@ function parseAndNormalizePoolConfig( const { url: parsed, usedDummyHost } = parsePostgresUrlStrict(config.postgresUrl); + let decodedHostname = ''; try { if (parsed.username.length > 0) { decodeURIComponent(parsed.username); @@ -384,7 +293,7 @@ function parseAndNormalizePoolConfig( decodeURIComponent(parsed.password); } if (!usedDummyHost && parsed.hostname.length > 0) { - decodeURIComponent(parsed.hostname); + decodedHostname = decodeURIComponent(parsed.hostname).trim(); } } catch { throw new ResearchCopilotExecutorError( @@ -393,26 +302,28 @@ function parseAndNormalizePoolConfig( ); } + // Match pg-connection-string precedence: query ?port=... takes precedence over authority port. + const queryPort = getLastExactQueryParam(parsed, 'port'); + const effectivePort = queryPort && queryPort.length > 0 ? queryPort : parsed.port; + if (effectivePort.length > 0) { + assertValidPort(effectivePort); + } if (parsed.port.length > 0) { - const portNum = Number(parsed.port); - if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: URL port must be an integer between 1 and 65535.' - ); - } + assertValidPort(parsed.port); } - const queryHost = parsed.searchParams.get('host')?.trim() ?? ''; - const queryHostAddr = parsed.searchParams.get('hostaddr')?.trim() ?? ''; - const effectiveHostname = usedDummyHost ? '' : parsed.hostname.trim(); - if (effectiveHostname.length === 0 && queryHost.length === 0 && queryHostAddr.length === 0) { + // Match pg-connection-string precedence: query ?host=... takes precedence over authority host. + // pg does not resolve hostaddr as a fallback host. + const queryHost = getLastExactQueryParam(parsed, 'host')?.trim() ?? ''; + const effectiveHost = queryHost.length > 0 ? queryHost : decodedHostname; + if (effectiveHost.length === 0) { throw new ResearchCopilotExecutorError( 'INVALID_CONFIG', 'Invalid PostgreSQL configuration: URL must specify a host or Unix socket host parameter.' ); } + // Match pg-connection-string: pg reads the database strictly from the URL pathname (never ?dbname=). let decodedDatabase = ''; try { decodedDatabase = @@ -423,16 +334,13 @@ function parseAndNormalizePoolConfig( 'Invalid PostgreSQL configuration: URL database name contains invalid percent-encoding.' ); } - const queryDbName = parsed.searchParams.get('dbname')?.trim() ?? ''; - if (decodedDatabase.length === 0 && queryDbName.length === 0) { + if (decodedDatabase.length === 0) { throw new ResearchCopilotExecutorError( 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: URL must specify a non-empty database name.' + 'Invalid PostgreSQL configuration: URL must specify a non-empty database name in the path.' ); } - const secretNeedles = collectSecretNeedles(config.postgresUrl, parsed); - const urlOptions: string[] = []; const keysToDelete: string[] = []; for (const [key, value] of parsed.searchParams.entries()) { @@ -455,7 +363,7 @@ function parseAndNormalizePoolConfig( normalizedConnectionString = normalizedConnectionString.replace('@___DUMMY_HOST___/', '@/'); } - const poolConfig: PoolConfig = { + return { connectionString: normalizedConnectionString, options: normalizedOptions, max: RESEARCH_COPILOT_PG_POOL_MAX, @@ -464,8 +372,6 @@ function parseAndNormalizePoolConfig( query_timeout: RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, lock_timeout: RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, }; - - return { poolConfig, secretNeedles }; } /** @@ -477,7 +383,7 @@ export async function openResearchCopilotExecutor( options?: OpenResearchCopilotExecutorOptions ): Promise { const env = options?.env ?? process.env; - const { poolConfig, secretNeedles } = parseAndNormalizePoolConfig(config, env); + const poolConfig = parseAndNormalizePoolConfig(config, env); const createPool = options?.createPool ?? ((cfg: PoolConfig): ResearchCopilotPoolLike => new Pool(cfg)); @@ -492,16 +398,14 @@ export async function openResearchCopilotExecutor( ); } - const handleIdlePoolError = (error: Error): void => { + const handleIdlePoolError = (_error: Error): void => { if (options?.onPoolError === undefined) { return; } - const safeError = isErrorSafeToSurface(error, secretNeedles) - ? error - : new ResearchCopilotExecutorError( - 'POOL_ERROR', - 'PostgreSQL research copilot pool encountered an idle client error.' - ); + const safeError = new ResearchCopilotExecutorError( + 'POOL_ERROR', + 'PostgreSQL research copilot pool encountered an idle client error.' + ); try { options.onPoolError(safeError); } catch { @@ -543,14 +447,11 @@ export async function openResearchCopilotExecutor( const result = await pool.query(text, params === undefined ? undefined : [...params]); return { rows: result.rows as readonly Row[] }; } catch (error) { - if (isErrorSafeToSurface(error, secretNeedles)) { - throw error; - } - const sqlState = extractSqlState(error); - if (sqlState !== undefined) { + const replaySqlState = extractFindingReplaySqlState(error); + if (replaySqlState !== undefined) { const sanitized = new Error('PostgreSQL research copilot query failed.'); Object.defineProperty(sanitized, 'code', { - value: sqlState, + value: replaySqlState, enumerable: true, configurable: true, }); 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 bff522fb..cdf130ca 100644 --- a/libs/data/postgres/test/research-copilot-executor-edge.test.ts +++ b/libs/data/postgres/test/research-copilot-executor-edge.test.ts @@ -1,9 +1,8 @@ import { EventEmitter } from 'node:events'; -import { createServer } from 'node:net'; +import { type Socket, createServer } from 'node:net'; import { describe, expect, test } from 'bun:test'; import type { PoolConfig } from 'pg'; import { - RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, ResearchCopilotExecutorError, type ResearchCopilotPoolLike, openResearchCopilotExecutor, @@ -197,10 +196,15 @@ describe('openResearchCopilotExecutor edge cases', () => { }); test( - 'enforces real pg.Pool connectionTimeoutMillis against a silent local TCP listener', + 'rejects silent local TCP listener via real pg.Pool connectionTimeoutMillis without leaking credentials', async () => { + const sockets = new Set(); const server = createServer(socket => { // Intentionally accept and hold the TCP connection silent without PostgreSQL handshake. + sockets.add(socket); + socket.on('close', () => { + sockets.delete(socket); + }); socket.on('error', () => {}); }); @@ -217,7 +221,6 @@ describe('openResearchCopilotExecutor edge cases', () => { }); const secret = 'silent_tcp_secret_99'; - const startedAt = Date.now(); let caught: unknown; try { await openResearchCopilotExecutor({ @@ -226,21 +229,20 @@ describe('openResearchCopilotExecutor edge cases', () => { } catch (error) { caught = error; } finally { + for (const socket of sockets) { + socket.destroy(); + } await new Promise(resolve => { server.close(() => resolve()); }); } - const elapsedMs = Date.now() - startedAt; expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); const err = caught as ResearchCopilotExecutorError; expect(err.code).toBe('CONNECT_FAILED'); expect(err.message).not.toContain(secret); expect(err.stack ?? '').not.toContain(secret); expect('cause' in err).toBe(false); - // Bounded around the 5s connectionTimeoutMillis (allow scheduling jitter). - expect(elapsedMs).toBeGreaterThanOrEqual(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS - 500); - expect(elapsedMs).toBeLessThan(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS + 5_000); }, 15_000 ); diff --git a/libs/data/postgres/test/research-copilot-executor.test.ts b/libs/data/postgres/test/research-copilot-executor.test.ts index 9b0c12cc..bbe85a57 100644 --- a/libs/data/postgres/test/research-copilot-executor.test.ts +++ b/libs/data/postgres/test/research-copilot-executor.test.ts @@ -77,11 +77,23 @@ describe('openResearchCopilotExecutor', () => { { postgresUrl: 'postgresql:/research_db?host=%2Fvar%2Frun%2Fpostgresql' }, ], ['missing host and host query param', { postgresUrl: 'postgres:///research_db' }], + ['hostaddr-only URL (ignored by pg)', { postgresUrl: 'postgres:///research_db?hostaddr=127.0.0.1' }], ['empty authority with port only', { postgresUrl: 'postgres://:5432/research_db' }], ['missing database name', { postgresUrl: 'postgres://u:supersecret@localhost:5432' }], ['trailing slash only (missing database)', { postgresUrl: 'postgres://u:supersecret@localhost:5432/' }], + [ + 'dbname-only URL with empty path (pg falls back to PGDATABASE)', + { postgresUrl: 'postgres://copilot:supersecret@db.example/?dbname=research' }, + ], + [ + 'dbname-only URL without trailing slash', + { postgresUrl: 'postgres://copilot@db.example?dbname=research' }, + ], ['blank percent-encoded database', { postgresUrl: 'postgres://u:supersecret@localhost:5432/%20' }], ['port zero', { postgresUrl: 'postgres://u:supersecret@localhost:0/research_db' }], + ['query port zero overriding authority port', { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db?port=0' }], + ['query port out of range', { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db?port=70000' }], + ['non-numeric query port', { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db?port=abc' }], ['invalid percent-encoding in password', { postgresUrl: 'postgres://u:%ZZsupersecret@localhost:5432/research_db' }], ['control character in URL', { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db\n' }], [ @@ -267,7 +279,7 @@ describe('openResearchCopilotExecutor', () => { }); describe('idle-client error handling', () => { - test('registers error listener and sanitizes credential-bearing idle errors', async () => { + test('registers error listener and always wraps idle errors with a fixed credential-free error', async () => { const fake = createFakePool(); const received: Error[] = []; const secret = 'idle_secret_99'; @@ -285,16 +297,25 @@ describe('openResearchCopilotExecutor', () => { expect(fake.emitter.listenerCount('error')).toBe(1); - const safeErr = new Error('terminating connection due to administrator command'); - fake.emitter.emit('error', safeErr); + const benignLookingErr = Object.assign( + new Error('terminating connection due to administrator command', { + cause: new Error('env PGPASSWORD=from_env_secret'), + }), + { detail: 'pgpass credential leak', extraDiag: 'hidden' } + ); + fake.emitter.emit('error', benignLookingErr); fake.emitter.emit('error', new Error(`fatal idle error with ${secret}`)); expect(received).toHaveLength(2); - expect(received[0]).toBe(safeErr); - expect(received[1]).toBeInstanceOf(ResearchCopilotExecutorError); - expect((received[1] as ResearchCopilotExecutorError).code).toBe('POOL_ERROR'); - expect(received[1]?.message).not.toContain(secret); - expect('cause' in (received[1] as Error)).toBe(false); + for (const err of received) { + expect(err).not.toBe(benignLookingErr); + expect(err).toBeInstanceOf(ResearchCopilotExecutorError); + expect((err as ResearchCopilotExecutorError).code).toBe('POOL_ERROR'); + expect(err.message).toBe('PostgreSQL research copilot pool encountered an idle client error.'); + expect('cause' in err).toBe(false); + expect('detail' in err).toBe(false); + expect('extraDiag' in err).toBe(false); + } await handle.close(); }); @@ -363,17 +384,37 @@ describe('openResearchCopilotExecutor', () => { expect(fake.getEndCalls()).toBe(1); }); - test('forwards queries with cloned params and preserves SQLSTATE 23505', async () => { + test('forwards queries with cloned params, copies only SQLSTATE 23505, and never exposes raw driver errors or fields', async () => { + const rawDuplicateErr = Object.assign( + new Error('duplicate key value violates unique constraint', { + cause: new Error('raw driver cause with env password'), + }), + { + code: '23505', + detail: 'Key (id)=(f-1) already exists.', + connectionDiagnostics: { password: 'env_password' }, + } + ); + const rawOtherSqlStateErr = Object.assign( + new Error('relation "missing" does not exist', { + cause: new Error('inner pgpass secret'), + }), + { + code: '42P01', + detail: 'sensitive detail', + } + ); + const fake = createFakePool({ onQuery: async (text, values) => { if (text === 'SELECT 1') { return { rows: [{ ok: 1 }] }; } if (text.startsWith('INSERT')) { - const pgErr = Object.assign(new Error('duplicate key value violates unique constraint'), { - code: '23505', - }); - throw pgErr; + throw rawDuplicateErr; + } + if (text === 'SELECT * FROM missing') { + throw rawOtherSqlStateErr; } return { rows: [{ echo: values }] }; }, @@ -394,7 +435,26 @@ describe('openResearchCopilotExecutor', () => { } catch (error) { duplicateErr = error; } + expect(duplicateErr).not.toBe(rawDuplicateErr); + expect(duplicateErr).toBeInstanceOf(Error); expect((duplicateErr as { code?: string }).code).toBe('23505'); + expect((duplicateErr as Error).message).toBe('PostgreSQL research copilot query failed.'); + expect('cause' in (duplicateErr as Error)).toBe(false); + expect('detail' in (duplicateErr as Error)).toBe(false); + expect('connectionDiagnostics' in (duplicateErr as Error)).toBe(false); + + let otherErr: unknown; + try { + await handle.executor.query('SELECT * FROM missing'); + } catch (error) { + otherErr = error; + } + expect(otherErr).not.toBe(rawOtherSqlStateErr); + expect(otherErr).toBeInstanceOf(ResearchCopilotExecutorError); + expect((otherErr as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED'); + expect((otherErr as Error).message).toBe('PostgreSQL research copilot query failed.'); + expect('cause' in (otherErr as Error)).toBe(false); + expect('detail' in (otherErr as Error)).toBe(false); await handle.close(); }); diff --git a/test/postgres/mcp-copilot-executor.test.ts b/test/postgres/mcp-copilot-executor.test.ts index e85a9134..67ca1cb1 100644 --- a/test/postgres/mcp-copilot-executor.test.ts +++ b/test/postgres/mcp-copilot-executor.test.ts @@ -340,8 +340,7 @@ describe.skipIf(!url)('PostgreSQL MCP copilot executor integration', () => { createdAt: FIXED_TS, }); - // Same-ID replay with the same idempotencyKey triggers PostgreSQL PK SQLSTATE 23505; - // executor must preserve SQLSTATE 23505 so the adapter resolves the original finding. + // Same-ID, same-key replay must also return the original receipt and keep 1 stored row. const sameIdReplay = await writePort.appendFinding( { ...baseFinding, @@ -355,6 +354,23 @@ describe.skipIf(!url)('PostgreSQL MCP copilot executor integration', () => { createdAt: FIXED_TS, }); + // Unkeyed duplicate-PK insert hits PostgreSQL's primary-key constraint directly; + // verify the executor observes and preserves real SQLSTATE 23505 without leaking driver fields. + let pkCollisionErr: unknown; + try { + await writePort.appendFinding({ + ...baseFinding, + createdAt: '2026-04-01T00:00:00.000Z', + }); + } catch (error) { + pkCollisionErr = error; + } + expect(pkCollisionErr).toBeInstanceOf(Error); + expect((pkCollisionErr as { code?: string }).code).toBe('23505'); + expect((pkCollisionErr as Error).message).toBe('PostgreSQL research copilot query failed.'); + expect('cause' in (pkCollisionErr as Error)).toBe(false); + expect('detail' in (pkCollisionErr as Error)).toBe(false); + const rowCount = await handle.executor.query<{ count: string }>( `SELECT count(*)::text AS count FROM ${f.schema}.findings` );