T-182: M2.1r — Stdio host composition for the MCP copilot: parseResearchCopilotHostConfig (injected env → validated config) + runResearchCopilotStdioHost (injected executor / store / library-reader factories → createPostgresResearchCopilotServer + createBarSessionDatesPort → runStdioServer, fail-closed, resources always closed) in libs/research/src/mcp/host/stdio-host.ts (no new deps, no live Postgres/DuckDB, no bin)
This commit is contained in:
parent
1236647fa0
commit
c9b20584de
2 changed files with 182 additions and 20 deletions
|
|
@ -200,6 +200,19 @@ function parsePostgresUrl(raw: string): string {
|
|||
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a postgres:// or postgresql:// URL with a non-empty host.`
|
||||
);
|
||||
}
|
||||
try {
|
||||
if (parsed.username.length > 0) {
|
||||
decodeURIComponent(parsed.username);
|
||||
}
|
||||
if (parsed.password.length > 0) {
|
||||
decodeURIComponent(parsed.password);
|
||||
}
|
||||
} catch {
|
||||
throw new ResearchCopilotHostConfigError(
|
||||
ENV_POSTGRES_URL,
|
||||
`Invalid configuration variable "${ENV_POSTGRES_URL}": URL credentials contain invalid percent-encoding.`
|
||||
);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
|
|
@ -526,6 +539,21 @@ export function parseResearchCopilotHostConfig(
|
|||
};
|
||||
}
|
||||
|
||||
function addRawAndDecodedNeedle(needles: Set<string>, raw: string): void {
|
||||
if (raw.length === 0) {
|
||||
return;
|
||||
}
|
||||
needles.add(raw);
|
||||
try {
|
||||
const decoded = decodeURIComponent(raw);
|
||||
if (decoded.length > 0) {
|
||||
needles.add(decoded);
|
||||
}
|
||||
} catch {
|
||||
// Malformed percent-encoding: raw needle is already registered.
|
||||
}
|
||||
}
|
||||
|
||||
function collectSecretNeedles(postgresUrl: string): readonly string[] {
|
||||
const needles = new Set<string>();
|
||||
if (postgresUrl.length > 0) {
|
||||
|
|
@ -536,15 +564,30 @@ function collectSecretNeedles(postgresUrl: string): readonly string[] {
|
|||
if (parsed.href.length > 0) {
|
||||
needles.add(parsed.href);
|
||||
}
|
||||
if (parsed.password.length > 0) {
|
||||
needles.add(parsed.password);
|
||||
try {
|
||||
const decoded = decodeURIComponent(parsed.password);
|
||||
if (decoded.length > 0) {
|
||||
needles.add(decoded);
|
||||
addRawAndDecodedNeedle(needles, parsed.password);
|
||||
for (const [key, value] of parsed.searchParams.entries()) {
|
||||
if (key.toLowerCase() === 'password' && value.length > 0) {
|
||||
needles.add(value);
|
||||
}
|
||||
}
|
||||
if (parsed.search.length > 1) {
|
||||
const pairs = parsed.search.slice(1).split('&');
|
||||
for (let i = 0; i < pairs.length; i += 1) {
|
||||
const pair = pairs[i] as string;
|
||||
const eqIdx = pair.indexOf('=');
|
||||
if (eqIdx <= 0) {
|
||||
continue;
|
||||
}
|
||||
const rawKey = pair.slice(0, eqIdx);
|
||||
let decodedKey = rawKey;
|
||||
try {
|
||||
decodedKey = decodeURIComponent(rawKey);
|
||||
} catch {
|
||||
// Keep rawKey if percent-decoding fails.
|
||||
}
|
||||
if (decodedKey.toLowerCase() === 'password') {
|
||||
addRawAndDecodedNeedle(needles, pair.slice(eqIdx + 1));
|
||||
}
|
||||
} catch {
|
||||
// Malformed percent-encoding in password: raw password needle is already covered.
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
|
|
@ -589,6 +632,19 @@ function isErrorSafeToSurface(
|
|||
if (cause !== undefined && !isErrorSafeToSurface(cause, needles, visited, depth + 1)) {
|
||||
return false;
|
||||
}
|
||||
if (error instanceof AggregateError || 'errors' in error) {
|
||||
const nested = (error as { readonly errors?: unknown }).errors;
|
||||
if (nested !== undefined) {
|
||||
if (!Array.isArray(nested)) {
|
||||
return false;
|
||||
}
|
||||
for (let i = 0; i < nested.length; i += 1) {
|
||||
if (!isErrorSafeToSurface(nested[i], needles, visited, depth + 1)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
|
|
@ -736,7 +792,7 @@ export async function runResearchCopilotStdioHost(
|
|||
store: storeHandle.store,
|
||||
vaultContext: { vaultCutoffTs: config.vaultCutoffTs },
|
||||
principalId: config.principalId,
|
||||
listLibraryCards: libraryReader.listLibraryCards,
|
||||
listLibraryCards: query => libraryReader.listLibraryCards(query),
|
||||
sessionDates,
|
||||
...(config.earlyCloses !== undefined ? { earlyCloses: config.earlyCloses } : {}),
|
||||
newId: deps.newId,
|
||||
|
|
|
|||
|
|
@ -59,14 +59,23 @@ function buildValidEnv(
|
|||
};
|
||||
}
|
||||
|
||||
function assertNoCredentialLeak(error: unknown): void {
|
||||
function assertNoCredentialLeak(error: unknown, visited: Set<unknown> = new Set()): void {
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
const err = error as Error & { cause?: unknown };
|
||||
if (visited.has(error)) {
|
||||
return;
|
||||
}
|
||||
visited.add(error);
|
||||
const err = error as Error & { cause?: unknown; errors?: unknown };
|
||||
expect(err.message).not.toContain(FAKE_POSTGRES_URL);
|
||||
expect(err.message).not.toContain(FAKE_ENCODED_PASSWORD);
|
||||
expect(err.message).not.toContain(FAKE_DECODED_PASSWORD);
|
||||
if (err.cause !== undefined) {
|
||||
assertNoCredentialLeak(err.cause);
|
||||
assertNoCredentialLeak(err.cause, visited);
|
||||
}
|
||||
if (Array.isArray(err.errors)) {
|
||||
for (const nested of err.errors) {
|
||||
assertNoCredentialLeak(nested, visited);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -295,6 +304,8 @@ describe('parseResearchCopilotHostConfig', () => {
|
|||
['missing host', `postgresql://user:${FAKE_ENCODED_PASSWORD}@/db`],
|
||||
['malformed URL', `not-a-url-${FAKE_DECODED_PASSWORD}`],
|
||||
['surrounding whitespace', ` ${FAKE_POSTGRES_URL} `],
|
||||
['invalid percent-encoding in password', 'postgresql://research_ro:%FF@127.0.0.1:5433/db'],
|
||||
['invalid percent-encoding in username', 'postgresql://user%FF:pass@127.0.0.1:5433/db'],
|
||||
] as const)('rejects invalid POSTGRES_URL (%s) without leaking URL or password', (_label, badUrl) => {
|
||||
const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: badUrl });
|
||||
let caught: unknown;
|
||||
|
|
@ -452,7 +463,6 @@ describe('runResearchCopilotStdioHost', () => {
|
|||
const config = parseResearchCopilotHostConfig(buildValidEnv());
|
||||
const fakeExec = createFakeExecutor();
|
||||
const fakeStore = createFakeStore();
|
||||
const libraryQueries: LibraryCardQuery[] = [];
|
||||
const expectedCard: LibraryCardRecord = {
|
||||
id: 'card-short-squeeze-01',
|
||||
title: 'Canadian Short Interest Spike',
|
||||
|
|
@ -461,6 +471,21 @@ describe('runResearchCopilotStdioHost', () => {
|
|||
tags: ['shorts', 'ca'],
|
||||
};
|
||||
|
||||
class StatefulLibraryCardReader {
|
||||
readonly queries: LibraryCardQuery[] = [];
|
||||
private readonly cards: readonly LibraryCardRecord[];
|
||||
|
||||
constructor(cards: readonly LibraryCardRecord[]) {
|
||||
this.cards = cards;
|
||||
}
|
||||
|
||||
async listLibraryCards(q: LibraryCardQuery): Promise<readonly LibraryCardRecord[]> {
|
||||
this.queries.push(q);
|
||||
return [...this.cards];
|
||||
}
|
||||
}
|
||||
|
||||
const reader = new StatefulLibraryCardReader([expectedCard]);
|
||||
const sink = createMemoryOutput();
|
||||
const { input } = createTrackingInput([
|
||||
{
|
||||
|
|
@ -506,12 +531,7 @@ describe('runResearchCopilotStdioHost', () => {
|
|||
store: fakeStore.store,
|
||||
close: async () => {},
|
||||
}),
|
||||
createLibraryCardReader: async () => ({
|
||||
listLibraryCards: async (q: LibraryCardQuery) => {
|
||||
libraryQueries.push(q);
|
||||
return [expectedCard];
|
||||
},
|
||||
}),
|
||||
createLibraryCardReader: async () => reader,
|
||||
newId: () => 'id-1',
|
||||
now: () => FIXED_NOW_MS,
|
||||
stdio: { input, output: sink.output },
|
||||
|
|
@ -550,7 +570,7 @@ describe('runResearchCopilotStdioHost', () => {
|
|||
expectedCard.title
|
||||
);
|
||||
|
||||
expect(libraryQueries).toHaveLength(1);
|
||||
expect(reader.queries).toHaveLength(1);
|
||||
expect(fakeExec.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
|
|
@ -1084,6 +1104,92 @@ describe('runResearchCopilotStdioHost', () => {
|
|||
assertNoCredentialLeak(caughtRaw);
|
||||
expect((caughtRaw as Error & { cause?: unknown }).cause).toBeUndefined();
|
||||
});
|
||||
|
||||
test('redacts decoded password supplied via DSN query parameter', async () => {
|
||||
const queryPasswordDsn = `postgresql://research_ro@127.0.0.1:5433/trading_bot_dev?sslmode=disable&password=${FAKE_ENCODED_PASSWORD}`;
|
||||
const config = parseResearchCopilotHostConfig(
|
||||
buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: queryPasswordDsn })
|
||||
);
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await runResearchCopilotStdioHost({
|
||||
config,
|
||||
openExecutor: async () => {
|
||||
throw new Error(`password authentication failed for "${FAKE_DECODED_PASSWORD}"`);
|
||||
},
|
||||
openStore: async () => ({ store: createFakeStore().store, close: async () => {} }),
|
||||
createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }),
|
||||
newId: () => 'id-1',
|
||||
now: () => FIXED_NOW_MS,
|
||||
stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output },
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
assertNoCredentialLeak(caught);
|
||||
expect((caught as Error).message).not.toContain(queryPasswordDsn);
|
||||
expect((caught as Error).message).toContain('executor');
|
||||
expect((caught as Error & { cause?: unknown }).cause).toBeUndefined();
|
||||
});
|
||||
|
||||
test('replaces AggregateError containing nested credentials while preserving safe AggregateError', async () => {
|
||||
const config = parseResearchCopilotHostConfig(buildValidEnv());
|
||||
|
||||
// 1. Unsafe AggregateError with nested DSN
|
||||
let caughtUnsafe: unknown;
|
||||
try {
|
||||
await runResearchCopilotStdioHost({
|
||||
config,
|
||||
openExecutor: async () => {
|
||||
throw new AggregateError(
|
||||
[
|
||||
new Error('primary host timed out'),
|
||||
new Error(`replica connect failed for ${FAKE_POSTGRES_URL}`),
|
||||
],
|
||||
'All database endpoints failed'
|
||||
);
|
||||
},
|
||||
openStore: async () => ({ store: createFakeStore().store, close: async () => {} }),
|
||||
createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }),
|
||||
newId: () => 'id-1',
|
||||
now: () => FIXED_NOW_MS,
|
||||
stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output },
|
||||
});
|
||||
} catch (err) {
|
||||
caughtUnsafe = err;
|
||||
}
|
||||
|
||||
assertNoCredentialLeak(caughtUnsafe);
|
||||
expect(caughtUnsafe).not.toBeInstanceOf(AggregateError);
|
||||
expect((caughtUnsafe as Error).message).toContain('executor');
|
||||
expect((caughtUnsafe as Error & { cause?: unknown }).cause).toBeUndefined();
|
||||
|
||||
// 2. Safe AggregateError is preserved by identity
|
||||
const safeAggregate = new AggregateError(
|
||||
[new Error('primary host timed out'), new Error('replica refused connection')],
|
||||
'All database endpoints failed'
|
||||
);
|
||||
let caughtSafe: unknown;
|
||||
try {
|
||||
await runResearchCopilotStdioHost({
|
||||
config,
|
||||
openExecutor: async () => {
|
||||
throw safeAggregate;
|
||||
},
|
||||
openStore: async () => ({ store: createFakeStore().store, close: async () => {} }),
|
||||
createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }),
|
||||
newId: () => 'id-1',
|
||||
now: () => FIXED_NOW_MS,
|
||||
stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output },
|
||||
});
|
||||
} catch (err) {
|
||||
caughtSafe = err;
|
||||
}
|
||||
|
||||
expect(caughtSafe).toBe(safeAggregate);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stdio-host dependency-free source invariants', () => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue