diff --git a/apps/stock/config/src/env-safety.ts b/apps/stock/config/src/env-safety.ts index 66df53ec..fda0dad9 100644 --- a/apps/stock/config/src/env-safety.ts +++ b/apps/stock/config/src/env-safety.ts @@ -14,13 +14,7 @@ interface ParsedMongoTarget { username?: string; } -const LOOPBACK_HOSTS = new Set([ - 'localhost', - '0.0.0.0', - '::1', - '0:0:0:0:0:0:0:1', - '::ffff:127.0.0.1', -]); +const LOOPBACK_HOSTS = new Set(['localhost', '0.0.0.0']); const FORBIDDEN_PROD_SECRETS = new Set([ 'trading_pass_dev', 'trading_mongo_dev', @@ -30,18 +24,126 @@ const FORBIDDEN_PROD_SECRETS = new Set([ 'admin123', ]); -function isIpv4Loopback(host: string): boolean { +function parseIpv4Octets(host: string): [number, number, number, number] | null { const octets = host.split('.'); - if (octets.length !== 4 || octets[0] !== '127') { - return false; + if (octets.length !== 4) { + return null; } - return octets.every(part => { + const values: number[] = []; + for (const part of octets) { if (!/^\d{1,3}$/.test(part)) { - return false; + return null; } const value = Number(part); - return value >= 0 && value <= 255; - }); + 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 { @@ -53,10 +155,11 @@ function isLoopbackHost(host?: string): boolean { .replace(/^\[|\]$/g, '') .replace(/\.+$/, '') .toLowerCase(); - if (LOOPBACK_HOSTS.has(normalized) || isIpv4Loopback(normalized)) { - return true; - } - return normalized.startsWith('::ffff:') && isIpv4Loopback(normalized.slice(7)); + return ( + LOOPBACK_HOSTS.has(normalized) || + isIpv4Loopback(normalized) || + isIpv6Loopback(normalized) + ); } function parseMongoHostPort( diff --git a/libs/core/config/src/schemas/database.schema.ts b/libs/core/config/src/schemas/database.schema.ts index 72c255d3..c9f08c8c 100644 --- a/libs/core/config/src/schemas/database.schema.ts +++ b/libs/core/config/src/schemas/database.schema.ts @@ -33,11 +33,94 @@ 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 (!/^\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 || !/^\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..01568b95 100644 --- a/libs/core/config/test/schemas.test.ts +++ b/libs/core/config/test/schemas.test.ts @@ -584,10 +584,44 @@ 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 validate URI format', () => { + const invalidUris = [ + 'invalid-uri', + 'http://localhost:27017/stock', + 'mongodb://', + 'mongodb://u:p@', + 'mongodb://u:p@localhost:27017,', + 'mongodb://u:p@localhost:99999/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/test/unit/environment-safety.test.ts b/test/unit/environment-safety.test.ts index 84e057a7..ab3b7948 100644 --- a/test/unit/environment-safety.test.ts +++ b/test/unit/environment-safety.test.ts @@ -24,7 +24,13 @@ function makeConfig(overrides: { mongoReadOnly?: boolean; mongoDatabase?: string; dragonflyPassword?: 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', @@ -50,8 +56,12 @@ function makeConfig(overrides: { }, 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', + uri: overrides.bypassSchemaValidation + ? defaultMongoUri + : (overrides.mongoUri ?? defaultMongoUri), + readUri: overrides.bypassSchemaValidation + ? defaultMongoReadUri + : (overrides.mongoReadUri ?? defaultMongoReadUri), readOnly: overrides.mongoReadOnly ?? false, database: overrides.mongoDatabase ?? 'stock_dev', }, @@ -78,11 +88,13 @@ function makeConfig(overrides: { features: {}, }); - if (overrides.mongoUri !== undefined) { - parsed.database.mongodb.uri = overrides.mongoUri; - } - if (overrides.mongoReadUri !== undefined) { - parsed.database.mongodb.readUri = overrides.mongoReadUri; + 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; @@ -336,6 +348,12 @@ describe('Environment safety & multi-env isolation', () => { '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', @@ -351,6 +369,14 @@ describe('Environment safety & multi-env isolation', () => { /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', () => { @@ -364,17 +390,18 @@ describe('Environment safety & multi-env isolation', () => { ); const edgeCaseUris = [ - 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock', - 'mongodb://u:p@localhost:/stock', - 'mongodb://localhost:27017,localhost:27018/stock', - 'mongodb://u:p@bad:port,localhost:27017/stock', + { 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: true }, + { uri: 'mongodb://u:p@bad:port,localhost:27017/stock', malformed: true }, ]; - for (const mongoUri of edgeCaseUris) { + 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/ @@ -423,6 +450,74 @@ describe('Environment safety & multi-env isolation', () => { ); }); + 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',