diff --git a/apps/stock/config/src/env-safety.ts b/apps/stock/config/src/env-safety.ts index b8002cc8..740e1395 100644 --- a/apps/stock/config/src/env-safety.ts +++ b/apps/stock/config/src/env-safety.ts @@ -163,6 +163,22 @@ function isLoopbackHost(host?: string): boolean { } const MAX_MONGO_HOST_DECODE_PASSES = 8; +const VALID_IPV6_ZONE_ID = /^[a-z0-9._~-]+$/i; +// Any URL authority/path/query/fragment delimiter, whitespace, or control char inside a +// decoded MongoDB seed host would be re-interpreted by ServerDescription.hostAddress's +// WHATWG URL re-parse (e.g., "localhost%2f:27018" -> "localhost/:27018" -> localhost:27017). +const FORBIDDEN_MONGO_HOST_CHARS = /[/?#@:\\[\],\s\x00-\x1f\x7f]/; +const FORBIDDEN_MONGO_IPV6_HOST_CHARS = /[/?#@\\[\],\s\x00-\x1f\x7f]/; + +function isValidIpv6WithZoneId(host: string): boolean { + const zoneIdx = host.indexOf('%'); + if (zoneIdx <= 0 || host.indexOf('%', zoneIdx + 1) !== -1) { + return false; + } + const addr = host.slice(0, zoneIdx); + const zone = host.slice(zoneIdx + 1); + return parseIpv6Hextets(addr) !== null && VALID_IPV6_ZONE_ID.test(zone); +} function decodeMongoHost(rawHost: string, isBracketedIpv6 = false): string { // MongoDB driver 6.22.0 decodes seed hostnames once in HostAddress.fromString during @@ -176,9 +192,10 @@ function decodeMongoHost(rawHost: string, isBracketedIpv6 = false): string { decoded = decodeURIComponent(current); } catch (error) { if (error instanceof URIError) { - // After the first decode of a bracketed IPv6 literal, a literal '%' marks - // an IPv6 zone ID (e.g., "::1%25lo" -> "::1%lo") rather than another escape. - if (isBracketedIpv6 && pass > 0) { + // After the first decode of a bracketed IPv6 literal, a literal '%' is allowed + // only when it separates a valid IPv6 address from a valid zone identifier + // (e.g., "::1%25lo" -> "::1%lo"). + if (isBracketedIpv6 && pass > 0 && isValidIpv6WithZoneId(current)) { break; } throw new Error(`Safety guard: invalid percent-encoding in MongoDB host "${rawHost}".`); @@ -189,10 +206,19 @@ function decodeMongoHost(rawHost: string, isBracketedIpv6 = false): string { break; } current = decoded; + if (isBracketedIpv6 && isValidIpv6WithZoneId(current)) { + break; + } } - if (!isBracketedIpv6 && current.includes('%')) { + if (current.includes('%') && !(isBracketedIpv6 && isValidIpv6WithZoneId(current))) { throw new Error(`Safety guard: invalid percent-encoding in MongoDB host "${rawHost}".`); } + const forbiddenChars = isBracketedIpv6 + ? FORBIDDEN_MONGO_IPV6_HOST_CHARS + : FORBIDDEN_MONGO_HOST_CHARS; + if (forbiddenChars.test(current)) { + throw new Error(`Safety guard: invalid characters in MongoDB host "${rawHost}".`); + } return current.toLowerCase(); } diff --git a/test/unit/environment-safety-encoded-host.test.ts b/test/unit/environment-safety-encoded-host.test.ts index a7db34e8..a9e61408 100644 --- a/test/unit/environment-safety-encoded-host.test.ts +++ b/test/unit/environment-safety-encoded-host.test.ts @@ -309,6 +309,9 @@ describe('Environment safety — percent-encoded MongoDB seed hosts', () => { 'mongodb://u:p@local%2:27017/stock', 'mongodb://u:p@localhost%:27017/stock', 'mongodb://u:p@[::1%zz]:27017/stock', + 'mongodb://u:p@[not-ipv6%25zz]:27017/stock', + 'mongodb://u:p@[::1%25]:27017/stock', + 'mongodb://u:p@[::1%25lo%2f]:27017/stock', ]; for (const mongoUri of malformedUris) { @@ -619,4 +622,30 @@ describe('Environment safety — percent-encoded MongoDB seed hosts', () => { }); expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow(); }); + + test('fails closed with an explicit error on decoded URL delimiters, backslashes, or whitespace in MongoDB host', () => { + const smuggledUris = [ + 'mongodb://u:p@localhost%252f:27018/stock_dev', + 'mongodb://u:p@localhost%5c:27018/stock_dev', + 'mongodb://u:p@localhost%20:27018/stock_dev', + 'mongodb://u:p@[::1%2f]:27018/stock_dev', + ]; + + for (const mongoUri of smuggledUris) { + const cfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock_dev', + bypassSchemaValidation: true, + }); + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow( + /Safety guard: invalid characters in MongoDB host/ + ); + expect(() => + assertEnvironmentSafety(cfg, 'dataIngestion', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).toThrow(/Safety guard: invalid characters in MongoDB host/); + } + }); });