T-9: Multi-host MongoDB URI bypasses the dev QA-Mongo guard
This commit is contained in:
commit
87e83117dd
7 changed files with 1004 additions and 39 deletions
|
|
@ -33,11 +33,103 @@ export const questdbConfigSchema = z.object({
|
|||
.describe('Deprecated: no effect on QuestDB client/writer'),
|
||||
});
|
||||
|
||||
function isValidMongoHostSegment(segment: string, allowPort: boolean): boolean {
|
||||
if (!segment || /\s/.test(segment)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (segment.startsWith('[')) {
|
||||
const closeIdx = segment.indexOf(']');
|
||||
if (closeIdx <= 1) {
|
||||
return false;
|
||||
}
|
||||
const host = segment.slice(1, closeIdx);
|
||||
if (!host || host.includes('[') || host.includes(']')) {
|
||||
return false;
|
||||
}
|
||||
const after = segment.slice(closeIdx + 1);
|
||||
if (after === '') {
|
||||
return true;
|
||||
}
|
||||
if (!allowPort || !after.startsWith(':')) {
|
||||
return false;
|
||||
}
|
||||
const portStr = after.slice(1);
|
||||
if (portStr === '') {
|
||||
return true;
|
||||
}
|
||||
if (!/^\d+$/.test(portStr)) {
|
||||
return false;
|
||||
}
|
||||
const port = Number(portStr);
|
||||
return port >= 1 && port <= 65535;
|
||||
}
|
||||
|
||||
const colonIdx = segment.indexOf(':');
|
||||
if (colonIdx === -1) {
|
||||
return true;
|
||||
}
|
||||
if (!allowPort || segment.indexOf(':', colonIdx + 1) !== -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const host = segment.slice(0, colonIdx);
|
||||
const portStr = segment.slice(colonIdx + 1);
|
||||
if (!host) {
|
||||
return false;
|
||||
}
|
||||
if (portStr === '') {
|
||||
return true;
|
||||
}
|
||||
if (!/^\d+$/.test(portStr)) {
|
||||
return false;
|
||||
}
|
||||
const port = Number(portStr);
|
||||
return port >= 1 && port <= 65535;
|
||||
}
|
||||
|
||||
function isValidMongoUri(uri: string): boolean {
|
||||
if (!uri || /\s/.test(uri)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/i.exec(uri);
|
||||
const rawScheme = schemeMatch?.[1];
|
||||
const rest = schemeMatch?.[2];
|
||||
if (!rawScheme || !rest) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const isSrv = rawScheme.toLowerCase() === 'mongodb+srv';
|
||||
const delimiterMatch = /[/?#]/.exec(rest);
|
||||
const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest;
|
||||
if (!authority) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const atIndex = authority.lastIndexOf('@');
|
||||
const hostList = atIndex >= 0 ? authority.slice(atIndex + 1) : authority;
|
||||
if (!hostList) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const segments = hostList.split(',');
|
||||
if (isSrv && segments.length !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return segments.every(segment => isValidMongoHostSegment(segment, !isSrv));
|
||||
}
|
||||
|
||||
const mongodbUriSchema = z.string().refine(isValidMongoUri, {
|
||||
message: 'Invalid MongoDB connection URI',
|
||||
});
|
||||
|
||||
// MongoDB configuration
|
||||
export const mongodbConfigSchema = z.object({
|
||||
enabled: z.boolean().default(true),
|
||||
uri: z.string().url(), // URI is required and contains all connection info
|
||||
readUri: z.string().url().optional(), // Optional read-only URI (e.g. dev data-pipeline reading QA MongoDB)
|
||||
uri: mongodbUriSchema, // URI is required and contains all connection info
|
||||
readUri: mongodbUriSchema.optional(), // Optional read-only URI (e.g. dev data-pipeline reading QA MongoDB)
|
||||
readOnly: z.boolean().default(false).optional(),
|
||||
database: z.string(), // Database name for reference
|
||||
poolSize: z.number().min(1).max(100).default(10),
|
||||
|
|
|
|||
|
|
@ -584,10 +584,66 @@ describe('Config Schemas', () => {
|
|||
expect(config).toEqual(input);
|
||||
});
|
||||
|
||||
it('should accept multi-host MongoDB seed lists for uri and readUri', () => {
|
||||
const config = mongodbConfigSchema.parse({
|
||||
uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin',
|
||||
readUri:
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017,[::1]:27018/stock?authSource=stock',
|
||||
database: 'stock_dev',
|
||||
});
|
||||
expect(config.uri).toBe(
|
||||
'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin'
|
||||
);
|
||||
expect(config.readUri).toBe(
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017,[::1]:27018/stock?authSource=stock'
|
||||
);
|
||||
});
|
||||
|
||||
it('should accept empty port spellings for mongodb:// in hostname and bracketed IPv6 forms', () => {
|
||||
const hostEmptyPort = mongodbConfigSchema.parse({
|
||||
uri: 'mongodb://mongo.prod.internal:/stock',
|
||||
readUri: 'mongodb://[::1]:/stock',
|
||||
database: 'stock',
|
||||
});
|
||||
expect(hostEmptyPort.uri).toBe('mongodb://mongo.prod.internal:/stock');
|
||||
expect(hostEmptyPort.readUri).toBe('mongodb://[::1]:/stock');
|
||||
|
||||
const seedListEmptyPort = mongodbConfigSchema.parse({
|
||||
uri: 'mongodb://u:p@mongo1.prod.internal:,[::1]:/stock',
|
||||
database: 'stock',
|
||||
});
|
||||
expect(seedListEmptyPort.uri).toBe('mongodb://u:p@mongo1.prod.internal:,[::1]:/stock');
|
||||
});
|
||||
|
||||
it('should validate URI format', () => {
|
||||
const invalidUris = [
|
||||
'invalid-uri',
|
||||
'http://localhost:27017/stock',
|
||||
'mongodb://',
|
||||
'mongodb://u:p@',
|
||||
'mongodb://u:p@localhost:27017,',
|
||||
'mongodb://u:p@:27017/stock',
|
||||
'mongodb://u:p@localhost:0/stock',
|
||||
'mongodb://u:p@localhost:99999/stock',
|
||||
'mongodb://u:p@[::1]:0/stock',
|
||||
'mongodb://u:p@[::1]:99999/stock',
|
||||
'mongodb://u:p@localhost:abc/stock',
|
||||
'mongodb+srv://u:p@localhost:/stock',
|
||||
'mongodb+srv://u:p@localhost:27017/stock',
|
||||
'mongodb+srv://u:p@host1.example.com,host2.example.com/stock',
|
||||
];
|
||||
for (const uri of invalidUris) {
|
||||
expect(() =>
|
||||
mongodbConfigSchema.parse({
|
||||
uri,
|
||||
database: 'testdb',
|
||||
})
|
||||
).toThrow();
|
||||
}
|
||||
expect(() =>
|
||||
mongodbConfigSchema.parse({
|
||||
uri: 'invalid-uri',
|
||||
uri: 'mongodb://localhost:27018/stock_dev',
|
||||
readUri: 'not-a-mongo-uri',
|
||||
database: 'testdb',
|
||||
})
|
||||
).toThrow();
|
||||
|
|
|
|||
|
|
@ -35,15 +35,33 @@ export type ContainerRegistrar = (
|
|||
) => void;
|
||||
|
||||
function extractMongoDatabaseFromUri(uri?: string): string | undefined {
|
||||
if (!uri) {
|
||||
const trimmed = uri?.trim();
|
||||
if (!trimmed) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const db = new URL(uri).pathname.replace(/^\/+/, '').split('/')[0];
|
||||
return db || undefined;
|
||||
} catch {
|
||||
|
||||
const schemeMatch = /^mongodb(?:\+srv)?:\/\/(.*)$/i.exec(trimmed);
|
||||
const rest = schemeMatch?.[1];
|
||||
if (!rest) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const delimiterMatch = /[/?#]/.exec(rest);
|
||||
if (!delimiterMatch || delimiterMatch[0] !== '/') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const pathPart = rest.slice(delimiterMatch.index).split(/[?#]/, 1)[0] ?? '';
|
||||
const rawDb = pathPart.replace(/^\/+/, '').split('/')[0];
|
||||
if (!rawDb) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
return decodeURIComponent(rawDb);
|
||||
} catch {
|
||||
return rawDb;
|
||||
}
|
||||
}
|
||||
|
||||
function getInfluxPort(config: { influxPort?: number; ilpPort?: number }): number {
|
||||
|
|
|
|||
|
|
@ -120,6 +120,49 @@ describe('ServiceContainerBuilder production configuration', () => {
|
|||
}
|
||||
});
|
||||
|
||||
it('extracts database from multi-host readUri when mongoReadOnly is enabled', async () => {
|
||||
const config = {
|
||||
...configuration(),
|
||||
database: {
|
||||
...configuration().database,
|
||||
mongodb: {
|
||||
enabled: true,
|
||||
uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin',
|
||||
readUri:
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock',
|
||||
database: 'stock_dev',
|
||||
},
|
||||
},
|
||||
};
|
||||
const container = await new ServiceContainerBuilder()
|
||||
.withConfig(config)
|
||||
.withOptions({
|
||||
enableMongoDB: true,
|
||||
mongoReadOnly: true,
|
||||
enablePostgres: false,
|
||||
enableQuestDB: false,
|
||||
enableCache: false,
|
||||
enableQueue: false,
|
||||
enableBrowser: false,
|
||||
enableProxy: false,
|
||||
})
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
try {
|
||||
const resolvedConfig = container.resolve('config');
|
||||
expect(resolvedConfig.mongodb.readOnly).toBe(true);
|
||||
expect(resolvedConfig.mongodb.database).toBe('stock');
|
||||
|
||||
const mongo = container.resolve('mongoClient');
|
||||
expect(mongo).not.toBeNull();
|
||||
expect(mongo!.isReadOnly()).toBe(true);
|
||||
expect(mongo!.getDefaultDatabase()).toBe('stock');
|
||||
} finally {
|
||||
await container.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects invalid settings and missing required app fields with schema errors', () => {
|
||||
expect(() =>
|
||||
new ServiceContainerBuilder().withConfig({
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue