T-13: Dev QA-Mongo guard misses percent-encoded loopback hostnames (confirmed reachable)
This commit is contained in:
parent
2dbecd7c95
commit
8eddb28935
2 changed files with 153 additions and 18 deletions
|
|
@ -162,15 +162,38 @@ function isLoopbackHost(host?: string): boolean {
|
|||
);
|
||||
}
|
||||
|
||||
function decodeMongoHost(rawHost: string): string {
|
||||
try {
|
||||
return decodeURIComponent(rawHost).toLowerCase();
|
||||
} catch (error) {
|
||||
if (error instanceof URIError) {
|
||||
throw new Error(`Safety guard: invalid percent-encoding in MongoDB host "${rawHost}".`);
|
||||
const MAX_MONGO_HOST_DECODE_PASSES = 8;
|
||||
|
||||
function decodeMongoHost(rawHost: string, isBracketedIpv6 = false): string {
|
||||
// MongoDB driver 6.22.0 decodes seed hostnames once in HostAddress.fromString during
|
||||
// URI parsing and a second time when ServerDescription.hostAddress reparses the
|
||||
// serialized address for ConnectionPool/Monitor. Decode iteratively to a fixed point
|
||||
// so double- or multi-encoded loopback hosts cannot bypass the guard.
|
||||
let current = rawHost;
|
||||
for (let pass = 0; pass < MAX_MONGO_HOST_DECODE_PASSES; pass++) {
|
||||
let decoded: string;
|
||||
try {
|
||||
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) {
|
||||
break;
|
||||
}
|
||||
throw new Error(`Safety guard: invalid percent-encoding in MongoDB host "${rawHost}".`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
throw error;
|
||||
if (decoded === current) {
|
||||
break;
|
||||
}
|
||||
current = decoded;
|
||||
}
|
||||
if (!isBracketedIpv6 && current.includes('%')) {
|
||||
throw new Error(`Safety guard: invalid percent-encoding in MongoDB host "${rawHost}".`);
|
||||
}
|
||||
return current.toLowerCase();
|
||||
}
|
||||
|
||||
function parseMongoHostPort(
|
||||
|
|
@ -191,7 +214,7 @@ function parseMongoHostPort(
|
|||
if (!rawHost) {
|
||||
return null;
|
||||
}
|
||||
const host = decodeMongoHost(rawHost).trim();
|
||||
const host = decodeMongoHost(rawHost, true).trim();
|
||||
if (!host) {
|
||||
return null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,24 @@
|
|||
import { createRequire } from 'node:module';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
assertEnvironmentSafety,
|
||||
stockAppSchema,
|
||||
type StockAppConfig,
|
||||
} from '@stock-bot/stock-config';
|
||||
import { MongoClient } from 'mongodb';
|
||||
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: {
|
||||
|
|
@ -331,31 +345,129 @@ describe('Environment safety — percent-encoded MongoDB seed hosts', () => {
|
|||
}
|
||||
});
|
||||
|
||||
test('matches MongoDB driver HostAddress parsing offline without connecting', () => {
|
||||
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:27017/stock',
|
||||
'mongodb://u:p@%256cocalhost:27018/stock_dev',
|
||||
'mongodb://u:p@mongo.internal:27017/stock',
|
||||
];
|
||||
|
||||
for (const uri of parityCases) {
|
||||
// Strictly offline: construct MongoClient only to inspect parsed options.hosts; never call connect().
|
||||
// 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 =>
|
||||
typeof entry.host === 'string' &&
|
||||
isDriverHostLoopback(entry.host) &&
|
||||
(entry.port === undefined || entry.port === 27017)
|
||||
);
|
||||
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',
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue