T-9: Multi-host MongoDB URI bypasses the dev QA-Mongo guard
This commit is contained in:
parent
890761e0d5
commit
2a28c402e8
2 changed files with 346 additions and 31 deletions
|
|
@ -2,7 +2,25 @@ import type { StockAppConfig } from './schemas';
|
|||
|
||||
export type StockServiceName = 'dataIngestion' | 'dataPipeline' | 'webApi' | 'orchestrator';
|
||||
|
||||
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0']);
|
||||
interface MongoTargetHost {
|
||||
host: string;
|
||||
port?: number;
|
||||
}
|
||||
|
||||
interface ParsedMongoTarget {
|
||||
hosts: MongoTargetHost[];
|
||||
host?: string;
|
||||
database?: string;
|
||||
username?: string;
|
||||
}
|
||||
|
||||
const LOOPBACK_HOSTS = new Set([
|
||||
'localhost',
|
||||
'0.0.0.0',
|
||||
'::1',
|
||||
'0:0:0:0:0:0:0:1',
|
||||
'::ffff:127.0.0.1',
|
||||
]);
|
||||
const FORBIDDEN_PROD_SECRETS = new Set([
|
||||
'trading_pass_dev',
|
||||
'trading_mongo_dev',
|
||||
|
|
@ -12,41 +30,162 @@ const FORBIDDEN_PROD_SECRETS = new Set([
|
|||
'admin123',
|
||||
]);
|
||||
|
||||
function isIpv4Loopback(host: string): boolean {
|
||||
const octets = host.split('.');
|
||||
if (octets.length !== 4 || octets[0] !== '127') {
|
||||
return false;
|
||||
}
|
||||
return octets.every(part => {
|
||||
if (!/^\d{1,3}$/.test(part)) {
|
||||
return false;
|
||||
}
|
||||
const value = Number(part);
|
||||
return value >= 0 && value <= 255;
|
||||
});
|
||||
}
|
||||
|
||||
function isLoopbackHost(host?: string): boolean {
|
||||
if (!host) {
|
||||
return false;
|
||||
}
|
||||
const normalized = host.replace(/^\[|\]$/g, '').toLowerCase();
|
||||
return LOOPBACK_HOSTS.has(normalized);
|
||||
const normalized = host
|
||||
.trim()
|
||||
.replace(/^\[|\]$/g, '')
|
||||
.replace(/\.+$/, '')
|
||||
.toLowerCase();
|
||||
if (LOOPBACK_HOSTS.has(normalized) || isIpv4Loopback(normalized)) {
|
||||
return true;
|
||||
}
|
||||
return normalized.startsWith('::ffff:') && isIpv4Loopback(normalized.slice(7));
|
||||
}
|
||||
|
||||
function parseMongoTarget(uri?: string): {
|
||||
host?: string;
|
||||
port?: number;
|
||||
database?: string;
|
||||
username?: string;
|
||||
} {
|
||||
if (!uri) {
|
||||
return {};
|
||||
function parseMongoHostPort(
|
||||
segment: string,
|
||||
defaultPort: number | undefined
|
||||
): MongoTargetHost | null {
|
||||
const trimmed = segment.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(uri);
|
||||
const database = parsed.pathname.replace(/^\/+/, '').split('/')[0] || undefined;
|
||||
const port = parsed.port ? Number(parsed.port) : parsed.protocol === 'mongodb:' ? 27017 : undefined;
|
||||
return {
|
||||
host: parsed.hostname || undefined,
|
||||
port: Number.isFinite(port) ? port : undefined,
|
||||
database,
|
||||
username: parsed.username ? decodeURIComponent(parsed.username) : undefined,
|
||||
};
|
||||
} catch {
|
||||
return {};
|
||||
|
||||
if (trimmed.startsWith('[')) {
|
||||
const closeIdx = trimmed.indexOf(']');
|
||||
if (closeIdx <= 1) {
|
||||
return null;
|
||||
}
|
||||
const host = trimmed.slice(1, closeIdx).trim();
|
||||
if (!host) {
|
||||
return null;
|
||||
}
|
||||
const after = trimmed.slice(closeIdx + 1).trim();
|
||||
if (after === '' || after === ':') {
|
||||
return { host, port: defaultPort };
|
||||
}
|
||||
if (!after.startsWith(':')) {
|
||||
return null;
|
||||
}
|
||||
const portStr = after.slice(1).trim();
|
||||
if (!/^\d+$/.test(portStr)) {
|
||||
return null;
|
||||
}
|
||||
const port = Number(portStr);
|
||||
if (port < 1 || port > 65535) {
|
||||
return null;
|
||||
}
|
||||
return { host, port };
|
||||
}
|
||||
|
||||
const colonIdx = trimmed.indexOf(':');
|
||||
if (colonIdx === -1) {
|
||||
return { host: trimmed, port: defaultPort };
|
||||
}
|
||||
if (trimmed.indexOf(':', colonIdx + 1) !== -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const host = trimmed.slice(0, colonIdx).trim();
|
||||
const portStr = trimmed.slice(colonIdx + 1).trim();
|
||||
if (!host) {
|
||||
return null;
|
||||
}
|
||||
if (portStr === '') {
|
||||
return { host, port: defaultPort };
|
||||
}
|
||||
if (!/^\d+$/.test(portStr)) {
|
||||
return null;
|
||||
}
|
||||
const port = Number(portStr);
|
||||
if (port < 1 || port > 65535) {
|
||||
return null;
|
||||
}
|
||||
return { host, port };
|
||||
}
|
||||
|
||||
function parseMongoTarget(uri?: string): ParsedMongoTarget {
|
||||
const trimmed = uri?.trim();
|
||||
if (!trimmed) {
|
||||
return { hosts: [] };
|
||||
}
|
||||
|
||||
const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/i.exec(trimmed);
|
||||
const rawScheme = schemeMatch?.[1];
|
||||
const rest = schemeMatch?.[2];
|
||||
if (!rawScheme || rest === undefined) {
|
||||
return { hosts: [] };
|
||||
}
|
||||
|
||||
const scheme = rawScheme.toLowerCase();
|
||||
const defaultPort = scheme === 'mongodb' ? 27017 : undefined;
|
||||
|
||||
const delimiterMatch = /[/?#]/.exec(rest);
|
||||
const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest;
|
||||
const remainder = delimiterMatch ? rest.slice(delimiterMatch.index) : '';
|
||||
|
||||
let database: string | undefined;
|
||||
if (remainder.startsWith('/')) {
|
||||
const pathPart = remainder.split(/[?#]/, 1)[0] ?? '';
|
||||
const firstSegment = pathPart.replace(/^\/+/, '').split('/')[0];
|
||||
database = firstSegment || undefined;
|
||||
}
|
||||
|
||||
const atIndex = authority.lastIndexOf('@');
|
||||
const userinfo = atIndex >= 0 ? authority.slice(0, atIndex) : '';
|
||||
const hostList = atIndex >= 0 ? authority.slice(atIndex + 1) : authority;
|
||||
|
||||
let username: string | undefined;
|
||||
if (userinfo) {
|
||||
const colonIndex = userinfo.indexOf(':');
|
||||
const rawUsername = colonIndex >= 0 ? userinfo.slice(0, colonIndex) : userinfo;
|
||||
if (rawUsername) {
|
||||
try {
|
||||
username = decodeURIComponent(rawUsername);
|
||||
} catch {
|
||||
username = rawUsername;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const hosts: MongoTargetHost[] = [];
|
||||
for (const segment of hostList.split(',')) {
|
||||
const parsedHost = parseMongoHostPort(segment, defaultPort);
|
||||
if (parsedHost) {
|
||||
hosts.push(parsedHost);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
hosts,
|
||||
host: hosts[0]?.host,
|
||||
database,
|
||||
username,
|
||||
};
|
||||
}
|
||||
|
||||
function isQaMongoTarget(uri: string | undefined): boolean {
|
||||
const target = parseMongoTarget(uri);
|
||||
return isLoopbackHost(target.host) && target.port === 27017;
|
||||
return target.hosts.some(
|
||||
entry => isLoopbackHost(entry.host) && (entry.port === undefined || entry.port === 27017)
|
||||
);
|
||||
}
|
||||
|
||||
function isQaPostgresTarget(pg: StockAppConfig['database']['postgres']): boolean {
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ function makeConfig(overrides: {
|
|||
mongoDatabase?: string;
|
||||
dragonflyPassword?: string;
|
||||
} = {}): StockAppConfig {
|
||||
return stockAppSchema.parse({
|
||||
const parsed = stockAppSchema.parse({
|
||||
name: 'stock-bot',
|
||||
version: '1.0.0',
|
||||
environment: overrides.environment ?? 'development',
|
||||
|
|
@ -50,12 +50,8 @@ function makeConfig(overrides: {
|
|||
},
|
||||
mongodb: {
|
||||
enabled: true,
|
||||
uri:
|
||||
overrides.mongoUri ??
|
||||
'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin',
|
||||
readUri:
|
||||
overrides.mongoReadUri ??
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock',
|
||||
uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin',
|
||||
readUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock',
|
||||
readOnly: overrides.mongoReadOnly ?? false,
|
||||
database: overrides.mongoDatabase ?? 'stock_dev',
|
||||
},
|
||||
|
|
@ -81,6 +77,15 @@ function makeConfig(overrides: {
|
|||
},
|
||||
features: {},
|
||||
});
|
||||
|
||||
if (overrides.mongoUri !== undefined) {
|
||||
parsed.database.mongodb.uri = overrides.mongoUri;
|
||||
}
|
||||
if (overrides.mongoReadUri !== undefined) {
|
||||
parsed.database.mongodb.readUri = overrides.mongoReadUri;
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
describe('Environment safety & multi-env isolation', () => {
|
||||
|
|
@ -247,6 +252,177 @@ describe('Environment safety & multi-env isolation', () => {
|
|||
);
|
||||
});
|
||||
|
||||
test('blocks multi-host MongoDB seed lists targeting QA loopback :27017 for dataIngestion and dataPipeline', () => {
|
||||
const qaFirstIngestion = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: 'mongodb://u:p@localhost:27017,localhost:27018/stock',
|
||||
mongoDatabase: 'stock',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(qaFirstIngestion, 'dataIngestion', {})).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(qaFirstIngestion, 'dataIngestion', {
|
||||
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
|
||||
})
|
||||
).not.toThrow();
|
||||
|
||||
const qaSecondIngestion = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: 'mongodb://u:p@localhost:27018,localhost:27017/stock_dev',
|
||||
mongoDatabase: 'stock_dev',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(qaSecondIngestion, 'dataIngestion', {})).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(qaSecondIngestion, 'dataIngestion', {
|
||||
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
|
||||
})
|
||||
).not.toThrow();
|
||||
|
||||
const qaPipelineNonReadOnly = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27018,localhost:27017/stock_dev',
|
||||
mongoReadOnly: false,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(qaPipelineNonReadOnly, 'dataPipeline', {})).toThrow(
|
||||
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
|
||||
);
|
||||
|
||||
const qaPipelineFallbackUri = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: 'mongodb://studio_stock_bot_read:secret@localhost:27018,localhost:27017/stock',
|
||||
mongoReadOnly: false,
|
||||
});
|
||||
qaPipelineFallbackUri.database.mongodb.readUri = undefined;
|
||||
expect(() => assertEnvironmentSafety(qaPipelineFallbackUri, 'dataPipeline', {})).toThrow(
|
||||
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
|
||||
);
|
||||
|
||||
const qaPipelineAdmin = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://trading_admin:pass@localhost:27017,localhost:27018/stock',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(qaPipelineAdmin, 'dataPipeline', {
|
||||
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
|
||||
})
|
||||
).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/);
|
||||
|
||||
const qaPipelineEncodedAdmin = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://trading%5Fadmin:pass@localhost:27018,localhost:27017/stock',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(qaPipelineEncodedAdmin, 'dataPipeline', {
|
||||
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
|
||||
})
|
||||
).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/);
|
||||
|
||||
const qaPipelineReadOnlyAllowed = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(qaPipelineReadOnlyAllowed, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('blocks omitted port, loopback variants, and mongodb+srv loopback URIs', () => {
|
||||
const qaLoopbackUris = [
|
||||
'mongodb://u:p@localhost:27018,localhost/stock_dev',
|
||||
'mongodb://u:p@localhost:27018,127.0.0.1/stock_dev',
|
||||
'mongodb://u:p@localhost:27018,[::1]:27017/stock_dev',
|
||||
'mongodb://u:p@localhost:27018,[::1]/stock_dev',
|
||||
'mongodb://u:p@localhost:27018,LOCALHOST.:27017/stock_dev',
|
||||
'mongodb://u:p@127.0.0.2:27017/stock_dev',
|
||||
'mongodb+srv://u:p@localhost/stock',
|
||||
];
|
||||
|
||||
for (const mongoUri of qaLoopbackUris) {
|
||||
const cfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri,
|
||||
mongoDatabase: 'stock_dev',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('handles multi-host MongoDB URI parsing edge cases without failing open', () => {
|
||||
const unencodedAtPipeline = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(unencodedAtPipeline, 'dataPipeline', {})).toThrow(
|
||||
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
|
||||
);
|
||||
|
||||
const edgeCaseUris = [
|
||||
'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock',
|
||||
'mongodb://u:p@localhost:/stock',
|
||||
'mongodb://localhost:27017,localhost:27018/stock',
|
||||
'mongodb://u:p@bad:port,localhost:27017/stock',
|
||||
];
|
||||
|
||||
for (const mongoUri of edgeCaseUris) {
|
||||
const cfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri,
|
||||
mongoDatabase: 'stock',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
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';
|
||||
|
||||
const devIngestion = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: devMultiHostUri,
|
||||
mongoDatabase: 'stock_dev',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(devIngestion, 'dataIngestion', {})).not.toThrow();
|
||||
|
||||
const devPipeline = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: devMultiHostUri,
|
||||
mongoReadUri: devMultiHostUri,
|
||||
mongoReadOnly: false,
|
||||
mongoDatabase: 'stock_dev',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(devPipeline, 'dataPipeline', {})).not.toThrow();
|
||||
|
||||
const prodMultiHostSafe = makeConfig({
|
||||
environment: 'production',
|
||||
pgHost: 'pg.prod.internal',
|
||||
pgDatabase: 'trading_bot_prod',
|
||||
pgPassword: 'super-strong-prod-password',
|
||||
mongoUri: 'mongodb://prod:strongpass@mongo1.prod.internal:27017,mongo2.prod.internal:27017/stock',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(prodMultiHostSafe, 'webApi', {})).not.toThrow();
|
||||
|
||||
const prodMultiHostDevSecret = makeConfig({
|
||||
environment: 'production',
|
||||
pgHost: 'pg.prod.internal',
|
||||
pgDatabase: 'trading_bot_prod',
|
||||
pgPassword: 'super-strong-prod-password',
|
||||
mongoUri: 'mongodb://prod:trading_mongo_dev@mongo1.prod.internal:27017,mongo2.prod.internal:27017/stock',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(prodMultiHostDevSecret, 'webApi', {})).toThrow(
|
||||
/production MongoDB \(mongo1\.prod\.internal\) cannot use a default dev\/qa credential/
|
||||
);
|
||||
});
|
||||
|
||||
test('blocks qa environment from targeting *_dev databases', () => {
|
||||
const cfg = makeConfig({
|
||||
environment: 'qa',
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue