import { createRequire } from 'node:module'; import { describe, expect, test } from 'bun:test'; import { MongoClient, type HostAddress, type ServerDescription } from 'mongodb'; import { setLoggerConfig } from '@stock-bot/logger'; import { assertEnvironmentSafety, stockAppSchema, type StockAppConfig, } from '@stock-bot/stock-config'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const requireFromHere = createRequire(import.meta.url); const { ServerDescription: DriverServerDescription } = requireFromHere( 'mongodb/lib/sdam/server_description' ) as { ServerDescription: new (address: HostAddress | string) => ServerDescription; }; const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1']); /** * Hosts the real driver would dial for `uri` (MongoClient options -> ServerDescription.hostAddress), * without opening a socket. Returns null when the driver itself rejects the URI. */ function driverDialHosts(uri: string): HostAddress[] | null { try { return new MongoClient(uri).options.hosts.map( seed => new DriverServerDescription(seed).hostAddress ); } catch { return null; } } function driverDialsQaMongo(hosts: HostAddress[]): boolean { return hosts.some( h => h.host !== undefined && LOOPBACK_HOSTS.has(h.host.toLowerCase()) && h.port === 27017 ); } /** Schema-valid dev config whose Mongo URIs are then overwritten, bypassing schema validation. */ function makeDevConfig(mongo: { uri?: string; readUri?: string; readOnly?: boolean; }): StockAppConfig { const parsed = stockAppSchema.parse({ name: 'stock-bot', version: '1.0.0', environment: 'development', service: { name: 'stock-bot', port: 2002, host: '127.0.0.1' }, log: { level: 'info', format: 'json' }, database: { postgres: { enabled: true, host: 'localhost', port: 5433, database: 'trading_bot_dev', user: 'dev_user', password: 'dev_pass', ssl: false, }, mongodb: { enabled: true, uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin', readUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock', readOnly: false, database: 'stock_dev', }, questdb: { enabled: false, host: 'localhost', ilpPort: 9010, httpPort: 9100, pgPort: 8813 }, dragonfly: { enabled: true, host: 'localhost', port: 6380 }, }, providers: { yahoo: { name: 'yahoo', enabled: false, priority: 1, timeout: 30000, baseUrl: 'https://query1.finance.yahoo.com', }, qm: { name: 'qm', enabled: false, priority: 2, username: '', password: '', baseUrl: 'https://app.quotemedia.com/quotetools', webmasterId: '', }, ib: { name: 'ib', enabled: false, priority: 3, gateway: { host: 'localhost', port: 5000, clientId: 1 }, marketDataType: 'delayed', }, eod: { name: 'eod', enabled: false, priority: 4, apiKey: '', baseUrl: 'https://eodhistoricaldata.com/api', tier: 'free', }, }, features: {}, }); if (mongo.uri !== undefined) { parsed.database.mongodb.uri = mongo.uri; } if (mongo.readUri !== undefined) { parsed.database.mongodb.readUri = mongo.readUri; } if (mongo.readOnly !== undefined) { parsed.database.mongodb.readOnly = mongo.readOnly; } return parsed; } function guardAllows(config: StockAppConfig, service: 'dataIngestion' | 'dataPipeline'): boolean { try { assertEnvironmentSafety(config, service, {}); return true; } catch { return false; } } /** Deterministic LCG so the fuzz corpus is identical on every run. */ function seededRandom(seed: number): () => number { let state = seed >>> 0; return () => { state = (Math.imul(state, 1103515245) + 12345) & 0x7fffffff; return state / 0x80000000; }; } const FUZZ_TOKENS = [ 'localhost', '127.0.0.1', '[::1]', ':27017', ':27018', '#', '@', '/', '?', ',', 'u', 'p', ':', 'x', '%40', '%23', '\\', ';', '[', ']', '%2C', '.', 'LOCALHOST', '\u0000', '\n', '\t', ' ', '27017', '%3A', 'dev_admin:dev_mongo_pass', ]; function buildFuzzCorpus(seed: number, count: number): string[] { const next = seededRandom(seed); const corpus: string[] = []; for (let i = 0; i < count; i++) { const length = 1 + Math.floor(next() * 8); let body = ''; for (let j = 0; j < length; j++) { body += FUZZ_TOKENS[Math.floor(next() * FUZZ_TOKENS.length)]; } corpus.push((next() < 0.85 ? 'mongodb://' : 'mongodb+srv://') + body); } return corpus; } describe('T-28: guard and driver agree on where the Mongo URI authority splits', () => { test('guard alone (schema bypassed) rejects each T-28 repro with the authority-specific reason', () => { // Arrange: each repro dials QA loopback:27017 in the real driver const cases: Array<{ uri: string; reason: RegExp }> = [ { uri: 'mongodb://localhost:27018#,localhost/stock', reason: /unencoded "#"/ }, { uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018#,localhost:27017/stock_dev?authSource=admin', reason: /unencoded "#"/, }, { uri: 'mongodb://u:p@localhost:27018#x,127.0.0.1/stock', reason: /unencoded "#"/ }, { uri: 'mongodb://u:p@localhost:27017@x:27018/stock', reason: /multiple unencoded "@"/ }, { uri: 'mongodb://u:p@local\nhost:27017/stock', reason: /control characters/ }, { uri: 'mongodb://\nlocalhost', reason: /control characters/ }, ]; for (const { uri, reason } of cases) { const hosts = driverDialHosts(uri); expect(hosts).not.toBeNull(); expect(driverDialsQaMongo(hosts ?? [])).toBe(true); // Act + Assert: ingestion (writable) and pipeline (both read-only modes) expect(() => assertEnvironmentSafety(makeDevConfig({ uri }), 'dataIngestion', {})).toThrow( reason ); for (const readOnly of [true, false]) { expect(() => assertEnvironmentSafety(makeDevConfig({ readUri: uri, readOnly }), 'dataPipeline', {}) ).toThrow(reason); } } }); test('read-only pipeline cannot smuggle trading_admin onto QA Mongo behind a raw "#"', () => { const uri = 'mongodb://trading_admin:x@localhost:27018#,localhost:27017/stock'; const hosts = driverDialHosts(uri); expect(driverDialsQaMongo(hosts ?? [])).toBe(true); expect(() => assertEnvironmentSafety(makeDevConfig({ readUri: uri, readOnly: true }), 'dataPipeline', {}) ).toThrow(/Safety guard:/); }); test('pipeline with no readUri falls back to uri and still fails closed on a split authority', () => { const config = makeDevConfig({ uri: 'mongodb://u:p@localhost:27017@x:27018/stock', readOnly: true, }); config.database.mongodb.readUri = undefined; expect(() => assertEnvironmentSafety(config, 'dataPipeline', {})).toThrow( /multiple unencoded "@"/ ); }); test('seeded differential fuzz: every URI the driver would dial to QA loopback:27017 is blocked', () => { // Arrange: fixed seed -> identical corpus each run const corpus = buildFuzzCorpus(0x7e28, 30000); const bypasses: string[] = []; let driverQaHits = 0; // Act for (const uri of corpus) { const hosts = driverDialHosts(uri); if (!hosts || !driverDialsQaMongo(hosts)) { continue; } driverQaHits++; if (guardAllows(makeDevConfig({ uri }), 'dataIngestion')) { bypasses.push(`dataIngestion ${JSON.stringify(uri)}`); } if (guardAllows(makeDevConfig({ readUri: uri, readOnly: false }), 'dataPipeline')) { bypasses.push(`dataPipeline ${JSON.stringify(uri)}`); } } // Assert: the corpus actually exercises the QA path, and nothing slips through expect(driverQaHits).toBeGreaterThan(200); expect(bypasses).toEqual([]); }); test('schema-accepted URIs that the driver dials only to non-QA hosts are not falsely blocked', () => { const uris = [ 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin', 'mongodb://dev_admin:p%40ss@localhost:27018/stock_dev?appName=a@b#note', 'mongodb://dev_admin:p%23ss@localhost:27018/stock_dev', 'mongodb://localhost:27018?authSource=admin#frag', // '@' after the path is only driver-valid when real userinfo precedes it 'mongodb://u:p@localhost:27018/stock_dev#frag@x', 'mongodb://dev_user@localhost:27018,127.0.0.1:27019/stock_dev', 'mongodb://u:p@[::1]:27018/stock_dev', ]; for (const uri of uris) { const hosts = driverDialHosts(uri); expect(hosts).not.toBeNull(); expect(driverDialsQaMongo(hosts ?? [])).toBe(false); expect( stockAppSchema.shape.database.shape.mongodb.safeParse({ enabled: true, uri, database: 'stock_dev', }).success ).toBe(true); expect(guardAllows(makeDevConfig({ uri }), 'dataIngestion')).toBe(true); expect(guardAllows(makeDevConfig({ readUri: uri, readOnly: false }), 'dataPipeline')).toBe( true ); } }); test('non-ASCII whitespace that the driver keeps inside the host list fails closed in schema and guard', () => { // The driver accepts these verbatim as part of the host (localhost:27017); neither the // ASCII control-char check nor a '#'/'@' rule catches them, so the /\s/ check must. const uris = [ 'mongodb://u:p@local host:27017/stock', 'mongodb://u:p@local
host:27017/stock', 'mongodb://u:p@localhost:27018, localhost/stock', ]; for (const uri of uris) { expect(driverDialHosts(uri)).not.toBeNull(); expect( stockAppSchema.shape.database.shape.mongodb.safeParse({ enabled: true, uri, database: 'stock_dev', }).success ).toBe(false); expect(() => assertEnvironmentSafety(makeDevConfig({ uri }), 'dataIngestion', {})).toThrow( /forbidden whitespace/ ); expect(() => assertEnvironmentSafety(makeDevConfig({ readUri: uri, readOnly: true }), 'dataPipeline', {}) ).toThrow(/forbidden whitespace/); } }); test('IPv6 loopback behind a raw "#" (driver dials [::1]:27017) fails closed in schema and guard', () => { const uri = 'mongodb://u:p@[::1]#:27018/stock'; const hosts = driverDialHosts(uri) ?? []; expect(driverDialsQaMongo(hosts)).toBe(true); expect( stockAppSchema.shape.database.shape.mongodb.safeParse({ enabled: true, uri, database: 'stock_dev', }).success ).toBe(false); expect(() => assertEnvironmentSafety(makeDevConfig({ uri }), 'dataIngestion', {})).toThrow( /unencoded "#"/ ); }); test('seeded fuzz through the real config path: no schema-accepted URI that dials QA loopback:27017 passes the guard', () => { // Arrange: different seed from the schema-bypassed fuzz above. Only the bypass direction is // asserted: the guard deliberately also blocks some non-QA URIs (percent-encoded hosts, // trailing-dot loopback, srv to loopback), so "allowed" is not expected to mirror the driver. const corpus = buildFuzzCorpus(0x28e7, 30000); const mongoSchema = stockAppSchema.shape.database.shape.mongodb; const bypasses: string[] = []; let schemaAcceptedQa = 0; // Act for (const uri of corpus) { if (!mongoSchema.safeParse({ enabled: true, uri, database: 'stock_dev' }).success) { continue; } const hosts = driverDialHosts(uri); if (!hosts || !driverDialsQaMongo(hosts)) { continue; } schemaAcceptedQa++; if (guardAllows(makeDevConfig({ uri }), 'dataIngestion')) { bypasses.push(`dataIngestion ${JSON.stringify(uri)}`); } if (guardAllows(makeDevConfig({ readUri: uri, readOnly: false }), 'dataPipeline')) { bypasses.push(`dataPipeline ${JSON.stringify(uri)}`); } } // Assert: the schema-valid QA path is exercised, and nothing slips through expect(schemaAcceptedQa).toBeGreaterThan(50); expect(bypasses).toEqual([]); }); test('disabled MongoDB in development is not parsed, so a placeholder URI never blocks startup', () => { const config = makeDevConfig({ uri: 'mongodb://disabled' }); config.database.mongodb.enabled = false; config.database.mongodb.readUri = 'not-a-uri'; expect(guardAllows(config, 'dataIngestion')).toBe(true); expect(guardAllows(config, 'dataPipeline')).toBe(true); }); });