T-200: merge dev
This commit is contained in:
commit
267e655e63
6 changed files with 1243 additions and 1168 deletions
|
|
@ -1,249 +1,428 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { type Socket, createServer } from 'node:net';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import type { PoolConfig } from 'pg';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createServer, type AddressInfo, type Socket } from 'node:net';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Client, Pool, 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,
|
||||
type ResearchCopilotExecutorPool,
|
||||
openResearchCopilotExecutor,
|
||||
} from '../src';
|
||||
} from '../src/index';
|
||||
|
||||
function createFakePool(options?: {
|
||||
onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>;
|
||||
onEnd?: () => Promise<void>;
|
||||
}): 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;
|
||||
}
|
||||
const cleanup: Array<() => Promise<void> | void> = [];
|
||||
afterEach(async () => {
|
||||
for (const fn of cleanup.splice(0).reverse()) {
|
||||
await fn();
|
||||
}
|
||||
});
|
||||
|
||||
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';
|
||||
test('strips URL timeout overrides while preserving search_path and enforcing executor timeouts', async () => {
|
||||
const capturedConfigs: PoolConfig[] = [];
|
||||
const fakePool: ResearchCopilotExecutorPool = {
|
||||
async query() {
|
||||
return { rows: [{ '?column?': 1 }] };
|
||||
},
|
||||
});
|
||||
async end() {},
|
||||
on() {
|
||||
return fakePool;
|
||||
},
|
||||
};
|
||||
|
||||
const hostileUrl =
|
||||
'postgres://u:p@127.0.0.1:5432/research_db' +
|
||||
'?sslmode=disable' +
|
||||
'&application_name=copilot_edge' +
|
||||
'&statement_timeout=99999' +
|
||||
'&LOCK_TIMEOUT=88888' +
|
||||
'&query_timeout=77777' +
|
||||
'&connect_timeout=66' +
|
||||
'&connectionTimeoutMillis=55555' +
|
||||
'&options=-c%20search_path%3Disolated_schema%20-c%20statement_timeout%3D60000%20-c%20lock_timeout%3D60000';
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: dsn },
|
||||
{ createPool: () => pool, env: {} }
|
||||
{ postgresUrl: hostileUrl },
|
||||
{
|
||||
createPool(poolConfig) {
|
||||
capturedConfigs.push(poolConfig);
|
||||
return fakePool;
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// 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);
|
||||
expect(capturedConfigs).toHaveLength(1);
|
||||
const poolConfig = capturedConfigs[0]!;
|
||||
const normalizedUrl = new URL(poolConfig.connectionString!);
|
||||
expect(normalizedUrl.searchParams.get('sslmode')).toBe('disable');
|
||||
expect(normalizedUrl.searchParams.get('application_name')).toBe('copilot_edge');
|
||||
expect(normalizedUrl.searchParams.has('statement_timeout')).toBe(false);
|
||||
expect(normalizedUrl.searchParams.has('LOCK_TIMEOUT')).toBe(false);
|
||||
expect(normalizedUrl.searchParams.has('query_timeout')).toBe(false);
|
||||
expect(normalizedUrl.searchParams.has('connect_timeout')).toBe(false);
|
||||
expect(normalizedUrl.searchParams.has('connectionTimeoutMillis')).toBe(false);
|
||||
expect(normalizedUrl.searchParams.has('options')).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);
|
||||
expect(poolConfig.options).toBe(
|
||||
`-c search_path=isolated_schema -c statement_timeout=60000 -c lock_timeout=60000 ` +
|
||||
`-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`
|
||||
);
|
||||
|
||||
// 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');
|
||||
// Verify pg's own ConnectionParameters parser resolves the enforced timeouts.
|
||||
const client = new Client(poolConfig);
|
||||
const params = (
|
||||
client as unknown as {
|
||||
connectionParameters: {
|
||||
statement_timeout?: unknown;
|
||||
lock_timeout?: unknown;
|
||||
query_timeout?: unknown;
|
||||
connect_timeout?: unknown;
|
||||
options?: string;
|
||||
application_name?: string;
|
||||
};
|
||||
}
|
||||
).connectionParameters;
|
||||
|
||||
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);
|
||||
expect(params.connect_timeout).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS / 1000);
|
||||
expect(params.application_name).toBe('copilot_edge');
|
||||
expect(params.options).toBe(poolConfig.options);
|
||||
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('rejects control characters in PGOPTIONS and URL options before creating a pool', async () => {
|
||||
let calls = 0;
|
||||
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;
|
||||
},
|
||||
};
|
||||
|
||||
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',
|
||||
'postgres:///research_db?host=/var/run/postgresql&statement_timeout=99999&lock_timeout=88888',
|
||||
},
|
||||
{
|
||||
createPool: cfg => {
|
||||
captured.push(cfg);
|
||||
return createFakePool();
|
||||
createPool(poolConfig) {
|
||||
capturedConfigs.push(poolConfig);
|
||||
return fakePool;
|
||||
},
|
||||
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=');
|
||||
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('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}`);
|
||||
},
|
||||
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;
|
||||
}
|
||||
});
|
||||
|
||||
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;
|
||||
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(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);
|
||||
expect(createPoolCalls).toBe(0);
|
||||
});
|
||||
|
||||
test(
|
||||
'rejects silent local TCP listener via real pg.Pool connectionTimeoutMillis without leaking credentials',
|
||||
async () => {
|
||||
const sockets = new Set<Socket>();
|
||||
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', () => {});
|
||||
});
|
||||
|
||||
const listenPort = await new Promise<number>((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';
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor({
|
||||
postgresUrl: `postgres://copilot:${secret}@127.0.0.1:${listenPort}/research_db`,
|
||||
});
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
} finally {
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
}
|
||||
await new Promise<void>(resolve => {
|
||||
server.close(() => resolve());
|
||||
});
|
||||
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;
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
},
|
||||
15_000
|
||||
);
|
||||
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 = {
|
||||
async query(text) {
|
||||
return { rows: [{ sql: text }] };
|
||||
},
|
||||
async end() {},
|
||||
on(event, listener) {
|
||||
if (event === 'error') {
|
||||
errorListeners.push(listener);
|
||||
}
|
||||
return fakePool;
|
||||
},
|
||||
};
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgres://127.0.0.1:5432/research_db' },
|
||||
{ createPool: () => fakePool }
|
||||
);
|
||||
|
||||
expect(errorListeners).toHaveLength(1);
|
||||
expect(() => errorListeners[0]!(new Error('idle client disconnected'))).not.toThrow();
|
||||
|
||||
const res = await handle.executor.query<{ sql: string }>('SELECT 2');
|
||||
expect(res.rows).toEqual([{ sql: 'SELECT 2' }]);
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('deduplicates concurrent close() calls and rejects queries started during shutdown', async () => {
|
||||
let resolveEnd!: () => void;
|
||||
let endCalls = 0;
|
||||
let queryCalls = 0;
|
||||
|
||||
const fakePool: ResearchCopilotExecutorPool = {
|
||||
async query() {
|
||||
queryCalls += 1;
|
||||
return { rows: [] };
|
||||
},
|
||||
end() {
|
||||
endCalls += 1;
|
||||
return new Promise<void>(resolve => {
|
||||
resolveEnd = resolve;
|
||||
});
|
||||
},
|
||||
on() {
|
||||
return fakePool;
|
||||
},
|
||||
};
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgres://127.0.0.1:5432/research_db' },
|
||||
{ createPool: () => fakePool }
|
||||
);
|
||||
expect(queryCalls).toBe(1);
|
||||
|
||||
const closeA = handle.close();
|
||||
const closeB = handle.close();
|
||||
|
||||
// Even while pool.end() is still in flight, new queries must reject immediately.
|
||||
await expect(handle.executor.query('SELECT 2')).rejects.toMatchObject({
|
||||
name: 'ResearchCopilotExecutorError',
|
||||
code: 'EXECUTOR_CLOSED',
|
||||
});
|
||||
expect(queryCalls).toBe(1);
|
||||
expect(endCalls).toBe(1);
|
||||
|
||||
resolveEnd();
|
||||
await Promise.all([closeA, closeB]);
|
||||
expect(endCalls).toBe(1);
|
||||
});
|
||||
|
||||
test('rejects with sanitized OPEN_FAILED when a real pg.Pool times out against a silent loopback listener', async () => {
|
||||
const sockets = new Set<Socket>();
|
||||
const server = createServer(socket => {
|
||||
sockets.add(socket);
|
||||
socket.on('close', () => sockets.delete(socket));
|
||||
// Intentionally accept and never reply so pg hits its connection timeout.
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once('error', reject);
|
||||
server.listen(0, '127.0.0.1', () => resolve());
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
for (const socket of sockets) {
|
||||
socket.destroy();
|
||||
}
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
const { port } = server.address() as AddressInfo;
|
||||
const secretPass = 'LoopbackSecretPass99';
|
||||
const loopbackUrl = `postgres://loopback_user:${secretPass}@127.0.0.1:${port}/research_db`;
|
||||
|
||||
let observedConfig: PoolConfig | undefined;
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor(
|
||||
{ postgresUrl: loopbackUrl },
|
||||
{
|
||||
createPool(poolConfig) {
|
||||
observedConfig = poolConfig;
|
||||
// Keep the default config assertions intact, but tighten connect timeout for fast local test execution.
|
||||
return new Pool({
|
||||
...poolConfig,
|
||||
connectionTimeoutMillis: 150,
|
||||
});
|
||||
},
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
expect(observedConfig?.max).toBe(RESEARCH_COPILOT_PG_POOL_MAX);
|
||||
expect(observedConfig?.connectionTimeoutMillis).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS);
|
||||
expect(observedConfig?.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS);
|
||||
expect(caught).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
const typed = caught as ResearchCopilotExecutorError;
|
||||
expect(typed.code).toBe('OPEN_FAILED');
|
||||
expect((typed as { cause?: unknown }).cause).toBeUndefined();
|
||||
expect(typed.message).not.toContain('loopback_user');
|
||||
expect(typed.message).not.toContain(secretPass);
|
||||
expect(typed.message).not.toContain('127.0.0.1');
|
||||
expect(typed.message).not.toContain(String(port));
|
||||
});
|
||||
|
||||
test('has no runtime import of @stock-bot/research', () => {
|
||||
const sourcePath = fileURLToPath(
|
||||
new URL('../src/research-copilot-executor.ts', import.meta.url)
|
||||
);
|
||||
const source = readFileSync(sourcePath, 'utf8');
|
||||
expect(source).not.toMatch(/from\s+['"]@stock-bot\/research/);
|
||||
expect(source).not.toMatch(/require\(\s*['"]@stock-bot\/research/);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import type { PoolConfig } from 'pg';
|
||||
import {
|
||||
|
|
@ -8,455 +7,417 @@ import {
|
|||
RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS,
|
||||
RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS,
|
||||
ResearchCopilotExecutorError,
|
||||
type ResearchCopilotPoolLike,
|
||||
type ResearchCopilotExecutorPool,
|
||||
openResearchCopilotExecutor,
|
||||
} from '../src';
|
||||
} from '../src/index';
|
||||
|
||||
interface FakePoolControls {
|
||||
readonly pool: ResearchCopilotPoolLike;
|
||||
readonly emitter: EventEmitter;
|
||||
const SECRET_USER = 'copilot_secret_user';
|
||||
const SECRET_PASS = 'Sup3rS3cretP@ssw0rd!';
|
||||
const SECRET_HOST = 'pg-internal-secret.example.test';
|
||||
const VALID_URL = `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`;
|
||||
|
||||
interface FakePoolState {
|
||||
readonly queries: Array<{ readonly text: string; readonly values?: unknown[] }>;
|
||||
getEndCalls(): number;
|
||||
readonly errorListeners: Array<(error: Error) => void>;
|
||||
endCalls: number;
|
||||
readonly pool: ResearchCopilotExecutorPool;
|
||||
}
|
||||
|
||||
function createFakePool(options?: {
|
||||
onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>;
|
||||
onEnd?: () => Promise<void>;
|
||||
}): FakePoolControls {
|
||||
const emitter = new EventEmitter();
|
||||
}): FakePoolState {
|
||||
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,
|
||||
const errorListeners: Array<(error: Error) => void> = [];
|
||||
const state: FakePoolState = {
|
||||
queries,
|
||||
getEndCalls: () => endCalls,
|
||||
errorListeners,
|
||||
endCalls: 0,
|
||||
pool: {
|
||||
async query(text: string, values?: unknown[]) {
|
||||
queries.push(values === undefined ? { text } : { text, values });
|
||||
if (options?.onQuery) {
|
||||
return options.onQuery(text, values);
|
||||
}
|
||||
return { rows: [] };
|
||||
},
|
||||
async end() {
|
||||
state.endCalls += 1;
|
||||
if (options?.onEnd) {
|
||||
return options.onEnd();
|
||||
}
|
||||
},
|
||||
on(event: 'error', listener: (error: Error) => void) {
|
||||
if (event === 'error') {
|
||||
errorListeners.push(listener);
|
||||
}
|
||||
return state.pool;
|
||||
},
|
||||
},
|
||||
};
|
||||
return state;
|
||||
}
|
||||
|
||||
function assertNoSecretsLeaked(error: unknown): void {
|
||||
expect(error).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
const typed = error as ResearchCopilotExecutorError;
|
||||
expect((typed as { cause?: unknown }).cause).toBeUndefined();
|
||||
expect('cause' in typed).toBe(false);
|
||||
expect('detail' in typed).toBe(false);
|
||||
expect('extraDiag' in typed).toBe(false);
|
||||
const message = typed.message;
|
||||
for (const needle of [
|
||||
VALID_URL,
|
||||
SECRET_USER,
|
||||
SECRET_PASS,
|
||||
encodeURIComponent(SECRET_PASS),
|
||||
SECRET_HOST,
|
||||
'raw-pg-secret',
|
||||
]) {
|
||||
expect(message).not.toContain(needle);
|
||||
}
|
||||
}
|
||||
|
||||
describe('openResearchCopilotExecutor', () => {
|
||||
describe('pre-pool config validation (fail closed)', () => {
|
||||
const invalidConfigs: ReadonlyArray<readonly [string, unknown]> = [
|
||||
['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' }],
|
||||
['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' }],
|
||||
[
|
||||
'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' },
|
||||
],
|
||||
test('opens a bounded pg pool, probes once with SELECT 1, and attaches an error listener', async () => {
|
||||
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;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
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 () => {
|
||||
const invalidUrls = [
|
||||
'',
|
||||
' ',
|
||||
` ${VALID_URL} `,
|
||||
`${VALID_URL}\n`,
|
||||
'not-a-url',
|
||||
`http://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`,
|
||||
`mysql://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:3306/research_db`,
|
||||
'postgres:/research_db?host=%2Ftmp',
|
||||
'postgresql:/research_db?host=%2Ftmp',
|
||||
'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://copilot@db.example/?dbname=research',
|
||||
`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/research_db?port=0`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=70000`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=abc`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=5432&port=5433`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%20%20`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/db/extra`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:0/research_db`,
|
||||
`postgres://%ZZ:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`,
|
||||
`postgres://${SECRET_USER}:%ZZ@${SECRET_HOST}:5432/research_db`,
|
||||
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%ZZ`,
|
||||
];
|
||||
|
||||
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: () => {
|
||||
let createPoolCalls = 0;
|
||||
for (const postgresUrl of invalidUrls) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor(
|
||||
{ postgresUrl },
|
||||
{
|
||||
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: {},
|
||||
}
|
||||
);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG');
|
||||
}
|
||||
expect(createPoolCalls).toBe(0);
|
||||
});
|
||||
|
||||
expect(captured).toHaveLength(1);
|
||||
expect(fake.queries).toEqual([{ text: 'SELECT 1', values: undefined }]);
|
||||
await handle.close();
|
||||
});
|
||||
test('rejects malformed config or deps with INVALID_CONFIG', async () => {
|
||||
await expect(
|
||||
openResearchCopilotExecutor(null as unknown as { postgresUrl: string })
|
||||
).rejects.toMatchObject({
|
||||
name: 'ResearchCopilotExecutorError',
|
||||
code: 'INVALID_CONFIG',
|
||||
});
|
||||
|
||||
await expect(
|
||||
openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{ createPool: 'not-a-fn' as unknown as () => ResearchCopilotExecutorPool }
|
||||
)
|
||||
).rejects.toMatchObject({
|
||||
name: 'ResearchCopilotExecutorError',
|
||||
code: 'INVALID_CONFIG',
|
||||
});
|
||||
});
|
||||
|
||||
test('ends pool and throws sanitized OPEN_FAILED when startup probe fails', async () => {
|
||||
const fake = createFakePool({
|
||||
async onQuery() {
|
||||
throw new Error(`password authentication failed for ${SECRET_USER} at ${SECRET_HOST} raw-pg-secret`);
|
||||
},
|
||||
});
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool });
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED');
|
||||
expect(fake.endCalls).toBe(1);
|
||||
});
|
||||
|
||||
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`;
|
||||
test('still throws OPEN_FAILED when both probe and cleanup end() fail', async () => {
|
||||
const fake = createFakePool({
|
||||
async onQuery() {
|
||||
throw new Error(`connect ECONNREFUSED ${SECRET_HOST} raw-pg-secret`);
|
||||
},
|
||||
async onEnd() {
|
||||
throw new Error(`pool end failed ${VALID_URL}`);
|
||||
},
|
||||
});
|
||||
|
||||
const fake = createFakePool({
|
||||
onQuery: async () => {
|
||||
throw new Error(`password authentication failed for ${dsn} (${secret})`);
|
||||
},
|
||||
});
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool });
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor(
|
||||
{ postgresUrl: dsn },
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED');
|
||||
expect(fake.endCalls).toBe(1);
|
||||
});
|
||||
|
||||
test('forwards parameters defensively without mutating caller arrays', async () => {
|
||||
const fake = createFakePool({
|
||||
async onQuery(text, values) {
|
||||
if (values) {
|
||||
values.push('mutated-by-driver');
|
||||
}
|
||||
return { rows: [{ text }] };
|
||||
},
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{ createPool: () => fake.pool }
|
||||
);
|
||||
|
||||
const callerParams = Object.freeze(['alpha', 7]);
|
||||
const res = await handle.executor.query('SELECT $1, $2', callerParams);
|
||||
expect(res.rows).toEqual([{ text: 'SELECT $1, $2' }]);
|
||||
expect(callerParams).toEqual(['alpha', 7]);
|
||||
|
||||
await handle.executor.query('SELECT 2');
|
||||
expect(fake.queries[2]).toEqual({ text: 'SELECT 2' });
|
||||
expect('values' in fake.queries[2]!).toBe(false);
|
||||
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('preserves SQLSTATE 23505 on sanitized unique-violation query errors without leaking cause or driver fields', async () => {
|
||||
let callCount = 0;
|
||||
const rawCause = new Error(`nested pgpass secret ${SECRET_PASS}`);
|
||||
const fake = createFakePool({
|
||||
async onQuery() {
|
||||
callCount += 1;
|
||||
if (callCount === 1) {
|
||||
return { rows: [{ '?column?': 1 }] };
|
||||
}
|
||||
const pgErr = Object.assign(
|
||||
new Error(`duplicate key value violates unique constraint on ${SECRET_HOST} raw-pg-secret`, {
|
||||
cause: rawCause,
|
||||
}),
|
||||
{
|
||||
createPool: () => fake.pool,
|
||||
env: {},
|
||||
code: '23505',
|
||||
detail: `Key (id)=(dup-1) already exists (${SECRET_PASS})`,
|
||||
extraDiag: 'sensitive-driver-field',
|
||||
}
|
||||
);
|
||||
} 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);
|
||||
throw pgErr;
|
||||
},
|
||||
});
|
||||
|
||||
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');
|
||||
},
|
||||
});
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{ createPool: () => fake.pool }
|
||||
);
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await openResearchCopilotExecutor(
|
||||
{ postgresUrl: 'postgres://user:secret@127.0.0.1:5432/research_db' },
|
||||
{
|
||||
createPool: () => fake.pool,
|
||||
env: {},
|
||||
}
|
||||
let caught: unknown;
|
||||
try {
|
||||
await handle.executor.query('INSERT INTO findings (id) VALUES ($1)', ['dup-1']);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('23505');
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
test('sanitizes generic query errors to QUERY_FAILED with no cause, extra fields, or raw text', async () => {
|
||||
let callCount = 0;
|
||||
const rawCause = new Error(`nested env PGPASSWORD=${SECRET_PASS}`);
|
||||
const fake = createFakePool({
|
||||
async onQuery() {
|
||||
callCount += 1;
|
||||
if (callCount === 1) {
|
||||
return { rows: [{ '?column?': 1 }] };
|
||||
}
|
||||
throw Object.assign(
|
||||
new Error(`relation "missing" does not exist on ${VALID_URL} raw-pg-secret`, {
|
||||
cause: rawCause,
|
||||
}),
|
||||
{ code: '42P01', detail: 'driver-detail', extraDiag: 'sensitive-driver-field' }
|
||||
);
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
|
||||
expect(fake.getEndCalls()).toBe(1);
|
||||
expect(caught).toBeInstanceOf(ResearchCopilotExecutorError);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('CONNECT_FAILED');
|
||||
},
|
||||
});
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{ createPool: () => fake.pool }
|
||||
);
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await handle.executor.query('SELECT * FROM missing');
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED');
|
||||
await handle.close();
|
||||
});
|
||||
|
||||
describe('idle-client error handling', () => {
|
||||
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';
|
||||
test('close() is idempotent and subsequent queries fail with EXECUTOR_CLOSED', async () => {
|
||||
const fake = createFakePool();
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{ createPool: () => fake.pool }
|
||||
);
|
||||
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: `postgres://user:${secret}@127.0.0.1:5432/research_db` },
|
||||
{
|
||||
createPool: () => fake.pool,
|
||||
onPoolError: err => {
|
||||
received.push(err);
|
||||
},
|
||||
env: {},
|
||||
}
|
||||
);
|
||||
await handle.close();
|
||||
await handle.close();
|
||||
expect(fake.endCalls).toBe(1);
|
||||
|
||||
expect(fake.emitter.listenerCount('error')).toBe(1);
|
||||
let caught: unknown;
|
||||
try {
|
||||
await handle.executor.query('SELECT 1');
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
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);
|
||||
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();
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED');
|
||||
expect(fake.queries).toHaveLength(1); // Only the initial SELECT 1 probe ran.
|
||||
});
|
||||
|
||||
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<void>(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('sanitizes pool.end() failures to CLOSE_FAILED with no cause or secret leakage', async () => {
|
||||
const fake = createFakePool({
|
||||
async onEnd() {
|
||||
throw new Error(`failed closing pool for ${VALID_URL} raw-pg-secret`);
|
||||
},
|
||||
});
|
||||
|
||||
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')) {
|
||||
throw rawDuplicateErr;
|
||||
}
|
||||
if (text === 'SELECT * FROM missing') {
|
||||
throw rawOtherSqlStateErr;
|
||||
}
|
||||
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).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);
|
||||
const handle = await openResearchCopilotExecutor(
|
||||
{ postgresUrl: VALID_URL },
|
||||
{ createPool: () => fake.pool }
|
||||
);
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await handle.close();
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
assertNoSecretsLeaked(caught);
|
||||
expect((caught as ResearchCopilotExecutorError).code).toBe('CLOSE_FAILED');
|
||||
expect(fake.endCalls).toBe(1);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,32 +1,50 @@
|
|||
import type { Pool } from 'pg';
|
||||
import type {
|
||||
ManagedPostgresExecutor,
|
||||
PostgresResearchCopilotExecutor,
|
||||
ResearchCopilotHostConfig,
|
||||
ResearchCopilotStdioHostDeps,
|
||||
} from '@stock-bot/research/mcp';
|
||||
import {
|
||||
type ManagedResearchCopilotExecutor,
|
||||
type ResearchCopilotPoolLike,
|
||||
type ResearchCopilotExecutor,
|
||||
type ResearchCopilotExecutorConfig,
|
||||
type ResearchCopilotExecutorDeps,
|
||||
type ResearchCopilotExecutorError,
|
||||
type ResearchCopilotExecutorErrorCode,
|
||||
type ResearchCopilotExecutorPool,
|
||||
openResearchCopilotExecutor,
|
||||
} from '../src';
|
||||
} from '../src/index';
|
||||
|
||||
// The managed handle returned by openResearchCopilotExecutor must satisfy ManagedPostgresExecutor.
|
||||
// The factory must plug directly into ResearchCopilotStdioHostDeps.openExecutor.
|
||||
openResearchCopilotExecutor satisfies ResearchCopilotStdioHostDeps['openExecutor'];
|
||||
|
||||
// Full host config is structurally assignable to the minimal executor config.
|
||||
declare const hostConfig: ResearchCopilotHostConfig;
|
||||
hostConfig satisfies ResearchCopilotExecutorConfig;
|
||||
|
||||
// Returned handle and executor are structurally assignable to the MCP host ports.
|
||||
declare const managedHandle: ManagedResearchCopilotExecutor;
|
||||
managedHandle satisfies ManagedPostgresExecutor;
|
||||
|
||||
// The factory itself must be directly assignable to ResearchCopilotStdioHostDeps['openExecutor'].
|
||||
const openExecutor: ResearchCopilotStdioHostDeps['openExecutor'] = openResearchCopilotExecutor;
|
||||
void openExecutor;
|
||||
declare const executor: ResearchCopilotExecutor;
|
||||
executor satisfies PostgresResearchCopilotExecutor;
|
||||
|
||||
// Calling openResearchCopilotExecutor with a full ResearchCopilotHostConfig returns ManagedPostgresExecutor.
|
||||
declare const hostConfig: ResearchCopilotHostConfig;
|
||||
const opened: Promise<ManagedPostgresExecutor> = openResearchCopilotExecutor(hostConfig);
|
||||
void opened;
|
||||
// Real pg.Pool satisfies the injected pool contract.
|
||||
declare const pgPool: Pool;
|
||||
pgPool satisfies ResearchCopilotExecutorPool;
|
||||
|
||||
// Real pg.Pool instances must satisfy the structural ResearchCopilotPoolLike interface.
|
||||
declare const realPool: Pool;
|
||||
realPool satisfies ResearchCopilotPoolLike;
|
||||
// Optional deps contract accepts createPool returning pg.Pool.
|
||||
const validDeps: ResearchCopilotExecutorDeps = {
|
||||
createPool: () => pgPool,
|
||||
};
|
||||
void validDeps;
|
||||
|
||||
// Missing postgresUrl must be rejected at compile time.
|
||||
// @ts-expect-error postgresUrl is required on ResearchCopilotExecutorConfig.
|
||||
// Error code union includes all sanitized lifecycle codes plus SQLSTATE 23505.
|
||||
declare const errorInstance: ResearchCopilotExecutorError;
|
||||
const errorCode: ResearchCopilotExecutorErrorCode = errorInstance.code;
|
||||
void errorCode;
|
||||
|
||||
// Negative checks: missing postgresUrl must fail typechecking.
|
||||
// @ts-expect-error postgresUrl is required.
|
||||
void openResearchCopilotExecutor({});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue