From abbab4b5a8c538326536d26833c5da8365766402 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 01:47:31 -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/data-ingestion/src/index.ts | 2 +- .../src/registrations/service.registration.ts | 2 +- libs/core/di/src/service-application.ts | 50 ++++- libs/core/di/test/service-application.test.ts | 66 ++++++- libs/core/queue/src/queue-manager.ts | 74 +++++++- libs/core/queue/src/queue.ts | 60 ++++++ libs/core/queue/test/queue-class.test.ts | 51 ++++- libs/data/mongodb/src/client.ts | 177 +++++++++++++++++- test/unit/environment-safety.test.ts | 63 ++++++- test/unit/mongodb-read-only.test.ts | 117 +++++++++++- 10 files changed, 644 insertions(+), 18 deletions(-) diff --git a/apps/stock/data-ingestion/src/index.ts b/apps/stock/data-ingestion/src/index.ts index f76fc371..d0ff90e3 100644 --- a/apps/stock/data-ingestion/src/index.ts +++ b/apps/stock/data-ingestion/src/index.ts @@ -29,7 +29,7 @@ const app = new ServiceApplication( serviceName: 'data-ingestion', 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/di/src/registrations/service.registration.ts b/libs/core/di/src/registrations/service.registration.ts index 7a5b1f26..52ab0dc7 100644 --- a/libs/core/di/src/registrations/service.registration.ts +++ b/libs/core/di/src/registrations/service.registration.ts @@ -72,7 +72,7 @@ export function registerApplicationServices( concurrency: defined(config.queue).concurrency ?? 1, defaultJobOptions: defined(config.queue).defaultJobOptions, }, - enableScheduledJobs: defined(config.queue).enableScheduledJobs ?? true, + enableScheduledJobs: defined(config.queue).enableScheduledJobs ?? false, autoDiscoverHandlers: true, }; diff --git a/libs/core/di/src/service-application.ts b/libs/core/di/src/service-application.ts index 90210af1..d1e571bc 100644 --- a/libs/core/di/src/service-application.ts +++ b/libs/core/di/src/service-application.ts @@ -445,11 +445,7 @@ export class ServiceApplication { if (scheduledJobsEnabled) { await this.initializeScheduledJobs(); } else { - const queueManager = this.resolveOptional('queueManager'); - if (queueManager?.startAllWorkers) { - queueManager.startAllWorkers(); - this.logger.info('Queue workers started (scheduled cron jobs disabled)'); - } + await this.disableScheduledJobs(); } // Call before start hook @@ -487,6 +483,50 @@ export class ServiceApplication { } } + /** + * Reconcile and remove this service's persisted scheduled jobs before starting workers + * when scheduled jobs are disabled. + */ + private async disableScheduledJobs(): Promise { + const queueManager = this.resolveOptional('queueManager'); + if (!queueManager) { + return; + } + + const handlerRegistry = this.resolveOptional('handlerRegistry'); + const ownedHandlers = new Set(); + const currentService = this.config.service.serviceName; + + if (handlerRegistry) { + if (typeof handlerRegistry.getAllHandlersWithSchedule === 'function') { + for (const [handlerName] of handlerRegistry.getAllHandlersWithSchedule()) { + const ownerService = + typeof handlerRegistry.getHandlerService === 'function' + ? handlerRegistry.getHandlerService(handlerName) + : undefined; + if (!ownerService || ownerService === currentService) { + ownedHandlers.add(handlerName); + } + } + } + + if (currentService && typeof handlerRegistry.getServiceHandlers === 'function') { + for (const metadata of handlerRegistry.getServiceHandlers(currentService)) { + ownedHandlers.add(metadata.name); + } + } + } + + if (ownedHandlers.size > 0 && typeof queueManager.removeScheduledJobsForQueues === 'function') { + await queueManager.removeScheduledJobsForQueues(Array.from(ownedHandlers)); + } + + if (queueManager.startAllWorkers) { + queueManager.startAllWorkers(); + this.logger.info('Queue workers started (scheduled cron jobs disabled)'); + } + } + /** * Initialize scheduled jobs from handler registry */ diff --git a/libs/core/di/test/service-application.test.ts b/libs/core/di/test/service-application.test.ts index 36f1059d..50df9d3e 100644 --- a/libs/core/di/test/service-application.test.ts +++ b/libs/core/di/test/service-application.test.ts @@ -394,7 +394,7 @@ describe('ServiceApplication', () => { 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 () => { + it('should reconcile owned repeat schedules before starting workers when scheduling is disabled while preserving manual jobs and other services', async () => { const serviceConfig: ServiceApplicationConfig = { serviceName: 'test-service', enableScheduledJobs: true, @@ -413,13 +413,60 @@ describe('ServiceApplication', () => { }, }, ]) { + // Simulated shared queue store persisted across restarts + const repeatSchedules = new Map([ + ['{test-service_eod}', ['{test-service_eod}:crawl']], + ['{other-service_sync}', ['{other-service_sync}:daily']], + ]); + const queuedJobs = new Map>([ + [ + '{test-service_eod}', + [ + { id: 'repeat-1', repeatJobKey: '{test-service_eod}:crawl' }, + { id: 'manual-1' }, + ], + ], + [ + '{other-service_sync}', + [{ id: 'other-repeat-1', repeatJobKey: '{other-service_sync}:daily' }], + ], + ]); + const callOrder: string[] = []; + + const mockHandlerRegistry = { + getAllHandlersWithSchedule: () => + new Map([ + ['eod', { scheduledJobs: [{ operation: 'crawl', cronPattern: '0 * * * *' }] }], + ['sync', { scheduledJobs: [{ operation: 'daily', cronPattern: '0 0 * * *' }] }], + ]), + getHandlerService: (handlerName: string) => + handlerName === 'eod' ? 'test-service' : 'other-service', + getServiceHandlers: (svc: string) => + svc === 'test-service' ? [{ name: 'eod' }] : [{ name: 'sync' }], + }; + const mockQueue = { addScheduledJob: mock(() => Promise.resolve()), }; const mockQueueManager = { getQueue: mock(() => mockQueue), - startAllWorkers: mock(() => {}), + removeScheduledJobsForQueues: mock(async (handlers: string[]) => { + callOrder.push(`reconcile:${handlers.join(',')}`); + for (const handler of handlers) { + const fullName = `{test-service_${handler}}`; + repeatSchedules.delete(fullName); + const existing = queuedJobs.get(fullName) ?? []; + queuedJobs.set( + fullName, + existing.filter(job => !job.repeatJobKey) + ); + } + return handlers.length; + }), + startAllWorkers: mock(() => { + callOrder.push('startAllWorkers'); + }), shutdown: mock(() => Promise.resolve()), }; @@ -428,6 +475,9 @@ describe('ServiceApplication', () => { if (name === 'serviceContainer') { return { test: 'container' }; } + if (name === 'handlerRegistry') { + return mockHandlerRegistry; + } if (name === 'queueManager') { return mockQueueManager; } @@ -440,7 +490,19 @@ describe('ServiceApplication', () => { expect(mockQueueManager.getQueue).not.toHaveBeenCalled(); expect(mockQueue.addScheduledJob).not.toHaveBeenCalled(); + expect(mockQueueManager.removeScheduledJobsForQueues).toHaveBeenCalledWith(['eod']); expect(mockQueueManager.startAllWorkers).toHaveBeenCalledTimes(1); + // Reconciliation must complete before workers start consuming jobs + expect(callOrder).toEqual(['reconcile:eod', 'startAllWorkers']); + // Own repeat schedule & repeat-spawned job cleared; manual job & other service preserved + expect(repeatSchedules.has('{test-service_eod}')).toBe(false); + expect(queuedJobs.get('{test-service_eod}')).toEqual([{ id: 'manual-1' }]); + expect(repeatSchedules.get('{other-service_sync}')).toEqual([ + '{other-service_sync}:daily', + ]); + expect(queuedJobs.get('{other-service_sync}')).toEqual([ + { id: 'other-repeat-1', repeatJobKey: '{other-service_sync}:daily' }, + ]); } }); }); diff --git a/libs/core/queue/src/queue-manager.ts b/libs/core/queue/src/queue-manager.ts index ec621569..64a0917b 100644 --- a/libs/core/queue/src/queue-manager.ts +++ b/libs/core/queue/src/queue-manager.ts @@ -6,9 +6,13 @@ import type { HandlerRegistry } from '@stock-bot/handler-registry'; import { defined } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; import type { LoggerLike as Logger } from '@stock-bot/logger'; -import { Queue, type QueueWorkerConfig } from './queue'; +import { + Queue, + removeScheduledJobsFromBullQueue, + type QueueWorkerConfig, +} from './queue'; import { QueueRateLimiter } from './rate-limiter'; -import { getFullQueueName, parseQueueName } from './service-utils'; +import { getFullQueueName, normalizeServiceName, parseQueueName } from './service-utils'; import type { GlobalStats, JobData, @@ -558,6 +562,72 @@ export class QueueManager { }); } + /** + * Reconcile and remove persisted repeatable/scheduled jobs for the specified + * handler queues owned by this service without starting workers. + * Manual jobs and other services' queues are preserved. + */ + async removeScheduledJobsForQueues(queueNames: string[]): Promise { + this.assertConnectionsOpen(); + let totalRemoved = 0; + const seenFullNames = new Set(); + const normalizedService = this.serviceName + ? normalizeServiceName(this.serviceName) + : undefined; + + for (const rawQueueName of queueNames) { + let fullQueueName = rawQueueName; + let isOwnQueue = true; + + if (this.serviceName) { + const parsed = parseQueueName(rawQueueName); + if (parsed) { + fullQueueName = rawQueueName; + isOwnQueue = + parsed.service === this.serviceName || parsed.service === normalizedService; + } else { + fullQueueName = getFullQueueName(this.serviceName, rawQueueName); + isOwnQueue = true; + } + } + + if (!isOwnQueue || seenFullNames.has(fullQueueName)) { + continue; + } + seenFullNames.add(fullQueueName); + + const existingQueue = this.queues.get(fullQueueName); + if (existingQueue) { + totalRemoved += await existingQueue.removeAllScheduledJobs(); + continue; + } + + // Open a workerless BullQueue handle to clear persisted repeat schedules + // before any worker can consume stale repeat jobs. + const tempQueue = new BullQueue(fullQueueName, { + connection: { ...this.redisConnection, maxRetriesPerRequest: 1, enableOfflineQueue: false }, + }); + try { + totalRemoved += await removeScheduledJobsFromBullQueue(tempQueue); + } finally { + await tempQueue.close().catch(error => { + this.logger.warn('Error closing temporary reconciliation queue', { + queueName: fullQueueName, + error, + }); + }); + } + } + + this.logger.info('Reconciled disabled scheduled jobs for service queues', { + service: this.serviceName || 'default', + queueCount: seenFullNames.size, + removedCount: totalRemoved, + }); + + return totalRemoved; + } + /** * Wait for all queues to be ready */ diff --git a/libs/core/queue/src/queue.ts b/libs/core/queue/src/queue.ts index 3c303086..11e97f90 100644 --- a/libs/core/queue/src/queue.ts +++ b/libs/core/queue/src/queue.ts @@ -6,6 +6,53 @@ import type { QueueManager } from './queue-manager'; import type { ExtendedJobOptions, JobData, JobOptions, QueueStats, RedisConfig } from './types'; import { getRedisConnection } from './utils'; +export type SchedulableBullQueue = Pick< + BullQueue, + 'getRepeatableJobs' | 'removeRepeatableByKey' | 'getJobs' +> & + Partial>; + +/** + * Remove all persisted repeatable/scheduled jobs and any pending repeat-spawned + * job instances from a BullMQ queue while preserving manual (non-repeating) jobs. + */ +export async function removeScheduledJobsFromBullQueue( + bullQueue: SchedulableBullQueue +): Promise { + const removedKeys = new Set(); + + const repeatableJobs = await bullQueue.getRepeatableJobs(); + for (const job of repeatableJobs) { + if (job.key) { + await bullQueue.removeRepeatableByKey(job.key); + removedKeys.add(job.key); + } + } + + if ( + typeof bullQueue.getJobSchedulers === 'function' && + typeof bullQueue.removeJobScheduler === 'function' + ) { + const schedulers = await bullQueue.getJobSchedulers(); + for (const scheduler of schedulers) { + if (scheduler.key && !removedKeys.has(scheduler.key)) { + await bullQueue.removeJobScheduler(scheduler.key); + removedKeys.add(scheduler.key); + } + } + } + + const pendingJobs = await bullQueue.getJobs(['waiting', 'delayed']); + for (const job of pendingJobs) { + const repeatKey = job?.repeatJobKey ?? job?.opts?.repeatJobKey; + if (repeatKey) { + await job.remove(); + } + } + + return removedKeys.size; +} + export interface QueueWorkerConfig { workers?: number; concurrency?: number; @@ -167,6 +214,19 @@ export class Queue { return await this.bullQueue.add(name, data, scheduledOptions); } + /** + * Remove all persisted repeatable/scheduled jobs and any pending repeat-spawned + * occurrences from this queue while preserving manual jobs. + */ + async removeAllScheduledJobs(): Promise { + const removedCount = await removeScheduledJobsFromBullQueue(this.bullQueue); + this.logger.info('Removed scheduled jobs from queue', { + queueName: this.queueName, + removedCount, + }); + return removedCount; + } + /** * Get queue statistics */ diff --git a/libs/core/queue/test/queue-class.test.ts b/libs/core/queue/test/queue-class.test.ts index a8d1cd3a..c2b3be93 100644 --- a/libs/core/queue/test/queue-class.test.ts +++ b/libs/core/queue/test/queue-class.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, mock } from 'bun:test'; -import { Queue } from '../src/queue'; +import { Queue, removeScheduledJobsFromBullQueue } from '../src/queue'; import type { QueueWorkerConfig, RedisConfig } from '../src/types'; describe('Queue Class', () => { @@ -122,4 +122,53 @@ describe('Queue Class', () => { expect(queue.getWorkerCount()).toBe(0); }); }); + + describe('scheduled job reconciliation', () => { + it('removes repeatable jobs, job schedulers, and pending repeat instances while preserving manual jobs', async () => { + const removedRepeatKeys: string[] = []; + const removedSchedulerKeys: string[] = []; + const removedJobIds: string[] = []; + + const fakeBullQueue = { + getRepeatableJobs: mock(async () => [ + { key: '{data-ingestion_eod}:crawl', name: 'crawl' }, + ]), + removeRepeatableByKey: mock(async (key: string) => { + removedRepeatKeys.push(key); + return true; + }), + getJobSchedulers: mock(async () => [ + { key: '{data-ingestion_eod}:crawl', name: 'crawl' }, + { key: '{data-ingestion_eod}:intraday', name: 'intraday' }, + ]), + removeJobScheduler: mock(async (key: string) => { + removedSchedulerKeys.push(key); + return true; + }), + getJobs: mock(async () => [ + { + id: 'repeat-job-1', + repeatJobKey: '{data-ingestion_eod}:crawl', + remove: mock(async () => { + removedJobIds.push('repeat-job-1'); + }), + }, + { + id: 'manual-eod-job-1', + opts: {}, + remove: mock(async () => { + removedJobIds.push('manual-eod-job-1'); + }), + }, + ]), + }; + + const removedCount = await removeScheduledJobsFromBullQueue(fakeBullQueue as any); + + expect(removedCount).toBe(2); + expect(removedRepeatKeys).toEqual(['{data-ingestion_eod}:crawl']); + expect(removedSchedulerKeys).toEqual(['{data-ingestion_eod}:intraday']); + expect(removedJobIds).toEqual(['repeat-job-1']); + }); + }); }); diff --git a/libs/data/mongodb/src/client.ts b/libs/data/mongodb/src/client.ts index 2df9c41d..6787ff13 100644 --- a/libs/data/mongodb/src/client.ts +++ b/libs/data/mongodb/src/client.ts @@ -1,5 +1,6 @@ import type { AggregateOptions, + AggregationCursor, BulkWriteOptions, CountDocumentsOptions, CreateCollectionOptions, @@ -185,6 +186,170 @@ export class MongoDBClient { return this.client.db(databaseName || this.defaultDatabase); } + private wrapReadOnlyAggregationCursor( + cursor: AggregationCursor + ): AggregationCursor { + const assertCursorPipelineSafe = (): void => { + if (Array.isArray(cursor.pipeline)) { + this.assertReadOnlyPipeline(cursor.pipeline); + } + }; + + const wrapped: Record = { + get id() { + return cursor.id; + }, + get namespace() { + return cursor.namespace; + }, + get readPreference() { + return cursor.readPreference; + }, + get readConcern() { + return cursor.readConcern; + }, + get closed() { + return cursor.closed; + }, + get killed() { + return cursor.killed; + }, + get loadBalanced() { + return cursor.loadBalanced; + }, + get pipeline() { + return Object.freeze(Array.isArray(cursor.pipeline) ? [...cursor.pipeline] : []); + }, + // Read / iteration operations + toArray: () => { + assertCursorPipelineSafe(); + return cursor.toArray(); + }, + next: () => { + assertCursorPipelineSafe(); + return cursor.next(); + }, + tryNext: () => { + assertCursorPipelineSafe(); + return cursor.tryNext(); + }, + hasNext: () => { + assertCursorPipelineSafe(); + return cursor.hasNext(); + }, + forEach: (iterator: (doc: T) => boolean | void) => { + assertCursorPipelineSafe(); + return cursor.forEach(iterator); + }, + stream: (...args: Parameters['stream']>) => { + assertCursorPipelineSafe(); + return cursor.stream(...args); + }, + explain: (...args: Parameters['explain']>) => { + assertCursorPipelineSafe(); + return cursor.explain(...args); + }, + close: (...args: Parameters['close']>) => cursor.close(...args), + rewind: () => cursor.rewind(), + bufferedCount: () => cursor.bufferedCount(), + readBufferedDocuments: (count?: number) => cursor.readBufferedDocuments(count), + [Symbol.asyncIterator]: () => { + assertCursorPipelineSafe(); + return cursor[Symbol.asyncIterator](); + }, + [Symbol.asyncDispose]: () => { + const disposable = cursor as unknown as Partial Promise>>; + const dispose = disposable[Symbol.asyncDispose]; + return typeof dispose === 'function' ? dispose.call(cursor) : cursor.close(); + }, + // Fluent stage builders (read-only stages validated and wrapped) + out: () => { + throw new Error( + 'MongoDB client is configured in read-only mode; aggregation cursor operation "out" is forbidden' + ); + }, + addStage: (stage: Document) => { + this.assertReadOnlyPipeline([stage]); + cursor.addStage(stage); + return wrapped; + }, + lookup: ($lookup: Document) => { + this.assertReadOnlyPipeline([{ $lookup }]); + cursor.lookup($lookup); + return wrapped; + }, + match: ($match: Document) => { + cursor.match($match); + return wrapped; + }, + project: ($project: Document) => { + cursor.project($project); + return wrapped; + }, + group: ($group: Document) => { + cursor.group($group); + return wrapped; + }, + sort: ($sort: Parameters['sort']>[0]) => { + cursor.sort($sort); + return wrapped; + }, + limit: ($limit: number) => { + cursor.limit($limit); + return wrapped; + }, + skip: ($skip: number) => { + cursor.skip($skip); + return wrapped; + }, + unwind: ($unwind: Document | string) => { + cursor.unwind($unwind); + return wrapped; + }, + redact: ($redact: Document) => { + cursor.redact($redact); + return wrapped; + }, + geoNear: ($geoNear: Document) => { + cursor.geoNear($geoNear); + return wrapped; + }, + // Fluent cursor modifiers + batchSize: (value: number) => { + cursor.batchSize(value); + return wrapped; + }, + maxTimeMS: (value: number) => { + cursor.maxTimeMS(value); + return wrapped; + }, + withReadPreference: (value: Parameters['withReadPreference']>[0]) => { + cursor.withReadPreference(value); + return wrapped; + }, + withReadConcern: (value: Parameters['withReadConcern']>[0]) => { + cursor.withReadConcern(value); + return wrapped; + }, + addCursorFlag: ( + flag: Parameters['addCursorFlag']>[0], + value: boolean + ) => { + cursor.addCursorFlag(flag, value); + return wrapped; + }, + map: (transform: (doc: T) => TMapped) => { + const mapped = cursor.map(transform); + return mapped === (cursor as unknown) + ? wrapped + : this.wrapReadOnlyAggregationCursor(mapped as unknown as AggregationCursor); + }, + clone: () => this.wrapReadOnlyAggregationCursor(cursor.clone()), + }; + + return wrapped as unknown as AggregationCursor; + } + private wrapReadOnlyCollection(collection: Collection): Collection { return new Proxy(collection, { get: (target, prop, receiver) => { @@ -192,9 +357,15 @@ export class MongoDBClient { return Reflect.get(target, prop, receiver); } if (prop === 'aggregate') { - return (pipeline: Document[] = [], options?: AggregateOptions) => { - this.assertReadOnlyPipeline(pipeline); - return target.aggregate(pipeline, options); + return ( + pipeline: Document[] = [], + options?: AggregateOptions + ) => { + const safePipeline = [...pipeline]; + this.assertReadOnlyPipeline(safePipeline); + return this.wrapReadOnlyAggregationCursor( + target.aggregate(safePipeline, options) + ); }; } if (READ_ONLY_COLLECTION_METHODS.has(prop)) { diff --git a/test/unit/environment-safety.test.ts b/test/unit/environment-safety.test.ts index d63cb243..f6bcbdf0 100644 --- a/test/unit/environment-safety.test.ts +++ b/test/unit/environment-safety.test.ts @@ -3,7 +3,13 @@ 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, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config'; +import { + assertEnvironmentSafety, + initializeStockConfig, + resetStockConfig, + stockAppSchema, + type StockAppConfig, +} from '@stock-bot/stock-config'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); @@ -121,6 +127,61 @@ describe('Environment safety & multi-env isolation', () => { 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', + ] 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; + + 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', diff --git a/test/unit/mongodb-read-only.test.ts b/test/unit/mongodb-read-only.test.ts index 7c279f86..a68f2811 100644 --- a/test/unit/mongodb-read-only.test.ts +++ b/test/unit/mongodb-read-only.test.ts @@ -7,6 +7,61 @@ setLoggerConfig({ logLevel: 'fatal', logConsole: false }); function createStubbedClient(readOnly: boolean) { const logger = getLogger('mongodb-read-only-unit-test'); + const driverClientSymbol = Symbol('kClient'); + const createCursorStub = (initialPipeline: Record[] = []) => { + const pipeline = [...initialPipeline]; + const docs = [{ _id: 'AAPL', count: 5 }]; + let nextIndex = 0; + + const cursorStub: Record = { + pipeline, + client: { db: mock(() => dbStub) }, + [driverClientSymbol]: { db: mock(() => dbStub) }, + out: mock((target: unknown) => { + pipeline.push({ $out: target }); + return cursorStub; + }), + addStage: mock((stage: Record) => { + pipeline.push(stage); + return cursorStub; + }), + lookup: mock((stage: Record) => { + pipeline.push({ $lookup: stage }); + return cursorStub; + }), + match: mock((stage: Record) => { + pipeline.push({ $match: stage }); + return cursorStub; + }), + project: mock((stage: Record) => { + pipeline.push({ $project: stage }); + return cursorStub; + }), + group: mock((stage: Record) => { + pipeline.push({ $group: stage }); + return cursorStub; + }), + limit: mock((n: number) => { + pipeline.push({ $limit: n }); + return cursorStub; + }), + batchSize: mock(() => cursorStub), + map: mock(() => cursorStub), + clone: mock(() => createCursorStub(pipeline)), + toArray: mock(async () => docs), + next: mock(async () => (nextIndex < docs.length ? docs[nextIndex++] : null)), + [Symbol.asyncIterator]: async function* () { + for (const doc of docs) { + yield doc; + } + }, + [Symbol.asyncDispose]: mock(async () => {}), + }; + return cursorStub; + }; + + let lastCursorStub: ReturnType | null = null; + const collectionStub = { collectionName: 'eodPrices', dbName: 'stock', @@ -18,7 +73,10 @@ function createStubbedClient(readOnly: boolean) { estimatedDocumentCount: mock(async () => 100), distinct: mock(async () => ['AAPL', 'MSFT']), listIndexes: mock(() => ({ toArray: async () => [{ name: '_id_' }] })), - aggregate: mock(() => ({ toArray: async () => [{ _id: 'AAPL', count: 5 }] })), + aggregate: mock((pipeline: Record[] = []) => { + lastCursorStub = createCursorStub(pipeline); + return lastCursorStub; + }), // Write & DDL methods insertOne: mock(async () => ({ insertedId: 'id-1' })), insertMany: mock(async () => ({ insertedCount: 1, insertedIds: { 0: 'id-1' } })), @@ -62,7 +120,13 @@ function createStubbedClient(readOnly: boolean) { isConnected: true, }); - return { client, dbStub, collectionStub }; + return { + client, + dbStub, + collectionStub, + driverClientSymbol, + getLastCursorStub: () => lastCursorStub, + }; } function assertZeroMutationCalls( @@ -164,6 +228,55 @@ describe('MongoDBClient read-only mode (offline)', () => { expect(collectionStub.aggregate).not.toHaveBeenCalled(); }); + test('wraps aggregation cursor in a read-only interface blocking fluent write stages and driver client access', async () => { + const { client, driverClientSymbol, getLastCursorStub } = createStubbedClient(true); + + const initialPipeline: Record[] = [{ $match: { symbol: 'AAPL' } }]; + const cursor = client.getDatabase().collection('eodPrices').aggregate(initialPipeline); + const rawCursor = getLastCursorStub()!; + + // Underlying driver client and internal symbols are not exposed + expect((cursor as unknown as Record).client).toBeUndefined(); + expect(Object.getOwnPropertySymbols(cursor)).not.toContain(driverClientSymbol); + + // Mutating caller's input pipeline array or frozen cursor.pipeline cannot inject write stages + initialPipeline.push({ $out: 'hijacked' }); + expect(rawCursor.pipeline).toEqual([{ $match: { symbol: 'AAPL' } }]); + expect(() => (cursor.pipeline as unknown as Record[]).push({ $out: 'hijacked' })).toThrow(); + + // Direct fluent write stages fail closed without touching the underlying cursor + expect(() => cursor.out('hijacked')).toThrow(/read-only mode/); + expect(() => cursor.addStage({ $out: 'hijacked' })).toThrow(/read-only mode/); + expect(() => cursor.addStage({ $merge: { into: 'hijacked' } })).toThrow(/read-only mode/); + expect(() => + cursor.addStage({ $unionWith: { coll: 'other', pipeline: [{ $out: 'hijacked' }] } }) + ).toThrow(/read-only mode/); + expect(() => + cursor.lookup({ from: 'other', pipeline: [{ $merge: { into: 'hijacked' } }], as: 'x' }) + ).toThrow(/read-only mode/); + + // Chained read-only stages, clone(), and map() preserve read-only enforcement + const chained = cursor + .match({ close: { $gt: 100 } }) + .addStage({ $limit: 10 }) + .project({ symbol: 1 }) + .batchSize(100); + expect(() => chained.out('hijacked')).toThrow(/read-only mode/); + expect(() => chained.addStage({ $merge: { into: 'hijacked' } })).toThrow(/read-only mode/); + expect(() => chained.clone().out('hijacked')).toThrow(/read-only mode/); + expect(() => chained.map(doc => doc).addStage({ $out: 'hijacked' })).toThrow(/read-only mode/); + expect(rawCursor.out).not.toHaveBeenCalled(); + + // Safe read iteration (toArray, next, for-await) still works + expect(await chained.toArray()).toEqual([{ _id: 'AAPL', count: 5 }]); + expect(await chained.next()).toEqual({ _id: 'AAPL', count: 5 }); + const iterated: unknown[] = []; + for await (const doc of chained) { + iterated.push(doc); + } + expect(iterated).toEqual([{ _id: 'AAPL', count: 5 }]); + }); + test('passes through safe read operations on client and proxies', async () => { const { client, dbStub, collectionStub } = createStubbedClient(true);