import { describe, expect, mock, test } from 'bun:test'; import { MongoClient } from 'mongodb'; 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 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', 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((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' } })), 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, driverClientSymbol, getLastCursorStub: () => lastCursorStub, }; } 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('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('builds aggregation stream from guarded iteration without exposing pinned driver cursor and preserves safe event listeners', async () => { const logger = getLogger('mongodb-read-only-stream-test'); // Unconnected real driver client — zero sockets opened const realMongoClient = new MongoClient('mongodb://127.0.0.1:1/stock'); const realDb = realMongoClient.db('stock'); const realCollection = realDb.collection('eodPrices'); const realCursor = realCollection.aggregate([{ $match: { symbol: 'AAPL' } }]); // Confirm the pinned driver's raw stream exposes the unwrapped cursor via `_cursor` const rawStream = realCursor.stream() as unknown as Record; expect(rawStream._cursor).toBe(realCursor); // Stub next() and close() on the real AggregationCursor so no network I/O occurs const docs = [ { _id: 'AAPL', close: 200 }, { _id: 'MSFT', close: 400 }, ]; let index = 0; const closeMock = mock(async () => {}); realCursor.next = mock(async () => (index < docs.length ? docs[index++] : null)) as never; realCursor.close = closeMock as never; const fakeDb = { databaseName: 'stock', collection: mock(() => ({ collectionName: 'eodPrices', aggregate: mock(() => realCursor), })), }; const client = new MongoDBClient( { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, logger ); Object.assign(client, { client: { db: mock(() => fakeDb) }, db: fakeDb, isConnected: true, }); const wrappedCursor = client .getDatabase() .collection('eodPrices') .aggregate([{ $match: { symbol: 'AAPL' } }]); // Safe EventEmitter methods bind `this` to `wrappedCursor` (never raw `realCursor`), // track caller references for `listeners()` / `off()` / `removeListener()`, and // keep the raw driver cursor inaccessible inside regular function listeners. let closeEvents = 0; let onceEvents = 0; const onReceivers: unknown[] = []; const onceReceivers: unknown[] = []; function onCloseListener(this: unknown) { closeEvents++; onReceivers.push(this); expect(this).toBe(wrappedCursor); expect(this).not.toBe(realCursor); expect((this as Record).client).toBeUndefined(); expect(() => (this as { out: (target: string) => unknown }).out('hijacked')).toThrow( /read-only mode/ ); } function onceCloseListener(this: unknown) { onceEvents++; onceReceivers.push(this); expect(this).toBe(wrappedCursor); expect(this).not.toBe(realCursor); expect((this as Record).client).toBeUndefined(); expect(() => (this as { out: (target: string) => unknown }).out('hijacked')).toThrow( /read-only mode/ ); } const onReturn = wrappedCursor.on('close', onCloseListener); const onceReturn = wrappedCursor.once('close', onceCloseListener); expect(onReturn).toBe(wrappedCursor); expect(onceReturn).toBe(wrappedCursor); expect(wrappedCursor.listeners('close')).toEqual([onCloseListener, onceCloseListener]); expect(wrappedCursor.listenerCount('close')).toBe(2); expect(wrappedCursor.eventNames()).toEqual(['close']); realCursor.emit('close'); expect(closeEvents).toBe(1); expect(onceEvents).toBe(1); expect(onReceivers).toEqual([wrappedCursor]); expect(onceReceivers).toEqual([wrappedCursor]); expect(wrappedCursor.listeners('close')).toEqual([onCloseListener]); realCursor.emit('close'); expect(closeEvents).toBe(2); expect(onceEvents).toBe(1); // `off` / `removeListener` unregisters using the caller function reference expect(wrappedCursor.off('close', onCloseListener)).toBe(wrappedCursor); expect(wrappedCursor.listeners('close')).toEqual([]); expect(wrappedCursor.listenerCount('close')).toBe(0); realCursor.emit('close'); expect(closeEvents).toBe(2); // Also verify `removeListener` unregisters a listener registered via `on` wrappedCursor.on('close', onCloseListener); expect(wrappedCursor.removeListener('close', onCloseListener)).toBe(wrappedCursor); expect(wrappedCursor.listeners('close')).toEqual([]); realCursor.emit('close'); expect(closeEvents).toBe(2); // Wrapped stream must not expose the raw AggregationCursor or MongoClient const guardedStream = wrappedCursor.stream({ transform: doc => ({ symbol: doc._id, doubled: Number(doc.close) * 2 }), }); const streamRecord = guardedStream as unknown as Record; expect(streamRecord._cursor).toBeUndefined(); for (const key of Reflect.ownKeys(guardedStream)) { expect(streamRecord[key]).not.toBe(realCursor); expect(streamRecord[key]).not.toBe(realMongoClient); } const streamed: unknown[] = []; for await (const chunk of guardedStream) { streamed.push(chunk); } expect(streamed).toEqual([ { symbol: 'AAPL', doubled: 400 }, { symbol: 'MSFT', doubled: 800 }, ]); // Destroying a guarded stream closes the underlying cursor index = 0; closeMock.mockClear(); const destroyStream = wrappedCursor.stream(); destroyStream.destroy(); await new Promise(resolve => setImmediate(resolve)); expect(closeMock).toHaveBeenCalledTimes(1); }); test('seals find(), listIndexes(), and listCollections() cursors against pinned-driver MongoClient/Db/Collection leaks', async () => { const logger = getLogger('mongodb-read-only-read-cursors-test'); // Unconnected real driver client — zero sockets opened const realMongoClient = new MongoClient('mongodb://127.0.0.1:1/stock'); const realDb = realMongoClient.db('stock'); const realCollection = realDb.collection('eodPrices'); const roClient = new MongoDBClient( { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, logger ); Object.assign(roClient, { client: realMongoClient, db: realDb, isConnected: true, }); const assertCursorSealed = ( cursorObj: unknown, forbiddenRefs: unknown[] ): void => { const record = cursorObj as Record; expect(record.client).toBeUndefined(); expect(record.cursorClient).toBeUndefined(); expect(record.parent).toBeUndefined(); expect(record.session).toBeUndefined(); expect(record.cursorSession).toBeUndefined(); expect(record.server).toBeUndefined(); expect(record.selectedServer).toBeUndefined(); expect(record.s).toBeUndefined(); for (const key of Reflect.ownKeys(cursorObj as object)) { const value = record[key]; for (const ref of forbiddenRefs) { expect(value).not.toBe(ref); } } }; // 1. Direct cursors from find(), listIndexes(), and listCollections() do not expose raw driver objects const findCursor = roClient.getCollection('eodPrices').find({}); const listIndexesCursor = roClient.getCollection('eodPrices').listIndexes(); const listCollectionsCursor = roClient.getDatabase().listCollections(); assertCursorSealed(findCursor, [realMongoClient, realDb, realCollection]); assertCursorSealed(listIndexesCursor, [realMongoClient, realDb, realCollection]); assertCursorSealed(listCollectionsCursor, [realMongoClient, realDb, realCollection]); // 2. Fluent modifiers, clone(), and map() on find() remain sealed const chainedFind = findCursor.sort({ date: -1 }).limit(5).batchSize(10); expect(chainedFind).toBe(findCursor); assertCursorSealed(chainedFind, [realMongoClient, realDb, realCollection]); const clonedFind = chainedFind.clone(); expect(clonedFind).not.toBe(chainedFind); assertCursorSealed(clonedFind, [realMongoClient, realDb, realCollection]); const mappedFind = chainedFind.map(doc => doc); assertCursorSealed(mappedFind, [realMongoClient, realDb, realCollection]); // 3 & 4 & 5. Verify guarded stream(), EventEmitter `this` binding, and safe reads on real stubbed cursors const cursorCases = [ { label: 'find', createRaw: () => realCollection.find({}), attachAndOpen: (raw: ReturnType) => { const fakeDb = { databaseName: 'stock', collection: mock(() => ({ collectionName: 'eodPrices', find: mock(() => raw), })), }; const wrappedClient = new MongoDBClient( { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, logger ); Object.assign(wrappedClient, { client: { db: mock(() => fakeDb) }, db: fakeDb, isConnected: true, }); return wrappedClient.getCollection('eodPrices').find({}); }, docs: [ { _id: '1', symbol: 'AAPL', close: 200 }, { _id: '2', symbol: 'MSFT', close: 400 }, ], }, { label: 'listIndexes', createRaw: () => realCollection.listIndexes(), attachAndOpen: (raw: ReturnType) => { const fakeDb = { databaseName: 'stock', collection: mock(() => ({ collectionName: 'eodPrices', listIndexes: mock(() => raw), })), }; const wrappedClient = new MongoDBClient( { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, logger ); Object.assign(wrappedClient, { client: { db: mock(() => fakeDb) }, db: fakeDb, isConnected: true, }); return wrappedClient.getCollection('eodPrices').listIndexes(); }, docs: [{ name: '_id_', key: { _id: 1 } }], }, { label: 'listCollections', createRaw: () => realDb.listCollections(), attachAndOpen: (raw: ReturnType) => { const fakeDb = { databaseName: 'stock', listCollections: mock(() => raw), }; const wrappedClient = new MongoDBClient( { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, logger ); Object.assign(wrappedClient, { client: { db: mock(() => fakeDb) }, db: fakeDb, isConnected: true, }); return wrappedClient.getDatabase().listCollections(); }, docs: [{ name: 'eodPrices', type: 'collection' }], }, ]; for (const c of cursorCases) { const rawCursor = c.createRaw(); // Confirm raw pinned driver cursor does expose the raw MongoClient expect((rawCursor as unknown as Record).client).toBe(realMongoClient); let nextIndex = 0; const closeMock = mock(async () => {}); rawCursor.next = mock(async () => nextIndex < c.docs.length ? c.docs[nextIndex++] : null ) as never; rawCursor.toArray = mock(async () => [...c.docs]) as never; rawCursor.close = closeMock as never; (rawCursor as unknown as Record)[Symbol.asyncIterator] = async function* () { for (const doc of c.docs) { yield doc; } }; const wrappedCursor = c.attachAndOpen(rawCursor as never); assertCursorSealed(wrappedCursor, [realMongoClient, realDb, realCollection, rawCursor]); // Stream does not expose `_cursor`, raw cursor, or raw MongoClient const stream = wrappedCursor.stream(); const streamRecord = stream as unknown as Record; expect(streamRecord._cursor).toBeUndefined(); for (const key of Reflect.ownKeys(stream)) { expect(streamRecord[key]).not.toBe(rawCursor); expect(streamRecord[key]).not.toBe(realMongoClient); } const streamed: unknown[] = []; for await (const doc of stream) { streamed.push(doc); } expect(streamed).toEqual(c.docs); // Destroying stream calls close() nextIndex = 0; closeMock.mockClear(); const destroyable = wrappedCursor.stream(); destroyable.destroy(); await new Promise(resolve => setImmediate(resolve)); expect(closeMock).toHaveBeenCalledTimes(1); // EventEmitter listeners receive wrappedCursor as `this` (never rawCursor) let onCalls = 0; let onceCalls = 0; function onClose(this: unknown) { onCalls++; expect(this).toBe(wrappedCursor); expect(this).not.toBe(rawCursor); expect((this as Record).client).toBeUndefined(); } function onceClose(this: unknown) { onceCalls++; expect(this).toBe(wrappedCursor); expect(this).not.toBe(rawCursor); expect((this as Record).client).toBeUndefined(); } wrappedCursor.on('close', onClose); wrappedCursor.once('close', onceClose); expect(wrappedCursor.listeners('close')).toEqual([onClose, onceClose]); rawCursor.emit('close'); expect(onCalls).toBe(1); expect(onceCalls).toBe(1); expect(wrappedCursor.listeners('close')).toEqual([onClose]); wrappedCursor.off('close', onClose); rawCursor.emit('close'); expect(onCalls).toBe(1); // Safe read methods work on real stubbed cursors expect(await wrappedCursor.toArray()).toEqual(c.docs); nextIndex = 0; expect(await wrappedCursor.next()).toEqual(c.docs[0]); const iterated: unknown[] = []; for await (const doc of wrappedCursor) { iterated.push(doc); } expect(iterated).toEqual(c.docs); } }); test('seals map() and forEach() callback receivers on pinned-driver find, listIndexes, listCollections, and aggregate cursors', async () => { const logger = getLogger('mongodb-read-only-map-receiver-test'); const realMongoClient = new MongoClient('mongodb://127.0.0.1:1/stock'); const realDb = realMongoClient.db('stock'); const realCollection = realDb.collection('eodPrices'); const seedCursorDocuments = (rawCursor: object, docs: Record[]) => { const queue = [...docs]; const raw = rawCursor as Record; raw.documents = { get length() { return queue.length; }, shift() { return queue.shift() ?? null; }, clear() { queue.length = 0; }, }; raw.fetchBatch = mock(async () => { raw.isClosed = true; }); raw.close = mock(async () => { raw.isClosed = true; }); }; const wrapRawCursor = ( kind: 'find' | 'listIndexes' | 'listCollections' | 'aggregate', rawCursor: object ) => { const fakeDb = { databaseName: 'stock', listCollections: mock(() => rawCursor), collection: mock(() => ({ collectionName: 'eodPrices', find: mock(() => rawCursor), listIndexes: mock(() => rawCursor), aggregate: mock(() => rawCursor), })), }; const wrappedClient = new MongoDBClient( { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, logger ); Object.assign(wrappedClient, { client: { db: mock(() => fakeDb) }, db: fakeDb, isConnected: true, }); if (kind === 'find') { return wrappedClient.getCollection('eodPrices').find({}); } if (kind === 'listIndexes') { return wrappedClient.getCollection('eodPrices').listIndexes(); } if (kind === 'listCollections') { return wrappedClient.getDatabase().listCollections(); } return wrappedClient.getDatabase().collection('eodPrices').aggregate([{ $match: {} }]); }; const kinds: Array<{ kind: 'find' | 'listIndexes' | 'listCollections' | 'aggregate'; createRaw: () => object; docs: Record[]; }> = [ { kind: 'find', createRaw: () => realCollection.find({}), docs: [ { _id: '1', symbol: 'AAPL', close: 200 }, { _id: '2', symbol: 'MSFT', close: 400 }, ], }, { kind: 'listIndexes', createRaw: () => realCollection.listIndexes(), docs: [ { name: '_id_', key: { _id: 1 } }, { name: 'symbol_1', key: { symbol: 1 } }, ], }, { kind: 'listCollections', createRaw: () => realDb.listCollections(), docs: [ { name: 'eodPrices', type: 'collection' }, { name: 'splits', type: 'collection' }, ], }, { kind: 'aggregate', createRaw: () => realCollection.aggregate([{ $match: {} }]), docs: [ { _id: 'AAPL', close: 200 }, { _id: 'MSFT', close: 400 }, ], }, ]; const assertGuardedReceiver = ( receiver: unknown, expectedCursor: unknown, rawCursor: object, isAggregate: boolean ) => { expect(receiver).toBe(expectedCursor); expect(receiver).not.toBe(rawCursor); const record = receiver as Record; expect(record.client).toBeUndefined(); expect(record.parent).toBeUndefined(); if (isAggregate) { expect(() => (receiver as { out: (target: string) => unknown }).out('x')).toThrow( /read-only mode/ ); } }; // Exercise map() across next(), toArray(), for-await, and stream() on every cursor kind const modes: Array<'next' | 'toArray' | 'forAwait' | 'stream'> = [ 'next', 'toArray', 'forAwait', 'stream', ]; for (const { kind, createRaw, docs } of kinds) { for (const mode of modes) { const rawCursor = createRaw(); seedCursorDocuments(rawCursor, docs); const wrapped = wrapRawCursor(kind, rawCursor) as { map: (fn: (doc: Record) => unknown) => Record; }; const receivers: unknown[] = []; const mappedCursor = wrapped.map(function (this: unknown, doc: Record) { receivers.push(this); assertGuardedReceiver(this, mappedCursor, rawCursor, kind === 'aggregate'); return { mapped: true, doc }; }); const results: unknown[] = []; if (mode === 'next') { while (true) { const item = await (mappedCursor.next as () => Promise)(); if (item === null || item === undefined) { break; } results.push(item); } } else if (mode === 'toArray') { results.push(...(await (mappedCursor.toArray as () => Promise)())); } else if (mode === 'forAwait') { for await (const item of mappedCursor as AsyncIterable) { results.push(item); } } else { for await (const item of (mappedCursor.stream as () => AsyncIterable)()) { results.push(item); } } expect(results).toEqual(docs.map(doc => ({ mapped: true, doc }))); expect(receivers.length).toBe(docs.length); } // Chained map().map() gives every transform the guarded cursor as `this` const rawChained = createRaw(); seedCursorDocuments(rawChained, docs); const wrappedChained = wrapRawCursor(kind, rawChained) as { map: (fn: (doc: unknown) => unknown) => { map: (fn: (doc: unknown) => unknown) => { toArray: () => Promise }; }; }; const firstReceivers: unknown[] = []; const secondReceivers: unknown[] = []; const step1 = wrappedChained.map(function (this: unknown, doc: unknown) { firstReceivers.push(this); assertGuardedReceiver(this, step1, rawChained, kind === 'aggregate'); return { step: 1, doc }; }); const step2 = step1.map(function (this: unknown, doc: unknown) { secondReceivers.push(this); assertGuardedReceiver(this, step2, rawChained, kind === 'aggregate'); return { step: 2, prev: doc }; }); const chainedOut = await step2.toArray(); expect(chainedOut).toEqual(docs.map(doc => ({ step: 2, prev: { step: 1, doc } }))); expect(firstReceivers.length).toBe(docs.length); expect(secondReceivers.length).toBe(docs.length); // clone() after map() calls the pinned driver's real clone(), stays sealed, leaves the // original transform uncalled when iterating the clone, and binds a new map() on the clone // to the cloned wrapper const rawOriginal = createRaw(); const wrappedOriginal = wrapRawCursor(kind, rawOriginal) as { map: (fn: (doc: unknown) => unknown) => { clone: () => { toArray: () => Promise; map: (fn: (doc: unknown) => unknown) => { toArray: () => Promise }; }; }; }; const originalTransformCalls: unknown[] = []; const mappedOriginal = wrappedOriginal.map(function (this: unknown, doc: unknown) { originalTransformCalls.push(this); assertGuardedReceiver(this, mappedOriginal, rawOriginal, kind === 'aggregate'); return { original: true, doc }; }); const realCloneFn = (rawOriginal as { clone: () => object }).clone; let capturedRawClone: object | undefined; (rawOriginal as Record).clone = () => { const realCloned = realCloneFn.call(rawOriginal); capturedRawClone = realCloned; seedCursorDocuments(realCloned, docs); return realCloned; }; const clonedForRead = mappedOriginal.clone(); expect(capturedRawClone).toBeDefined(); expect((clonedForRead as unknown as Record).client).toBeUndefined(); expect((clonedForRead as unknown as Record).parent).toBeUndefined(); expect(await clonedForRead.toArray()).toEqual(docs); expect(originalTransformCalls.length).toBe(0); const clonedForMap = mappedOriginal.clone(); const rawCloneForMap = capturedRawClone!; const cloneReceivers: unknown[] = []; const mappedClone = clonedForMap.map(function (this: unknown, doc: unknown) { cloneReceivers.push(this); assertGuardedReceiver(this, mappedClone, rawCloneForMap, kind === 'aggregate'); return { cloned: true, doc }; }); expect(await mappedClone.toArray()).toEqual(docs.map(doc => ({ cloned: true, doc }))); expect(cloneReceivers.length).toBe(docs.length); expect(originalTransformCalls.length).toBe(0); // forEach() also binds `this` to the wrapped cursor (never rawCursor) const rawForEach = createRaw(); seedCursorDocuments(rawForEach, docs); const wrappedForEach = wrapRawCursor(kind, rawForEach) as { forEach: (fn: (doc: unknown) => void) => Promise; }; const forEachReceivers: unknown[] = []; const visited: unknown[] = []; await wrappedForEach.forEach(function (this: unknown, doc: unknown) { forEachReceivers.push(this); assertGuardedReceiver(this, wrappedForEach, rawForEach, kind === 'aggregate'); visited.push(doc); }); expect(visited).toEqual(docs); expect(forEachReceivers.length).toBe(docs.length); } }); test('skips null and undefined stream transform results without truncating exports, closes once on EOF, and propagates transform errors', async () => { const logger = getLogger('mongodb-read-only-stream-transform-test'); const realMongoClient = new MongoClient('mongodb://127.0.0.1:1/stock'); const realCollection = realMongoClient.db('stock').collection('eodPrices'); const rows = [ { _id: '1', symbol: 'AAPL', close: 200 }, { _id: '2', symbol: 'SKIP', close: 0 }, { _id: '3', symbol: 'MSFT', close: 400 }, ]; const openWrappedFind = (rawCursor: object) => { const fakeDb = { databaseName: 'stock', collection: mock(() => ({ collectionName: 'eodPrices', find: mock(() => rawCursor), })), }; const wrappedClient = new MongoDBClient( { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, logger ); Object.assign(wrappedClient, { client: { db: mock(() => fakeDb) }, db: fakeDb, isConnected: true, }); return wrappedClient.getCollection('eodPrices').find({}); }; for (const skipValue of [null, undefined] as const) { const rawCursor = realCollection.find({}); let index = 0; let exhausted = false; const closeMock = mock(async () => {}); rawCursor.next = mock(async () => { if (index < rows.length) { return rows[index++]; } exhausted = true; return null; }) as never; rawCursor.close = closeMock as never; const wrapped = openWrappedFind(rawCursor); const stream = wrapped.stream({ transform: (doc: Record) => doc.symbol === 'SKIP' ? skipValue : { symbol: doc.symbol, close: doc.close }, }); const emitted: unknown[] = []; let endFiredWhenExhausted = false; stream.on('end', () => { endFiredWhenExhausted = exhausted; }); for await (const chunk of stream) { emitted.push(chunk); } expect(emitted).toEqual([ { symbol: 'AAPL', close: 200 }, { symbol: 'MSFT', close: 400 }, ]); expect(endFiredWhenExhausted).toBe(true); expect(closeMock).toHaveBeenCalledTimes(1); } // Mapped-then-streamed cursor skips nullish stream transforms while sealing map() receiver { const rawCursor = realCollection.find({}); const queue = [...rows]; const raw = rawCursor as unknown as Record; const closeMock = mock(async () => { raw.isClosed = true; }); raw.documents = { get length() { return queue.length; }, shift() { return queue.shift() ?? null; }, clear() { queue.length = 0; }, }; raw.fetchBatch = mock(async () => { raw.isClosed = true; }); raw.close = closeMock; const wrapped = openWrappedFind(rawCursor); const mapReceivers: unknown[] = []; const mapped = wrapped.map(function (this: unknown, doc: Record) { mapReceivers.push(this); expect(this).toBe(mapped); expect((this as Record).client).toBeUndefined(); return { sym: doc.symbol, doubled: Number(doc.close) * 2 }; }); const emitted: unknown[] = []; for await (const chunk of mapped.stream({ transform: (doc: { sym: unknown; doubled: number }) => doc.sym === 'SKIP' ? null : doc, })) { emitted.push(chunk); } expect(emitted).toEqual([ { sym: 'AAPL', doubled: 400 }, { sym: 'MSFT', doubled: 800 }, ]); expect(mapReceivers.length).toBe(3); expect(closeMock).toHaveBeenCalledTimes(1); } // Error case: throwing transform destroys the stream with that error and closes the cursor once { const rawCursor = realCollection.find({}); let index = 0; const closeMock = mock(async () => {}); rawCursor.next = mock(async () => (index < rows.length ? rows[index++] : null)) as never; rawCursor.close = closeMock as never; const wrapped = openWrappedFind(rawCursor); const boom = new Error('transform boom'); const stream = wrapped.stream({ transform: (doc: Record) => { if (doc.symbol === 'SKIP') { throw boom; } return doc; }, }); const emitted: unknown[] = []; let caughtError: unknown = null; try { for await (const chunk of stream) { emitted.push(chunk); } } catch (err) { caughtError = err; } expect(emitted).toEqual([rows[0]]); expect(caughtError).toBe(boom); expect(stream.destroyed).toBe(true); expect(closeMock).toHaveBeenCalledTimes(1); } }); test('stream treats both null and undefined cursor.next() as EOF but passes falsy non-nullish transform results (0, false, empty string) through', async () => { const logger = getLogger('mongodb-read-only-stream-nullish-test'); const realMongoClient = new MongoClient('mongodb://127.0.0.1:1/stock'); const realCollection = realMongoClient.db('stock').collection('eodPrices'); const rows = [ { _id: '1', v: 0 }, { _id: '2', v: false }, { _id: '3', v: '' }, { _id: '4', v: null }, { _id: '5', v: 'tail' }, ]; const openWrappedFind = (rawCursor: object) => { const fakeDb = { databaseName: 'stock', collection: mock(() => ({ collectionName: 'eodPrices', find: mock(() => rawCursor), })), }; const wrappedClient = new MongoDBClient( { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, logger ); Object.assign(wrappedClient, { client: { db: mock(() => fakeDb) }, db: fakeDb, isConnected: true, }); return wrappedClient.getCollection('eodPrices').find({}); }; for (const eofValue of [null, undefined] as const) { const rawCursor = realCollection.find({}); let index = 0; let eofReads = 0; const closeMock = mock(async () => {}); rawCursor.next = mock(async () => { if (index < rows.length) { return rows[index++]; } eofReads++; return eofValue; }) as never; rawCursor.close = closeMock as never; // Object mode: a raw `null` chunk would end a Readable, so falsy values are only safe // because the guard skips strictly nullish outputs (row 4) and pushes 0/false/'' as-is. const stream = openWrappedFind(rawCursor).stream({ transform: (doc: Record) => doc.v, }); const emitted: unknown[] = []; for await (const chunk of stream) { emitted.push(chunk); } expect(emitted).toEqual([0, false, '', 'tail']); expect(eofReads).toBe(1); expect(closeMock).toHaveBeenCalledTimes(1); } }); test('hides raw MongoClient/Db/Collection via property descriptor reflection on read-only proxies', () => { const logger = getLogger('mongodb-read-only-reflection-test'); const realMongoClient = new MongoClient('mongodb://127.0.0.1:1/stock'); const realDb = realMongoClient.db('stock'); const wrappedClient = new MongoDBClient( { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, logger ); Object.assign(wrappedClient, { client: realMongoClient, db: realDb, isConnected: true, }); const roDb = wrappedClient.getDatabase(); const roCollection = wrappedClient.getCollection('eodPrices'); for (const key of ['client', 's'] as const) { expect(Object.getOwnPropertyDescriptor(roDb, key)).toBeUndefined(); } for (const key of ['client', 'db', 's'] as const) { expect(Object.getOwnPropertyDescriptor(roCollection, key)).toBeUndefined(); } expect(Reflect.ownKeys(roDb)).toEqual([]); expect(Reflect.ownKeys(roCollection)).toEqual([]); // Safe read-only metadata getters still resolve properly on the pinned driver expect(roDb.databaseName).toBe('stock'); expect(roDb.namespace).toBe('stock'); expect(roCollection.collectionName).toBe('eodPrices'); expect(roCollection.dbName).toBe('stock'); expect(roCollection.namespace).toBe('stock.eodPrices'); }); 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); }); });