import { readFileSync } from 'fs'; import path from 'path'; import { describe, expect, test } from 'bun:test'; import { queueConfigSchema as coreQueueConfigSchema } from '../../libs/core/config/src/schemas'; import { queueConfigSchema as diQueueConfigSchema } from '@stock-bot/di'; import { setLoggerConfig } from '@stock-bot/logger'; import { assertEnvironmentSafety, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config'; // T-7 edge cases for the dev QA-Mongo guard and the scheduled-jobs default. // Pure config objects only: nothing here opens a socket. setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const DEV_MONGO_URI = 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin'; const READ_URI = 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock'; const PIPELINE_ERROR = /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/; const WRITE_ERROR = /cannot open a writable MongoDB connection to QA MongoDB/; function makeConfig(o: { environment?: 'development' | 'qa' | 'test' | 'production'; mongoEnabled?: boolean; mongoUri?: string; mongoReadUri?: string | null; mongoReadOnly?: boolean; mongoDatabase?: string; pgDatabase?: string; } = {}): StockAppConfig { const mongodb: Record = { enabled: o.mongoEnabled ?? true, uri: o.mongoUri ?? DEV_MONGO_URI, readOnly: o.mongoReadOnly ?? false, database: o.mongoDatabase ?? 'stock_dev', }; if (o.mongoReadUri !== null) { mongodb.readUri = o.mongoReadUri ?? READ_URI; } return stockAppSchema.parse({ name: 'stock-bot', version: '1.0.0', environment: o.environment ?? 'development', service: { name: 'stock-bot', port: 2002, host: '127.0.0.1' }, log: { level: 'info', format: 'json' }, database: { postgres: { enabled: true, host: 'localhost', port: 5433, database: o.pgDatabase ?? 'trading_bot_dev', user: 'dev_user', password: 'dev_pass', ssl: false, }, mongodb, questdb: { enabled: false, host: 'localhost', ilpPort: 9010, httpPort: 9100, pgPort: 8813 }, dragonfly: { enabled: true, host: 'localhost', port: 6380 }, }, providers: { yahoo: { name: 'yahoo', enabled: false, priority: 1, timeout: 30000, baseUrl: 'https://query1.finance.yahoo.com' }, qm: { name: 'qm', enabled: false, priority: 2, username: '', password: '', baseUrl: 'https://app.quotemedia.com/quotetools', webmasterId: '' }, ib: { name: 'ib', enabled: false, priority: 3, gateway: { host: 'localhost', port: 5000, clientId: 1 }, marketDataType: 'delayed' }, eod: { name: 'eod', enabled: false, priority: 4, apiKey: '', baseUrl: 'https://eodhistoricaldata.com/api', tier: 'free' }, }, features: {}, }); } describe('dev QA-Mongo guard: loopback :27017 host variants', () => { const qaVariants = [ 'mongodb://studio_stock_bot_read:secret@127.0.0.1:27017/stock', 'mongodb://studio_stock_bot_read:secret@0.0.0.0:27017/stock', 'mongodb://studio_stock_bot_read:secret@[::1]:27017/stock', 'mongodb://studio_stock_bot_read:secret@LOCALHOST:27017/stock', // No explicit port: the driver defaults to 27017. 'mongodb://studio_stock_bot_read:secret@localhost/stock', // No db path and no trailing slash. 'mongodb://studio_stock_bot_read:secret@localhost:27017', // Different db name on the same QA server is still the QA server. 'mongodb://studio_stock_bot_read:secret@localhost:27017/other', ]; for (const uri of qaVariants) { test(`non-readOnly dataPipeline reading ${uri} throws with fix guidance`, () => { const cfg = makeConfig({ mongoReadUri: uri, mongoReadOnly: false }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR); }); test(`readOnly dataPipeline reading ${uri} as the read user passes`, () => { const cfg = makeConfig({ mongoReadUri: uri, mongoReadOnly: true }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow(); }); test(`writable dataIngestion on ${uri} throws`, () => { const cfg = makeConfig({ mongoUri: uri, mongoReadUri: null, mongoDatabase: 'other' }); expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow(WRITE_ERROR); }); } test('non-loopback host on :27017 is not treated as local QA Mongo', () => { const cfg = makeConfig({ mongoUri: 'mongodb://writer:pw@10.0.0.51:27017/stock', mongoReadUri: 'mongodb://reader:pw@10.0.0.51:27017/stock', mongoReadOnly: false, }); expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow(); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow(); }); }); describe('dev QA-Mongo guard: dataPipeline credential and target rules', () => { test('percent-encoded trading_admin username is still recognised and blocked', () => { const cfg = makeConfig({ mongoReadUri: 'mongodb://trading%5Fadmin:pw@localhost:27017/stock', mongoReadOnly: true, }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR); }); test('without readUri the pipeline falls back to uri, so trading_admin@27017 in uri throws', () => { const cfg = makeConfig({ mongoUri: 'mongodb://trading_admin:pw@localhost:27017/stock', mongoReadUri: null, mongoReadOnly: true, mongoDatabase: 'stock', }); expect(cfg.database.mongodb.readUri).toBeUndefined(); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR); }); test('without readUri, a non-readOnly pipeline on uri localhost:27017 throws', () => { const cfg = makeConfig({ mongoUri: READ_URI, mongoReadUri: null, mongoReadOnly: false }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR); }); test('readUri wins over uri: a dev :27018 readUri passes even when uri points at QA :27017', () => { const cfg = makeConfig({ mongoUri: 'mongodb://trading_admin:pw@localhost:27017/stock', mongoReadUri: DEV_MONGO_URI, mongoReadOnly: false, }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow(); }); test('STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE does not unlock a non-readOnly pipeline', () => { const cfg = makeConfig({ mongoReadOnly: false }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true' }) ).toThrow(PIPELINE_ERROR); }); test('only the literal string "true" opens the ingestion escape hatch', () => { const cfg = makeConfig({ mongoUri: 'mongodb://trading_admin:pw@localhost:27017', mongoReadUri: null, }); for (const value of ['1', 'TRUE', 'yes', '']) { expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: value }) ).toThrow(WRITE_ERROR); } }); test('readOnly ingestion-style service on QA :27017 keeps the pre-existing allowance', () => { const cfg = makeConfig({ mongoUri: READ_URI, mongoReadUri: null, mongoReadOnly: true }); expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow(); expect(() => assertEnvironmentSafety(cfg, 'webApi', {})).not.toThrow(); }); test('unnamed development service writing to QA :27017 is blocked', () => { const cfg = makeConfig({ mongoUri: READ_URI, mongoReadUri: null }); expect(() => assertEnvironmentSafety(cfg, undefined, {})).toThrow(/development service "app"/); }); test('disabled MongoDB skips the Mongo guard for the pipeline', () => { const cfg = makeConfig({ mongoEnabled: false, mongoReadUri: 'mongodb://trading_admin:pw@localhost:27017/stock', }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow(); }); test('qa and test environments never apply the dev Mongo guard to the pipeline', () => { for (const environment of ['qa', 'test'] as const) { const cfg = makeConfig({ environment, mongoUri: 'mongodb://trading_admin:pw@localhost:27017/stock', mongoReadUri: 'mongodb://trading_admin:pw@localhost:27017/stock', mongoReadOnly: false, mongoDatabase: 'stock', pgDatabase: 'trading_bot', }); expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow(); } }); }); describe('enableScheduledJobs defaults off', () => { test('core queueConfigSchema: unset -> false, explicit true -> true', () => { expect(coreQueueConfigSchema.parse({ redis: {} }).enableScheduledJobs).toBe(false); expect( coreQueueConfigSchema.parse({ redis: {}, enableScheduledJobs: true }).enableScheduledJobs ).toBe(true); }); test('DI queueConfigSchema: unset -> false, explicit true -> true', () => { expect(diQueueConfigSchema.parse({}).enableScheduledJobs).toBe(false); expect(diQueueConfigSchema.parse({ enableScheduledJobs: true }).enableScheduledJobs).toBe(true); }); test('stock default.json ships enableScheduledJobs=false', () => { const defaults = JSON.parse( readFileSync(path.resolve(import.meta.dir, '../../apps/stock/config/config/default.json'), 'utf8') ); expect(defaults.queue.enableScheduledJobs).toBe(false); }); test('pipeline and ingestion entrypoints fall back to false, and the pipeline requests mongoReadOnly', () => { for (const app of ['data-pipeline', 'data-ingestion']) { const src = readFileSync( path.resolve(import.meta.dir, `../../apps/stock/${app}/src/index.ts`), 'utf8' ); expect(src).toContain('enableScheduledJobs: config.queue?.enableScheduledJobs ?? false'); expect(src).not.toMatch(/enableScheduledJobs\s*\?\?\s*true/); } const pipelineSrc = readFileSync( path.resolve(import.meta.dir, '../../apps/stock/data-pipeline/src/index.ts'), 'utf8' ); expect(pipelineSrc).toContain("initializeStockConfig('dataPipeline', { mongoReadOnly: true })"); }); test('env-safety no longer warns on the pipeline admin case', () => { const src = readFileSync( path.resolve(import.meta.dir, '../../apps/stock/config/src/env-safety.ts'), 'utf8' ); expect(src).not.toContain('logger.warn'); }); });