diff --git a/apps/stock/config/src/env-safety.ts b/apps/stock/config/src/env-safety.ts index d4187560..fda0dad9 100644 --- a/apps/stock/config/src/env-safety.ts +++ b/apps/stock/config/src/env-safety.ts @@ -2,7 +2,19 @@ import type { StockAppConfig } from './schemas'; export type StockServiceName = 'dataIngestion' | 'dataPipeline' | 'webApi' | 'orchestrator'; -const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0']); +interface MongoTargetHost { + host: string; + port?: number; +} + +interface ParsedMongoTarget { + hosts: MongoTargetHost[]; + host?: string; + database?: string; + username?: string; +} + +const LOOPBACK_HOSTS = new Set(['localhost', '0.0.0.0']); const FORBIDDEN_PROD_SECRETS = new Set([ 'trading_pass_dev', 'trading_mongo_dev', @@ -12,41 +24,271 @@ const FORBIDDEN_PROD_SECRETS = new Set([ 'admin123', ]); +function parseIpv4Octets(host: string): [number, number, number, number] | null { + const octets = host.split('.'); + if (octets.length !== 4) { + return null; + } + const values: number[] = []; + for (const part of octets) { + if (!/^\d{1,3}$/.test(part)) { + return null; + } + const value = Number(part); + if (value < 0 || value > 255) { + return null; + } + values.push(value); + } + const [a, b, c, d] = values; + if (a === undefined || b === undefined || c === undefined || d === undefined) { + return null; + } + return [a, b, c, d]; +} + +function isIpv4Loopback(host: string): boolean { + const octets = parseIpv4Octets(host); + return octets !== null && octets[0] === 127; +} + +function parseIpv6Side(side: string, allowIpv4Tail: boolean): number[] | null { + if (side === '') { + return []; + } + const parts = side.split(':'); + const groups: number[] = []; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + if (part === undefined) { + return null; + } + if (i === parts.length - 1 && allowIpv4Tail && part.includes('.')) { + const octets = parseIpv4Octets(part); + if (!octets) { + return null; + } + groups.push((octets[0] << 8) | octets[1], (octets[2] << 8) | octets[3]); + continue; + } + if (!/^[0-9a-f]{1,4}$/i.test(part)) { + return null; + } + groups.push(parseInt(part, 16)); + } + return groups; +} + +function parseIpv6Hextets(host: string): number[] | null { + if (!host.includes(':')) { + return null; + } + const zoneIdx = host.indexOf('%'); + const addr = zoneIdx >= 0 ? host.slice(0, zoneIdx) : host; + const halves = addr.split('::'); + if (halves.length > 2) { + return null; + } + + const firstHalf = halves[0]; + if (firstHalf === undefined) { + return null; + } + + if (halves.length === 1) { + const groups = parseIpv6Side(firstHalf, true); + return groups && groups.length === 8 ? groups : null; + } + + const secondHalf = halves[1]; + if (secondHalf === undefined) { + return null; + } + + const left = parseIpv6Side(firstHalf, false); + const right = parseIpv6Side(secondHalf, true); + if (!left || !right) { + return null; + } + const missing = 8 - left.length - right.length; + if (missing < 1) { + return null; + } + return [...left, ...Array(missing).fill(0), ...right]; +} + +function isIpv6Loopback(host: string): boolean { + const hextets = parseIpv6Hextets(host); + if (!hextets) { + return false; + } + const [h0, h1, h2, h3, h4, h5, h6, h7] = hextets; + if ( + h0 === undefined || + h1 === undefined || + h2 === undefined || + h3 === undefined || + h4 === undefined || + h5 === undefined || + h6 === undefined || + h7 === undefined + ) { + return false; + } + if (h0 === 0 && h1 === 0 && h2 === 0 && h3 === 0 && h4 === 0 && h5 === 0 && h6 === 0) { + return h7 === 0 || h7 === 1; + } + // IPv4-mapped IPv6 (::ffff:0:0/96): match 127.0.0.0/8 and 0.0.0.0 in both dotted and hex forms + if (h0 === 0 && h1 === 0 && h2 === 0 && h3 === 0 && h4 === 0 && h5 === 0xffff) { + const firstOctet = (h6 >> 8) & 0xff; + return firstOctet === 127 || (h6 === 0 && h7 === 0); + } + return false; +} + function isLoopbackHost(host?: string): boolean { if (!host) { return false; } - const normalized = host.replace(/^\[|\]$/g, '').toLowerCase(); - return LOOPBACK_HOSTS.has(normalized); + const normalized = host + .trim() + .replace(/^\[|\]$/g, '') + .replace(/\.+$/, '') + .toLowerCase(); + return ( + LOOPBACK_HOSTS.has(normalized) || + isIpv4Loopback(normalized) || + isIpv6Loopback(normalized) + ); } -function parseMongoTarget(uri?: string): { - host?: string; - port?: number; - database?: string; - username?: string; -} { - if (!uri) { - return {}; +function parseMongoHostPort( + segment: string, + defaultPort: number | undefined +): MongoTargetHost | null { + const trimmed = segment.trim(); + if (!trimmed) { + return null; } - try { - const parsed = new URL(uri); - const database = parsed.pathname.replace(/^\/+/, '').split('/')[0] || undefined; - const port = parsed.port ? Number(parsed.port) : parsed.protocol === 'mongodb:' ? 27017 : undefined; - return { - host: parsed.hostname || undefined, - port: Number.isFinite(port) ? port : undefined, - database, - username: parsed.username ? decodeURIComponent(parsed.username) : undefined, - }; - } catch { - return {}; + + if (trimmed.startsWith('[')) { + const closeIdx = trimmed.indexOf(']'); + if (closeIdx <= 1) { + return null; + } + const host = trimmed.slice(1, closeIdx).trim(); + if (!host) { + return null; + } + const after = trimmed.slice(closeIdx + 1).trim(); + if (after === '' || after === ':') { + return { host, port: defaultPort }; + } + if (!after.startsWith(':')) { + return null; + } + const portStr = after.slice(1).trim(); + if (!/^\d+$/.test(portStr)) { + return null; + } + const port = Number(portStr); + if (port < 1 || port > 65535) { + return null; + } + return { host, port }; } + + const colonIdx = trimmed.indexOf(':'); + if (colonIdx === -1) { + return { host: trimmed, port: defaultPort }; + } + if (trimmed.indexOf(':', colonIdx + 1) !== -1) { + return null; + } + + const host = trimmed.slice(0, colonIdx).trim(); + const portStr = trimmed.slice(colonIdx + 1).trim(); + if (!host) { + return null; + } + if (portStr === '') { + return { host, port: defaultPort }; + } + if (!/^\d+$/.test(portStr)) { + return null; + } + const port = Number(portStr); + if (port < 1 || port > 65535) { + return null; + } + return { host, port }; +} + +function parseMongoTarget(uri?: string): ParsedMongoTarget { + const trimmed = uri?.trim(); + if (!trimmed) { + return { hosts: [] }; + } + + const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/i.exec(trimmed); + const rawScheme = schemeMatch?.[1]; + const rest = schemeMatch?.[2]; + if (!rawScheme || rest === undefined) { + return { hosts: [] }; + } + + const scheme = rawScheme.toLowerCase(); + const defaultPort = scheme === 'mongodb' ? 27017 : undefined; + + const delimiterMatch = /[/?#]/.exec(rest); + const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest; + const remainder = delimiterMatch ? rest.slice(delimiterMatch.index) : ''; + + let database: string | undefined; + if (remainder.startsWith('/')) { + const pathPart = remainder.split(/[?#]/, 1)[0] ?? ''; + const firstSegment = pathPart.replace(/^\/+/, '').split('/')[0]; + database = firstSegment || undefined; + } + + const atIndex = authority.lastIndexOf('@'); + const userinfo = atIndex >= 0 ? authority.slice(0, atIndex) : ''; + const hostList = atIndex >= 0 ? authority.slice(atIndex + 1) : authority; + + let username: string | undefined; + if (userinfo) { + const colonIndex = userinfo.indexOf(':'); + const rawUsername = colonIndex >= 0 ? userinfo.slice(0, colonIndex) : userinfo; + if (rawUsername) { + try { + username = decodeURIComponent(rawUsername); + } catch { + username = rawUsername; + } + } + } + + const hosts: MongoTargetHost[] = []; + for (const segment of hostList.split(',')) { + const parsedHost = parseMongoHostPort(segment, defaultPort); + if (parsedHost) { + hosts.push(parsedHost); + } + } + + return { + hosts, + host: hosts[0]?.host, + database, + username, + }; } function isQaMongoTarget(uri: string | undefined): boolean { const target = parseMongoTarget(uri); - return isLoopbackHost(target.host) && target.port === 27017; + return target.hosts.some( + entry => isLoopbackHost(entry.host) && (entry.port === undefined || entry.port === 27017) + ); } function isQaPostgresTarget(pg: StockAppConfig['database']['postgres']): boolean { diff --git a/libs/core/config/src/schemas/database.schema.ts b/libs/core/config/src/schemas/database.schema.ts index 72c255d3..f68f4aa7 100644 --- a/libs/core/config/src/schemas/database.schema.ts +++ b/libs/core/config/src/schemas/database.schema.ts @@ -33,11 +33,103 @@ export const questdbConfigSchema = z.object({ .describe('Deprecated: no effect on QuestDB client/writer'), }); +function isValidMongoHostSegment(segment: string, allowPort: boolean): boolean { + if (!segment || /\s/.test(segment)) { + return false; + } + + if (segment.startsWith('[')) { + const closeIdx = segment.indexOf(']'); + if (closeIdx <= 1) { + return false; + } + const host = segment.slice(1, closeIdx); + if (!host || host.includes('[') || host.includes(']')) { + return false; + } + const after = segment.slice(closeIdx + 1); + if (after === '') { + return true; + } + if (!allowPort || !after.startsWith(':')) { + return false; + } + const portStr = after.slice(1); + if (portStr === '') { + return true; + } + if (!/^\d+$/.test(portStr)) { + return false; + } + const port = Number(portStr); + return port >= 1 && port <= 65535; + } + + const colonIdx = segment.indexOf(':'); + if (colonIdx === -1) { + return true; + } + if (!allowPort || segment.indexOf(':', colonIdx + 1) !== -1) { + return false; + } + + const host = segment.slice(0, colonIdx); + const portStr = segment.slice(colonIdx + 1); + if (!host) { + return false; + } + if (portStr === '') { + return true; + } + if (!/^\d+$/.test(portStr)) { + return false; + } + const port = Number(portStr); + return port >= 1 && port <= 65535; +} + +function isValidMongoUri(uri: string): boolean { + if (!uri || /\s/.test(uri)) { + return false; + } + + const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/i.exec(uri); + const rawScheme = schemeMatch?.[1]; + const rest = schemeMatch?.[2]; + if (!rawScheme || !rest) { + return false; + } + + const isSrv = rawScheme.toLowerCase() === 'mongodb+srv'; + const delimiterMatch = /[/?#]/.exec(rest); + const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest; + if (!authority) { + return false; + } + + const atIndex = authority.lastIndexOf('@'); + const hostList = atIndex >= 0 ? authority.slice(atIndex + 1) : authority; + if (!hostList) { + return false; + } + + const segments = hostList.split(','); + if (isSrv && segments.length !== 1) { + return false; + } + + return segments.every(segment => isValidMongoHostSegment(segment, !isSrv)); +} + +const mongodbUriSchema = z.string().refine(isValidMongoUri, { + message: 'Invalid MongoDB connection URI', +}); + // MongoDB configuration export const mongodbConfigSchema = z.object({ enabled: z.boolean().default(true), - uri: z.string().url(), // URI is required and contains all connection info - readUri: z.string().url().optional(), // Optional read-only URI (e.g. dev data-pipeline reading QA MongoDB) + uri: mongodbUriSchema, // URI is required and contains all connection info + readUri: mongodbUriSchema.optional(), // Optional read-only URI (e.g. dev data-pipeline reading QA MongoDB) readOnly: z.boolean().default(false).optional(), database: z.string(), // Database name for reference poolSize: z.number().min(1).max(100).default(10), diff --git a/libs/core/config/test/schemas.test.ts b/libs/core/config/test/schemas.test.ts index 4cee74d2..bfa6c8a9 100644 --- a/libs/core/config/test/schemas.test.ts +++ b/libs/core/config/test/schemas.test.ts @@ -584,10 +584,66 @@ describe('Config Schemas', () => { expect(config).toEqual(input); }); + it('should accept multi-host MongoDB seed lists for uri and readUri', () => { + const config = mongodbConfigSchema.parse({ + uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin', + readUri: + 'mongodb://studio_stock_bot_read:secret@localhost:27017,[::1]:27018/stock?authSource=stock', + database: 'stock_dev', + }); + expect(config.uri).toBe( + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin' + ); + expect(config.readUri).toBe( + 'mongodb://studio_stock_bot_read:secret@localhost:27017,[::1]:27018/stock?authSource=stock' + ); + }); + + it('should accept empty port spellings for mongodb:// in hostname and bracketed IPv6 forms', () => { + const hostEmptyPort = mongodbConfigSchema.parse({ + uri: 'mongodb://mongo.prod.internal:/stock', + readUri: 'mongodb://[::1]:/stock', + database: 'stock', + }); + expect(hostEmptyPort.uri).toBe('mongodb://mongo.prod.internal:/stock'); + expect(hostEmptyPort.readUri).toBe('mongodb://[::1]:/stock'); + + const seedListEmptyPort = mongodbConfigSchema.parse({ + uri: 'mongodb://u:p@mongo1.prod.internal:,[::1]:/stock', + database: 'stock', + }); + expect(seedListEmptyPort.uri).toBe('mongodb://u:p@mongo1.prod.internal:,[::1]:/stock'); + }); + it('should validate URI format', () => { + const invalidUris = [ + 'invalid-uri', + 'http://localhost:27017/stock', + 'mongodb://', + 'mongodb://u:p@', + 'mongodb://u:p@localhost:27017,', + 'mongodb://u:p@:27017/stock', + 'mongodb://u:p@localhost:0/stock', + 'mongodb://u:p@localhost:99999/stock', + 'mongodb://u:p@[::1]:0/stock', + 'mongodb://u:p@[::1]:99999/stock', + 'mongodb://u:p@localhost:abc/stock', + 'mongodb+srv://u:p@localhost:/stock', + 'mongodb+srv://u:p@localhost:27017/stock', + 'mongodb+srv://u:p@host1.example.com,host2.example.com/stock', + ]; + for (const uri of invalidUris) { + expect(() => + mongodbConfigSchema.parse({ + uri, + database: 'testdb', + }) + ).toThrow(); + } expect(() => mongodbConfigSchema.parse({ - uri: 'invalid-uri', + uri: 'mongodb://localhost:27018/stock_dev', + readUri: 'not-a-mongo-uri', database: 'testdb', }) ).toThrow(); diff --git a/libs/core/di/src/container/builder.ts b/libs/core/di/src/container/builder.ts index 4cd9b5d9..421e0342 100644 --- a/libs/core/di/src/container/builder.ts +++ b/libs/core/di/src/container/builder.ts @@ -35,15 +35,33 @@ export type ContainerRegistrar = ( ) => void; function extractMongoDatabaseFromUri(uri?: string): string | undefined { - if (!uri) { + const trimmed = uri?.trim(); + if (!trimmed) { return undefined; } - try { - const db = new URL(uri).pathname.replace(/^\/+/, '').split('/')[0]; - return db || undefined; - } catch { + + const schemeMatch = /^mongodb(?:\+srv)?:\/\/(.*)$/i.exec(trimmed); + const rest = schemeMatch?.[1]; + if (!rest) { return undefined; } + + const delimiterMatch = /[/?#]/.exec(rest); + if (!delimiterMatch || delimiterMatch[0] !== '/') { + return undefined; + } + + const pathPart = rest.slice(delimiterMatch.index).split(/[?#]/, 1)[0] ?? ''; + const rawDb = pathPart.replace(/^\/+/, '').split('/')[0]; + if (!rawDb) { + return undefined; + } + + try { + return decodeURIComponent(rawDb); + } catch { + return rawDb; + } } function getInfluxPort(config: { influxPort?: number; ilpPort?: number }): number { diff --git a/libs/core/di/test/container-builder.test.ts b/libs/core/di/test/container-builder.test.ts index e630b16a..6f72f326 100644 --- a/libs/core/di/test/container-builder.test.ts +++ b/libs/core/di/test/container-builder.test.ts @@ -120,6 +120,49 @@ describe('ServiceContainerBuilder production configuration', () => { } }); + it('extracts database from multi-host readUri when mongoReadOnly is enabled', async () => { + const config = { + ...configuration(), + database: { + ...configuration().database, + 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,localhost:27018/stock?authSource=stock', + database: 'stock_dev', + }, + }, + }; + const container = await new ServiceContainerBuilder() + .withConfig(config) + .withOptions({ + enableMongoDB: true, + mongoReadOnly: true, + enablePostgres: false, + enableQuestDB: false, + enableCache: false, + enableQueue: false, + enableBrowser: false, + enableProxy: false, + }) + .skipInitialization() + .build(); + + try { + const resolvedConfig = container.resolve('config'); + expect(resolvedConfig.mongodb.readOnly).toBe(true); + expect(resolvedConfig.mongodb.database).toBe('stock'); + + const mongo = container.resolve('mongoClient'); + expect(mongo).not.toBeNull(); + expect(mongo!.isReadOnly()).toBe(true); + expect(mongo!.getDefaultDatabase()).toBe('stock'); + } finally { + await container.dispose(); + } + }); + it('rejects invalid settings and missing required app fields with schema errors', () => { expect(() => new ServiceContainerBuilder().withConfig({ diff --git a/test/unit/environment-safety-multi-host.test.ts b/test/unit/environment-safety-multi-host.test.ts new file mode 100644 index 00000000..d9d2dd0a --- /dev/null +++ b/test/unit/environment-safety-multi-host.test.ts @@ -0,0 +1,208 @@ +import { describe, expect, test } from 'bun:test'; +import { MongoClient } from 'mongodb'; +import { ServiceContainerBuilder } from '@stock-bot/di'; +import { setLoggerConfig } from '@stock-bot/logger'; +import { assertEnvironmentSafety, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config'; + +// T-9 QA: multi-host (seed list) MongoDB URIs and the dev QA-Mongo guard. +// The installed MongoDB driver is used only as a parsing oracle (new MongoClient +// parses the URI without connecting). Nothing here opens a socket. + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); + +const DEV_MONGO_URI = 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin'; +const WRITE_ERROR = /cannot open a writable MongoDB connection to QA MongoDB/; +const PIPELINE_ERROR = /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/; + +function makeConfig(o: { + mongoUri?: string; + mongoReadUri?: string | null; + mongoReadOnly?: boolean; + mongoDatabase?: string; +} = {}): StockAppConfig { + const mongodb: Record = { + enabled: true, + uri: o.mongoUri ?? DEV_MONGO_URI, + readOnly: o.mongoReadOnly ?? false, + database: o.mongoDatabase ?? 'stock_dev', + }; + if (o.mongoReadUri !== null && o.mongoReadUri !== undefined) { + mongodb.readUri = o.mongoReadUri; + } + return 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, + 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: {}, + }); +} + +/** Independent oracle: does the real driver resolve any seed to a plain loopback :27017 address? */ +function driverSeesQaSeed(uri: string): boolean { + const client = new MongoClient(uri); + return client.options.hosts.some(h => { + const host = (h.host ?? '').toLowerCase(); + const loopback = host === 'localhost' || host === '::1' || host === '0.0.0.0' || /^127\.\d+\.\d+\.\d+$/.test(host); + return loopback && h.port === 27017; + }); +} + +describe('T-9 guard verdict matches the driver for seed lists that pass schema validation', () => { + const qaSeedLists = [ + 'mongodb://u:p@localhost:27017,localhost:27018/stock', + 'mongodb://u:p@localhost:27018,localhost:27017/stock_dev', + 'mongodb://u:p@db1.dev.internal:27018,db2.dev.internal:27018,127.0.0.1:27017/stock_dev', + 'mongodb://u:p@localhost:27018,localhost:27019,localhost/stock_dev?replicaSet=rs0', + 'mongodb://u:p@localhost:27018,0.0.0.0:27017/stock_dev', + 'mongodb://u:p@localhost:27018,localhost:027017/stock_dev', + 'mongodb://u:p,w@localhost:27018,localhost:27017/stock', + 'mongodb://localhost:27018,localhost:27017', + ]; + const safeSeedLists = [ + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin', + // localhost:27017 only inside the query string is not a seed host. + 'mongodb://u:p@localhost:27018,localhost:27019/stock_dev?appName=localhost:27017', + 'mongodb://u:p@10.0.0.51:27017,10.0.0.52:27017/stock', + ]; + + for (const uri of qaSeedLists) { + test(`blocks writable dataIngestion and non-readOnly dataPipeline on ${uri}`, () => { + expect(driverSeesQaSeed(uri)).toBe(true); + + const ingestion = makeConfig({ mongoUri: uri, mongoDatabase: 'stock' }); + expect(() => assertEnvironmentSafety(ingestion, 'dataIngestion', {})).toThrow(WRITE_ERROR); + + const pipeline = makeConfig({ mongoReadUri: uri, mongoReadOnly: false }); + expect(() => assertEnvironmentSafety(pipeline, 'dataPipeline', {})).toThrow(PIPELINE_ERROR); + }); + } + + for (const uri of safeSeedLists) { + test(`allows dev dataIngestion and dataPipeline on ${uri}`, () => { + expect(driverSeesQaSeed(uri)).toBe(false); + + const ingestion = makeConfig({ mongoUri: uri }); + expect(() => assertEnvironmentSafety(ingestion, 'dataIngestion', {})).not.toThrow(); + + const pipeline = makeConfig({ mongoReadUri: uri, mongoReadOnly: false }); + expect(() => assertEnvironmentSafety(pipeline, 'dataPipeline', {})).not.toThrow(); + }); + } +}); + +describe('T-9 guard: every non-pipeline dev service is covered for seed lists', () => { + const qaSeedList = 'mongodb://u:p@localhost:27018,localhost:27017/stock'; + + test('webApi, orchestrator and an unnamed service are blocked from writing', () => { + const cfg = makeConfig({ mongoUri: qaSeedList, mongoDatabase: 'stock' }); + expect(() => assertEnvironmentSafety(cfg, 'webApi', {})).toThrow(/"webApi"/); + expect(() => assertEnvironmentSafety(cfg, 'orchestrator', {})).toThrow(/"orchestrator"/); + expect(() => assertEnvironmentSafety(cfg, undefined, {})).toThrow(/"app"/); + }); + + test('pipeline without readUri falls back to a seed-list uri and blocks trading_admin', () => { + const cfg = makeConfig({ + mongoUri: 'mongodb://trading_admin:pw@localhost:27018,localhost:27017/stock', + mongoReadUri: null, + mongoReadOnly: true, + mongoDatabase: 'stock', + }); + expect(cfg.database.mongodb.readUri).toBeUndefined(); + expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR); + }); + + test('pipeline without readUri allows the read user on a seed-list uri in readOnly mode', () => { + const cfg = makeConfig({ + mongoUri: 'mongodb://studio_stock_bot_read:pw@localhost:27018,localhost:27017/stock', + mongoReadUri: null, + mongoReadOnly: true, + mongoDatabase: 'stock', + }); + expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow(); + }); +}); + +describe('T-9 guard: seed lists the driver accepts but the schema rejects still fail closed', () => { + // The driver tolerates empty seed entries; the guard must not treat them as a + // reason to drop the QA seed. + const driverAcceptedSchemaRejected = [ + 'mongodb://u:p@localhost:27018,,localhost:27017/stock', + 'mongodb://u:p@localhost:27018,localhost:27017,/stock', + ]; + + for (const uri of driverAcceptedSchemaRejected) { + test(`schema rejects but guard still blocks ${uri}`, () => { + expect(driverSeesQaSeed(uri)).toBe(true); + expect(() => makeConfig({ mongoUri: uri })).toThrow(/Invalid MongoDB connection URI/); + + const cfg = makeConfig(); + cfg.database.mongodb.uri = uri; + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow(WRITE_ERROR); + }); + } +}); + +describe('T-9 container: read-only database selection agrees with the driver', () => { + const cases: Array<{ readUri: string; expected: string }> = [ + { readUri: 'mongodb://r:pw@localhost:27017,localhost:27018/stock?authSource=stock', expected: 'stock' }, + { readUri: 'mongodb://r:pw@h1.internal:27017,h2.internal/stock%5Fqa?authSource=admin', expected: 'stock_qa' }, + { readUri: 'mongodb://r:pw@h1.internal,h2.internal/stock#frag', expected: 'stock' }, + // No database in the URI: the container keeps the configured database. + { readUri: 'mongodb://r:pw@h1.internal:27017,h2.internal:27018/?replicaSet=rs0', expected: 'stock_dev' }, + { readUri: 'mongodb://r:pw@h1.internal,h2.internal', expected: 'stock_dev' }, + ]; + + for (const { readUri, expected } of cases) { + test(`selects "${expected}" for ${readUri}`, async () => { + const driverDb = new MongoClient(readUri).options.dbName; + // The driver defaults to "test" when the URI has no database; the container uses config. + expect(driverDb === 'test' ? 'stock_dev' : driverDb).toBe(expected); + + const cfg = makeConfig({ mongoReadUri: readUri, mongoReadOnly: true }); + const { container, shutdown } = await new ServiceContainerBuilder() + .withConfig(cfg) + .withOptions({ + enableMongoDB: true, + mongoReadOnly: true, + enablePostgres: false, + enableQuestDB: false, + enableCache: false, + enableQueue: false, + enableBrowser: false, + enableProxy: false, + skipInitialization: true, + }) + .buildOwned(); + try { + const mongo = container.resolve('mongoClient'); + expect(mongo).not.toBeNull(); + expect(mongo!.isReadOnly()).toBe(true); + expect(mongo!.getDefaultDatabase()).toBe(expected); + } finally { + await shutdown(); + } + }); + } +}); diff --git a/test/unit/environment-safety.test.ts b/test/unit/environment-safety.test.ts index bc0bc88d..4a45a3b5 100644 --- a/test/unit/environment-safety.test.ts +++ b/test/unit/environment-safety.test.ts @@ -24,8 +24,14 @@ function makeConfig(overrides: { mongoReadOnly?: boolean; mongoDatabase?: string; dragonflyPassword?: string; + bypassSchemaValidation?: boolean; } = {}): StockAppConfig { - return stockAppSchema.parse({ + 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', @@ -50,12 +56,12 @@ function makeConfig(overrides: { }, mongodb: { enabled: true, - uri: - overrides.mongoUri ?? - 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin', - readUri: - overrides.mongoReadUri ?? - 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock', + uri: overrides.bypassSchemaValidation + ? defaultMongoUri + : (overrides.mongoUri ?? defaultMongoUri), + readUri: overrides.bypassSchemaValidation + ? defaultMongoReadUri + : (overrides.mongoReadUri ?? defaultMongoReadUri), readOnly: overrides.mongoReadOnly ?? false, database: overrides.mongoDatabase ?? 'stock_dev', }, @@ -81,6 +87,17 @@ function makeConfig(overrides: { }, 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; } describe('Environment safety & multi-env isolation', () => { @@ -247,6 +264,261 @@ describe('Environment safety & multi-env isolation', () => { ); }); + test('blocks multi-host MongoDB seed lists targeting QA loopback :27017 for dataIngestion and dataPipeline', () => { + const qaFirstIngestion = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://u:p@localhost:27017,localhost:27018/stock', + mongoDatabase: 'stock', + }); + expect(() => assertEnvironmentSafety(qaFirstIngestion, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + expect(() => + assertEnvironmentSafety(qaFirstIngestion, 'dataIngestion', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).not.toThrow(); + + const qaSecondIngestion = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://u:p@localhost:27018,localhost:27017/stock_dev', + mongoDatabase: 'stock_dev', + }); + expect(() => assertEnvironmentSafety(qaSecondIngestion, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + expect(() => + assertEnvironmentSafety(qaSecondIngestion, 'dataIngestion', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).not.toThrow(); + + const qaPipelineNonReadOnly = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27018,localhost:27017/stock_dev', + mongoReadOnly: false, + }); + expect(() => assertEnvironmentSafety(qaPipelineNonReadOnly, 'dataPipeline', {})).toThrow( + /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ + ); + + const qaPipelineFallbackUri = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://studio_stock_bot_read:secret@localhost:27018,localhost:27017/stock', + mongoReadOnly: false, + }); + qaPipelineFallbackUri.database.mongodb.readUri = undefined; + expect(() => assertEnvironmentSafety(qaPipelineFallbackUri, 'dataPipeline', {})).toThrow( + /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ + ); + + const qaPipelineAdmin = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://trading_admin:pass@localhost:27017,localhost:27018/stock', + mongoReadOnly: true, + }); + expect(() => + assertEnvironmentSafety(qaPipelineAdmin, 'dataPipeline', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/); + + const qaPipelineEncodedAdmin = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://trading%5Fadmin:pass@localhost:27018,localhost:27017/stock', + mongoReadOnly: true, + }); + expect(() => + assertEnvironmentSafety(qaPipelineEncodedAdmin, 'dataPipeline', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/); + + const qaPipelineReadOnlyAllowed = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock', + mongoReadOnly: true, + }); + expect(() => assertEnvironmentSafety(qaPipelineReadOnlyAllowed, 'dataPipeline', {})).not.toThrow(); + }); + + test('blocks omitted port, loopback variants, and mongodb+srv loopback URIs', () => { + const qaLoopbackUris = [ + 'mongodb://u:p@localhost:27018,localhost/stock_dev', + 'mongodb://u:p@localhost:27018,127.0.0.1/stock_dev', + 'mongodb://u:p@localhost:27018,[::1]:27017/stock_dev', + 'mongodb://u:p@localhost:27018,[::1]/stock_dev', + 'mongodb://u:p@[0:0:0:0:0:0:0:0001]:27017/stock', + 'mongodb://u:p@[::ffff:7f00:1]:27017/stock', + 'mongodb://u:p@[::ffff:7f00:0001]/stock', + 'mongodb://u:p@[::ffff:7f01:0203]:27017/stock', + 'mongodb://u:p@[0:0:0:0:0:ffff:7f00:1]:27017/stock', + 'mongodb://u:p@[::ffff:127.0.0.2]:27017/stock', + 'mongodb://u:p@localhost:27018,LOCALHOST.:27017/stock_dev', + 'mongodb://u:p@127.0.0.2:27017/stock_dev', + 'mongodb+srv://u:p@localhost/stock', + ]; + + for (const mongoUri of qaLoopbackUris) { + const cfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock_dev', + }); + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + } + + // Non-loopback IPv4-mapped IPv6 addresses must not false-positive as QA loopback + const nonLoopbackMappedCfg = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://u:p@[::ffff:0a00:1]:27017/stock_dev', + mongoDatabase: 'stock_dev', + }); + expect(() => assertEnvironmentSafety(nonLoopbackMappedCfg, 'dataIngestion', {})).not.toThrow(); + }); + + test('handles multi-host MongoDB URI parsing edge cases without failing open', () => { + const unencodedAtPipeline = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock', + mongoReadOnly: true, + }); + expect(() => assertEnvironmentSafety(unencodedAtPipeline, 'dataPipeline', {})).toThrow( + /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ + ); + + const edgeCaseUris = [ + { uri: 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock', malformed: false }, + { uri: 'mongodb://localhost:27017,localhost:27018/stock', malformed: false }, + { uri: 'mongodb://u:p@localhost:/stock', malformed: false }, + { uri: 'mongodb://u:p@[::1]:/stock', malformed: false }, + { uri: 'mongodb://u:p@bad:port,localhost:27017/stock', malformed: true }, + ]; + + for (const { uri: mongoUri, malformed } of edgeCaseUris) { + const cfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock', + bypassSchemaValidation: malformed, + }); + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + } + }); + + test('allows non-QA multi-host dev seed lists and validates production multi-host URIs', () => { + const devMultiHostUri = + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin'; + + const devIngestion = makeConfig({ + environment: 'development', + mongoUri: devMultiHostUri, + mongoDatabase: 'stock_dev', + }); + expect(() => assertEnvironmentSafety(devIngestion, 'dataIngestion', {})).not.toThrow(); + + const devPipeline = makeConfig({ + environment: 'development', + mongoUri: devMultiHostUri, + mongoReadUri: devMultiHostUri, + mongoReadOnly: false, + mongoDatabase: 'stock_dev', + }); + expect(() => assertEnvironmentSafety(devPipeline, 'dataPipeline', {})).not.toThrow(); + + const prodMultiHostSafe = makeConfig({ + environment: 'production', + pgHost: 'pg.prod.internal', + pgDatabase: 'trading_bot_prod', + pgPassword: 'super-strong-prod-password', + mongoUri: 'mongodb://prod:strongpass@mongo1.prod.internal:27017,mongo2.prod.internal:27017/stock', + }); + expect(() => assertEnvironmentSafety(prodMultiHostSafe, 'webApi', {})).not.toThrow(); + + const prodMultiHostDevSecret = makeConfig({ + environment: 'production', + pgHost: 'pg.prod.internal', + pgDatabase: 'trading_bot_prod', + pgPassword: 'super-strong-prod-password', + mongoUri: 'mongodb://prod:trading_mongo_dev@mongo1.prod.internal:27017,mongo2.prod.internal:27017/stock', + }); + expect(() => assertEnvironmentSafety(prodMultiHostDevSecret, 'webApi', {})).toThrow( + /production MongoDB \(mongo1\.prod\.internal\) cannot use a default dev\/qa credential/ + ); + }); + + test('initializeStockConfig validates and guards multi-host MongoDB seed lists end-to-end', () => { + const envKeys = [ + 'NODE_ENV', + 'POSTGRES_HOST', + 'POSTGRES_PORT', + 'POSTGRES_DB', + 'POSTGRES_USER', + 'POSTGRES_PASSWORD', + 'MONGODB_URI', + 'MONGODB_READ_URI', + 'MONGODB_DATABASE', + 'HTTP_PROXY', + 'HTTPS_PROXY', + 'http_proxy', + 'https_proxy', + ] as const; + const savedEnv: Partial> = {}; + for (const key of envKeys) { + savedEnv[key] = process.env[key]; + } + + try { + process.env.NODE_ENV = 'development'; + process.env.POSTGRES_HOST = 'localhost'; + process.env.POSTGRES_PORT = '5433'; + process.env.POSTGRES_DB = 'trading_bot_dev'; + process.env.POSTGRES_USER = 'dev_user'; + process.env.POSTGRES_PASSWORD = 'dev_pass'; + process.env.MONGODB_URI = + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin'; + process.env.MONGODB_READ_URI = + 'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock'; + process.env.MONGODB_DATABASE = 'stock_dev'; + delete process.env.HTTP_PROXY; + delete process.env.HTTPS_PROXY; + delete process.env.http_proxy; + delete process.env.https_proxy; + + // Approved dev seed list passes schema validation and guard for dataIngestion + resetStockConfig(); + const ingestionCfg = initializeStockConfig('dataIngestion'); + expect(ingestionCfg.database.mongodb.uri).toBe(process.env.MONGODB_URI); + + // Approved QA read-only seed list passes schema validation and guard for dataPipeline + resetStockConfig(); + const pipelineCfg = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); + expect(pipelineCfg.database.mongodb.readUri).toBe(process.env.MONGODB_READ_URI); + expect(pipelineCfg.database.mongodb.readOnly).toBe(true); + + // Guarded QA seed list passes schema validation and is blocked by the safety guard + process.env.MONGODB_URI = + 'mongodb://trading_admin:trading_mongo_dev@[::ffff:7f00:1]:27017/stock?authSource=admin'; + resetStockConfig(); + expect(() => initializeStockConfig('dataIngestion')).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + } finally { + for (const key of envKeys) { + if (savedEnv[key] === undefined) { + delete process.env[key]; + } else { + process.env[key] = savedEnv[key]; + } + } + resetStockConfig(); + } + }); + test('blocks qa environment from targeting *_dev databases', () => { const cfg = makeConfig({ environment: 'qa', @@ -397,4 +669,38 @@ describe('MongoDBClient read-only enforcement', () => { await shutdown(); } }); + + test('ServiceContainerBuilder extracts database from multi-host readUri when mongoReadOnly=true', async () => { + const cfg = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin', + mongoReadUri: + 'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock', + mongoDatabase: 'stock_dev', + mongoReadOnly: true, + }); + const { container, shutdown } = await new ServiceContainerBuilder() + .withConfig(cfg) + .withOptions({ + enableMongoDB: true, + mongoReadOnly: true, + enablePostgres: false, + enableQuestDB: false, + enableCache: false, + enableQueue: false, + enableBrowser: false, + enableProxy: false, + skipInitialization: true, + }) + .buildOwned(); + + try { + const mongo = container.resolve('mongoClient'); + expect(mongo).not.toBeNull(); + expect(mongo!.isReadOnly()).toBe(true); + expect(mongo!.getDefaultDatabase()).toBe('stock'); + } finally { + await shutdown(); + } + }); });