T-7: M0.3a — Harden dev Mongo safety: env-safety throws on unsafe data-pipeline QA reads, scheduled jobs default off, read-only bypass tests

This commit is contained in:
Studio 2026-11-27 01:47:31 -05:00
parent 7cf940afce
commit abbab4b5a8
10 changed files with 644 additions and 18 deletions

View file

@ -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'],

View file

@ -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,
};

View file

@ -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<void> {
const queueManager = this.resolveOptional('queueManager');
if (!queueManager) {
return;
}
const handlerRegistry = this.resolveOptional('handlerRegistry');
const ownedHandlers = new Set<string>();
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
*/

View file

@ -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<string, string[]>([
['{test-service_eod}', ['{test-service_eod}:crawl']],
['{other-service_sync}', ['{other-service_sync}:daily']],
]);
const queuedJobs = new Map<string, Array<{ id: string; repeatJobKey?: string }>>([
[
'{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' },
]);
}
});
});

View file

@ -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<number> {
this.assertConnectionsOpen();
let totalRemoved = 0;
const seenFullNames = new Set<string>();
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
*/

View file

@ -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<Pick<BullQueue, 'getJobSchedulers' | 'removeJobScheduler'>>;
/**
* 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<number> {
const removedKeys = new Set<string>();
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<number> {
const removedCount = await removeScheduledJobsFromBullQueue(this.bullQueue);
this.logger.info('Removed scheduled jobs from queue', {
queueName: this.queueName,
removedCount,
});
return removedCount;
}
/**
* Get queue statistics
*/

View file

@ -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']);
});
});
});

View file

@ -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<T extends Document>(
cursor: AggregationCursor<T>
): AggregationCursor<T> {
const assertCursorPipelineSafe = (): void => {
if (Array.isArray(cursor.pipeline)) {
this.assertReadOnlyPipeline(cursor.pipeline);
}
};
const wrapped: Record<PropertyKey, unknown> = {
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<AggregationCursor<T>['stream']>) => {
assertCursorPipelineSafe();
return cursor.stream(...args);
},
explain: (...args: Parameters<AggregationCursor<T>['explain']>) => {
assertCursorPipelineSafe();
return cursor.explain(...args);
},
close: (...args: Parameters<AggregationCursor<T>['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<Record<symbol, () => Promise<void>>>;
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<AggregationCursor<T>['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<AggregationCursor<T>['withReadPreference']>[0]) => {
cursor.withReadPreference(value);
return wrapped;
},
withReadConcern: (value: Parameters<AggregationCursor<T>['withReadConcern']>[0]) => {
cursor.withReadConcern(value);
return wrapped;
},
addCursorFlag: (
flag: Parameters<AggregationCursor<T>['addCursorFlag']>[0],
value: boolean
) => {
cursor.addCursorFlag(flag, value);
return wrapped;
},
map: <TMapped>(transform: (doc: T) => TMapped) => {
const mapped = cursor.map(transform);
return mapped === (cursor as unknown)
? wrapped
: this.wrapReadOnlyAggregationCursor(mapped as unknown as AggregationCursor<Document>);
},
clone: () => this.wrapReadOnlyAggregationCursor(cursor.clone()),
};
return wrapped as unknown as AggregationCursor<T>;
}
private wrapReadOnlyCollection<T extends Document>(collection: Collection<T>): Collection<T> {
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 <TDoc extends Document = Document>(
pipeline: Document[] = [],
options?: AggregateOptions
) => {
const safePipeline = [...pipeline];
this.assertReadOnlyPipeline(safePipeline);
return this.wrapReadOnlyAggregationCursor(
target.aggregate<TDoc>(safePipeline, options)
);
};
}
if (READ_ONLY_COLLECTION_METHODS.has(prop)) {

View file

@ -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<Record<(typeof envKeys)[number], string | undefined>> = {};
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',

View file

@ -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<string, unknown>[] = []) => {
const pipeline = [...initialPipeline];
const docs = [{ _id: 'AAPL', count: 5 }];
let nextIndex = 0;
const cursorStub: Record<PropertyKey, unknown> = {
pipeline,
client: { db: mock(() => dbStub) },
[driverClientSymbol]: { db: mock(() => dbStub) },
out: mock((target: unknown) => {
pipeline.push({ $out: target });
return cursorStub;
}),
addStage: mock((stage: Record<string, unknown>) => {
pipeline.push(stage);
return cursorStub;
}),
lookup: mock((stage: Record<string, unknown>) => {
pipeline.push({ $lookup: stage });
return cursorStub;
}),
match: mock((stage: Record<string, unknown>) => {
pipeline.push({ $match: stage });
return cursorStub;
}),
project: mock((stage: Record<string, unknown>) => {
pipeline.push({ $project: stage });
return cursorStub;
}),
group: mock((stage: Record<string, unknown>) => {
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<typeof createCursorStub> | 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<string, unknown>[] = []) => {
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<string, unknown>[] = [{ $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<string, unknown>).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<string, unknown>[]).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);