From 220651568117ffda550e85b4fd322e7bc63e2693 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 13:32:01 -0500 Subject: [PATCH] T-28: Dev QA-Mongo guard bypass: raw '#' or a second '@' in the host list (guard and driver split the URI authority differently) --- apps/stock/config/src/env-safety.ts | 75 ++++++-- .../config/src/schemas/database.schema.ts | 30 ++- libs/core/config/test/schemas.test.ts | 37 ++++ test/unit/environment-safety.test.ts | 182 +++++++++++++++++- 4 files changed, 300 insertions(+), 24 deletions(-) diff --git a/apps/stock/config/src/env-safety.ts b/apps/stock/config/src/env-safety.ts index 740e1395..e70fd1c9 100644 --- a/apps/stock/config/src/env-safety.ts +++ b/apps/stock/config/src/env-safety.ts @@ -296,25 +296,52 @@ function parseMongoHostPort( return { host, port }; } +function hasAsciiControlChar(value: string): boolean { + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if (code <= 0x1f || code === 0x7f) { + return true; + } + } + return false; +} + function parseMongoTarget(uri?: string): ParsedMongoTarget { - const trimmed = uri?.trim(); - if (!trimmed) { - return { hosts: [] }; + if (!uri) { + throw new Error('Safety guard: MongoDB URI is missing or empty.'); + } + if (hasAsciiControlChar(uri)) { + throw new Error( + 'Safety guard: MongoDB URI contains forbidden whitespace or control characters.' + ); + } + const trimmed = uri.trim(); + if (!trimmed || /\s/.test(trimmed)) { + throw new Error('Safety guard: MongoDB URI is empty or contains forbidden whitespace.'); } - const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/i.exec(trimmed); + const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/is.exec(trimmed); const rawScheme = schemeMatch?.[1]; const rest = schemeMatch?.[2]; if (!rawScheme || rest === undefined) { - return { hosts: [] }; + throw new Error('Safety guard: MongoDB URI must use the mongodb:// or mongodb+srv:// scheme.'); } const scheme = rawScheme.toLowerCase(); const defaultPort = scheme === 'mongodb' ? 27017 : undefined; - const delimiterMatch = /[/?#]/.exec(rest); + // Match mongodb-connection-string-url: authority ends at '/' or '?', never '#' + const delimiterMatch = /[/?]/.exec(rest); const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest; const remainder = delimiterMatch ? rest.slice(delimiterMatch.index) : ''; + if (!authority) { + throw new Error('Safety guard: MongoDB URI authority is empty.'); + } + if (authority.includes('#')) { + throw new Error( + 'Safety guard: MongoDB URI authority cannot contain an unencoded "#" character.' + ); + } let database: string | undefined; if (remainder.startsWith('/')) { @@ -323,9 +350,21 @@ function parseMongoTarget(uri?: string): ParsedMongoTarget { database = firstSegment || undefined; } - const atIndex = authority.lastIndexOf('@'); - const userinfo = atIndex >= 0 ? authority.slice(0, atIndex) : ''; - const hostList = atIndex >= 0 ? authority.slice(atIndex + 1) : authority; + const firstAtIndex = authority.indexOf('@'); + if (firstAtIndex === 0) { + throw new Error('Safety guard: MongoDB URI authority cannot have empty userinfo before "@".'); + } + if (firstAtIndex !== -1 && authority.indexOf('@', firstAtIndex + 1) !== -1) { + throw new Error( + 'Safety guard: MongoDB URI authority cannot contain multiple unencoded "@" characters.' + ); + } + + const userinfo = firstAtIndex >= 0 ? authority.slice(0, firstAtIndex) : ''; + const hostList = firstAtIndex >= 0 ? authority.slice(firstAtIndex + 1) : authority; + if (!hostList) { + throw new Error('Safety guard: MongoDB URI host list is empty.'); + } let username: string | undefined; if (userinfo) { @@ -347,6 +386,9 @@ function parseMongoTarget(uri?: string): ParsedMongoTarget { hosts.push(parsedHost); } } + if (hosts.length === 0) { + throw new Error('Safety guard: MongoDB URI did not contain any valid host.'); + } return { hosts, @@ -356,13 +398,16 @@ function parseMongoTarget(uri?: string): ParsedMongoTarget { }; } -function isQaMongoTarget(uri: string | undefined): boolean { - const target = parseMongoTarget(uri); +function isQaMongoTargetHosts(target: ParsedMongoTarget): boolean { return target.hosts.some( entry => isLoopbackHost(entry.host) && (entry.port === undefined || entry.port === 27017) ); } +function isQaMongoTarget(uri: string | undefined): boolean { + return isQaMongoTargetHosts(parseMongoTarget(uri)); +} + function isQaPostgresTarget(pg: StockAppConfig['database']['postgres']): boolean { return isLoopbackHost(pg.host) && pg.port === 5432 && pg.database === 'trading_bot'; } @@ -401,7 +446,7 @@ export function assertEnvironmentSafety( const effectiveUri = mongo.readUri ?? mongo.uri; const readTarget = parseMongoTarget(effectiveUri); if ( - isQaMongoTarget(effectiveUri) && + isQaMongoTargetHosts(readTarget) && (mongo.readOnly !== true || readTarget.username === 'trading_admin') ) { throw new Error( @@ -447,7 +492,9 @@ export function assertEnvironmentSafety( if (FORBIDDEN_PROD_SECRETS.has(config.database.postgres.password)) { throw new Error('Safety guard: production PostgreSQL password cannot use a default dev/qa credential.'); } - const mongoTarget = parseMongoTarget(config.database.mongodb.uri); + const mongoTarget = config.database.mongodb.enabled + ? parseMongoTarget(config.database.mongodb.uri) + : undefined; const mongoUriHasDevPass = Array.from(FORBIDDEN_PROD_SECRETS).some(secret => config.database.mongodb.uri.includes(`:${secret}@`) ); @@ -456,7 +503,7 @@ export function assertEnvironmentSafety( (config.database.mongodb.password && FORBIDDEN_PROD_SECRETS.has(config.database.mongodb.password)) ) { throw new Error( - `Safety guard: production MongoDB (${mongoTarget.host ?? 'configured URI'}) cannot use a default dev/qa credential.` + `Safety guard: production MongoDB (${mongoTarget?.host ?? 'configured URI'}) cannot use a default dev/qa credential.` ); } if ( diff --git a/libs/core/config/src/schemas/database.schema.ts b/libs/core/config/src/schemas/database.schema.ts index f68f4aa7..db0d199c 100644 --- a/libs/core/config/src/schemas/database.schema.ts +++ b/libs/core/config/src/schemas/database.schema.ts @@ -88,12 +88,22 @@ function isValidMongoHostSegment(segment: string, allowPort: boolean): boolean { return port >= 1 && port <= 65535; } +function hasControlOrWhitespace(value: string): boolean { + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if (code <= 0x20 || code === 0x7f) { + return true; + } + } + return /\s/.test(value); +} + function isValidMongoUri(uri: string): boolean { - if (!uri || /\s/.test(uri)) { + if (!uri || hasControlOrWhitespace(uri)) { return false; } - const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/i.exec(uri); + const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/is.exec(uri); const rawScheme = schemeMatch?.[1]; const rest = schemeMatch?.[2]; if (!rawScheme || !rest) { @@ -101,14 +111,22 @@ function isValidMongoUri(uri: string): boolean { } const isSrv = rawScheme.toLowerCase() === 'mongodb+srv'; - const delimiterMatch = /[/?#]/.exec(rest); + // Match mongodb-connection-string-url: authority ends at '/' or '?', never '#' + const delimiterMatch = /[/?]/.exec(rest); const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest; - if (!authority) { + if (!authority || authority.includes('#')) { return false; } - const atIndex = authority.lastIndexOf('@'); - const hostList = atIndex >= 0 ? authority.slice(atIndex + 1) : authority; + const firstAtIndex = authority.indexOf('@'); + if (firstAtIndex === 0) { + return false; + } + if (firstAtIndex !== -1 && authority.indexOf('@', firstAtIndex + 1) !== -1) { + return false; + } + + const hostList = firstAtIndex >= 0 ? authority.slice(firstAtIndex + 1) : authority; if (!hostList) { return false; } diff --git a/libs/core/config/test/schemas.test.ts b/libs/core/config/test/schemas.test.ts index bfa6c8a9..fe492668 100644 --- a/libs/core/config/test/schemas.test.ts +++ b/libs/core/config/test/schemas.test.ts @@ -615,12 +615,31 @@ describe('Config Schemas', () => { expect(seedListEmptyPort.uri).toBe('mongodb://u:p@mongo1.prod.internal:,[::1]:/stock'); }); + it('should accept percent-encoded @ in credentials, passwordless user, and @/# after / or ?', () => { + const validUris = [ + 'mongodb://dev_admin:p%40ss@localhost:27018/stock_dev', + 'mongodb://dev_admin:p%40ss@localhost:27018/stock_dev?appName=a@b#note', + 'mongodb://localhost:27018?authSource=admin#frag', + 'mongodb://dev_user@localhost:27018/stock_dev', + ]; + for (const uri of validUris) { + const config = mongodbConfigSchema.parse({ + uri, + readUri: uri, + database: 'stock_dev', + }); + expect(config.uri).toBe(uri); + expect(config.readUri).toBe(uri); + } + }); + it('should validate URI format', () => { const invalidUris = [ 'invalid-uri', 'http://localhost:27017/stock', 'mongodb://', 'mongodb://u:p@', + 'mongodb://@localhost:27018/stock', 'mongodb://u:p@localhost:27017,', 'mongodb://u:p@:27017/stock', 'mongodb://u:p@localhost:0/stock', @@ -628,9 +647,20 @@ describe('Config Schemas', () => { 'mongodb://u:p@[::1]:0/stock', 'mongodb://u:p@[::1]:99999/stock', 'mongodb://u:p@localhost:abc/stock', + 'mongodb://localhost:27018#,localhost/stock', + 'mongodb://localhost:27018#frag', + 'mongodb://u:p@localhost:27018#x,127.0.0.1/stock', + 'mongodb://u:p@localhost:27017@x:27018/stock', + 'mongodb://trading_admin:p@ss@localhost:27018/stock_dev', + 'mongodb://u:p@local\nhost:27017/stock', + 'mongodb://u:p@local\thost:27017/stock', + 'mongodb://u:p@localhost:27018/stock\x00', + 'mongodb://u:p@localhost:27018/stock?a=1\rb=2', 'mongodb+srv://u:p@localhost:/stock', 'mongodb+srv://u:p@localhost:27017/stock', 'mongodb+srv://u:p@host1.example.com,host2.example.com/stock', + 'mongodb+srv://u:p@cluster.example.com#x/stock', + 'mongodb+srv://u:p@cluster.example.com@other.example.com/stock', ]; for (const uri of invalidUris) { expect(() => @@ -639,6 +669,13 @@ describe('Config Schemas', () => { database: 'testdb', }) ).toThrow(); + expect(() => + mongodbConfigSchema.parse({ + uri: 'mongodb://localhost:27018/stock_dev', + readUri: uri, + database: 'testdb', + }) + ).toThrow(); } expect(() => mongodbConfigSchema.parse({ diff --git a/test/unit/environment-safety.test.ts b/test/unit/environment-safety.test.ts index 4a45a3b5..134166f3 100644 --- a/test/unit/environment-safety.test.ts +++ b/test/unit/environment-safety.test.ts @@ -10,6 +10,8 @@ import { stockAppSchema, type StockAppConfig, } from '@stock-bot/stock-config'; +import { MongoClient } from 'mongodb'; +import { ServerDescription } from 'mongodb/lib/sdam/server_description'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); @@ -380,17 +382,46 @@ describe('Environment safety & multi-env isolation', () => { }); test('handles multi-host MongoDB URI parsing edge cases without failing open', () => { - const unencodedAtPipeline = makeConfig({ + const encodedAtPipeline = makeConfig({ environment: 'development', - mongoReadUri: 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock', + mongoReadUri: 'mongodb://trading_admin:p%40ss@localhost:27018,localhost:27017/stock', mongoReadOnly: true, }); - expect(() => assertEnvironmentSafety(unencodedAtPipeline, 'dataPipeline', {})).toThrow( + expect(() => assertEnvironmentSafety(encodedAtPipeline, 'dataPipeline', {})).toThrow( /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ ); + const unencodedDoubleAtUri = + 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock'; + expect(() => + makeConfig({ environment: 'development', mongoUri: unencodedDoubleAtUri }) + ).toThrow(); + expect(() => + makeConfig({ environment: 'development', mongoReadUri: unencodedDoubleAtUri }) + ).toThrow(); + + const unencodedAtIngestion = makeConfig({ + environment: 'development', + mongoUri: unencodedDoubleAtUri, + mongoDatabase: 'stock', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(unencodedAtIngestion, 'dataIngestion', {})).toThrow( + /Safety guard:/ + ); + + const unencodedAtPipeline = makeConfig({ + environment: 'development', + mongoReadUri: unencodedDoubleAtUri, + mongoReadOnly: true, + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(unencodedAtPipeline, 'dataPipeline', {})).toThrow( + /Safety guard:/ + ); + const edgeCaseUris = [ - { uri: 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock', malformed: false }, + { uri: 'mongodb://trading_admin:p%40ss@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 }, @@ -410,6 +441,149 @@ describe('Environment safety & multi-env isolation', () => { } }); + test('blocks T-28 raw #, second @, and control-char authority splits matching MongoClient + ServerDescription', () => { + const bypassUris = [ + 'mongodb://localhost:27018#,localhost/stock', + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018#,localhost:27017/stock_dev?authSource=admin', + 'mongodb://u:p@localhost:27018#x,127.0.0.1/stock', + 'mongodb://u:p@localhost:27017@x:27018/stock', + 'mongodb://localhost#x:27018/stock', + 'mongodb://u@localhost:27017@x:27018/stock', + 'mongodb://u:p@local\nhost:27017/stock', + 'mongodb://u:p@local\thost:27017/stock', + ]; + + for (const uri of bypassUris) { + // Offline driver parity: verify the real MongoDB driver resolves a loopback :27017 host + const client = new MongoClient(uri); + const resolvedHosts = client.options.hosts.map( + host => new ServerDescription(host).hostAddress + ); + const dialsQaLoopback = resolvedHosts.some( + addr => + (addr.host === 'localhost' || addr.host === '127.0.0.1') && addr.port === 27017 + ); + expect(dialsQaLoopback).toBe(true); + + // Schema must reject the URI on both uri and readUri + expect(() => + makeConfig({ environment: 'development', mongoUri: uri }) + ).toThrow(); + expect(() => + makeConfig({ environment: 'development', mongoReadUri: uri }) + ).toThrow(); + + // Guard must fail closed even when schema validation is bypassed + const ingestionCfg = makeConfig({ + environment: 'development', + mongoUri: uri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( + /Safety guard:/ + ); + + for (const mongoReadOnly of [true, false]) { + const pipelineCfg = makeConfig({ + environment: 'development', + mongoReadUri: uri, + mongoReadOnly, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow( + /Safety guard:/ + ); + } + } + }); + + test('fails closed on zero-host, empty/non-mongo, control-char, and malformed mongodb/mongodb+srv URIs', () => { + const failClosedUris = [ + 'mongodb:///stock', + 'mongodb://u:p@/stock', + 'mongodb://u:p@bad:port/stock', + 'mongodb://,/stock', + 'mongodb+srv:///stock', + '', + ' ', + 'http://localhost:27017/stock', + 'mongodb://@localhost:27018/stock', + 'mongodb://u:p@localhost:27017/stock?a=1\nb=2', + 'mongodb://u:p@localhost:27018/stock\x00', + 'mongodb://u:p@localhost:27018/stock\r\n', + 'mongodb://localhost:27018#frag', + 'mongodb+srv://u:p@cluster.example.com#x/stock', + 'mongodb+srv://u:p@cluster.example.com@other.example.com/stock', + ]; + + for (const uri of failClosedUris) { + expect(() => + makeConfig({ environment: 'development', mongoUri: uri }) + ).toThrow(); + + const ingestionCfg = makeConfig({ + environment: 'development', + mongoUri: uri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( + /Safety guard:/ + ); + + const pipelineCfg = makeConfig({ + environment: 'development', + mongoReadUri: uri, + mongoReadOnly: true, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow( + /Safety guard:/ + ); + } + }); + + test('allows valid URIs with %40 in credentials, @/# after / or ?, passwordless user, srv prod, and disabled mongo', () => { + const allowedDevUris = [ + 'mongodb://dev_admin:p%40ss@localhost:27018/stock_dev', + 'mongodb://dev_admin:p%40ss@localhost:27018/stock_dev?appName=a@b#note', + 'mongodb://localhost:27018?authSource=admin#frag', + 'mongodb://dev_user@localhost:27018/stock_dev', + ]; + + for (const mongoUri of allowedDevUris) { + const cfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock_dev', + }); + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow(); + } + + const prodSrvCfg = makeConfig({ + environment: 'production', + pgHost: 'pg.prod.internal', + pgDatabase: 'trading_bot_prod', + pgPassword: 'super-strong-prod-password', + mongoUri: 'mongodb+srv://prod:strongpass@cluster.prod.internal/stock?appName=a@b#note', + }); + expect(() => assertEnvironmentSafety(prodSrvCfg, 'webApi', {})).not.toThrow(); + + // Disabled MongoDB (postgresOnly using mongodb://disabled) remains valid in dev and prod + const prodDisabledMongo = makeConfig({ + environment: 'production', + pgHost: 'pg.prod.internal', + pgDatabase: 'trading_bot_prod', + pgPassword: 'super-strong-prod-password', + mongoUri: 'mongodb://disabled', + }); + prodDisabledMongo.database.mongodb.enabled = false; + expect(() => assertEnvironmentSafety(prodDisabledMongo, 'webApi', {})).not.toThrow(); + }); + 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';