import { describe, expect, mock, test } from 'bun:test'; import { createHash } from 'node:crypto'; import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { BSON } from 'mongodb'; import { createReadOnlyMongoRawBsonSource, exportRawBsonCollection, RAW_BSON_EXPORT_COLLECTIONS, RawBsonExportError, validateRawBsonFrame, walkRawBsonFrames, type ExportRawBsonFileHandle, type ExportRawBsonFsHooks, type RawBsonFindOptions, type ReadOnlyMongoRawBsonClient, type ReadOnlyRawBsonSource, } from '../src/security-master/export-raw-bson'; const EMPTY_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'; function sha256Hex(bytes: Uint8Array): string { return createHash('sha256').update(bytes).digest('hex'); } function concatBytes(chunks: readonly Uint8Array[]): Uint8Array { const total = chunks.reduce((acc, c) => acc + c.byteLength, 0); const out = new Uint8Array(total); let offset = 0; for (const chunk of chunks) { out.set(chunk, offset); offset += chunk.byteLength; } return out; } function createFakeSource( docs: readonly unknown[], options: { readOnly?: boolean; errorAfter?: number; error?: Error; onFind?: (collection: string, filter: Record, findOpts: RawBsonFindOptions) => void; onCursorClose?: () => void; } = {} ): ReadOnlyRawBsonSource { const readOnly = options.readOnly ?? true; return { isReadOnly: () => readOnly, find(collection, filter, findOpts) { options.onFind?.(collection, filter, findOpts); return { async *[Symbol.asyncIterator]() { let index = 0; try { for (const doc of docs) { if (options.errorAfter !== undefined && index === options.errorAfter) { throw options.error ?? new Error('Simulated mid-stream cursor failure'); } yield doc; index += 1; } } finally { options.onCursorClose?.(); } }, }; }, }; } async function withTempDir(fn: (dir: string) => Promise): Promise { const dir = await mkdtemp(join(tmpdir(), 'export-raw-bson-test-')); try { return await fn(dir); } finally { await rm(dir, { recursive: true, force: true }); } } describe('exportRawBsonCollection', () => { test('streams raw BSON frames verbatim, matches concatenation, round-trips via 4-byte LE framing, and is deterministic', async () => { const originalDocs = [ { eodSearchCode: 'AAPL.US', date: '2025-01-02', open: 248.93, high: 249.1, low: 241.82, close: 243.85, volume: 55740731, ts: new Date('2025-01-02T21:00:00.000Z'), meta: { exchange: 'US', adjusted: false }, }, { eodSearchCode: 'RY.TO', date: '2025-01-02', open: 173.4, high: 175.0, low: 172.8, close: 174.65, volume: 2150000, tags: ['CA', 'TSX'], }, { eodSearchCode: 'NVDA.US', date: '2024-06-10', open: 120.37, high: 123.1, low: 117.01, close: 121.79, volume: 314162700, }, ]; const serialized = originalDocs.map(doc => Uint8Array.from(BSON.serialize(doc))); const expectedBytes = concatBytes(serialized); const expectedSha = sha256Hex(expectedBytes); await withTempDir(async outDir => { const findCalls: Array<{ collection: string; filter: Record; options: RawBsonFindOptions; }> = []; const source = createFakeSource(serialized, { onFind: (collection, filter, options) => { findCalls.push({ collection, filter, options }); }, }); const run1 = await exportRawBsonCollection(source, { collection: 'eodPrices', outDir, }); expect(run1.collection).toBe('eodPrices'); expect(run1.outPath).toBe(join(outDir, 'eodPrices.bson')); expect(run1.docsWritten).toBe(originalDocs.length); expect(run1.bytesWritten).toBe(expectedBytes.byteLength); expect(run1.elapsedMs).toBeGreaterThanOrEqual(0); expect(run1.sha256).toBe(expectedSha); expect(run1.filter).toEqual({}); expect(findCalls).toEqual([ { collection: 'eodPrices', filter: {}, options: { raw: true, batchSize: 4096 }, }, ]); const fileBytes = Uint8Array.from(await readFile(run1.outPath)); expect(fileBytes).toEqual(expectedBytes); // Cross-language framing parity: walk output by 4-byte LE length prefix const walked = walkRawBsonFrames(fileBytes); expect(walked).toHaveLength(originalDocs.length); for (let i = 0; i < originalDocs.length; i++) { const frame = walked[i]; expect(frame).toEqual(serialized[i]); expect(BSON.deserialize(frame!)).toEqual(originalDocs[i]); } // Determinism / replay invariant: running twice yields byte-identical output and sha256 const run2 = await exportRawBsonCollection(source, { collection: 'eodPrices', outDir, }); const fileBytes2 = Uint8Array.from(await readFile(run2.outPath)); expect(run2.sha256).toBe(run1.sha256); expect(run2.bytesWritten).toBe(run1.bytesWritten); expect(fileBytes2).toEqual(fileBytes); expect(await readdir(outDir)).toEqual(['eodPrices.bson']); }); }); test('publishes a 0-byte file with docsWritten === 0 and empty SHA-256 for an empty collection', async () => { await withTempDir(async outDir => { const source = createFakeSource([]); const result = await exportRawBsonCollection(source, { collection: 'ceoShorts', outDir, }); expect(result.collection).toBe('ceoShorts'); expect(result.docsWritten).toBe(0); expect(result.bytesWritten).toBe(0); expect(result.sha256).toBe(EMPTY_SHA256); const fileBytes = await readFile(result.outPath); expect(fileBytes.byteLength).toBe(0); expect(await readdir(outDir)).toEqual(['ceoShorts.bson']); }); }); test('rejects invalid BSON frames with typed error naming collection and ordinal, cleans temp file, and preserves existing output', async () => { const validDoc = Uint8Array.from(BSON.serialize({ a: 1 })); const shortFrame = new Uint8Array([4, 0, 0, 0]); const tooSmallPrefix = Uint8Array.from(validDoc); tooSmallPrefix[0] = (tooSmallPrefix[0] ?? 0) - 1; const tooLargePrefix = Uint8Array.from(validDoc); tooLargePrefix[0] = (tooLargePrefix[0] ?? 0) + 1; const missingTerminator = Uint8Array.from(validDoc); missingTerminator[missingTerminator.byteLength - 1] = 0x01; const oversizedDoc = Uint8Array.from(BSON.serialize({ payload: 'x'.repeat(200) })); const cases: Array<{ name: string; docs: unknown[]; expectedOrdinal: number; maxDocBytes?: number; }> = [ { name: 'shorter than 5 bytes', docs: [validDoc, shortFrame], expectedOrdinal: 1 }, { name: 'LE prefix smaller than byteLength', docs: [validDoc, tooSmallPrefix], expectedOrdinal: 1 }, { name: 'LE prefix larger than byteLength', docs: [tooLargePrefix], expectedOrdinal: 0 }, { name: 'missing trailing 0x00', docs: [validDoc, validDoc, missingTerminator], expectedOrdinal: 2 }, { name: 'non-Uint8Array chunk', docs: [validDoc, { plain: 'object' }], expectedOrdinal: 1 }, { name: 'exceeds maxDocBytes', docs: [validDoc, oversizedDoc], expectedOrdinal: 1, maxDocBytes: 64, }, ]; for (const c of cases) { await withTempDir(async outDir => { const existingPath = join(outDir, 'qmSplits.bson'); const sentinel = Uint8Array.from(BSON.serialize({ sentinel: c.name })); await writeFile(existingPath, sentinel); const source = createFakeSource(c.docs); let caught: unknown; try { await exportRawBsonCollection(source, { collection: 'qmSplits', outDir, maxDocBytes: c.maxDocBytes, }); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(RawBsonExportError); const typed = caught as RawBsonExportError; expect(typed.code).toBe('INVALID_BSON_FRAME'); expect(typed.collection).toBe('qmSplits'); expect(typed.docOrdinal).toBe(c.expectedOrdinal); expect(typed.message).toContain('qmSplits'); expect(typed.message).toContain(`doc#${c.expectedOrdinal}`); // No temp file left behind and pre-existing output is byte-identical expect(await readdir(outDir)).toEqual(['qmSplits.bson']); expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel); }); } }); test('cleans up temp file, closes cursor/handle, and preserves existing output on mid-stream cursor, write, short-write, fsync, and rename errors', async () => { const docs = [ Uint8Array.from(BSON.serialize({ seq: 0 })), Uint8Array.from(BSON.serialize({ seq: 1 })), Uint8Array.from(BSON.serialize({ seq: 2 })), ]; // 1. Mid-stream cursor error await withTempDir(async outDir => { const existingPath = join(outDir, 'qmDividends.bson'); const sentinel = Uint8Array.from(BSON.serialize({ sentinel: 'cursor-err' })); await writeFile(existingPath, sentinel); let cursorClosed = false; const source = createFakeSource(docs, { errorAfter: 2, error: new Error('Cursor network reset'), onCursorClose: () => { cursorClosed = true; }, }); await expect( exportRawBsonCollection(source, { collection: 'qmDividends', outDir }) ).rejects.toThrow('Cursor network reset'); expect(cursorClosed).toBe(true); expect(await readdir(outDir)).toEqual(['qmDividends.bson']); expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel); }); // 2. Write, short-write, fsync, and rename errors const failureModes = ['write', 'shortWrite', 'sync', 'rename'] as const; for (const mode of failureModes) { await withTempDir(async outDir => { const existingPath = join(outDir, 'qmPrices.bson'); const sentinel = Uint8Array.from(BSON.serialize({ sentinel: mode })); await writeFile(existingPath, sentinel); let handleClosed = false; let tempFileCreated: string | null = null; let unlinkedPath: string | null = null; const fsHooks: ExportRawBsonFsHooks = { open: async (filePath: string) => { tempFileCreated = filePath; await writeFile(filePath, new Uint8Array()); const handle: ExportRawBsonFileHandle = { write: async (_buf, _off, len) => { if (mode === 'write') { throw new Error('ENOSPC simulated write failure'); } if (mode === 'shortWrite') { return { bytesWritten: 0 }; } return { bytesWritten: len ?? 0 }; }, sync: async () => { if (mode === 'sync') { throw new Error('EIO simulated fsync failure'); } }, close: async () => { handleClosed = true; }, }; return handle; }, rename: async () => { if (mode === 'rename') { throw new Error('EXDEV simulated rename failure'); } }, unlink: async filePath => { unlinkedPath = String(filePath); await rm(filePath, { force: true }); }, }; const source = createFakeSource(docs); await expect( exportRawBsonCollection(source, { collection: 'qmPrices', outDir, fs: fsHooks, }) ).rejects.toThrow(); expect(handleClosed).toBe(true); expect(tempFileCreated).not.toBeNull(); expect(unlinkedPath).toBe(tempFileCreated); expect(await readdir(outDir)).toEqual(['qmPrices.bson']); expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel); }); } }); test('enforces bounded write buffer size, handles oversized single docs, and strictly awaits write backpressure', async () => { const smallDocs = Array.from({ length: 120 }, (_, i) => Uint8Array.from( BSON.serialize({ eodSearchCode: `SYM${String(i).padStart(4, '0')}.US`, date: '2025-01-02', open: 10 + i, close: 11 + i, volume: 1000 + i, }) ) ); const largeDoc = Uint8Array.from( BSON.serialize({ eodSearchCode: 'LARGE.US', payload: 'A'.repeat(350), }) ); const allDocs = [...smallDocs.slice(0, 60), largeDoc, ...smallDocs.slice(60)]; const expectedConcat = concatBytes(allDocs); const writeBufferBytes = 256; expect(largeDoc.byteLength).toBeGreaterThan(writeBufferBytes); const writeLengths: number[] = []; const writtenChunks: Uint8Array[] = []; let inFlight = 0; let maxInFlight = 0; await withTempDir(async outDir => { const fsHooks: ExportRawBsonFsHooks = { open: async () => ({ write: async (buf, offset, length) => { inFlight += 1; if (inFlight > maxInFlight) { maxInFlight = inFlight; } const start = offset ?? 0; const len = length ?? buf.byteLength - start; writeLengths.push(len); // Copy slice immediately to simulate kernel read of buffer before async completion const copy = Uint8Array.from(buf.subarray(start, start + len)); await new Promise(resolve => setTimeout(resolve, 0)); writtenChunks.push(copy); inFlight -= 1; return { bytesWritten: len }; }, sync: async () => {}, close: async () => {}, }), rename: async () => {}, unlink: async () => {}, }; const source = createFakeSource(allDocs); const result = await exportRawBsonCollection(source, { collection: 'eodPrices', outDir, writeBufferBytes, fs: fsHooks, }); expect(maxInFlight).toBe(1); expect(writeLengths.length).toBeGreaterThan(10); // Every write must be <= writeBufferBytes except the single oversized document write const oversizedWrites = writeLengths.filter(len => len > writeBufferBytes); expect(oversizedWrites).toEqual([largeDoc.byteLength]); for (const len of writeLengths) { expect(len).toBeLessThanOrEqual(Math.max(writeBufferBytes, largeDoc.byteLength)); } const assembled = concatBytes(writtenChunks); expect(assembled).toEqual(expectedConcat); expect(result.docsWritten).toBe(allDocs.length); expect(result.bytesWritten).toBe(expectedConcat.byteLength); expect(result.sha256).toBe(sha256Hex(expectedConcat)); }); }); test('rejects disallowed collections, invalid filters, and non-read-only sources before any source or fs call', async () => { const findMock = mock(() => { throw new Error('source.find should never be called'); }); const openMock = mock(async () => { throw new Error('fs.open should never be called'); }); const source: ReadOnlyRawBsonSource = { isReadOnly: () => true, find: findMock, }; const fsHooks: ExportRawBsonFsHooks = { open: openMock }; for (const disallowed of ['eodIntraday1M', 'qmIntraday', 'qmFinancials', 'ceoPosts', 'symbols']) { await expect( exportRawBsonCollection(source, { collection: disallowed, outDir: '/tmp/unused', fs: fsHooks }) ).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION', collection: disallowed }); } await expect( exportRawBsonCollection(source, { collection: 'teMarketData', outDir: '/tmp/unused', eodSymbol: 'CAD.FOREX', fs: fsHooks, }) ).rejects.toMatchObject({ code: 'INVALID_OPTION' }); await expect( exportRawBsonCollection(source, { collection: 'eodPrices', outDir: '/tmp/unused', teSymbol: 'USDCAD', fs: fsHooks, }) ).rejects.toMatchObject({ code: 'INVALID_OPTION' }); const writableSource: ReadOnlyRawBsonSource = { isReadOnly: () => false, find: findMock, }; await expect( exportRawBsonCollection(writableSource, { collection: 'eodPrices', outDir: '/tmp/unused', fs: fsHooks, }) ).rejects.toMatchObject({ code: 'INVALID_SOURCE' }); expect(findMock).not.toHaveBeenCalled(); expect(openMock).not.toHaveBeenCalled(); }); test('applies eodSymbol, teSymbol, and limit filters and defensively caps output at limit', async () => { const docs = Array.from({ length: 5 }, (_, i) => Uint8Array.from(BSON.serialize({ seq: i })) ); await withTempDir(async outDir => { const calls: Array<{ collection: string; filter: Record; options: RawBsonFindOptions }> = []; const source = createFakeSource(docs, { onFind: (collection, filter, options) => { calls.push({ collection, filter, options }); }, }); const eodRes = await exportRawBsonCollection(source, { collection: 'eodPrices', outDir, eodSymbol: 'CAD.FOREX', limit: 2, batchSize: 64, }); expect(eodRes.docsWritten).toBe(2); expect(eodRes.filter).toEqual({ eodSearchCode: 'CAD.FOREX' }); expect(calls[0]).toEqual({ collection: 'eodPrices', filter: { eodSearchCode: 'CAD.FOREX' }, options: { raw: true, batchSize: 64, limit: 2 }, }); const teRes = await exportRawBsonCollection(source, { collection: 'teMarketData', outDir, teSymbol: 'USDCAD', limit: 3, }); expect(teRes.docsWritten).toBe(3); expect(teRes.filter).toEqual({ teSymbol: 'USDCAD' }); expect(calls[1]).toEqual({ collection: 'teMarketData', filter: { teSymbol: 'USDCAD' }, options: { raw: true, batchSize: 4096, limit: 3 }, }); }); }); test('createReadOnlyMongoRawBsonSource enforces read-only, rejects buffered arrays, and always closes cursors', async () => { const writableClient: ReadOnlyMongoRawBsonClient = { isReadOnly: () => false, getCollection: () => { throw new Error('should not be called'); }, }; expect(() => createReadOnlyMongoRawBsonSource(writableClient)).toThrow(RawBsonExportError); const bufferedArrayClient: ReadOnlyMongoRawBsonClient = { isReadOnly: () => true, getCollection: () => ({ find: () => [] as unknown as ReturnType extends { find: (...args: never[]) => infer R; } ? R : never, }), }; const badSource = createReadOnlyMongoRawBsonSource(bufferedArrayClient); expect(() => badSource.find('eodPrices', {}, { raw: true })).toThrow(RawBsonExportError); // Cursor close is called on normal exhaustion and early break const closeMock = mock(async () => {}); const docs = [ Uint8Array.from(BSON.serialize({ a: 1 })), Uint8Array.from(BSON.serialize({ a: 2 })), Uint8Array.from(BSON.serialize({ a: 3 })), ]; const goodClient: ReadOnlyMongoRawBsonClient = { isReadOnly: () => true, getCollection: () => ({ find: () => ({ close: closeMock, async *[Symbol.asyncIterator]() { for (const d of docs) { yield d; } }, }), }), }; const source = createReadOnlyMongoRawBsonSource(goodClient); await withTempDir(async outDir => { const res = await exportRawBsonCollection(source, { collection: 'qmFilings', outDir, limit: 1, }); expect(res.docsWritten).toBe(1); expect(closeMock).toHaveBeenCalledTimes(1); }); // Limited export with rejecting cursor.close() must surface the close error, // clean up the temp file, and leave any pre-existing output file byte-identical. const rejectingCloseClient: ReadOnlyMongoRawBsonClient = { isReadOnly: () => true, getCollection: () => ({ find: () => ({ close: async () => { throw new Error('Cursor close rejected after limit break'); }, async *[Symbol.asyncIterator]() { for (const d of docs) { yield d; } }, }), }), }; const rejectingSource = createReadOnlyMongoRawBsonSource(rejectingCloseClient); await withTempDir(async outDir => { const existingPath = join(outDir, 'qmFilings.bson'); const sentinel = Uint8Array.from(BSON.serialize({ sentinel: 'preserve-on-close-error' })); await writeFile(existingPath, sentinel); await expect( exportRawBsonCollection(rejectingSource, { collection: 'qmFilings', outDir, limit: 1, }) ).rejects.toThrow('Cursor close rejected after limit break'); expect(await readdir(outDir)).toEqual(['qmFilings.bson']); expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel); }); // When iteration itself fails AND cursor.close() rejects, the primary iteration error wins. const dualFailureClient: ReadOnlyMongoRawBsonClient = { isReadOnly: () => true, getCollection: () => ({ find: () => ({ close: async () => { throw new Error('Secondary cursor close failure'); }, async *[Symbol.asyncIterator]() { yield docs[0]; throw new Error('Primary cursor iteration failure'); }, }), }), }; const dualFailureSource = createReadOnlyMongoRawBsonSource(dualFailureClient); await withTempDir(async outDir => { await expect( exportRawBsonCollection(dualFailureSource, { collection: 'qmFilings', outDir, }) ).rejects.toThrow('Primary cursor iteration failure'); expect(await readdir(outDir)).toEqual([]); }); }); test('exports exact M1 allowlist of 8 collections and validateRawBsonFrame accepts minimal 5-byte empty BSON doc', () => { expect([...RAW_BSON_EXPORT_COLLECTIONS]).toEqual([ 'eodPrices', 'qmSplits', 'qmDividends', 'qmPrices', 'teMarketData', 'ceoShorts', 'qmFilings', 'qmEarnings', ]); const emptyBson = new Uint8Array([5, 0, 0, 0, 0]); expect(validateRawBsonFrame(emptyBson, 'eodPrices', 0)).toBe(emptyBson); }); });