import { createRequire } from 'node:module'; import { describe, expect, test } from 'bun:test'; import { assertEnvironmentSafety, stockAppSchema, type StockAppConfig, } from '@stock-bot/stock-config'; import { MongoClient, type HostAddress, type ServerDescription } from 'mongodb'; const requireFromHere = createRequire(import.meta.url); const { ServerDescription: DriverServerDescription } = requireFromHere( 'mongodb/lib/sdam/server_description' ) as { ServerDescription: new (address: HostAddress | string) => ServerDescription; }; function getDriverDialHostAddress(seed: HostAddress): HostAddress { // Mirrors Topology -> ServerDescription -> Server/Monitor (description.hostAddress) // without opening any socket or calling connect(). return new DriverServerDescription(seed).hostAddress; } function makeConfig( overrides: { environment?: 'development' | 'qa' | 'test' | 'production'; pgHost?: string; pgPort?: number; pgDatabase?: string; pgPassword?: string; mongoUri?: string; mongoReadUri?: string; mongoReadOnly?: boolean; mongoDatabase?: string; bypassSchemaValidation?: boolean; } = {} ): StockAppConfig { const defaultMongoUri = 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin'; const defaultMongoReadUri = 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock'; const parsed = stockAppSchema.parse({ name: 'stock-bot', version: '1.0.0', environment: overrides.environment ?? 'development', service: { name: 'stock-bot', port: 2002, host: '127.0.0.1', }, log: { level: 'info', format: 'json', }, database: { postgres: { enabled: true, host: overrides.pgHost ?? 'localhost', port: overrides.pgPort ?? 5433, database: overrides.pgDatabase ?? 'trading_bot_dev', user: 'dev_user', password: overrides.pgPassword ?? 'dev_pass', ssl: false, }, mongodb: { enabled: true, uri: overrides.bypassSchemaValidation ? defaultMongoUri : (overrides.mongoUri ?? defaultMongoUri), readUri: overrides.bypassSchemaValidation ? defaultMongoReadUri : (overrides.mongoReadUri ?? defaultMongoReadUri), readOnly: overrides.mongoReadOnly ?? false, database: overrides.mongoDatabase ?? '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 (overrides.bypassSchemaValidation) { if (overrides.mongoUri !== undefined) { parsed.database.mongodb.uri = overrides.mongoUri; } if (overrides.mongoReadUri !== undefined) { parsed.database.mongodb.readUri = overrides.mongoReadUri; } } return parsed; } function isDriverHostLoopback(host: string): boolean { const normalized = host .trim() .replace(/^\[|\]$/g, '') .replace(/\.+$/, '') .toLowerCase(); if (normalized === 'localhost' || normalized === '0.0.0.0' || normalized === '::1') { return true; } if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(normalized)) { return true; } if (normalized.startsWith('::1%')) { return true; } if (/^::ffff:(?:7f[0-9a-f]{2}:[0-9a-f]{1,4}|127\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(normalized)) { return true; } return false; } describe('Environment safety — percent-encoded MongoDB seed hosts', () => { test('blocks percent-encoded localhost QA URI for dataIngestion and unsafe dataPipeline', () => { const encodedQaUri = 'mongodb://u:p@%6cocalhost:27017/stock'; const ingestionCfg = makeConfig({ environment: 'development', mongoUri: encodedQaUri, mongoDatabase: 'stock', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( /cannot open a writable MongoDB connection to QA MongoDB/ ); const pipelineNonReadOnly = makeConfig({ environment: 'development', mongoReadUri: encodedQaUri, mongoReadOnly: false, mongoDatabase: 'stock', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(pipelineNonReadOnly, 'dataPipeline', {})).toThrow( /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ ); const pipelineAdmin = makeConfig({ environment: 'development', mongoReadUri: 'mongodb://trading_admin:pass@%6cocalhost:27017/stock', mongoReadOnly: true, mongoDatabase: 'stock', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(pipelineAdmin, 'dataPipeline', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', }) ).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/); }); test('blocks encoded loopback variants (IPv4, mixed-case, trailing dot, omitted port, srv, IPv6)', () => { const encodedLoopbackUris = [ 'mongodb://u:p@%6cocalhost:27017/stock', 'mongodb://u:p@%31%32%37%2e%30%2e%30%2e%31:27017/stock', 'mongodb://u:p@127%2E0.0.1:27017/stock', 'mongodb://u:p@%4C%6fCalHost:27017/stock', 'mongodb://u:p@%4C%4F%43%41%4C%48%4F%53%54:27017/stock', 'mongodb://u:p@%6cocalhost%2e:27017/stock', 'mongodb://u:p@%6cocalhost/stock', 'mongodb+srv://u:p@%6cocalhost/stock', 'mongodb://u:p@[::1%25lo]:27017/stock', 'mongodb://u:p@[::ffff:%37%66%30%30:1]:27017/stock', ]; for (const mongoUri of encodedLoopbackUris) { const ingestionCfg = makeConfig({ environment: 'development', mongoUri, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( /cannot open a writable MongoDB connection to QA MongoDB/ ); const pipelineCfg = makeConfig({ environment: 'development', mongoReadUri: mongoUri, mongoReadOnly: false, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow( /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ ); } }); test('blocks encoded QA loopback hosts inside multi-host seed lists', () => { const multiHostUris = [ 'mongodb://u:p@localhost:27018,%6cocalhost:27017/stock_dev', 'mongodb://u:p@localhost:27018,%31%32%37.0.0.1/stock_dev', ]; for (const mongoUri of multiHostUris) { const ingestionCfg = makeConfig({ environment: 'development', mongoUri, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( /cannot open a writable MongoDB connection to QA MongoDB/ ); const pipelineCfg = makeConfig({ environment: 'development', mongoReadUri: mongoUri, mongoReadOnly: false, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow( /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ ); } }); test('allows safe dev URIs, read-only encoded QA dataPipeline, and explicit escape hatch', () => { const safeDevUris = [ 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev', 'mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27018/stock_dev', 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev', ]; for (const mongoUri of safeDevUris) { const cfg = makeConfig({ environment: 'development', mongoUri, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow(); } const readOnlyEncodedPipeline = makeConfig({ environment: 'development', mongoReadUri: 'mongodb://studio_stock_bot_read:secret@%6cocalhost:27017/stock?authSource=stock', mongoReadOnly: true, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(readOnlyEncodedPipeline, 'dataPipeline', {})).not.toThrow(); const escapedEncodedIngestion = makeConfig({ environment: 'development', mongoUri: 'mongodb://u:p@%6cocalhost:27017/stock', mongoDatabase: 'stock', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(escapedEncodedIngestion, 'dataIngestion', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', }) ).not.toThrow(); }); test('fails closed with an explicit error on malformed percent-encoding in MongoDB host', () => { const malformedUris = [ 'mongodb://u:p@%zz:27017/stock', 'mongodb://u:p@%zz:27018/stock_dev', 'mongodb://u:p@localhost:27018,%zz:27017/stock_dev', 'mongodb://u:p@local%2:27017/stock', 'mongodb://u:p@localhost%:27017/stock', 'mongodb://u:p@[::1%zz]:27017/stock', ]; for (const mongoUri of malformedUris) { const ingestionCfg = makeConfig({ environment: 'development', mongoUri, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( /Safety guard: invalid percent-encoding in MongoDB host/ ); expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', }) ).toThrow(/Safety guard: invalid percent-encoding in MongoDB host/); const pipelineCfg = makeConfig({ environment: 'development', mongoReadUri: mongoUri, mongoReadOnly: true, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow( /Safety guard: invalid percent-encoding in MongoDB host/ ); expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', }) ).toThrow(/Safety guard: invalid percent-encoding in MongoDB host/); } }); test('blocks double-encoded and multi-encoded loopback seeds that ServerDescription reparses to loopback', () => { // Strictly offline: verify MongoDB 6.22.0 ServerDescription.hostAddress decodes a second time. const doubleEncodedLocalhost = 'mongodb://u:p@%256cocalhost:27017/stock'; const doubleEncodedIpv4 = 'mongodb://u:p@%2531%2532%2537.0.0.1:27017/stock'; const localhostSeed = new MongoClient(doubleEncodedLocalhost).options.hosts[0]; expect(localhostSeed?.toString()).toBe('%6cocalhost:27017'); expect(getDriverDialHostAddress(localhostSeed!).toString()).toBe('localhost:27017'); const ipv4Seed = new MongoClient(doubleEncodedIpv4).options.hosts[0]; expect(ipv4Seed?.toString()).toBe('%31%32%37.0.0.1:27017'); expect(getDriverDialHostAddress(ipv4Seed!).toString()).toBe('127.0.0.1:27017'); const multiEncodedQaUris = [ doubleEncodedLocalhost, doubleEncodedIpv4, 'mongodb://u:p@localhost:27018,%256cocalhost:27017/stock_dev', 'mongodb://u:p@%25256cocalhost:27017/stock', ]; for (const mongoUri of multiEncodedQaUris) { const ingestionCfg = makeConfig({ environment: 'development', mongoUri, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( /cannot open a writable MongoDB connection to QA MongoDB/ ); const pipelineNonReadOnly = makeConfig({ environment: 'development', mongoReadUri: mongoUri, mongoReadOnly: false, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(pipelineNonReadOnly, 'dataPipeline', {})).toThrow( /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ ); } const pipelineAdmin = makeConfig({ environment: 'development', mongoReadUri: 'mongodb://trading_admin:pass@%256cocalhost:27017/stock', mongoReadOnly: true, mongoDatabase: 'stock', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(pipelineAdmin, 'dataPipeline', {})).toThrow( /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ ); // Safe dev port and read-only dataPipeline with double-encoded loopback still pass. const devPortCfg = makeConfig({ environment: 'development', mongoUri: 'mongodb://dev_admin:dev_mongo_pass@%256cocalhost:27018/stock_dev', mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(devPortCfg, 'dataIngestion', {})).not.toThrow(); const readOnlyPipelineCfg = makeConfig({ environment: 'development', mongoReadUri: 'mongodb://studio_stock_bot_read:secret@%256cocalhost:27017/stock?authSource=stock', mongoReadOnly: true, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(readOnlyPipelineCfg, 'dataPipeline', {})).not.toThrow(); // Double-encoded malformed escape (%25zz -> %zz) and excessive nesting fail closed. const doubleMalformedUri = 'mongodb://u:p@%25zz:27017/stock'; const doubleMalformedSeed = new MongoClient(doubleMalformedUri).options.hosts[0]; expect(() => getDriverDialHostAddress(doubleMalformedSeed!)).toThrow(); for (const badUri of [ doubleMalformedUri, 'mongodb://u:p@%2525252525252525256cocalhost:27017/stock', ]) { const cfg = makeConfig({ environment: 'development', mongoUri: badUri, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow( /Safety guard: invalid percent-encoding in MongoDB host/ ); } }); test('matches MongoDB driver ServerDescription.hostAddress dial target offline without connecting', () => { const parityCases = [ 'mongodb://u:p@localhost:27017/stock', 'mongodb://u:p@%6cocalhost:27017/stock', 'mongodb://u:p@%256cocalhost:27017/stock', 'mongodb://u:p@%4C%6fCalHost:27017/stock', 'mongodb://u:p@%31%32%37%2e%30%2e%30%2e%31:27017/stock', 'mongodb://u:p@%2531%2532%2537.0.0.1:27017/stock', 'mongodb://u:p@127%2E0.0.1:27017/stock', 'mongodb://u:p@%6cocalhost/stock', 'mongodb://u:p@localhost:27018,%6cocalhost:27017/stock_dev', 'mongodb://u:p@localhost:27018,%256cocalhost:27017/stock_dev', 'mongodb://u:p@localhost:27018,%31%32%37.0.0.1/stock_dev', 'mongodb://u:p@localhost:27018/stock_dev', 'mongodb://u:p@%6cocalhost:27018/stock_dev', 'mongodb://u:p@%256cocalhost:27018/stock_dev', 'mongodb://u:p@mongo.internal:27017/stock', ]; for (const uri of parityCases) { // Strictly offline: inspect the final HostAddress produced by ServerDescription.hostAddress; never call connect(). const client = new MongoClient(uri); const driverTargetsQa = client.options.hosts.some(entry => { const dialHost = getDriverDialHostAddress(entry); return ( typeof dialHost.host === 'string' && isDriverHostLoopback(dialHost.host) && (dialHost.port === undefined || dialHost.port === 27017) ); }); const cfg = makeConfig({ environment: 'development', mongoUri: uri, mongoDatabase: 'stock_dev', bypassSchemaValidation: true, }); let guardBlocked = false; try { assertEnvironmentSafety(cfg, 'dataIngestion', {}); } catch { guardBlocked = true; } expect(guardBlocked).toBe(driverTargetsQa); } // Malformed percent-encoding: both guard and MongoClient reject it offline. const malformedUri = 'mongodb://u:p@%zz:27017/stock'; expect(() => new MongoClient(malformedUri)).toThrow(); const malformedCfg = makeConfig({ environment: 'development', mongoUri: malformedUri, mongoDatabase: 'stock', bypassSchemaValidation: true, }); expect(() => assertEnvironmentSafety(malformedCfg, 'dataIngestion', {})).toThrow( /Safety guard: invalid percent-encoding in MongoDB host/ ); }); test('does not throw on literal IPv6 zone ID in raw PostgreSQL host', () => { const cfg = makeConfig({ environment: 'development', pgHost: 'fe80::1%eth0', pgPort: 5432, pgDatabase: 'trading_bot', }); expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow(); }); });