From c9b20584de69bd9e8f19b32be116ef1d524dd5a3 Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 18:30:38 -0500 Subject: [PATCH] =?UTF-8?q?T-182:=20M2.1r=20=E2=80=94=20Stdio=20host=20com?= =?UTF-8?q?position=20for=20the=20MCP=20copilot:=20`parseResearchCopilotHo?= =?UTF-8?q?stConfig`=20(injected=20env=20=E2=86=92=20validated=20config)?= =?UTF-8?q?=20+=20`runResearchCopilotStdioHost`=20(injected=20executor=20/?= =?UTF-8?q?=20store=20/=20library-reader=20factories=20=E2=86=92=20`create?= =?UTF-8?q?PostgresResearchCopilotServer`=20+=20`createBarSessionDatesPort?= =?UTF-8?q?`=20=E2=86=92=20`runStdioServer`,=20fail-closed,=20resources=20?= =?UTF-8?q?always=20closed)=20in=20`libs/research/src/mcp/host/stdio-host.?= =?UTF-8?q?ts`=20(no=20new=20deps,=20no=20live=20Postgres/DuckDB,=20no=20b?= =?UTF-8?q?in)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/host/stdio-host.ts | 74 +++++++++++-- libs/research/test/mcp-stdio-host.test.ts | 128 ++++++++++++++++++++-- 2 files changed, 182 insertions(+), 20 deletions(-) diff --git a/libs/research/src/mcp/host/stdio-host.ts b/libs/research/src/mcp/host/stdio-host.ts index c8a7a8a0..b7ff3c3a 100644 --- a/libs/research/src/mcp/host/stdio-host.ts +++ b/libs/research/src/mcp/host/stdio-host.ts @@ -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, 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(); 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, diff --git a/libs/research/test/mcp-stdio-host.test.ts b/libs/research/test/mcp-stdio-host.test.ts index fc76e210..3dd7cdee 100644 --- a/libs/research/test/mcp-stdio-host.test.ts +++ b/libs/research/test/mcp-stdio-host.test.ts @@ -59,14 +59,23 @@ function buildValidEnv( }; } -function assertNoCredentialLeak(error: unknown): void { +function assertNoCredentialLeak(error: unknown, visited: Set = 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 { + 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', () => {