stock-bot/test/unit/environment-safety-encoded-host.test.ts
2026-11-27 14:12:53 -05:00

858 lines
30 KiB
TypeScript

import { createRequire } from 'node:module';
import { describe, expect, test } from 'bun:test';
import {
assertEnvironmentSafety,
stockAppSchema,
type StockAppConfig,
} from '@stock-bot/stock-config';
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: {
environment?: 'development' | 'qa' | 'test' | 'production';
pgHost?: string;
pgPort?: number;
pgDatabase?: string;
pgPassword?: string;
mongoUri?: string;
mongoReadUri?: string;
mongoReadOnly?: boolean;
mongoDatabase?: 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',
environment: overrides.environment ?? 'development',
service: {
name: 'stock-bot',
port: 2002,
host: '127.0.0.1',
},
log: {
level: 'info',
format: 'json',
},
database: {
postgres: {
enabled: true,
host: overrides.pgHost ?? 'localhost',
port: overrides.pgPort ?? 5433,
database: overrides.pgDatabase ?? 'trading_bot_dev',
user: 'dev_user',
password: overrides.pgPassword ?? 'dev_pass',
ssl: false,
},
mongodb: {
enabled: true,
uri: overrides.bypassSchemaValidation
? defaultMongoUri
: (overrides.mongoUri ?? defaultMongoUri),
readUri: overrides.bypassSchemaValidation
? defaultMongoReadUri
: (overrides.mongoReadUri ?? defaultMongoReadUri),
readOnly: overrides.mongoReadOnly ?? false,
database: overrides.mongoDatabase ?? 'stock_dev',
},
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: {},
});
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;
}
function isDriverHostLoopback(host: string): boolean {
const normalized = host
.trim()
.replace(/^\[|\]$/g, '')
.replace(/\.+$/, '')
.toLowerCase();
if (normalized === 'localhost' || normalized === '0.0.0.0' || normalized === '::1') {
return true;
}
if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(normalized)) {
return true;
}
if (normalized.startsWith('::1%')) {
return true;
}
if (/^::ffff:(?:7f[0-9a-f]{2}:[0-9a-f]{1,4}|127\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(normalized)) {
return true;
}
return false;
}
describe('Environment safety — percent-encoded MongoDB seed hosts', () => {
test('blocks percent-encoded localhost QA URI for dataIngestion and unsafe dataPipeline', () => {
const encodedQaUri = 'mongodb://u:p@%6cocalhost:27017/stock';
const ingestionCfg = makeConfig({
environment: 'development',
mongoUri: encodedQaUri,
mongoDatabase: 'stock',
bypassSchemaValidation: true,
});
expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow(
/cannot open a writable MongoDB connection to QA MongoDB/
);
const pipelineNonReadOnly = makeConfig({
environment: 'development',
mongoReadUri: encodedQaUri,
mongoReadOnly: false,
mongoDatabase: 'stock',
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@%6cocalhost:27017/stock',
mongoReadOnly: true,
mongoDatabase: 'stock',
bypassSchemaValidation: true,
});
expect(() =>
assertEnvironmentSafety(pipelineAdmin, 'dataPipeline', {
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
})
).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/);
});
test('blocks encoded loopback variants (IPv4, mixed-case, trailing dot, omitted port, srv, IPv6)', () => {
const encodedLoopbackUris = [
'mongodb://u:p@%6cocalhost:27017/stock',
'mongodb://u:p@%31%32%37%2e%30%2e%30%2e%31:27017/stock',
'mongodb://u:p@127%2E0.0.1:27017/stock',
'mongodb://u:p@%4C%6fCalHost:27017/stock',
'mongodb://u:p@%4C%4F%43%41%4C%48%4F%53%54:27017/stock',
'mongodb://u:p@%6cocalhost%2e:27017/stock',
'mongodb://u:p@%6cocalhost/stock',
'mongodb+srv://u:p@%6cocalhost/stock',
'mongodb://u:p@[::1%25lo]:27017/stock',
'mongodb://u:p@[::ffff:%37%66%30%30:1]:27017/stock',
];
for (const mongoUri of encodedLoopbackUris) {
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 pipelineCfg = makeConfig({
environment: 'development',
mongoReadUri: mongoUri,
mongoReadOnly: false,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow(
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
);
}
});
test('blocks encoded QA loopback hosts inside multi-host seed lists', () => {
const multiHostUris = [
'mongodb://u:p@localhost:27018,%6cocalhost:27017/stock_dev',
'mongodb://u:p@localhost:27018,%31%32%37.0.0.1/stock_dev',
];
for (const mongoUri of multiHostUris) {
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 pipelineCfg = makeConfig({
environment: 'development',
mongoReadUri: mongoUri,
mongoReadOnly: false,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow(
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
);
}
});
test('allows safe dev URIs, read-only encoded QA dataPipeline, and explicit escape hatch', () => {
const safeDevUris = [
'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev',
'mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27018/stock_dev',
'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev',
];
for (const mongoUri of safeDevUris) {
const cfg = makeConfig({
environment: 'development',
mongoUri,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow();
}
const readOnlyEncodedPipeline = makeConfig({
environment: 'development',
mongoReadUri: 'mongodb://studio_stock_bot_read:secret@%6cocalhost:27017/stock?authSource=stock',
mongoReadOnly: true,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
expect(() => assertEnvironmentSafety(readOnlyEncodedPipeline, 'dataPipeline', {})).not.toThrow();
const escapedEncodedIngestion = makeConfig({
environment: 'development',
mongoUri: 'mongodb://u:p@%6cocalhost:27017/stock',
mongoDatabase: 'stock',
bypassSchemaValidation: true,
});
expect(() =>
assertEnvironmentSafety(escapedEncodedIngestion, 'dataIngestion', {
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
})
).not.toThrow();
});
test('fails closed with an explicit error on malformed percent-encoding in MongoDB host', () => {
const malformedUris = [
'mongodb://u:p@%zz:27017/stock',
'mongodb://u:p@%zz:27018/stock_dev',
'mongodb://u:p@localhost:27018,%zz:27017/stock_dev',
'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) {
const ingestionCfg = makeConfig({
environment: 'development',
mongoUri,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow(
/Safety guard: invalid percent-encoding in MongoDB host/
);
expect(() =>
assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
})
).toThrow(/Safety guard: invalid percent-encoding in MongoDB host/);
const pipelineCfg = makeConfig({
environment: 'development',
mongoReadUri: mongoUri,
mongoReadOnly: true,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow(
/Safety guard: invalid percent-encoding in MongoDB host/
);
expect(() =>
assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
})
).toThrow(/Safety guard: invalid percent-encoding in MongoDB host/);
}
});
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:27018/stock_dev',
'mongodb://u:p@mongo.internal:27017/stock',
];
for (const uri of parityCases) {
// 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 => {
const dialHost = getDriverDialHostAddress(entry);
return (
typeof dialHost.host === 'string' &&
isDriverHostLoopback(dialHost.host) &&
(dialHost.port === undefined || dialHost.port === 27017)
);
});
const cfg = makeConfig({
environment: 'development',
mongoUri: uri,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
let guardBlocked = false;
try {
assertEnvironmentSafety(cfg, 'dataIngestion', {});
} catch {
guardBlocked = true;
}
expect(guardBlocked).toBe(driverTargetsQa);
}
// Malformed percent-encoding: both guard and MongoClient reject it offline.
const malformedUri = 'mongodb://u:p@%zz:27017/stock';
expect(() => new MongoClient(malformedUri)).toThrow();
const malformedCfg = makeConfig({
environment: 'development',
mongoUri: malformedUri,
mongoDatabase: 'stock',
bypassSchemaValidation: true,
});
expect(() => assertEnvironmentSafety(malformedCfg, 'dataIngestion', {})).toThrow(
/Safety guard: invalid percent-encoding in MongoDB host/
);
});
test('blocks seeds whose decoded host smuggles a URL delimiter that ServerDescription reparses to QA loopback', () => {
// QA regression: HostAddress decodes "localhost%2f" to host "localhost/" and keeps the explicit
// port, so the seed serializes as "localhost/:27018". ServerDescription.hostAddress then reparses
// that string with WHATWG URL, which stops the authority at "/" and dials localhost:27017 (QA).
const delimiterSmuggledUris = [
'mongodb://u:p@localhost%2f:27018/stock_dev',
'mongodb://u:p@%6cocalhost%2f:27018/stock_dev',
'mongodb://u:p@localhost%3f:27018/stock_dev',
'mongodb://u:p@localhost%23:27018/stock_dev',
'mongodb://u:p@%6cocalhost%3a27017%2f:27018/stock_dev',
'mongodb://u:p@x%40localhost%3a27017%2f:27018/stock_dev',
'mongodb://u:p@%5b%3a%3a1%5d%3a27017%2f:27018/stock_dev',
'mongodb://u:p@localhost:27018,localhost%2f:27019/stock_dev',
];
for (const mongoUri of delimiterSmuggledUris) {
// Arrange: prove offline that the driver's final dial target is QA MongoDB.
const dialTargets = new MongoClient(mongoUri).options.hosts.map(seed =>
getDriverDialHostAddress(seed)
);
expect(
dialTargets.some(
target =>
typeof target.host === 'string' && isDriverHostLoopback(target.host) && target.port === 27017
)
).toBe(true);
const ingestionCfg = makeConfig({
environment: 'development',
mongoUri,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
const pipelineCfg = makeConfig({
environment: 'development',
mongoReadUri: mongoUri,
mongoReadOnly: false,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
// Act + assert: the guard must not allow either service to start.
expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow(
/Safety guard/
);
expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow(/Safety guard/);
}
});
test('never allows a seed whose driver dial target is QA loopback:27017 (offline parity sweep)', () => {
// Every case is built so the guard sees a non-QA seed unless it follows the driver's reparse.
const hostSpellings = [
'localhost',
'%6cocalhost',
'%256cocalhost',
'127.0.0.1',
'%31%32%37.0.0.1',
'[::1]',
'localhost%2f',
'localhost%3f',
'localhost%23',
'localhost%3a27017%2f',
'localhost%3a27017',
'localhost%2c127.0.0.1',
'mongo.internal',
'mongo.internal%2f',
];
const ports = [':27017', ':27018', ''];
const bypasses: string[] = [];
for (const host of hostSpellings) {
for (const port of ports) {
const uri = `mongodb://u:p@${host}${port}/stock_dev`;
let dialsQa = false;
try {
dialsQa = new MongoClient(uri).options.hosts.some(seed => {
const target = getDriverDialHostAddress(seed);
return (
typeof target.host === 'string' &&
isDriverHostLoopback(target.host) &&
target.port === 27017
);
});
} catch {
// The driver refuses this URI before dialing, so no QA connection is possible.
dialsQa = false;
}
const cfg = makeConfig({
environment: 'development',
mongoUri: uri,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
let guardBlocked = false;
try {
assertEnvironmentSafety(cfg, 'dataIngestion', {});
} catch {
guardBlocked = true;
}
if (dialsQa && !guardBlocked) {
bypasses.push(uri);
}
}
}
expect(bypasses).toEqual([]);
});
test('does not throw on literal IPv6 zone ID in raw PostgreSQL host', () => {
const cfg = makeConfig({
environment: 'development',
pgHost: 'fe80::1%eth0',
pgPort: 5432,
pgDatabase: 'trading_bot',
});
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/);
}
});
test('fails closed with an explicit error on percent-encoded ASCII control characters (including non-whitespace NUL, 0x1f, DEL) in MongoDB host', () => {
// %00, %01, %1f and %7f are not matched by \s, so only the explicit control-char check
// in decodeMongoHost rejects them (T-29 moved that check out of the forbidden-char regex).
const smuggledUris = [
'mongodb://u:p@localhost%00:27018/stock_dev',
'mongodb://u:p@loc%0aalhost:27018/stock_dev',
'mongodb://u:p@localhost%1f:27018/stock_dev',
'mongodb://u:p@localhost%7f:27018/stock_dev',
'mongodb://u:p@localhost%7F:27018/stock_dev',
'mongodb://u:p@local%01host:27018/stock_dev',
'mongodb://u:p@localhost%2500:27018/stock_dev',
'mongodb://u:p@localhost%257f:27018/stock_dev',
'mongodb://u:p@mongo.internal:27018,localhost%1f:27018/stock_dev',
'mongodb://u:p@[::1%00]:27018/stock_dev',
'mongodb://u:p@[::1%7f]:27018/stock_dev',
];
for (const mongoUri of smuggledUris) {
const cfg = makeConfig({
environment: 'development',
mongoUri,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {}), mongoUri).toThrow(
/Safety guard: invalid characters in MongoDB host/
);
expect(
() =>
assertEnvironmentSafety(cfg, 'dataIngestion', {
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
}),
mongoUri
).toThrow(/Safety guard: invalid characters in MongoDB host/);
}
});
test('still accepts printable non-delimiter hosts next to the control-character boundary (0x20 is whitespace, 0x7e is allowed)', () => {
const cfg = makeConfig({
environment: 'development',
mongoUri: 'mongodb://u:p@mongo%7einternal:27018/stock_dev',
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow();
});
test('seeded random percent-encoding sweep never allows a seed the driver dials as QA loopback:27017', () => {
// Deterministic LCG (fixed seed) so the sweep is reproducible; strictly offline, no connect().
let state = 20261127;
const nextRandom = (): number => {
state = (Math.imul(state, 1103515245) + 12345) & 0x7fffffff;
return state / 0x7fffffff;
};
const encodeChar = (ch: string): string => {
const hex = ch.charCodeAt(0).toString(16).padStart(2, '0');
return `%${nextRandom() < 0.5 ? hex.toUpperCase() : hex}`;
};
const encodeHost = (host: string, depth: number): string => {
let out = '';
for (const ch of host) {
out += nextRandom() < 0.4 ? encodeChar(ch) : ch;
}
for (let level = 1; level < depth; level++) {
out = out.replace(/%/g, '%25');
}
return out;
};
const baseHosts = [
'localhost',
'LocalHost',
'localhost.',
'127.0.0.1',
'127.1.2.3',
'0.0.0.0',
'[::1]',
'localhost/',
'localhost?',
'localhost#',
'localhost:27017',
'localhost:27017/',
'[::1]:27017/',
'localhost,localhost',
'loc%0aalhost',
'localhost%09',
'loc%00alhost',
'x%40localhost',
'%5b::1%5d',
'mongo.internal',
];
const portSuffixes = [':27017', ':27018', ''];
const bypasses: string[] = [];
let driverQaDialCount = 0;
for (let iteration = 0; iteration < 3000; iteration++) {
const base = baseHosts[Math.floor(nextRandom() * baseHosts.length)] ?? 'localhost';
const port = portSuffixes[Math.floor(nextRandom() * portSuffixes.length)] ?? '';
const depth = 1 + Math.floor(nextRandom() * 3);
const uri = `mongodb://u:p@${encodeHost(base, depth)}${port}/stock_dev`;
let dialsQa = false;
try {
dialsQa = new MongoClient(uri).options.hosts.some(seed => {
const target = getDriverDialHostAddress(seed);
return (
typeof target.host === 'string' &&
isDriverHostLoopback(target.host) &&
target.port === 27017
);
});
} catch {
// Driver refuses the URI or seed before dialing, so no QA socket can be opened.
dialsQa = false;
}
if (!dialsQa) {
continue;
}
driverQaDialCount++;
const cfg = makeConfig({
environment: 'development',
mongoUri: uri,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
let guardBlocked = false;
try {
assertEnvironmentSafety(cfg, 'dataIngestion', {});
} catch {
guardBlocked = true;
}
if (!guardBlocked) {
bypasses.push(uri);
}
}
// Guard against a vacuous sweep: plenty of generated URIs must really dial QA.
expect(driverQaDialCount).toBeGreaterThan(500);
expect(bypasses).toEqual([]);
});
test('allows encoded dev-port loopback seeds that the driver dials on 27018', () => {
const devUris = [
'mongodb://dev_admin:dev_mongo_pass@%6C%4F%63%61%6C%68%6F%73%74:27018/stock_dev',
'mongodb://dev_admin:dev_mongo_pass@%2531%2532%2537.0.0.1:27018/stock_dev',
'mongodb://dev_admin:dev_mongo_pass@[::1]:27018/stock_dev',
'mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27018,127%2e0.0.1:27019/stock_dev',
];
for (const mongoUri of devUris) {
// Arrange: confirm offline the driver never dials QA for these seeds.
const dialTargets = new MongoClient(mongoUri).options.hosts.map(seed =>
getDriverDialHostAddress(seed)
);
expect(dialTargets.every(target => target.port !== 27017)).toBe(true);
const cfg = makeConfig({
environment: 'development',
mongoUri,
mongoDatabase: 'stock_dev',
bypassSchemaValidation: true,
});
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow();
}
});
test('schema-validated config path blocks percent-encoded QA seed for dataIngestion', () => {
// No bypassSchemaValidation: the URI must survive stockAppSchema.parse and still be blocked.
const cfg = makeConfig({
environment: 'development',
mongoUri: 'mongodb://dev_admin:dev_mongo_pass@%6cocalhost:27017/stock?authSource=admin',
mongoDatabase: 'stock',
});
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow(
/cannot open a writable MongoDB connection to QA MongoDB/
);
});
test('production and qa guards still accept ordinary TCP and SRV MongoDB hosts', () => {
const prodUris = [
'mongodb+srv://prod_user:Str0ngProdSecret@cluster0.prod-db.example.net/stock?retryWrites=true',
'mongodb://prod_user:Str0ngProdSecret@mongo-0.prod.internal:27017,mongo-1.prod.internal:27017/stock?replicaSet=rs0',
'mongodb://prod_user:Str0ngProdSecret@%6dongo-0.prod.internal:27017/stock',
];
for (const mongoUri of prodUris) {
const prodCfg = makeConfig({
environment: 'production',
pgPassword: 'Str0ngProdPgSecret',
mongoUri,
mongoDatabase: 'stock',
});
expect(() => assertEnvironmentSafety(prodCfg, 'dataIngestion', {})).not.toThrow();
const qaCfg = makeConfig({
environment: 'qa',
pgDatabase: 'trading_bot',
mongoUri,
mongoDatabase: 'stock',
});
expect(() => assertEnvironmentSafety(qaCfg, 'dataIngestion', {})).not.toThrow();
}
});
});