From 91e087c42defaf7b9741251db37e6b5f7e642587 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 02:18:49 -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 --- libs/data/mongodb/src/client.ts | 78 ++++-- test/unit/mongodb-read-only.test.ts | 393 ++++++++++++++++++++++++++++ 2 files changed, 456 insertions(+), 15 deletions(-) diff --git a/libs/data/mongodb/src/client.ts b/libs/data/mongodb/src/client.ts index d7a0a34d..b265483c 100644 --- a/libs/data/mongodb/src/client.ts +++ b/libs/data/mongodb/src/client.ts @@ -220,8 +220,13 @@ export class MongoDBClient { ): Readable { beforeRead?.(); const transform = options?.transform; - const closeCursor = (): Promise => - typeof cursor.close === 'function' ? cursor.close() : Promise.resolve(); + let closePromise: Promise | null = null; + const closeCursor = (): Promise => { + if (!closePromise) { + closePromise = typeof cursor.close === 'function' ? cursor.close() : Promise.resolve(); + } + return closePromise; + }; let readInProgress = false; return new Readable({ @@ -246,7 +251,18 @@ export class MongoDBClient { doc => { if (doc == null) { readInProgress = false; - this.push(null); + closeCursor().then( + () => { + if (!this.destroyed) { + this.push(null); + } + }, + closeError => { + this.destroy( + closeError instanceof Error ? closeError : new Error(String(closeError)) + ); + } + ); return; } if (this.destroyed) { @@ -263,6 +279,10 @@ export class MongoDBClient { this.destroy(err instanceof Error ? err : new Error(String(err))); return; } + if (output == null) { + readNext(); + return; + } } if (this.push(output)) { readNext(); @@ -478,7 +498,16 @@ export class MongoDBClient { next: delegate('next'), tryNext: delegate('tryNext'), hasNext: delegate('hasNext'), - forEach: delegate('forEach'), + forEach: (iterator: (doc: unknown) => boolean | void) => { + const fn = rawCursor.forEach; + if (typeof fn !== 'function') { + throw new TypeError('Cursor does not implement "forEach"'); + } + if (typeof iterator !== 'function') { + return fn.call(cursor, iterator); + } + return fn.call(cursor, (doc: unknown) => iterator.call(wrapped, doc)); + }, count: delegate('count'), explain: delegate('explain'), close: delegate('close'), @@ -513,12 +542,20 @@ export class MongoDBClient { if (typeof fn !== 'function') { throw new TypeError('Cursor does not implement "map"'); } - const mapped = fn.call(cursor, transform); - return mapped === cursor - ? wrapped - : mapped && typeof mapped === 'object' - ? this.wrapReadOnlyCursor(mapped as object) - : mapped; + let receiver: unknown; + const guardedTransform = + typeof transform === 'function' + ? (doc: unknown) => transform.call(receiver, doc) + : transform; + const mapped = fn.call(cursor, guardedTransform); + const result = + mapped === cursor + ? wrapped + : mapped && typeof mapped === 'object' + ? this.wrapReadOnlyCursor(mapped as object) + : mapped; + receiver = result; + return result; }, clone: () => { const fn = rawCursor.clone; @@ -606,7 +643,10 @@ export class MongoDBClient { }, forEach: (iterator: (doc: T) => boolean | void) => { assertCursorPipelineSafe(); - return cursor.forEach(iterator); + if (typeof iterator !== 'function') { + return cursor.forEach(iterator); + } + return cursor.forEach(doc => iterator.call(wrapped, doc)); }, stream: (options?: Parameters['stream']>[0]) => this.createGuardedCursorStream( @@ -711,10 +751,18 @@ export class MongoDBClient { 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); + let receiver: unknown; + const guardedTransform = + typeof transform === 'function' + ? (doc: T) => transform.call(receiver, doc) + : transform; + const mapped = cursor.map(guardedTransform); + const result = + mapped === (cursor as unknown) + ? wrapped + : this.wrapReadOnlyAggregationCursor(mapped as unknown as AggregationCursor); + receiver = result; + return result; }, clone: () => this.wrapReadOnlyAggregationCursor(cursor.clone()), }; diff --git a/test/unit/mongodb-read-only.test.ts b/test/unit/mongodb-read-only.test.ts index 8898ff4c..18de98fe 100644 --- a/test/unit/mongodb-read-only.test.ts +++ b/test/unit/mongodb-read-only.test.ts @@ -408,6 +408,7 @@ describe('MongoDBClient read-only mode (offline)', () => { // Destroying a guarded stream closes the underlying cursor index = 0; + closeMock.mockClear(); const destroyStream = wrappedCursor.stream(); destroyStream.destroy(); await new Promise(resolve => setImmediate(resolve)); @@ -586,6 +587,7 @@ describe('MongoDBClient read-only mode (offline)', () => { // Destroying stream calls close() nextIndex = 0; + closeMock.mockClear(); const destroyable = wrappedCursor.stream(); destroyable.destroy(); await new Promise(resolve => setImmediate(resolve)); @@ -631,6 +633,397 @@ describe('MongoDBClient read-only mode (offline)', () => { } }); + 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) 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() stays sealed and a map() on the clone binds `this` to the cloned wrapper + const rawOriginal = createRaw(); + const wrappedOriginal = wrapRawCursor(kind, rawOriginal) as { + map: (fn: (doc: unknown) => unknown) => { + clone: () => { + map: (fn: (doc: unknown) => unknown) => { toArray: () => Promise }; + }; + }; + }; + const mappedOriginal = wrappedOriginal.map(function (this: unknown, doc: unknown) { + return doc; + }); + const rawClone = createRaw(); + seedCursorDocuments(rawClone, docs); + (rawOriginal as Record).clone = mock(() => rawClone); + const cloned = mappedOriginal.clone(); + expect((cloned as unknown as Record).client).toBeUndefined(); + expect((cloned as unknown as Record).parent).toBeUndefined(); + const cloneReceivers: unknown[] = []; + const mappedClone = cloned.map(function (this: unknown, doc: unknown) { + cloneReceivers.push(this); + assertGuardedReceiver(this, mappedClone, rawClone, kind === 'aggregate'); + return { cloned: true, doc }; + }); + expect(await mappedClone.toArray()).toEqual(docs.map(doc => ({ cloned: true, doc }))); + expect(cloneReceivers.length).toBe(docs.length); + + // 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('passes through safe read operations on client and proxies', async () => { const { client, dbStub, collectionStub } = createStubbedClient(true);