T-200: merge dev
This commit is contained in:
commit
267e655e63
6 changed files with 1243 additions and 1168 deletions
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue