import { describe, expect, test } from 'bun:test'; import { ConfigManager } from '@stock-bot/config'; import { ServiceContainerBuilder } from '@stock-bot/di'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { MongoDBClient } from '@stock-bot/mongodb'; import { assertEnvironmentSafety, initializeStockConfig, resetStockConfig, stockAppSchema, type StockAppConfig, } from '@stock-bot/stock-config'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); function makeConfig(overrides: { environment?: 'development' | 'qa' | 'test' | 'production'; pgHost?: string; pgPort?: number; pgDatabase?: string; pgPassword?: string; mongoUri?: string; mongoReadUri?: string; mongoReadOnly?: boolean; mongoDatabase?: string; dragonflyPassword?: 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, password: overrides.dragonflyPassword, }, }, 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; } describe('Environment safety & multi-env isolation', () => { test('ConfigManager detects qa environment from NODE_ENV=qa', () => { const prev = process.env.NODE_ENV; try { process.env.NODE_ENV = 'qa'; const manager = new ConfigManager({ loaders: [] }); expect(manager.getEnvironment()).toBe('qa'); } finally { process.env.NODE_ENV = prev; } }); test('blocks development from targeting QA PostgreSQL (5432/trading_bot)', () => { const cfg = makeConfig({ environment: 'development', pgPort: 5432, pgDatabase: 'trading_bot', }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow( /development environment cannot target QA PostgreSQL/ ); }); test('blocks development dataIngestion from writing to QA MongoDB (27017/stock)', () => { const cfg = makeConfig({ environment: 'development', mongoUri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', mongoDatabase: 'stock', }); expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow( /cannot open a writable MongoDB connection to QA MongoDB/ ); }); test('allows development dataIngestion on dev MongoDB (27018/stock_dev) and dev Postgres (5433)', () => { const cfg = makeConfig({ environment: 'development' }); expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow(); }); test('allows development dataPipeline to read QA MongoDB via readUri when readOnly=true', () => { const cfg = makeConfig({ environment: 'development', mongoReadOnly: true }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow(); }); test('initializeStockConfig applies mongoReadOnly override before safety validation for dev dataPipeline', () => { const envKeys = [ 'NODE_ENV', 'POSTGRES_HOST', 'POSTGRES_PORT', 'POSTGRES_DB', 'POSTGRES_USER', 'POSTGRES_PASSWORD', 'MONGODB_URI', 'MONGODB_READ_URI', 'MONGODB_DATABASE', 'QUEUE_ENABLE_SCHEDULED_JOBS', 'HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy', ] as const; const savedEnv: Partial> = {}; for (const key of envKeys) { savedEnv[key] = process.env[key]; } try { process.env.NODE_ENV = 'development'; process.env.POSTGRES_HOST = 'localhost'; process.env.POSTGRES_PORT = '5433'; process.env.POSTGRES_DB = 'trading_bot_dev'; process.env.POSTGRES_USER = 'dev_user'; process.env.POSTGRES_PASSWORD = 'dev_pass'; process.env.MONGODB_URI = 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin'; process.env.MONGODB_READ_URI = 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock'; process.env.MONGODB_DATABASE = 'stock_dev'; delete process.env.QUEUE_ENABLE_SCHEDULED_JOBS; delete process.env.HTTP_PROXY; delete process.env.HTTPS_PROXY; delete process.env.http_proxy; delete process.env.https_proxy; resetStockConfig(); const cfg = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); expect(cfg.database.mongodb.readOnly).toBe(true); expect(cfg.service.serviceName).toBe('data-pipeline'); expect(cfg.queue?.enableScheduledJobs).toBe(false); // Omitting { mongoReadOnly: true } must fail closed during initializeStockConfig resetStockConfig(); expect(() => initializeStockConfig('dataPipeline')).toThrow( /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ ); } finally { for (const key of envKeys) { if (savedEnv[key] === undefined) { delete process.env[key]; } else { process.env[key] = savedEnv[key]; } } resetStockConfig(); } }); test('blocks development dataPipeline from reading QA MongoDB with trading_admin even when readOnly=true or escape hatch is set', () => { const cfg = makeConfig({ environment: 'development', mongoReadUri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', mongoReadOnly: true, }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true' }) ).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/); }); test('blocks development dataPipeline from reading QA MongoDB when readOnly is false', () => { const cfg = makeConfig({ environment: 'development', mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock', mongoReadOnly: false, }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow( /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ ); }); test('blocks loopback :27017 URI omitting /stock for both dataIngestion and non-readOnly dataPipeline', () => { const ingestionCfg = makeConfig({ environment: 'development', mongoUri: 'mongodb://trading_admin:pass@localhost:27017', mongoDatabase: 'other_db', }); expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow( /cannot open a writable MongoDB connection to QA MongoDB/ ); expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', }) ).not.toThrow(); const ipv6IngestionCfg = makeConfig({ environment: 'development', mongoUri: 'mongodb://trading_admin:pass@[::1]:27017', mongoDatabase: 'other_db', }); expect(() => assertEnvironmentSafety(ipv6IngestionCfg, 'dataIngestion', {})).toThrow( /cannot open a writable MongoDB connection to QA MongoDB/ ); const pipelineCfg = makeConfig({ environment: 'development', mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017', mongoReadOnly: false, mongoDatabase: 'other_db', }); expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow( /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ ); }); 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@[0:0:0:0:0:0:0:0001]:27017/stock', 'mongodb://u:p@[::ffff:7f00:1]:27017/stock', 'mongodb://u:p@[::ffff:7f00:0001]/stock', 'mongodb://u:p@[::ffff:7f01:0203]:27017/stock', 'mongodb://u:p@[0:0:0:0:0:ffff:7f00:1]:27017/stock', 'mongodb://u:p@[::ffff:127.0.0.2]:27017/stock', '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/ ); } // Non-loopback IPv4-mapped IPv6 addresses must not false-positive as QA loopback const nonLoopbackMappedCfg = makeConfig({ environment: 'development', mongoUri: 'mongodb://u:p@[::ffff:0a00:1]:27017/stock_dev', mongoDatabase: 'stock_dev', }); expect(() => assertEnvironmentSafety(nonLoopbackMappedCfg, 'dataIngestion', {})).not.toThrow(); }); 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 = [ { uri: 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock', malformed: false }, { uri: 'mongodb://localhost:27017,localhost:27018/stock', malformed: false }, { uri: 'mongodb://u:p@localhost:/stock', malformed: false }, { uri: 'mongodb://u:p@[::1]:/stock', malformed: false }, { uri: 'mongodb://u:p@bad:port,localhost:27017/stock', malformed: true }, ]; for (const { uri: mongoUri, malformed } of edgeCaseUris) { const cfg = makeConfig({ environment: 'development', mongoUri, mongoDatabase: 'stock', bypassSchemaValidation: malformed, }); 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('initializeStockConfig validates and guards multi-host MongoDB seed lists end-to-end', () => { const envKeys = [ 'NODE_ENV', 'POSTGRES_HOST', 'POSTGRES_PORT', 'POSTGRES_DB', 'POSTGRES_USER', 'POSTGRES_PASSWORD', 'MONGODB_URI', 'MONGODB_READ_URI', 'MONGODB_DATABASE', 'HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy', ] as const; const savedEnv: Partial> = {}; for (const key of envKeys) { savedEnv[key] = process.env[key]; } try { process.env.NODE_ENV = 'development'; process.env.POSTGRES_HOST = 'localhost'; process.env.POSTGRES_PORT = '5433'; process.env.POSTGRES_DB = 'trading_bot_dev'; process.env.POSTGRES_USER = 'dev_user'; process.env.POSTGRES_PASSWORD = 'dev_pass'; process.env.MONGODB_URI = 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin'; process.env.MONGODB_READ_URI = 'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock'; process.env.MONGODB_DATABASE = 'stock_dev'; delete process.env.HTTP_PROXY; delete process.env.HTTPS_PROXY; delete process.env.http_proxy; delete process.env.https_proxy; // Approved dev seed list passes schema validation and guard for dataIngestion resetStockConfig(); const ingestionCfg = initializeStockConfig('dataIngestion'); expect(ingestionCfg.database.mongodb.uri).toBe(process.env.MONGODB_URI); // Approved QA read-only seed list passes schema validation and guard for dataPipeline resetStockConfig(); const pipelineCfg = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); expect(pipelineCfg.database.mongodb.readUri).toBe(process.env.MONGODB_READ_URI); expect(pipelineCfg.database.mongodb.readOnly).toBe(true); // Guarded QA seed list passes schema validation and is blocked by the safety guard process.env.MONGODB_URI = 'mongodb://trading_admin:trading_mongo_dev@[::ffff:7f00:1]:27017/stock?authSource=admin'; resetStockConfig(); expect(() => initializeStockConfig('dataIngestion')).toThrow( /cannot open a writable MongoDB connection to QA MongoDB/ ); } finally { for (const key of envKeys) { if (savedEnv[key] === undefined) { delete process.env[key]; } else { process.env[key] = savedEnv[key]; } } resetStockConfig(); } }); test('blocks qa environment from targeting *_dev databases', () => { const cfg = makeConfig({ environment: 'qa', pgPort: 5433, pgDatabase: 'trading_bot_dev', }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow( /qa environment cannot target dev PostgreSQL/ ); }); test('blocks production from using dev/placeholder credentials or disabling auth', () => { const withDevPass = makeConfig({ environment: 'production', pgHost: 'pg.prod.internal', pgDatabase: 'trading_bot_prod', pgPassword: 'trading_pass_dev', mongoUri: 'mongodb://prod:strongpass@mongo.prod.internal:27017/stock', }); expect(() => assertEnvironmentSafety(withDevPass, 'webApi', {})).toThrow( /default dev\/qa credential/ ); const withSafeSecrets = makeConfig({ environment: 'production', pgHost: 'pg.prod.internal', pgDatabase: 'trading_bot_prod', pgPassword: 'super-strong-prod-password', mongoUri: 'mongodb://prod:strongpass@mongo.prod.internal:27017/stock', }); expect(() => assertEnvironmentSafety(withSafeSecrets, 'webApi', { STOCK_BOT_AUTH_DISABLED: 'true' }) ).toThrow(/STOCK_BOT_AUTH_DISABLED=true is forbidden/); expect(() => assertEnvironmentSafety(withSafeSecrets, 'webApi', {})).not.toThrow(); }); }); describe('MongoDBClient read-only enforcement', () => { const logger = getLogger('mongo-readonly-test'); const roClient = new MongoDBClient( { host: 'localhost', port: 27017, database: 'stock', readOnly: true, }, logger ); test('rejects all write and schema-mutation operations when readOnly=true', async () => { expect(roClient.isReadOnly()).toBe(true); await expect( roClient.insertOne('qmSymbols', { source: 'test' } as never) ).rejects.toThrow(/read-only mode/); await expect(roClient.insertMany('qmSymbols', [{ a: 1 }])).rejects.toThrow(/read-only mode/); await expect(roClient.updateOne('qmSymbols', {}, { $set: { a: 1 } })).rejects.toThrow( /read-only mode/ ); await expect(roClient.updateMany('qmSymbols', {}, { $set: { a: 1 } })).rejects.toThrow( /read-only mode/ ); await expect(roClient.deleteOne('qmSymbols', {})).rejects.toThrow(/read-only mode/); await expect(roClient.deleteMany('qmSymbols', {})).rejects.toThrow(/read-only mode/); await expect(roClient.batchUpsert('qmSymbols', [], 'symbol')).rejects.toThrow(/read-only mode/); await expect(roClient.createIndex('qmSymbols', { symbol: 1 })).rejects.toThrow(/read-only mode/); await expect(roClient.dropIndex('qmSymbols', 'symbol_1')).rejects.toThrow(/read-only mode/); await expect(roClient.createCollection('tmp')).rejects.toThrow(/read-only mode/); await expect(roClient.dropCollection('tmp')).rejects.toThrow(/read-only mode/); await expect( roClient.aggregate('qmSymbols', [{ $match: {} }, { $out: 'evil' }]) ).rejects.toThrow(/aggregation stage "\$out" is forbidden/); await expect( roClient.aggregate('qmSymbols', [{ $merge: { into: 'evil' } }]) ).rejects.toThrow(/aggregation stage "\$merge" is forbidden/); }); test('wraps getDatabase/getCollection/collection in fail-closed read-only proxies', () => { const fakeCollection = { collectionName: 'qmSymbols', find: () => ({ toArray: async () => [{ symbol: 'AAPL' }] }), aggregate: () => ({ toArray: async () => [] }), insertOne: async () => ({}), updateOne: async () => ({}), deleteOne: async () => ({}), bulkWrite: async () => ({}), drop: async () => true, }; const fakeDb = { databaseName: 'stock', collection: () => fakeCollection, listCollections: () => ({ toArray: async () => [] }), createCollection: async () => ({}), dropCollection: async () => true, dropDatabase: async () => true, command: async () => ({}), }; const attached = new MongoDBClient( { host: 'localhost', port: 27017, database: 'stock', readOnly: true }, logger ); Object.assign(attached, { client: { db: () => fakeDb }, db: fakeDb, isConnected: true, }); // Safe read accessors succeed expect(attached.getDatabase().databaseName).toBe('stock'); expect(typeof attached.getDatabase().collection('qmSymbols').find).toBe('function'); // Escape-hatch mutations on getDatabase(), getDb(), database, getCollection(), collection() fail closed expect(() => attached.getDatabase().createCollection('evil')).toThrow(/read-only mode/); expect(() => attached.getDb().dropDatabase()).toThrow(/read-only mode/); expect(() => attached.database!.command({ dropDatabase: 1 })).toThrow(/read-only mode/); expect(() => attached.getCollection('qmSymbols').insertOne({ a: 1 })).toThrow(/read-only mode/); expect(() => attached.collection('qmSymbols').bulkWrite([])).toThrow(/read-only mode/); expect(() => attached.getDatabase().collection('qmSymbols').deleteOne({})).toThrow( /read-only mode/ ); expect(() => attached.getCollection('qmSymbols').aggregate([{ $out: 'hijack' }]) ).toThrow(/aggregation stage "\$out" is forbidden/); }); test('ServiceContainerBuilder resolves readUri and read-only mode when mongoReadOnly=true', async () => { const cfg = makeConfig({ environment: 'development' }); const { container, shutdown } = await new ServiceContainerBuilder() .withConfig(cfg) .withOptions({ enableMongoDB: true, mongoReadOnly: true, enablePostgres: false, enableQuestDB: false, enableCache: false, enableQueue: false, enableBrowser: false, enableProxy: false, skipInitialization: true, }) .buildOwned(); try { const mongo = container.resolve('mongoClient'); expect(mongo).not.toBeNull(); expect(mongo!.isReadOnly()).toBe(true); expect(mongo!.getDefaultDatabase()).toBe('stock'); } finally { await shutdown(); } }); test('ServiceContainerBuilder extracts database from multi-host readUri when mongoReadOnly=true', async () => { const cfg = makeConfig({ environment: 'development', mongoUri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin', mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock', mongoDatabase: 'stock_dev', mongoReadOnly: true, }); const { container, shutdown } = await new ServiceContainerBuilder() .withConfig(cfg) .withOptions({ enableMongoDB: true, mongoReadOnly: true, enablePostgres: false, enableQuestDB: false, enableCache: false, enableQueue: false, enableBrowser: false, enableProxy: false, skipInitialization: true, }) .buildOwned(); try { const mongo = container.resolve('mongoClient'); expect(mongo).not.toBeNull(); expect(mongo!.isReadOnly()).toBe(true); expect(mongo!.getDefaultDatabase()).toBe('stock'); } finally { await shutdown(); } }); });