T-13: Dev QA-Mongo guard misses percent-encoded loopback hostnames (confirmed reachable)

This commit is contained in:
Studio 2026-11-27 12:38:42 -05:00
parent f712c3619b
commit 2dbecd7c95
2 changed files with 426 additions and 3 deletions

View file

@ -162,6 +162,17 @@ 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}".`);
}
throw error;
}
}
function parseMongoHostPort(
segment: string,
defaultPort: number | undefined
@ -176,7 +187,11 @@ function parseMongoHostPort(
if (closeIdx <= 1) {
return null;
}
const host = trimmed.slice(1, closeIdx).trim();
const rawHost = trimmed.slice(1, closeIdx).trim();
if (!rawHost) {
return null;
}
const host = decodeMongoHost(rawHost).trim();
if (!host) {
return null;
}
@ -200,14 +215,22 @@ function parseMongoHostPort(
const colonIdx = trimmed.indexOf(':');
if (colonIdx === -1) {
return { host: trimmed, port: defaultPort };
const host = decodeMongoHost(trimmed).trim();
if (!host) {
return null;
}
return { host, port: defaultPort };
}
if (trimmed.indexOf(':', colonIdx + 1) !== -1) {
return null;
}
const host = trimmed.slice(0, colonIdx).trim();
const rawHost = trimmed.slice(0, colonIdx).trim();
const portStr = trimmed.slice(colonIdx + 1).trim();
if (!rawHost) {
return null;
}
const host = decodeMongoHost(rawHost).trim();
if (!host) {
return null;
}

View file

@ -0,0 +1,400 @@
import { describe, expect, test } from 'bun:test';
import {
assertEnvironmentSafety,
stockAppSchema,
type StockAppConfig,
} from '@stock-bot/stock-config';
import { MongoClient } from 'mongodb';
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',
];
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('matches MongoDB driver HostAddress parsing offline without connecting', () => {
const parityCases = [
'mongodb://u:p@localhost:27017/stock',
'mongodb://u:p@%6cocalhost: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@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,%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@mongo.internal:27017/stock',
];
for (const uri of parityCases) {
// Strictly offline: construct MongoClient only to inspect parsed options.hosts; 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 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('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();
});
});