diff --git a/libs/data/postgres/src/index.ts b/libs/data/postgres/src/index.ts index eadd1545..82a95bc7 100644 --- a/libs/data/postgres/src/index.ts +++ b/libs/data/postgres/src/index.ts @@ -1,6 +1,21 @@ export { PostgreSQLClient } from './client'; export { PostgreSQLTransactionManager } from './transactions'; export { runPostgresMigrations, type MigrationTrack } from './migrations'; +export { + 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, + openResearchCopilotExecutor, + type ManagedResearchCopilotExecutor, + type OpenResearchCopilotExecutorOptions, + type ResearchCopilotExecutor, + type ResearchCopilotExecutorConfig, + type ResearchCopilotExecutorErrorCode, + type ResearchCopilotPoolLike, +} from './research-copilot-executor'; export type { ConnectionEvents, PoolMetrics, diff --git a/libs/data/postgres/src/research-copilot-executor.ts b/libs/data/postgres/src/research-copilot-executor.ts new file mode 100644 index 00000000..5f0ba467 --- /dev/null +++ b/libs/data/postgres/src/research-copilot-executor.ts @@ -0,0 +1,584 @@ +/** + * Managed PostgreSQL executor factory for the MCP research copilot stdio host + * (`runResearchCopilotStdioHost` in `@stock-bot/research/mcp`). + * + * - Fail-closed configuration validation before any `pg.Pool` is constructed. + * - Normalizes connection parameters and `options`/`PGOPTIONS` so every pool + * connection enforces bounded pool size (`max = 4`) and timeouts (5 s connect, + * 10 s statement, 15 s query, 2 s lock) while preserving `search_path`. + * - Runs one startup probe (`SELECT 1`), closes the pool on connect failure, + * attaches an idle-client error listener, provides idempotent shutdown, and + * never exposes credentials or raw DSNs in error messages or causes. + */ + +import { Pool, type PoolConfig } from 'pg'; + +/** Maximum concurrent PostgreSQL connections opened by the research copilot executor. */ +export const RESEARCH_COPILOT_PG_POOL_MAX = 4; + +/** TCP/startup connection timeout in milliseconds (5 seconds). */ +export const RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS = 5_000; + +/** PostgreSQL server-side `statement_timeout` in milliseconds (10 seconds). */ +export const RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS = 10_000; + +/** Client-side `pg` `query_timeout` in milliseconds (15 seconds). */ +export const RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS = 15_000; + +/** PostgreSQL server-side `lock_timeout` in milliseconds (2 seconds). */ +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}$/; + +function hasControlChar(value: string): boolean { + for (let i = 0; i < value.length; i += 1) { + const code = value.charCodeAt(i); + if (code <= 0x1f || code === 0x7f) { + return true; + } + } + return false; +} + +const OVERRIDDEN_QUERY_PARAMS = new Set([ + 'options', + 'statement_timeout', + 'lock_timeout', + 'query_timeout', + 'connectiontimeoutmillis', + 'connect_timeout', + 'max', + 'min', + 'idletimeoutmillis', +]); + +/** Error codes thrown by {@link ResearchCopilotExecutorError}. */ +export type ResearchCopilotExecutorErrorCode = + | 'INVALID_CONFIG' + | 'CONNECT_FAILED' + | 'EXECUTOR_CLOSED' + | 'CLOSE_FAILED' + | 'QUERY_FAILED' + | 'POOL_ERROR'; + +/** + * Credential-safe error thrown by {@link openResearchCopilotExecutor} and its + * managed executor handle. Never embeds raw DSNs, passwords, or raw driver causes. + */ +export class ResearchCopilotExecutorError extends Error { + readonly code: ResearchCopilotExecutorErrorCode; + + constructor(code: ResearchCopilotExecutorErrorCode, message: string) { + super(message); + this.name = 'ResearchCopilotExecutorError'; + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** + * Minimal structural configuration accepted by {@link openResearchCopilotExecutor}. + * Compatible with `ResearchCopilotHostConfig` from `@stock-bot/research/mcp`. + */ +export interface ResearchCopilotExecutorConfig { + readonly postgresUrl: string; + readonly postgresSchema?: string; +} + +/** + * Structural query executor compatible with `PostgresResearchCopilotExecutor` + * from `@stock-bot/research/mcp`. + */ +export interface ResearchCopilotExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }>; +} + +/** + * Managed executor handle compatible with `ManagedPostgresExecutor` from + * `@stock-bot/research/mcp`. + */ +export interface ManagedResearchCopilotExecutor { + readonly executor: ResearchCopilotExecutor; + close(): Promise; +} + +/** + * Minimal structural subset of `pg.Pool` required by {@link openResearchCopilotExecutor}, + * allowing deterministic pool injection in unit tests while accepting real `pg.Pool`. + */ +export interface ResearchCopilotPoolLike { + query( + text: string, + values?: unknown[] + ): Promise<{ readonly rows: readonly unknown[] }>; + end(): Promise; + on(event: 'error', listener: (error: Error) => void): unknown; +} + +/** Optional dependency injection and environment hooks for {@link openResearchCopilotExecutor}. */ +export interface OpenResearchCopilotExecutorOptions { + readonly createPool?: (poolConfig: PoolConfig) => ResearchCopilotPoolLike; + readonly onPoolError?: (error: Error) => void; + 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 { + 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 undefined; +} + +function parsePostgresUrlStrict(raw: string): { readonly url: URL; readonly usedDummyHost: boolean } { + if (raw.length === 0 || raw !== raw.trim()) { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: expected a non-empty postgres:// or postgresql:// URL without surrounding whitespace.' + ); + } + if (hasControlChar(raw)) { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: URL must not contain control characters.' + ); + } + if (!POSTGRES_URL_PREFIX_RE.test(raw)) { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: URL must start with postgres:// or postgresql://.' + ); + } + + let usedDummyHost = false; + let parsed: URL; + try { + parsed = new URL(raw); + } catch { + // Support libpq Unix socket URLs with userinfo and empty authority host, + // e.g. postgres://user:pass@/research_db?host=/tmp + if (raw.includes('@/')) { + try { + parsed = new URL(raw.replace('@/', '@___DUMMY_HOST___/')); + usedDummyHost = true; + } catch { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: expected a valid postgres:// or postgresql:// URL.' + ); + } + } else { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: expected a valid postgres:// or postgresql:// URL.' + ); + } + } + + if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: URL must use the postgres:// or postgresql:// scheme.' + ); + } + + return { url: parsed, usedDummyHost }; +} + +function normalizePgOptions( + urlOptions: readonly string[], + envPgOptions: string | undefined +): string { + const parts: string[] = []; + + if (typeof envPgOptions === 'string') { + const trimmed = envPgOptions.trim(); + if (trimmed.length > 0) { + if (hasControlChar(trimmed)) { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: PGOPTIONS must not contain control characters.' + ); + } + parts.push(trimmed); + } + } + + for (let i = 0; i < urlOptions.length; i += 1) { + const trimmed = (urlOptions[i] as string).trim(); + if (trimmed.length > 0) { + if (hasControlChar(trimmed)) { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: URL options parameter must not contain control characters.' + ); + } + parts.push(trimmed); + } + } + + parts.push( + `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS}`, + `-c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` + ); + + return parts.join(' '); +} + +function parseAndNormalizePoolConfig( + config: ResearchCopilotExecutorConfig, + env: Readonly> +): NormalizedPoolSetup { + if (typeof config !== 'object' || config === null) { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: expected a configuration object.' + ); + } + if (typeof config.postgresUrl !== 'string') { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: postgresUrl must be a non-empty string.' + ); + } + if (config.postgresSchema !== undefined) { + if (typeof config.postgresSchema !== 'string' || !SCHEMA_IDENT_RE.test(config.postgresSchema)) { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: postgresSchema must match ^[a-z_][a-z0-9_]*$.' + ); + } + } + + const { url: parsed, usedDummyHost } = parsePostgresUrlStrict(config.postgresUrl); + + try { + if (parsed.username.length > 0) { + decodeURIComponent(parsed.username); + } + if (parsed.password.length > 0) { + decodeURIComponent(parsed.password); + } + if (!usedDummyHost && parsed.hostname.length > 0) { + decodeURIComponent(parsed.hostname); + } + } catch { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: URL contains invalid percent-encoding.' + ); + } + + 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.' + ); + } + } + + 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) { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: URL must specify a host or Unix socket host parameter.' + ); + } + + let decodedDatabase = ''; + try { + decodedDatabase = + parsed.pathname.length > 1 ? decodeURIComponent(parsed.pathname.slice(1)).trim() : ''; + } catch { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: URL database name contains invalid percent-encoding.' + ); + } + const queryDbName = parsed.searchParams.get('dbname')?.trim() ?? ''; + if (decodedDatabase.length === 0 && queryDbName.length === 0) { + throw new ResearchCopilotExecutorError( + 'INVALID_CONFIG', + 'Invalid PostgreSQL configuration: URL must specify a non-empty database name.' + ); + } + + const secretNeedles = collectSecretNeedles(config.postgresUrl, parsed); + + const urlOptions: string[] = []; + const keysToDelete: string[] = []; + for (const [key, value] of parsed.searchParams.entries()) { + const lower = key.toLowerCase(); + if (lower === 'options') { + urlOptions.push(value); + keysToDelete.push(key); + } else if (OVERRIDDEN_QUERY_PARAMS.has(lower)) { + keysToDelete.push(key); + } + } + for (let i = 0; i < keysToDelete.length; i += 1) { + parsed.searchParams.delete(keysToDelete[i] as string); + } + + const normalizedOptions = normalizePgOptions(urlOptions, env.PGOPTIONS); + let normalizedConnectionString = parsed.toString(); + if (usedDummyHost) { + normalizedConnectionString = normalizedConnectionString.replace('@___dummy_host___/', '@/'); + normalizedConnectionString = normalizedConnectionString.replace('@___DUMMY_HOST___/', '@/'); + } + + const poolConfig: PoolConfig = { + connectionString: normalizedConnectionString, + options: normalizedOptions, + 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, + }; + + return { poolConfig, secretNeedles }; +} + +/** + * Opens a bounded, fail-closed PostgreSQL executor backed by `pg.Pool` for the + * MCP research copilot stdio host (`ResearchCopilotStdioHostDeps['openExecutor']`). + */ +export async function openResearchCopilotExecutor( + config: ResearchCopilotExecutorConfig, + options?: OpenResearchCopilotExecutorOptions +): Promise { + const env = options?.env ?? process.env; + const { poolConfig, secretNeedles } = parseAndNormalizePoolConfig(config, env); + + const createPool = + options?.createPool ?? ((cfg: PoolConfig): ResearchCopilotPoolLike => new Pool(cfg)); + + let pool: ResearchCopilotPoolLike; + try { + pool = createPool(poolConfig); + } catch { + throw new ResearchCopilotExecutorError( + 'CONNECT_FAILED', + 'Failed to initialize PostgreSQL pool for research copilot executor.' + ); + } + + 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.' + ); + try { + options.onPoolError(safeError); + } catch { + // Never allow an idle-client error callback to crash the host process. + } + }; + + try { + pool.on('error', handleIdlePoolError); + await pool.query('SELECT 1'); + } catch { + try { + await pool.end(); + } catch { + // Preserve the primary startup connection failure. + } + throw new ResearchCopilotExecutorError( + 'CONNECT_FAILED', + 'Failed to connect PostgreSQL research copilot executor.' + ); + } + + let closing = false; + let closePromise: Promise | null = null; + + const executor: ResearchCopilotExecutor = { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + if (closing) { + throw new ResearchCopilotExecutorError( + 'EXECUTOR_CLOSED', + 'PostgreSQL research copilot executor is closed.' + ); + } + + try { + 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 sanitized = new Error('PostgreSQL research copilot query failed.'); + Object.defineProperty(sanitized, 'code', { + value: sqlState, + enumerable: true, + configurable: true, + }); + throw sanitized; + } + throw new ResearchCopilotExecutorError( + 'QUERY_FAILED', + 'PostgreSQL research copilot query failed.' + ); + } + }, + }; + + const close = (): Promise => { + closing = true; + if (closePromise === null) { + closePromise = pool.end().catch(() => { + throw new ResearchCopilotExecutorError( + 'CLOSE_FAILED', + 'Failed to close PostgreSQL research copilot executor.' + ); + }); + } + return closePromise; + }; + + return { + executor, + close, + }; +} diff --git a/libs/data/postgres/test/research-copilot-executor-edge.test.ts b/libs/data/postgres/test/research-copilot-executor-edge.test.ts new file mode 100644 index 00000000..bff522fb --- /dev/null +++ b/libs/data/postgres/test/research-copilot-executor-edge.test.ts @@ -0,0 +1,247 @@ +import { EventEmitter } from 'node:events'; +import { 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, +} from '../src'; + +function createFakePool(options?: { + onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>; + onEnd?: () => Promise; +}): ResearchCopilotPoolLike { + const emitter = new EventEmitter(); + const pool: ResearchCopilotPoolLike = { + async query(text: string, values?: unknown[]) { + if (options?.onQuery) { + return await options.onQuery(text, values); + } + return { rows: [{ ok: 1 }] }; + }, + async end() { + if (options?.onEnd) { + await options.onEnd(); + } + }, + on(event: 'error', listener: (error: Error) => void) { + emitter.on(event, listener); + return pool; + }, + }; + return pool; +} + +describe('openResearchCopilotExecutor edge cases', () => { + test('redacts query-param passwords and nested causes on query errors while preserving SQLSTATE 23505', async () => { + const querySecret = 'QueryPass#42'; + const dsn = `postgres://copilot@127.0.0.1:5432/research_db?password=${encodeURIComponent(querySecret)}`; + + const pool = createFakePool({ + onQuery: async text => { + if (text === 'SELECT 1') { + return { rows: [{ ok: 1 }] }; + } + if (text === 'DUP_WITH_SECRET') { + const err = Object.assign(new Error(`duplicate key leaked ${querySecret}`), { + code: '23505', + }); + throw err; + } + if (text === 'NESTED_CAUSE') { + const inner = new Error(`inner failure ${querySecret}`); + throw new Error('outer message', { cause: inner }); + } + throw 'non-error string with secret'; + }, + }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: dsn }, + { createPool: () => pool, env: {} } + ); + + // SQLSTATE 23505 preserved even when the error message had to be redacted. + let dupErr: unknown; + try { + await handle.executor.query('DUP_WITH_SECRET'); + } catch (error) { + dupErr = error; + } + expect(dupErr).toBeInstanceOf(Error); + expect((dupErr as { code?: string }).code).toBe('23505'); + expect((dupErr as Error).message).not.toContain(querySecret); + expect('cause' in (dupErr as Error)).toBe(false); + + // Nested cause containing secret is replaced with credential-free QUERY_FAILED. + let nestedErr: unknown; + try { + await handle.executor.query('NESTED_CAUSE'); + } catch (error) { + nestedErr = error; + } + expect(nestedErr).toBeInstanceOf(ResearchCopilotExecutorError); + expect((nestedErr as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED'); + expect((nestedErr as Error).message).not.toContain(querySecret); + expect('cause' in (nestedErr as Error)).toBe(false); + + // Non-Error thrown value is wrapped safely. + let nonErr: unknown; + try { + await handle.executor.query('NON_ERROR'); + } catch (error) { + nonErr = error; + } + expect(nonErr).toBeInstanceOf(ResearchCopilotExecutorError); + expect((nonErr as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED'); + + await handle.close(); + }); + + test('rejects control characters in PGOPTIONS and URL options before creating a pool', async () => { + let calls = 0; + + let envErr: unknown; + try { + await openResearchCopilotExecutor( + { postgresUrl: 'postgres://u:p@127.0.0.1:5432/research_db' }, + { + createPool: () => { + calls += 1; + return createFakePool(); + }, + env: { PGOPTIONS: '-c search_path=ok\n-c evil=1' }, + } + ); + } catch (error) { + envErr = error; + } + expect(calls).toBe(0); + expect(envErr).toBeInstanceOf(ResearchCopilotExecutorError); + expect((envErr as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG'); + + let urlOptErr: unknown; + try { + await openResearchCopilotExecutor( + { postgresUrl: 'postgres://u:p@127.0.0.1:5432/research_db?options=-c%20search_path%3Dok%00' }, + { + createPool: () => { + calls += 1; + return createFakePool(); + }, + env: {}, + } + ); + } catch (error) { + urlOptErr = error; + } + expect(calls).toBe(0); + expect(urlOptErr).toBeInstanceOf(ResearchCopilotExecutorError); + expect((urlOptErr as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG'); + }); + + test('normalizes case-insensitive query params and combines multiple options entries', async () => { + const captured: PoolConfig[] = []; + const handle = await openResearchCopilotExecutor( + { + postgresUrl: + 'postgres://u:p@127.0.0.1:5432/research_db?OPTIONS=-c%20search_path%3Ds1&options=-c%20work_mem%3D16MB&STATEMENT_TIMEOUT=0&LOCK_TIMEOUT=0&application_name=copilot_edge', + }, + { + createPool: cfg => { + captured.push(cfg); + return createFakePool(); + }, + env: {}, + } + ); + + const cfg = captured[0] as PoolConfig; + expect(cfg.options).toBe( + '-c search_path=s1 -c work_mem=16MB -c statement_timeout=10000 -c lock_timeout=2000' + ); + expect(cfg.connectionString).toContain('application_name=copilot_edge'); + expect(cfg.connectionString?.toLowerCase()).not.toContain('statement_timeout='); + expect(cfg.connectionString?.toLowerCase()).not.toContain('lock_timeout='); + expect(cfg.connectionString?.toLowerCase()).not.toContain('options='); + + await handle.close(); + }); + + test('redacts pool.end() failure as CLOSE_FAILED without leaking credentials', async () => { + const secret = 'close_secret_77'; + const pool = createFakePool({ + onEnd: async () => { + throw new Error(`failed closing pool for ${secret}`); + }, + }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: `postgres://u:${secret}@127.0.0.1:5432/research_db` }, + { createPool: () => pool, env: {} } + ); + + let closeErr: unknown; + try { + await handle.close(); + } catch (error) { + closeErr = error; + } + + expect(closeErr).toBeInstanceOf(ResearchCopilotExecutorError); + expect((closeErr as ResearchCopilotExecutorError).code).toBe('CLOSE_FAILED'); + expect((closeErr as Error).message).not.toContain(secret); + expect('cause' in (closeErr as Error)).toBe(false); + }); + + test( + 'enforces real pg.Pool connectionTimeoutMillis against a silent local TCP listener', + async () => { + const server = createServer(socket => { + // Intentionally accept and hold the TCP connection silent without PostgreSQL handshake. + socket.on('error', () => {}); + }); + + const listenPort = await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + if (address === null || typeof address === 'string') { + reject(new Error('Expected TCP address info')); + return; + } + resolve(address.port); + }); + }); + + const secret = 'silent_tcp_secret_99'; + const startedAt = Date.now(); + let caught: unknown; + try { + await openResearchCopilotExecutor({ + postgresUrl: `postgres://copilot:${secret}@127.0.0.1:${listenPort}/research_db`, + }); + } catch (error) { + caught = error; + } finally { + 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 new file mode 100644 index 00000000..9b0c12cc --- /dev/null +++ b/libs/data/postgres/test/research-copilot-executor.test.ts @@ -0,0 +1,402 @@ +import { EventEmitter } from 'node:events'; +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 ResearchCopilotPoolLike, + openResearchCopilotExecutor, +} from '../src'; + +interface FakePoolControls { + readonly pool: ResearchCopilotPoolLike; + readonly emitter: EventEmitter; + readonly queries: Array<{ readonly text: string; readonly values?: unknown[] }>; + getEndCalls(): number; +} + +function createFakePool(options?: { + onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>; + onEnd?: () => Promise; +}): FakePoolControls { + const emitter = new EventEmitter(); + const queries: Array<{ readonly text: string; readonly values?: unknown[] }> = []; + let endCalls = 0; + + const pool: ResearchCopilotPoolLike = { + async query(text: string, values?: unknown[]) { + queries.push({ text, values }); + if (options?.onQuery) { + return await options.onQuery(text, values); + } + return { rows: [{ ok: 1 }] }; + }, + async end() { + endCalls += 1; + if (options?.onEnd) { + await options.onEnd(); + } + }, + on(event: 'error', listener: (error: Error) => void) { + emitter.on(event, listener); + return pool; + }, + }; + + return { + pool, + emitter, + queries, + getEndCalls: () => endCalls, + }; +} + +describe('openResearchCopilotExecutor', () => { + describe('pre-pool config validation (fail closed)', () => { + const invalidConfigs: ReadonlyArray = [ + ['null config', null], + ['missing postgresUrl', {}], + ['empty postgresUrl', { postgresUrl: '' }], + ['whitespace postgresUrl', { postgresUrl: ' ' }], + [ + 'leading/trailing whitespace around valid URL', + { postgresUrl: ' postgres://u:supersecret@localhost:5432/research_db ' }, + ], + ['http scheme', { postgresUrl: 'http://u:supersecret@localhost:5432/research_db' }], + ['mysql scheme', { postgresUrl: 'mysql://u:supersecret@localhost:5432/research_db' }], + [ + 'single-slash postgres:/ URI (T-189 regression)', + { postgresUrl: 'postgres:/research_db?host=%2Ftmp' }, + ], + [ + 'single-slash postgresql:/ URI', + { postgresUrl: 'postgresql:/research_db?host=%2Fvar%2Frun%2Fpostgresql' }, + ], + ['missing host and host query param', { postgresUrl: 'postgres:///research_db' }], + ['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/' }], + ['blank percent-encoded database', { postgresUrl: 'postgres://u:supersecret@localhost:5432/%20' }], + ['port zero', { postgresUrl: 'postgres://u:supersecret@localhost:0/research_db' }], + ['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' }], + [ + 'invalid postgresSchema with uppercase', + { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db', postgresSchema: 'Public' }, + ], + [ + 'invalid postgresSchema with hyphen', + { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db', postgresSchema: 'my-schema' }, + ], + ]; + + for (const [label, invalidConfig] of invalidConfigs) { + test(`rejects ${label} before creating any pool`, async () => { + let createPoolCalls = 0; + + let caught: unknown; + try { + await openResearchCopilotExecutor(invalidConfig as { postgresUrl: string }, { + createPool: () => { + createPoolCalls += 1; + return createFakePool().pool; + }, + env: {}, + }); + } catch (error) { + caught = error; + } + + expect(createPoolCalls).toBe(0); + expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); + const err = caught as ResearchCopilotExecutorError; + expect(err.code).toBe('INVALID_CONFIG'); + expect(err.message).not.toContain('supersecret'); + expect('cause' in err).toBe(false); + }); + } + }); + + describe('valid Unix socket URLs and pool normalization', () => { + const validSocketUrls = [ + 'postgres:///research_db?host=/var/run/postgresql', + 'postgresql:///research_db?host=%2Ftmp', + 'postgres://research_user:socketpass@/research_db?host=/tmp', + 'postgres://%2Fvar%2Frun%2Fpostgresql/research_db', + ]; + + for (const socketUrl of validSocketUrls) { + test(`accepts Unix socket URL: ${socketUrl}`, async () => { + const captured: PoolConfig[] = []; + const fake = createFakePool(); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: socketUrl }, + { + createPool: cfg => { + captured.push(cfg); + return fake.pool; + }, + env: {}, + } + ); + + expect(captured).toHaveLength(1); + expect(fake.queries).toEqual([{ text: 'SELECT 1', values: undefined }]); + await handle.close(); + }); + } + + test('applies bounded pool max and timeouts while preserving search_path from URL options and PGOPTIONS', async () => { + const captured: PoolConfig[] = []; + const fake = createFakePool(); + + const handle = await openResearchCopilotExecutor( + { + postgresUrl: + 'postgresql://reader:topsecret@127.0.0.1:5432/research_db?options=-c%20search_path%3Durl_schema&statement_timeout=0&lock_timeout=0&query_timeout=0&connect_timeout=999&max=50', + postgresSchema: 'url_schema', + }, + { + createPool: cfg => { + captured.push(cfg); + return fake.pool; + }, + env: { + PGOPTIONS: '-c search_path=env_schema -c statement_timeout=0', + }, + } + ); + + expect(captured).toHaveLength(1); + const poolConfig = captured[0] as PoolConfig; + expect(poolConfig.max).toBe(RESEARCH_COPILOT_PG_POOL_MAX); + expect(poolConfig.max).toBe(4); + expect(poolConfig.connectionTimeoutMillis).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS); + expect(poolConfig.connectionTimeoutMillis).toBe(5_000); + expect(poolConfig.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); + expect(poolConfig.statement_timeout).toBe(10_000); + expect(poolConfig.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS); + expect(poolConfig.query_timeout).toBe(15_000); + expect(poolConfig.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); + expect(poolConfig.lock_timeout).toBe(2_000); + + expect(poolConfig.connectionString).not.toContain('statement_timeout='); + expect(poolConfig.connectionString).not.toContain('lock_timeout='); + expect(poolConfig.connectionString).not.toContain('query_timeout='); + expect(poolConfig.connectionString).not.toContain('connect_timeout='); + expect(poolConfig.connectionString).not.toContain('max='); + expect(poolConfig.connectionString).not.toContain('options='); + + expect(poolConfig.options).toBe( + '-c search_path=env_schema -c statement_timeout=0 -c search_path=url_schema -c statement_timeout=10000 -c lock_timeout=2000' + ); + + await handle.close(); + }); + }); + + describe('startup probe, cleanup, and error redaction', () => { + test('runs exactly one SELECT 1 probe and cleans up pool on connect failure without leaking credentials', async () => { + const secret = 'P@ssw0rd_Secret_123'; + const encoded = encodeURIComponent(secret); + const dsn = `postgres://copilot:${encoded}@127.0.0.1:5432/research_db`; + + const fake = createFakePool({ + onQuery: async () => { + throw new Error(`password authentication failed for ${dsn} (${secret})`); + }, + }); + + let caught: unknown; + try { + await openResearchCopilotExecutor( + { postgresUrl: dsn }, + { + createPool: () => fake.pool, + env: {}, + } + ); + } catch (error) { + caught = error; + } + + expect(fake.queries).toEqual([{ text: 'SELECT 1', values: undefined }]); + expect(fake.getEndCalls()).toBe(1); + expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); + const err = caught as ResearchCopilotExecutorError; + expect(err.code).toBe('CONNECT_FAILED'); + expect(err.message).not.toContain(secret); + expect(err.message).not.toContain(encoded); + expect(err.message).not.toContain(dsn); + expect(err.stack ?? '').not.toContain(secret); + expect('cause' in err).toBe(false); + }); + + test('preserves CONNECT_FAILED even when pool.end() also fails during startup cleanup', async () => { + const fake = createFakePool({ + onQuery: async () => { + throw new Error('ECONNREFUSED'); + }, + onEnd: async () => { + throw new Error('pool end failure'); + }, + }); + + let caught: unknown; + try { + await openResearchCopilotExecutor( + { postgresUrl: 'postgres://user:secret@127.0.0.1:5432/research_db' }, + { + createPool: () => fake.pool, + env: {}, + } + ); + } catch (error) { + caught = error; + } + + expect(fake.getEndCalls()).toBe(1); + expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); + expect((caught as ResearchCopilotExecutorError).code).toBe('CONNECT_FAILED'); + }); + }); + + describe('idle-client error handling', () => { + test('registers error listener and sanitizes credential-bearing idle errors', async () => { + const fake = createFakePool(); + const received: Error[] = []; + const secret = 'idle_secret_99'; + + const handle = await openResearchCopilotExecutor( + { postgresUrl: `postgres://user:${secret}@127.0.0.1:5432/research_db` }, + { + createPool: () => fake.pool, + onPoolError: err => { + received.push(err); + }, + env: {}, + } + ); + + expect(fake.emitter.listenerCount('error')).toBe(1); + + const safeErr = new Error('terminating connection due to administrator command'); + fake.emitter.emit('error', safeErr); + 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); + + await handle.close(); + }); + + test('does not crash when idle error fires without onPoolError or when callback throws', async () => { + const fake1 = createFakePool(); + const handle1 = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://user:pass@127.0.0.1:5432/research_db' }, + { createPool: () => fake1.pool, env: {} } + ); + expect(() => fake1.emitter.emit('error', new Error('idle reset'))).not.toThrow(); + await handle1.close(); + + const fake2 = createFakePool(); + const handle2 = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://user:pass@127.0.0.1:5432/research_db' }, + { + createPool: () => fake2.pool, + onPoolError: () => { + throw new Error('listener boom'); + }, + env: {}, + } + ); + expect(() => fake2.emitter.emit('error', new Error('idle reset'))).not.toThrow(); + await handle2.close(); + }); + }); + + describe('shutdown lifecycle and query gating', () => { + test('concurrent and repeated close() calls share one shutdown and reject new queries immediately', async () => { + let releaseEnd: (() => void) | undefined; + const endGate = new Promise(resolve => { + releaseEnd = resolve; + }); + + const fake = createFakePool({ + onEnd: () => endGate, + }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://user:pass@127.0.0.1:5432/research_db' }, + { createPool: () => fake.pool, env: {} } + ); + + // Start concurrent close() calls while pool.end() is still pending. + const close1 = handle.close(); + const close2 = handle.close(); + + // New query must reject immediately as soon as shutdown starts. + let queryErr: unknown; + try { + await handle.executor.query('SELECT 2'); + } catch (error) { + queryErr = error; + } + + expect(queryErr).toBeInstanceOf(ResearchCopilotExecutorError); + expect((queryErr as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED'); + expect(fake.queries).toHaveLength(1); // Only the initial SELECT 1 ran. + + releaseEnd?.(); + await Promise.all([close1, close2]); + await handle.close(); + + expect(fake.getEndCalls()).toBe(1); + }); + + test('forwards queries with cloned params and preserves SQLSTATE 23505', async () => { + 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; + } + return { rows: [{ echo: values }] }; + }, + }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://user:pass@127.0.0.1:5432/research_db' }, + { createPool: () => fake.pool, env: {} } + ); + + const params: readonly unknown[] = ['a', 42]; + const res = await handle.executor.query<{ echo: unknown[] }>('SELECT $1, $2', params); + expect(res.rows).toEqual([{ echo: ['a', 42] }]); + + let duplicateErr: unknown; + try { + await handle.executor.query('INSERT INTO findings VALUES ($1)', ['f-1']); + } catch (error) { + duplicateErr = error; + } + expect((duplicateErr as { code?: string }).code).toBe('23505'); + + await handle.close(); + }); + }); +}); diff --git a/libs/data/postgres/test/research-copilot-executor.type-test.ts b/libs/data/postgres/test/research-copilot-executor.type-test.ts new file mode 100644 index 00000000..7ebb2e65 --- /dev/null +++ b/libs/data/postgres/test/research-copilot-executor.type-test.ts @@ -0,0 +1,32 @@ +import type { Pool } from 'pg'; +import type { + ManagedPostgresExecutor, + ResearchCopilotHostConfig, + ResearchCopilotStdioHostDeps, +} from '@stock-bot/research/mcp'; +import { + type ManagedResearchCopilotExecutor, + type ResearchCopilotPoolLike, + openResearchCopilotExecutor, +} from '../src'; + +// The managed handle returned by openResearchCopilotExecutor must satisfy ManagedPostgresExecutor. +declare const managedHandle: ManagedResearchCopilotExecutor; +managedHandle satisfies ManagedPostgresExecutor; + +// The factory itself must be directly assignable to ResearchCopilotStdioHostDeps['openExecutor']. +const openExecutor: ResearchCopilotStdioHostDeps['openExecutor'] = openResearchCopilotExecutor; +void openExecutor; + +// Calling openResearchCopilotExecutor with a full ResearchCopilotHostConfig returns ManagedPostgresExecutor. +declare const hostConfig: ResearchCopilotHostConfig; +const opened: Promise = openResearchCopilotExecutor(hostConfig); +void opened; + +// Real pg.Pool instances must satisfy the structural ResearchCopilotPoolLike interface. +declare const realPool: Pool; +realPool satisfies ResearchCopilotPoolLike; + +// Missing postgresUrl must be rejected at compile time. +// @ts-expect-error postgresUrl is required on ResearchCopilotExecutorConfig. +void openResearchCopilotExecutor({}); diff --git a/test/postgres/mcp-copilot-executor.test.ts b/test/postgres/mcp-copilot-executor.test.ts new file mode 100644 index 00000000..029f4973 --- /dev/null +++ b/test/postgres/mcp-copilot-executor.test.ts @@ -0,0 +1,353 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Client, Pool, type PoolConfig } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { + PostgreSQLClient, + RESEARCH_COPILOT_PG_POOL_MAX, + ResearchCopilotExecutorError, + openResearchCopilotExecutor, + runPostgresMigrations, +} from '@stock-bot/postgres'; +import { + type FiledFindingRecord, + createPostgresFindingWritePort, + createPostgresTrialRefLookupPort, +} from '../../libs/research/src/mcp/index'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('mcp-copilot-executor-pg-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); + +// Vault cutoff date 2025-06-30 (exclusive): sample_end must be < 2025-06-30 to be research-visible. +const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); +const FIXED_TS = '2026-01-15T12:34:56.789Z'; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + let firstError: unknown; + for (const close of cleanup.splice(0).reverse()) { + try { + await close(); + } catch (err) { + firstError ??= err; + } + } + if (firstError !== undefined) { + throw firstError; + } +}); + +function assertSafetyDatabaseUrl(connectionString: string | undefined): string { + if (!connectionString) { + throw new Error('Dedicated stock_bot_safety database required'); + } + let parsed: URL; + try { + parsed = new URL(connectionString); + } catch { + throw new Error('Dedicated stock_bot_safety database required'); + } + if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { + throw new Error('Dedicated stock_bot_safety database required'); + } + const client = new Client({ connectionString }); + const effectiveDb = ( + client as unknown as { connectionParameters?: { database?: unknown } } + ).connectionParameters?.database; + if ( + typeof effectiveDb !== 'string' || + !effectiveDb.startsWith('stock_bot_safety') || + !parsed.pathname.startsWith('/stock_bot_safety') + ) { + throw new Error('Dedicated stock_bot_safety database required'); + } + return connectionString; +} + +function buildSchemaUrl( + connectionString: string, + schema: string, + extraQuery?: Record +): string { + const parsed = new URL(connectionString); + parsed.searchParams.set('options', `-c search_path=${schema} -c statement_timeout=0 -c lock_timeout=0`); + if (extraQuery) { + for (const [k, v] of Object.entries(extraQuery)) { + parsed.searchParams.set(k, v); + } + } + return parsed.toString(); +} + +function buildIsolatedPoolConfig(connectionString: string, schema: string): PoolConfig { + const parsed = new URL(connectionString); + const existingOptions = parsed.searchParams + .getAll('options') + .map(value => value.trim()) + .filter(value => value.length > 0); + parsed.searchParams.delete('options'); + const options = [ + ...existingOptions, + `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, + ].join(' '); + return { + connectionString: parsed.toString(), + options, + }; +} + +async function createIsolatedFixture(connectionString: string | undefined = url) { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: safeUrl }); + cleanup.push(async () => { + await admin.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`); + await admin.end(); + }); + + await admin.query(`CREATE SCHEMA ${schema}`); + const migrationPool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); + cleanup.push(async () => { + await migrationPool.end(); + }); + + for (const filename of [ + '06-create-backtest-tables.sql', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', + ]) { + await migrationPool.query(readFileSync(`${initDir}${filename}`, 'utf8')); + } + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => migrationPool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'research' }); + + return { admin, migrationPool, safeUrl, schema }; +} + +async function waitForZeroBackends( + admin: Pool, + appName: string, + timeoutMs = 3000 +): Promise { + const deadline = Date.now() + timeoutMs; + let lastCount = -1; + while (Date.now() < deadline) { + const { rows } = await admin.query<{ count: string }>( + 'SELECT count(*)::text AS count FROM pg_stat_activity WHERE application_name = $1', + [appName] + ); + lastCount = Number(rows[0]?.count ?? '0'); + if (lastCount === 0) { + return 0; + } + await new Promise(resolve => setTimeout(resolve, 25)); + } + return lastCount; +} + +describe('PostgreSQL MCP copilot executor safety guard', () => { + test('rejects unsafe database targets before connecting', () => { + expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( + 'Dedicated stock_bot_safety database required' + ); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') + ).toThrow('Dedicated stock_bot_safety database required'); + }); +}); + +describe.skipIf(!url)('PostgreSQL MCP copilot executor integration', () => { + test('enforces effective 10s statement_timeout, 2s lock_timeout, preserved search_path, max 4 backends, and 0 backends after close', async () => { + const f = await createIsolatedFixture(); + const appName = `copilot_exec_${randomUUID().replaceAll('-', '').slice(0, 12)}`; + const postgresUrl = buildSchemaUrl(f.safeUrl, f.schema, { application_name: appName }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl, postgresSchema: f.schema }, + { env: {} } + ); + cleanup.push(() => handle.close()); + + const settings = await handle.executor.query<{ + statement_timeout: string; + lock_timeout: string; + search_path: string; + current_schema: string; + }>( + `SELECT + current_setting('statement_timeout') AS statement_timeout, + current_setting('lock_timeout') AS lock_timeout, + current_setting('search_path') AS search_path, + current_schema() AS current_schema` + ); + + expect(settings.rows[0]?.statement_timeout).toBe('10s'); + expect(settings.rows[0]?.lock_timeout).toBe('2s'); + expect(settings.rows[0]?.current_schema).toBe(f.schema); + expect(settings.rows[0]?.search_path).toContain(f.schema); + + // Run 8 concurrent queries and observe peak backend count <= 4. + const sleeps = Array.from({ length: 8 }, () => + handle.executor.query('SELECT pg_sleep(0.08)') + ); + await new Promise(resolve => setTimeout(resolve, 30)); + const active = await f.admin.query<{ count: string }>( + 'SELECT count(*)::text AS count FROM pg_stat_activity WHERE application_name = $1', + [appName] + ); + const activeCount = Number(active.rows[0]?.count ?? '0'); + expect(activeCount).toBeGreaterThanOrEqual(1); + expect(activeCount).toBeLessThanOrEqual(RESEARCH_COPILOT_PG_POOL_MAX); + + await Promise.all(sleeps); + + await handle.close(); + // Idempotent second close. + await handle.close(); + + // Post-close query rejects immediately with EXECUTOR_CLOSED. + let closedErr: unknown; + try { + await handle.executor.query('SELECT 1'); + } catch (error) { + closedErr = error; + } + expect(closedErr).toBeInstanceOf(ResearchCopilotExecutorError); + expect((closedErr as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED'); + + const remaining = await waitForZeroBackends(f.admin, appName); + expect(remaining).toBe(0); + }); + + test('preserves PGOPTIONS search_path while overriding weakening timeouts', async () => { + const f = await createIsolatedFixture(); + const parsed = new URL(f.safeUrl); + parsed.searchParams.delete('options'); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: parsed.toString(), postgresSchema: f.schema }, + { env: { PGOPTIONS: `-c search_path=${f.schema} -c statement_timeout=0 -c lock_timeout=0` } } + ); + cleanup.push(() => handle.close()); + + const settings = await handle.executor.query<{ + statement_timeout: string; + lock_timeout: string; + current_schema: string; + }>( + `SELECT + current_setting('statement_timeout') AS statement_timeout, + current_setting('lock_timeout') AS lock_timeout, + current_schema() AS current_schema` + ); + + expect(settings.rows[0]?.statement_timeout).toBe('10s'); + expect(settings.rows[0]?.lock_timeout).toBe('2s'); + expect(settings.rows[0]?.current_schema).toBe(f.schema); + + await handle.close(); + }); + + test('supports idempotent finding replay (same-ID and same-key) and Vault-fenced trial visibility in migrated schema', async () => { + const f = await createIsolatedFixture(); + const postgresUrl = buildSchemaUrl(f.safeUrl, f.schema); + + // Seed one trial strictly before the 2025-06-30 UTC Vault cutoff and one on the cutoff. + await f.migrationPool.query( + `INSERT INTO trial_ledger ( + trial_id, principal_id, stage, universe_market, horizon_bucket, expression_hash, + sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series + ) + OVERRIDING SYSTEM VALUE + VALUES + (1, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), + '2020-01-01'::date, '2025-06-29'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[]), + (2, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('b', 64), + '2020-01-01'::date, '2025-06-30'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])` + ); + + const handle = await openResearchCopilotExecutor( + { postgresUrl, postgresSchema: f.schema }, + { env: {} } + ); + cleanup.push(() => handle.close()); + + // 1. Vault-fenced trial_ledger visibility check. + const trialLookup = createPostgresTrialRefLookupPort({ + executor: handle.executor, + schema: f.schema, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + expect(await trialLookup.hasVisibleTrialRef('1')).toBe(true); + expect(await trialLookup.hasVisibleTrialRef('2')).toBe(false); + + // 2. Findings idempotent replay (both same-ID 23505 path and same-key ON CONFLICT path). + const writePort = createPostgresFindingWritePort({ + executor: handle.executor, + schema: f.schema, + }); + + const findingId = `finding-${randomUUID()}`; + const idempotencyKey = `key-${randomUUID()}`; + const baseFinding: FiledFindingRecord = { + id: findingId, + kind: 'finding', + title: 'Executor replay verification finding', + status: 'pending_review', + createdAt: FIXED_TS, + summary: 'Verifies SQLSTATE 23505 and ON CONFLICT replay through openResearchCopilotExecutor.', + trialRefs: ['1'], + evidenceRefs: ['evidence:e1'], + idempotencyKey, + }; + + const first = await writePort.appendFinding(baseFinding); + expect(first.replayed).toBe(false); + expect(first.id).toBe(findingId); + expect(first.createdAt).toBe(FIXED_TS); + + // Same-key replay with a different ID and later timestamp must return the original finding. + const sameKeyReplay = await writePort.appendFinding({ + ...baseFinding, + id: `finding-${randomUUID()}`, + createdAt: '2026-02-01T00:00:00.000Z', + }); + expect(sameKeyReplay.replayed).toBe(true); + expect(sameKeyReplay.id).toBe(findingId); + expect(sameKeyReplay.createdAt).toBe(FIXED_TS); + + // Same-ID replay without idempotencyKey triggers SQLSTATE 23505 primary-key replay path. + const sameIdReplay = await writePort.appendFinding({ + ...baseFinding, + idempotencyKey: undefined, + createdAt: '2026-03-01T00:00:00.000Z', + }); + expect(sameIdReplay.replayed).toBe(true); + expect(sameIdReplay.id).toBe(findingId); + expect(sameIdReplay.createdAt).toBe(FIXED_TS); + + const rowCount = await handle.executor.query<{ count: string }>( + `SELECT count(*)::text AS count FROM ${f.schema}.findings` + ); + expect(rowCount.rows[0]?.count).toBe('1'); + + await handle.close(); + }); +}); diff --git a/tsconfig.check.json b/tsconfig.check.json index d67c308a..74f157e6 100644 --- a/tsconfig.check.json +++ b/tsconfig.check.json @@ -32,7 +32,8 @@ "apps/stock/**/src/**/*.tsx", "tools/**/src/**/*.ts", "apps/stock/orchestrator/examples/canonical-regime-research.ts", - "libs/core/services/test/contracts.type-test.ts" + "libs/core/services/test/contracts.type-test.ts", + "libs/data/postgres/test/research-copilot-executor.type-test.ts" ], "exclude": ["node_modules", "**/dist/**", "**/*.test.ts", "**/*.spec.ts"] }