import { describe, expect, mock, test } from 'bun:test'; import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import type { StockAppConfig } from '@stock-bot/stock-config'; import { BSON } from 'mongodb'; import { DEFAULT_RAW_BSON_BATCH_SIZE, RAW_BSON_EXPORT_COLLECTIONS, RawBsonExportError, type ReadOnlyMongoRawBsonClient, } from '../src/security-master/export-raw-bson'; import { assertExportRawBsonSafety, EXPORT_RAW_BSON_USAGE, parseExportRawBsonArgs, runCli, runExportRawBson, } from '../src/security-master/run-export-raw-bson'; function createBaseConfig(overrides: Partial = {}): StockAppConfig { return { environment: 'development', database: { postgres: { enabled: true, host: 'localhost', port: 5432, database: 'trading_bot', user: 'trading_user', password: 'pw', ssl: false, poolSize: 5, idleTimeout: 10000, connectionTimeout: 5000, }, mongodb: { enabled: true, uri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock', readUri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock', readOnly: true, host: 'localhost', port: 27017, database: 'stock', poolSize: 5, ...overrides, }, dragonfly: { enabled: false, host: 'localhost', port: 6380, }, questdb: { enabled: false, host: 'localhost', port: 9100, }, }, } as unknown as StockAppConfig; } describe('parseExportRawBsonArgs', () => { test('parses valid flags in both space-separated and equals forms', () => { const parsed1 = parseExportRawBsonArgs([ '--out-dir', './tmp/bson', '--collections', 'eodPrices', '--eod-symbol', 'CAD.FOREX', '--limit', '100', '--batch-size', '512', ]); expect(parsed1).toEqual({ help: false, outDir: './tmp/bson', collections: ['eodPrices'], eodSymbol: 'CAD.FOREX', limit: 100, batchSize: 512, }); const parsed2 = parseExportRawBsonArgs([ '--out-dir=./tmp/te', '--collections=teMarketData', '--te-symbol=USDCAD', ]); expect(parsed2).toEqual({ help: false, outDir: './tmp/te', collections: ['teMarketData'], teSymbol: 'USDCAD', batchSize: DEFAULT_RAW_BSON_BATCH_SIZE, }); const parsedDefault = parseExportRawBsonArgs(['--out-dir', './tmp/all']); expect(parsedDefault).toEqual({ help: false, outDir: './tmp/all', collections: [...RAW_BSON_EXPORT_COLLECTIONS], batchSize: DEFAULT_RAW_BSON_BATCH_SIZE, }); expect(parseExportRawBsonArgs(['--help'])).toEqual({ help: true }); }); test('rejects unknown, duplicate, missing-value, positional, and malformed flags', () => { expect(() => parseExportRawBsonArgs([])).toThrow(/Missing required argument: --out-dir/); expect(() => parseExportRawBsonArgs(['--out-dir', './tmp', '--bogus'])).toThrow(/Unknown argument/); expect(() => parseExportRawBsonArgs(['--out-dir', './tmp', 'positional'])).toThrow(/Unknown argument/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--out-dir', './b'])).toThrow(/Duplicate flag/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '10', '--limit=20']) ).toThrow(/Duplicate flag/); expect(() => parseExportRawBsonArgs(['--out-dir', '--collections', 'eodPrices'])).toThrow( /Missing value for --out-dir/ ); expect(() => parseExportRawBsonArgs(['--out-dir='])).toThrow(/Missing value for --out-dir/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '0'])).toThrow(/Invalid --limit/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '-5'])).toThrow(/Invalid --limit/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '1.5'])).toThrow(/Invalid --limit/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--batch-size', '0'])).toThrow( /Invalid --batch-size/ ); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--batch-size', '999999'])).toThrow( /Invalid --batch-size/ ); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,']) ).toThrow(/Malformed --collections/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,eodPrices']) ).toThrow(/Duplicate collection/); expect(() => parseExportRawBsonArgs(['--help', '--help'])).toThrow(/Duplicate flag: --help/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--eod-symbol=--help']) ).toThrow(/Invalid value for --eod-symbol/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--eod-symbol', '--help']) ).toThrow(/Missing value for --eod-symbol/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--te-symbol=--limit']) ).toThrow(/Invalid value for --te-symbol/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--te-symbol', '--limit']) ).toThrow(/Missing value for --te-symbol/); }); test('rejects disallowed collections and mismatched --eod-symbol / --te-symbol filters', () => { expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodIntraday1M']) ).toThrow(RawBsonExportError); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'symbols']) ).toThrow(RawBsonExportError); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--eod-symbol', 'CAD.FOREX']) ).toThrow(/--eod-symbol is only permitted/); expect(() => parseExportRawBsonArgs([ '--out-dir', './a', '--collections', 'eodPrices,qmSplits', '--eod-symbol', 'CAD.FOREX', ]) ).toThrow(/--eod-symbol is only permitted/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--eod-symbol', 'CAD.FOREX']) ).toThrow(/--eod-symbol is only permitted/); expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--te-symbol', 'USDCAD']) ).toThrow(/--te-symbol is only permitted/); }); }); describe('assertExportRawBsonSafety', () => { test('allows read-only dev MongoDB even if Postgres config points to QA, and rejects disabled/writable/admin MongoDB', () => { expect(() => assertExportRawBsonSafety(createBaseConfig(), {})).not.toThrow(); expect(() => assertExportRawBsonSafety(createBaseConfig({ enabled: false }), {})).toThrow( /MongoDB is disabled/ ); expect(() => assertExportRawBsonSafety(createBaseConfig({ readOnly: false }), {})).toThrow( /read-only MongoDB configuration/ ); expect(() => assertExportRawBsonSafety( createBaseConfig({ readUri: 'mongodb://trading_admin:pw@localhost:27017/stock?authSource=admin', readOnly: true, }), {} ) ).toThrow(/Safety guard/); }); }); describe('runExportRawBson & runCli', () => { test('--help prints usage and performs zero config, Mongo, or fs I/O', async () => { const stdout: string[] = []; const initConfigMock = mock(() => { throw new Error('initializeConfig must not be called on --help'); }); const createClientMock = mock(() => { throw new Error('createMongoClient must not be called on --help'); }); await runCli(['--help'], { initializeConfig: initConfigMock as never, createMongoClient: createClientMock, writeStdout: text => stdout.push(text), }); expect(stdout.join('')).toBe(`${EXPORT_RAW_BSON_USAGE}\n`); expect(initConfigMock).not.toHaveBeenCalled(); expect(createClientMock).not.toHaveBeenCalled(); }); test('runCli initializes config with mongoReadOnly: true, issues strictly raw find(), calls zero write methods, and closes client', async () => { const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-cli-')); try { const sampleBytes = Uint8Array.from( BSON.serialize({ eodSearchCode: 'CAD.FOREX', date: '2025-01-02', close: 1.44 }) ); const findCalls: Array<{ collection: string; filter: unknown; options: unknown }> = []; const forbiddenWrite = mock(() => { throw new Error('Write/DDL method must never be called'); }); const closeMongoMock = mock(async () => {}); const closeCursorMock = mock(async () => {}); const fakeClient: ReadOnlyMongoRawBsonClient & Record = { isReadOnly: () => true, insertOne: forbiddenWrite, updateOne: forbiddenWrite, deleteMany: forbiddenWrite, createIndex: forbiddenWrite, dropCollection: forbiddenWrite, getCollection: (name: string) => ({ find: (filter, options) => { findCalls.push({ collection: name, filter, options }); return { close: closeCursorMock, async *[Symbol.asyncIterator]() { yield sampleBytes; }, }; }, }), }; const initCalls: Array<{ service: string; opts: unknown }> = []; const stdout: string[] = []; await runCli( [ '--out-dir', outDir, '--collections', 'eodPrices', '--eod-symbol', 'CAD.FOREX', '--batch-size', '256', ], { initializeConfig: ((service: string, opts?: unknown) => { initCalls.push({ service, opts }); return createBaseConfig(); }) as never, createMongoClient: async () => ({ client: fakeClient, close: closeMongoMock, }), writeStdout: text => stdout.push(text), } ); expect(initCalls).toEqual([{ service: 'dataPipeline', opts: { mongoReadOnly: true } }]); expect(findCalls).toEqual([ { collection: 'eodPrices', filter: { eodSearchCode: 'CAD.FOREX' }, options: { raw: true, batchSize: 256 }, }, ]); expect(forbiddenWrite).not.toHaveBeenCalled(); expect(closeCursorMock).toHaveBeenCalledTimes(1); expect(closeMongoMock).toHaveBeenCalledTimes(1); const written = Uint8Array.from(await readFile(join(outDir, 'eodPrices.bson'))); expect(written).toEqual(sampleBytes); expect(stdout.join('')).toContain('eodPrices: docs=1'); expect(stdout.join('')).toContain('sha256='); } finally { await rm(outDir, { recursive: true, force: true }); } }); test('runExportRawBson closes Mongo client on mid-stream export failure and preserves primary error', async () => { const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-fail-')); try { const closeMongoMock = mock(async () => {}); const fakeClient: ReadOnlyMongoRawBsonClient = { isReadOnly: () => true, getCollection: () => ({ find: () => ({ async *[Symbol.asyncIterator]() { yield Uint8Array.from(BSON.serialize({ ok: 1 })); throw new Error('Mid-stream Mongo failure'); }, }), }), }; await expect( runExportRawBson( { createMongoClient: () => ({ client: fakeClient, close: closeMongoMock }), writeStdout: () => {}, }, { outDir, collections: ['qmSplits'], } ) ).rejects.toThrow('Mid-stream Mongo failure'); expect(closeMongoMock).toHaveBeenCalledTimes(1); } finally { await rm(outDir, { recursive: true, force: true }); } }); test('runExportRawBson rejects disallowed collections before calling assertSafety or createMongoClient', async () => { const assertSafetyMock = mock(() => {}); const createClientMock = mock(() => { throw new Error('createMongoClient must not be called'); }); await expect( runExportRawBson( { assertSafety: assertSafetyMock, createMongoClient: createClientMock, }, { outDir: '/tmp/unused', collections: ['eodIntraday1M' as never], } ) ).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION' }); expect(assertSafetyMock).not.toHaveBeenCalled(); expect(createClientMock).not.toHaveBeenCalled(); }); test('runCli rejects flag-shaped --eod-symbol and --te-symbol values before config or MongoDB access and preserves existing output', async () => { const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-flag-val-')); try { const existingEodPath = join(outDir, 'eodPrices.bson'); const sentinel = Uint8Array.from(BSON.serialize({ eodSearchCode: 'CAD.FOREX', close: 1.44 })); await writeFile(existingEodPath, sentinel); const initConfigMock = mock(() => { throw new Error('initializeConfig must not be called on malformed filter'); }); const createClientMock = mock(() => { throw new Error('createMongoClient must not be called on malformed filter'); }); const invalidInvocations: string[][] = [ ['--out-dir', outDir, '--collections', 'eodPrices', '--eod-symbol=--help'], ['--out-dir', outDir, '--collections', 'eodPrices', '--eod-symbol', '--help'], ['--out-dir', outDir, '--collections', 'teMarketData', '--te-symbol=--help'], ['--out-dir', outDir, '--collections', 'teMarketData', '--te-symbol', '--help'], ]; for (const argv of invalidInvocations) { await expect( runCli(argv, { initializeConfig: initConfigMock as never, createMongoClient: createClientMock, }) ).rejects.toThrow(/(?:Invalid|Missing) value for --(?:eod|te)-symbol/); } expect(initConfigMock).not.toHaveBeenCalled(); expect(createClientMock).not.toHaveBeenCalled(); expect(Uint8Array.from(await readFile(existingEodPath))).toEqual(sentinel); } finally { await rm(outDir, { recursive: true, force: true }); } }); });