247 lines
8.2 KiB
TypeScript
247 lines
8.2 KiB
TypeScript
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<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;
|
|
}
|
|
|
|
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<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';
|
|
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<void>(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
|
|
);
|
|
});
|