From 7cf940afce3f49d6d6a70a0e01167f2363253e80 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 01:39:15 -0500 Subject: [PATCH] =?UTF-8?q?T-7:=20M0.3a=20=E2=80=94=20Harden=20dev=20Mongo?= =?UTF-8?q?=20safety:=20env-safety=20throws=20on=20unsafe=20data-pipeline?= =?UTF-8?q?=20QA=20reads,=20scheduled=20jobs=20default=20off,=20read-only?= =?UTF-8?q?=20bypass=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/stock/config/config/default.json | 2 +- apps/stock/config/src/config-instance.ts | 23 +- apps/stock/config/src/env-safety.ts | 26 +-- apps/stock/config/src/index.ts | 1 + apps/stock/data-pipeline/src/index.ts | 4 +- .../core/config/src/schemas/service.schema.ts | 2 +- libs/core/config/test/env.loader.test.ts | 17 ++ libs/core/config/test/schemas.test.ts | 8 +- .../di/src/config/schemas/service.schema.ts | 2 +- libs/core/di/src/container/builder.ts | 2 +- libs/core/di/src/service-application.ts | 2 +- libs/core/di/test/service-application.test.ts | 63 ++++- test/unit/environment-safety.test.ts | 61 ++++- test/unit/mongodb-read-only.test.ts | 220 ++++++++++++++++++ 14 files changed, 407 insertions(+), 26 deletions(-) create mode 100644 test/unit/mongodb-read-only.test.ts diff --git a/apps/stock/config/config/default.json b/apps/stock/config/config/default.json index 082a601b..e34d7aca 100644 --- a/apps/stock/config/config/default.json +++ b/apps/stock/config/config/default.json @@ -79,7 +79,7 @@ }, "workers": 5, "concurrency": 2, - "enableScheduledJobs": true, + "enableScheduledJobs": false, "defaultJobOptions": { "attempts": 3, "backoff": { diff --git a/apps/stock/config/src/config-instance.ts b/apps/stock/config/src/config-instance.ts index 67fb5d7b..b5eda87a 100644 --- a/apps/stock/config/src/config-instance.ts +++ b/apps/stock/config/src/config-instance.ts @@ -11,12 +11,18 @@ let configInstance: ConfigManager | null = null; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); +export interface InitializeStockConfigOptions { + mongoReadOnly?: boolean; +} + /** * Initialize the stock application configuration * @param serviceName - Optional service name to override port configuration + * @param options - Optional initialization overrides (e.g. mongoReadOnly) */ export function initializeStockConfig( - serviceName?: StockServiceName + serviceName?: StockServiceName, + options?: InitializeStockConfigOptions ): StockAppConfig { try { if (!configInstance) { @@ -25,7 +31,20 @@ export function initializeStockConfig( }); } - const config = configInstance.initialize(stockAppSchema); + const rawConfig = configInstance.initialize(stockAppSchema); + const config: StockAppConfig = + options?.mongoReadOnly === true + ? { + ...rawConfig, + database: { + ...rawConfig.database, + mongodb: { + ...rawConfig.database.mongodb, + readOnly: true, + }, + }, + } + : rawConfig; assertEnvironmentSafety(config, serviceName); // If a service name is provided, override the service port diff --git a/apps/stock/config/src/env-safety.ts b/apps/stock/config/src/env-safety.ts index 9d65e22f..d4187560 100644 --- a/apps/stock/config/src/env-safety.ts +++ b/apps/stock/config/src/env-safety.ts @@ -1,4 +1,3 @@ -import { getLogger } from '@stock-bot/logger'; import type { StockAppConfig } from './schemas'; export type StockServiceName = 'dataIngestion' | 'dataPipeline' | 'webApi' | 'orchestrator'; @@ -17,7 +16,8 @@ function isLoopbackHost(host?: string): boolean { if (!host) { return false; } - return LOOPBACK_HOSTS.has(host.toLowerCase()); + const normalized = host.replace(/^\[|\]$/g, '').toLowerCase(); + return LOOPBACK_HOSTS.has(normalized); } function parseMongoTarget(uri?: string): { @@ -44,10 +44,9 @@ function parseMongoTarget(uri?: string): { } } -function isQaMongoTarget(uri: string | undefined, fallbackDb?: string): boolean { +function isQaMongoTarget(uri: string | undefined): boolean { const target = parseMongoTarget(uri); - const db = target.database || fallbackDb; - return isLoopbackHost(target.host) && target.port === 27017 && db === 'stock'; + return isLoopbackHost(target.host) && target.port === 27017; } function isQaPostgresTarget(pg: StockAppConfig['database']['postgres']): boolean { @@ -63,7 +62,6 @@ export function assertEnvironmentSafety( serviceName?: StockServiceName, env: Record = process.env ): void { - const logger = getLogger('stock-config-safety'); const environment = config.environment; if (environment === 'test') { @@ -86,19 +84,21 @@ export function assertEnvironmentSafety( const mongo = config.database.mongodb; if (mongo.enabled) { if (isReadOnlyPipeline) { - const readTarget = parseMongoTarget(mongo.readUri ?? mongo.uri); + const effectiveUri = mongo.readUri ?? mongo.uri; + const readTarget = parseMongoTarget(effectiveUri); if ( - isQaMongoTarget(mongo.readUri ?? mongo.uri, mongo.database) && - readTarget.username === 'trading_admin' + isQaMongoTarget(effectiveUri) && + (mongo.readOnly !== true || readTarget.username === 'trading_admin') ) { - logger.warn( - 'Development data-pipeline is reading QA MongoDB using admin credentials; ' + - 'configure MONGODB_READ_URI with the read-only user (studio_stock_bot_read) for defense in depth.' + throw new Error( + 'Safety guard: development data-pipeline cannot read QA MongoDB (localhost:27017) ' + + 'with admin credentials or without read-only mode enabled. ' + + 'Configure MONGODB_READ_URI with the read-only user (studio_stock_bot_read) and enable mongoReadOnly: true.' ); } } else if ( !mongo.readOnly && - isQaMongoTarget(mongo.uri, mongo.database) && + isQaMongoTarget(mongo.uri) && env.STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE !== 'true' ) { throw new Error( diff --git a/apps/stock/config/src/index.ts b/apps/stock/config/src/index.ts index 28ced46f..82123add 100644 --- a/apps/stock/config/src/index.ts +++ b/apps/stock/config/src/index.ts @@ -9,6 +9,7 @@ export { getProviderConfig, isFeatureEnabled, resetStockConfig, + type InitializeStockConfigOptions, } from './config-instance'; // Export environment safety guard diff --git a/apps/stock/data-pipeline/src/index.ts b/apps/stock/data-pipeline/src/index.ts index 98cf0e36..11ddfeda 100644 --- a/apps/stock/data-pipeline/src/index.ts +++ b/apps/stock/data-pipeline/src/index.ts @@ -11,7 +11,7 @@ import { createRoutes } from './routes/create-routes'; import { initializeAllHandlers } from './handlers'; // Initialize configuration with service-specific overrides -const config = initializeStockConfig('dataPipeline'); +const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); const security = createHttpSecurity({ ...httpSecurityOptions(), environment: config.environment }); // Log the full configuration @@ -29,7 +29,7 @@ const app = new ServiceApplication( serviceName: 'data-pipeline', hostname: security.hostname, enableHandlers: true, - enableScheduledJobs: config.queue?.enableScheduledJobs ?? true, + enableScheduledJobs: config.queue?.enableScheduledJobs ?? false, corsConfig: { origin: '*', allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'], diff --git a/libs/core/config/src/schemas/service.schema.ts b/libs/core/config/src/schemas/service.schema.ts index f92361ca..9986c8ae 100644 --- a/libs/core/config/src/schemas/service.schema.ts +++ b/libs/core/config/src/schemas/service.schema.ts @@ -44,7 +44,7 @@ export const queueConfigSchema = z.object({ }), workers: z.number().default(1), concurrency: z.number().default(1), - enableScheduledJobs: z.boolean().default(true), + enableScheduledJobs: z.boolean().default(false), defaultJobOptions: z .object({ attempts: z.number().default(3), diff --git a/libs/core/config/test/env.loader.test.ts b/libs/core/config/test/env.loader.test.ts index cd8bfe57..b6c37589 100644 --- a/libs/core/config/test/env.loader.test.ts +++ b/libs/core/config/test/env.loader.test.ts @@ -2,6 +2,7 @@ import { readFileSync } from 'fs'; import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import { ConfigLoaderError } from '../src/errors'; import { EnvLoader } from '../src/loaders/env.loader'; +import { queueConfigSchema } from '../src/schemas'; // Mock fs module mock.module('fs', () => ({ @@ -251,6 +252,22 @@ describe('EnvLoader', () => { }); }); + it('should map QUEUE_ENABLE_SCHEDULED_JOBS=true while defaulting unset to false in schema', () => { + loader = new EnvLoader(); + const unsetConfig = loader.load(); + expect((unsetConfig.queue as Record | undefined)?.enableScheduledJobs).toBeUndefined(); + expect(queueConfigSchema.parse({ redis: {}, ...(unsetConfig.queue as object) }).enableScheduledJobs).toBe( + false + ); + + process.env.QUEUE_ENABLE_SCHEDULED_JOBS = 'true'; + const optedInConfig = loader.load(); + expect((optedInConfig.queue as Record | undefined)?.enableScheduledJobs).toBe(true); + expect( + queueConfigSchema.parse({ redis: {}, ...(optedInConfig.queue as object) }).enableScheduledJobs + ).toBe(true); + }); + it('should not apply provider mappings when prefix is set', () => { process.env.APP_WEBSHARE_API_KEY = 'key'; diff --git a/libs/core/config/test/schemas.test.ts b/libs/core/config/test/schemas.test.ts index 61414a93..4cee74d2 100644 --- a/libs/core/config/test/schemas.test.ts +++ b/libs/core/config/test/schemas.test.ts @@ -214,7 +214,7 @@ describe('Config Schemas', () => { }, workers: 1, concurrency: 1, - enableScheduledJobs: true, + enableScheduledJobs: false, defaultJobOptions: { attempts: 3, backoff: { @@ -253,6 +253,12 @@ describe('Config Schemas', () => { const config = queueConfigSchema.parse(input); expect(config).toEqual(input); + + const optedIn = queueConfigSchema.parse({ + redis: {}, + enableScheduledJobs: true, + }); + expect(optedIn.enableScheduledJobs).toBe(true); }); it('should validate backoff type', () => { diff --git a/libs/core/di/src/config/schemas/service.schema.ts b/libs/core/di/src/config/schemas/service.schema.ts index 73ba1947..1496a99b 100644 --- a/libs/core/di/src/config/schemas/service.schema.ts +++ b/libs/core/di/src/config/schemas/service.schema.ts @@ -21,7 +21,7 @@ export const queueConfigSchema = z.object({ enabled: z.boolean().optional().default(true), workers: z.number().optional().default(1), concurrency: z.number().optional().default(1), - enableScheduledJobs: z.boolean().optional().default(true), + enableScheduledJobs: z.boolean().optional().default(false), defaultJobOptions: z .object({ attempts: z.number().default(3), diff --git a/libs/core/di/src/container/builder.ts b/libs/core/di/src/container/builder.ts index 6ea7bd49..bfcce6b1 100644 --- a/libs/core/di/src/container/builder.ts +++ b/libs/core/di/src/container/builder.ts @@ -209,7 +209,7 @@ export class ServiceContainerBuilder { enabled: true, workers: 1, concurrency: 1, - enableScheduledJobs: true, + enableScheduledJobs: false, defaultJobOptions: { attempts: 3, backoff: { type: 'exponential' as const, delay: 1000 }, diff --git a/libs/core/di/src/service-application.ts b/libs/core/di/src/service-application.ts index d2a82f38..90210af1 100644 --- a/libs/core/di/src/service-application.ts +++ b/libs/core/di/src/service-application.ts @@ -441,7 +441,7 @@ export class ServiceApplication { // Initialize scheduled jobs if enabled in both serviceConfig and runtime queue config const scheduledJobsEnabled = - this.serviceConfig.enableScheduledJobs && (this.config.queue?.enableScheduledJobs ?? true); + this.serviceConfig.enableScheduledJobs && (this.config.queue?.enableScheduledJobs ?? false); if (scheduledJobsEnabled) { await this.initializeScheduledJobs(); } else { diff --git a/libs/core/di/test/service-application.test.ts b/libs/core/di/test/service-application.test.ts index 2d07aea8..36f1059d 100644 --- a/libs/core/di/test/service-application.test.ts +++ b/libs/core/di/test/service-application.test.ts @@ -366,7 +366,18 @@ describe('ServiceApplication', () => { const jobContainerFactory = mock(async () => containerWithJobs); - app = new ServiceApplication(mockConfig, serviceConfig); + const configWithScheduledJobs = { + ...mockConfig, + queue: { + enabled: true, + redis: { host: 'localhost', port: 6379, db: 1 }, + workers: 1, + concurrency: 1, + enableScheduledJobs: true, + }, + }; + + app = new ServiceApplication(configWithScheduledJobs as any, serviceConfig); await app.start(jobContainerFactory, mockRouteFactory); @@ -382,6 +393,56 @@ describe('ServiceApplication', () => { expect(mockQueueManager.startAllWorkers).toHaveBeenCalled(); expect(mockLogger.info).toHaveBeenCalledWith('Scheduled jobs created', { totalJobs: 1 }); }); + + it('should skip scheduled jobs and still start workers when queue.enableScheduledJobs is omitted or false', async () => { + const serviceConfig: ServiceApplicationConfig = { + serviceName: 'test-service', + enableScheduledJobs: true, + }; + + for (const runtimeConfig of [ + mockConfig, + { + ...mockConfig, + queue: { + enabled: true, + redis: { host: 'localhost', port: 6379, db: 1 }, + workers: 1, + concurrency: 1, + enableScheduledJobs: false, + }, + }, + ]) { + const mockQueue = { + addScheduledJob: mock(() => Promise.resolve()), + }; + + const mockQueueManager = { + getQueue: mock(() => mockQueue), + startAllWorkers: mock(() => {}), + shutdown: mock(() => Promise.resolve()), + }; + + const containerWithJobs = { + resolve: mock((name: string) => { + if (name === 'serviceContainer') { + return { test: 'container' }; + } + if (name === 'queueManager') { + return mockQueueManager; + } + return null; + }), + }; + + app = new ServiceApplication(runtimeConfig as any, serviceConfig); + await app.start(async () => containerWithJobs as any, mockRouteFactory); + + expect(mockQueueManager.getQueue).not.toHaveBeenCalled(); + expect(mockQueue.addScheduledJob).not.toHaveBeenCalled(); + expect(mockQueueManager.startAllWorkers).toHaveBeenCalledTimes(1); + } + }); }); describe('stop method', () => { diff --git a/test/unit/environment-safety.test.ts b/test/unit/environment-safety.test.ts index f49c5650..d63cb243 100644 --- a/test/unit/environment-safety.test.ts +++ b/test/unit/environment-safety.test.ts @@ -116,11 +116,68 @@ describe('Environment safety & multi-env isolation', () => { expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow(); }); - test('allows development dataPipeline to read QA MongoDB via readUri while writing dev Postgres', () => { - const cfg = makeConfig({ environment: 'development' }); + 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('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 qa environment from targeting *_dev databases', () => { const cfg = makeConfig({ environment: 'qa', diff --git a/test/unit/mongodb-read-only.test.ts b/test/unit/mongodb-read-only.test.ts new file mode 100644 index 00000000..7c279f86 --- /dev/null +++ b/test/unit/mongodb-read-only.test.ts @@ -0,0 +1,220 @@ +import { describe, expect, mock, test } from 'bun:test'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { MongoDBClient } from '@stock-bot/mongodb'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); + +function createStubbedClient(readOnly: boolean) { + const logger = getLogger('mongodb-read-only-unit-test'); + + const collectionStub = { + collectionName: 'eodPrices', + dbName: 'stock', + namespace: 'stock.eodPrices', + // Safe read methods + find: mock(() => ({ toArray: async () => [{ symbol: 'AAPL', close: 200 }] })), + findOne: mock(async () => ({ symbol: 'AAPL', close: 200 })), + countDocuments: mock(async () => 42), + estimatedDocumentCount: mock(async () => 100), + distinct: mock(async () => ['AAPL', 'MSFT']), + listIndexes: mock(() => ({ toArray: async () => [{ name: '_id_' }] })), + aggregate: mock(() => ({ toArray: async () => [{ _id: 'AAPL', count: 5 }] })), + // Write & DDL methods + insertOne: mock(async () => ({ insertedId: 'id-1' })), + insertMany: mock(async () => ({ insertedCount: 1, insertedIds: { 0: 'id-1' } })), + updateOne: mock(async () => ({ matchedCount: 1, modifiedCount: 1, upsertedCount: 0, upsertedId: null })), + updateMany: mock(async () => ({ matchedCount: 1, modifiedCount: 1, upsertedCount: 0, upsertedId: null })), + deleteOne: mock(async () => ({ deletedCount: 1 })), + deleteMany: mock(async () => ({ deletedCount: 1 })), + bulkWrite: mock(async () => ({ upsertedCount: 1, modifiedCount: 0 })), + createIndex: mock(async () => 'symbol_1'), + dropIndex: mock(async () => ({})), + drop: mock(async () => true), + rename: mock(async () => ({})), + }; + + const dbStub = { + databaseName: 'stock', + namespace: 'stock', + collection: mock(() => collectionStub), + listCollections: mock(() => ({ toArray: async () => [{ name: 'eodPrices' }] })), + stats: mock(async () => ({ ok: 1 })), + createCollection: mock(async () => collectionStub), + dropCollection: mock(async () => true), + dropDatabase: mock(async () => true), + command: mock(async () => ({ ok: 1 })), + }; + + const client = new MongoDBClient( + { + host: 'localhost', + port: 27017, + database: 'stock', + readOnly, + }, + logger + ); + + // Inject stubbed driver objects directly so zero network sockets are opened + Object.assign(client, { + client: { db: mock(() => dbStub) }, + db: dbStub, + isConnected: true, + }); + + return { client, dbStub, collectionStub }; +} + +function assertZeroMutationCalls( + dbStub: ReturnType['dbStub'], + collectionStub: ReturnType['collectionStub'] +) { + expect(collectionStub.insertOne).not.toHaveBeenCalled(); + expect(collectionStub.insertMany).not.toHaveBeenCalled(); + expect(collectionStub.updateOne).not.toHaveBeenCalled(); + expect(collectionStub.updateMany).not.toHaveBeenCalled(); + expect(collectionStub.deleteOne).not.toHaveBeenCalled(); + expect(collectionStub.deleteMany).not.toHaveBeenCalled(); + expect(collectionStub.bulkWrite).not.toHaveBeenCalled(); + expect(collectionStub.createIndex).not.toHaveBeenCalled(); + expect(collectionStub.dropIndex).not.toHaveBeenCalled(); + expect(collectionStub.drop).not.toHaveBeenCalled(); + expect(collectionStub.rename).not.toHaveBeenCalled(); + expect(dbStub.createCollection).not.toHaveBeenCalled(); + expect(dbStub.dropCollection).not.toHaveBeenCalled(); + expect(dbStub.dropDatabase).not.toHaveBeenCalled(); + expect(dbStub.command).not.toHaveBeenCalled(); +} + +describe('MongoDBClient read-only mode (offline)', () => { + test('blocks all direct client write and DDL methods without calling driver stubs', async () => { + const { client, dbStub, collectionStub } = createStubbedClient(true); + + expect(client.isReadOnly()).toBe(true); + await expect(client.insertOne('x', { symbol: 'AAPL' } as never)).rejects.toThrow(/read-only mode/); + await expect(client.insertMany('x', [{ symbol: 'AAPL' }])).rejects.toThrow(/read-only mode/); + await expect(client.updateOne('x', { symbol: 'AAPL' }, { $set: { close: 1 } })).rejects.toThrow( + /read-only mode/ + ); + await expect(client.updateMany('x', {}, { $set: { close: 1 } })).rejects.toThrow(/read-only mode/); + await expect(client.deleteOne('x', { symbol: 'AAPL' })).rejects.toThrow(/read-only mode/); + await expect(client.deleteMany('x', {})).rejects.toThrow(/read-only mode/); + await expect(client.batchUpsert('x', [{ symbol: 'AAPL' } as never], 'symbol')).rejects.toThrow( + /read-only mode/ + ); + await expect(client.createIndex('x', { symbol: 1 })).rejects.toThrow(/read-only mode/); + await expect(client.dropIndex('x', 'symbol_1')).rejects.toThrow(/read-only mode/); + await expect(client.createCollection('x')).rejects.toThrow(/read-only mode/); + await expect(client.dropCollection('x')).rejects.toThrow(/read-only mode/); + + assertZeroMutationCalls(dbStub, collectionStub); + }); + + test('blocks mutations through getDatabase, getDb, database, getCollection, and collection proxies', () => { + const { client, dbStub, collectionStub } = createStubbedClient(true); + + // Collection write paths through every accessor + expect(() => client.getDatabase().collection('x').insertOne({ a: 1 })).toThrow(/read-only mode/); + expect(() => client.getDb().collection('x').updateOne({ a: 1 }, { $set: { b: 2 } })).toThrow( + /read-only mode/ + ); + expect(() => client.database!.collection('x').deleteMany({})).toThrow(/read-only mode/); + expect(() => client.getCollection('x').insertOne({ a: 1 })).toThrow(/read-only mode/); + expect(() => client.collection('x').bulkWrite([])).toThrow(/read-only mode/); + + // Collection DDL paths + expect(() => client.getCollection('x').createIndex({ symbol: 1 })).toThrow(/read-only mode/); + expect(() => client.collection('x').dropIndex('symbol_1')).toThrow(/read-only mode/); + expect(() => client.getDatabase().collection('x').drop()).toThrow(/read-only mode/); + expect(() => client.getDb().collection('x').rename('y')).toThrow(/read-only mode/); + + // Database DDL/admin paths + expect(() => client.getDatabase().createCollection('x')).toThrow(/read-only mode/); + expect(() => client.getDb().dropCollection('x')).toThrow(/read-only mode/); + expect(() => client.database!.dropDatabase()).toThrow(/read-only mode/); + expect(() => client.getDatabase().command({ dropDatabase: 1 })).toThrow(/read-only mode/); + + assertZeroMutationCalls(dbStub, collectionStub); + }); + + test('blocks $out and $merge aggregation stages (including nested) on client and proxied collections', async () => { + const { client, collectionStub } = createStubbedClient(true); + + const outPipeline = [{ $match: { symbol: 'AAPL' } }, { $out: 'hijacked' }]; + const mergePipeline = [{ $merge: { into: 'hijacked' } }]; + const nestedUnionWith = [ + { $unionWith: { coll: 'other', pipeline: [{ $out: 'hijacked' }] } }, + ]; + const nestedFacet = [ + { $facet: { branch: [{ $merge: { into: 'hijacked' } }] } }, + ]; + + await expect(client.aggregate('x', outPipeline)).rejects.toThrow(/read-only mode/); + await expect(client.aggregate('x', mergePipeline)).rejects.toThrow(/read-only mode/); + await expect(client.aggregate('x', nestedUnionWith)).rejects.toThrow(/read-only mode/); + await expect(client.aggregate('x', nestedFacet)).rejects.toThrow(/read-only mode/); + + expect(() => client.getCollection('x').aggregate(outPipeline)).toThrow(/read-only mode/); + expect(() => client.collection('x').aggregate(mergePipeline)).toThrow(/read-only mode/); + expect(() => client.getDatabase().collection('x').aggregate(nestedUnionWith)).toThrow( + /read-only mode/ + ); + expect(() => client.database!.collection('x').aggregate(nestedFacet)).toThrow(/read-only mode/); + + expect(collectionStub.aggregate).not.toHaveBeenCalled(); + }); + + test('passes through safe read operations on client and proxies', async () => { + const { client, dbStub, collectionStub } = createStubbedClient(true); + + expect(await client.find('eodPrices', { symbol: 'AAPL' })).toEqual([ + { symbol: 'AAPL', close: 200 }, + ]); + expect(await client.findOne('eodPrices', { symbol: 'AAPL' })).toEqual({ + symbol: 'AAPL', + close: 200, + }); + expect(await client.countDocuments('eodPrices', {})).toBe(42); + expect(await client.listIndexes('eodPrices')).toEqual([{ name: '_id_' }]); + expect(await client.listCollections()).toEqual([{ name: 'eodPrices' }]); + expect(await client.aggregate('eodPrices', [{ $match: { symbol: 'AAPL' } }])).toEqual([ + { _id: 'AAPL', count: 5 }, + ]); + + // Proxied read methods + expect(await client.getCollection('eodPrices').estimatedDocumentCount()).toBe(100); + expect(await client.collection('eodPrices').distinct('symbol')).toEqual(['AAPL', 'MSFT']); + expect( + await client.getDatabase().collection('eodPrices').find({ symbol: 'AAPL' }).toArray() + ).toEqual([{ symbol: 'AAPL', close: 200 }]); + expect( + await client + .getDb() + .collection('eodPrices') + .aggregate([{ $group: { _id: '$symbol' } }]) + .toArray() + ).toEqual([{ _id: 'AAPL', count: 5 }]); + + expect(collectionStub.find).toHaveBeenCalledTimes(2); + expect(collectionStub.findOne).toHaveBeenCalledTimes(1); + expect(collectionStub.countDocuments).toHaveBeenCalledTimes(1); + expect(collectionStub.estimatedDocumentCount).toHaveBeenCalledTimes(1); + expect(collectionStub.distinct).toHaveBeenCalledTimes(1); + expect(collectionStub.listIndexes).toHaveBeenCalledTimes(1); + expect(collectionStub.aggregate).toHaveBeenCalledTimes(2); + expect(dbStub.listCollections).toHaveBeenCalledTimes(1); + }); + + test('allows writes when readOnly is false (control check)', async () => { + const { client, dbStub, collectionStub } = createStubbedClient(false); + + expect(client.isReadOnly()).toBe(false); + const inserted = await client.insertOne('eodPrices', { symbol: 'AAPL' } as never); + expect((inserted as Record)._id).toBe('id-1'); + await client.getDatabase().collection('eodPrices').insertOne({ symbol: 'MSFT' }); + await client.getDatabase().createCollection('tmp'); + + expect(collectionStub.insertOne).toHaveBeenCalledTimes(2); + expect(dbStub.createCollection).toHaveBeenCalledTimes(1); + }); +});