From e9659f4dfb71ca72d19b8573295b3e60e6a0af52 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 11:37:04 -0500 Subject: [PATCH 01/20] =?UTF-8?q?T-10:=20M0.3b=20=E2=80=94=20Delete=20lega?= =?UTF-8?q?cy=20MongoDB-writing=20sync-ib-exchanges=20operation=20and=20it?= =?UTF-8?q?s=20web-api/web-app=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handlers/exchanges/exchanges.handler.ts | 14 -- .../sync-ib-exchanges.operations.ts | 212 ------------------ .../web-api/src/routes/pipeline.routes.ts | 10 - .../web-api/src/services/pipeline.service.ts | 32 --- .../src/features/pipeline/PipelinePage.tsx | 12 - .../features/pipeline/hooks/usePipeline.ts | 6 - .../features/pipeline/services/pipelineApi.ts | 4 - scripts/test/pipeline-legacy-removal.test.ts | 79 +++++++ 8 files changed, 79 insertions(+), 290 deletions(-) delete mode 100644 apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts create mode 100644 scripts/test/pipeline-legacy-removal.test.ts diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts b/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts index b4e8bfd2..3f56480a 100644 --- a/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts +++ b/apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts @@ -5,7 +5,6 @@ import { getExchangeStats } from './operations/exchange-stats.operations'; import { getProviderMappingStats } from './operations/provider-mapping-stats.operations'; import { syncQMExchanges } from './operations/qm-exchanges.operations'; import { syncAllExchanges } from './operations/sync-all-exchanges.operations'; -import { syncIBExchanges } from './operations/sync-ib-exchanges.operations'; import { syncQMProviderMappings } from './operations/sync-qm-provider-mappings.operations'; @Handler('exchanges') @@ -41,19 +40,6 @@ class ExchangesHandler extends BaseHandler { return syncQMExchanges({}, this); } - /** - * Sync exchanges from Interactive Brokers - */ - @Operation('sync-ib-exchanges') - @ScheduledOperation('sync-ib-exchanges', '0 3 * * *', { - priority: 3, - description: 'Daily sync of IB exchanges at 3 AM', - }) - async syncIBExchanges(): Promise { - this.log('info', 'Starting IB exchanges sync...'); - return syncIBExchanges({}, this); - } - /** * Sync provider mappings from QuestionsAndMethods */ diff --git a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts b/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts deleted file mode 100644 index 6d242194..00000000 --- a/apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { getLogger } from '@stock-bot/logger'; -import type { MasterExchange } from '@stock-bot/mongodb'; -import { requireServices, type IServiceContainer } from '@stock-bot/services'; -import type { JobPayload } from '../../../types/job-payloads'; - -const logger = getLogger('sync-ib-exchanges'); - -interface IBExchange { - id?: string; - _id?: unknown; - name?: string; - code?: string; - country_code?: string; - currency?: string; -} - -export async function syncIBExchanges( - payload: JobPayload, - container: IServiceContainer -): Promise<{ syncedCount: number; totalExchanges: number }> { - logger.info('Syncing IB exchanges from database...'); - - try { - const { mongodb: mongoClient } = requireServices(container, 'mongodb'); - const db = mongoClient.getDatabase(); - - // Filter by country code US and CA - const ibExchanges = await db - .collection('ibExchanges') - .find({ - country_code: { $in: ['US', 'CA'] }, - }) - .toArray(); - - logger.info('Found IB exchanges in database', { count: ibExchanges.length }); - - let syncedCount = 0; - - for (const exchange of ibExchanges) { - try { - await createOrUpdateMasterExchange(exchange, container); - syncedCount++; - - logger.debug('Synced IB exchange', { - ibId: exchange.id, - country: exchange.country_code, - }); - } catch (error) { - logger.error('Failed to sync IB exchange', { exchange: exchange.id, error }); - } - } - - logger.info('IB exchange sync completed', { - syncedCount, - totalExchanges: ibExchanges.length, - }); - - return { syncedCount, totalExchanges: ibExchanges.length }; - } catch (error) { - logger.error('Failed to fetch IB exchanges from database', { error }); - return { syncedCount: 0, totalExchanges: 0 }; - } -} - -/** - * Create or update master exchange record 1:1 from IB exchange - */ -async function createOrUpdateMasterExchange( - ibExchange: IBExchange, - container: IServiceContainer -): Promise { - const { mongodb: mongoClient } = requireServices(container, 'mongodb'); - const db = mongoClient.getDatabase(); - const collection = db.collection('masterExchanges'); - - const masterExchangeId = generateMasterExchangeId(ibExchange); - const now = new Date(); - - // Check if master exchange already exists - const existing = await collection.findOne({ masterExchangeId }); - - if (existing) { - // Update existing record - await collection.updateOne( - { masterExchangeId }, - { - $set: { - officialName: ibExchange.name || `Exchange ${ibExchange.id}`, - country: ibExchange.country_code || 'UNKNOWN', - currency: ibExchange.currency || 'USD', - timezone: inferTimezone(ibExchange), - updated_at: now, - }, - } - ); - - logger.debug('Updated existing master exchange', { masterExchangeId }); - } else { - // Create new master exchange - const masterExchange: MasterExchange = { - masterExchangeId, - shortName: masterExchangeId, // Set shortName to masterExchangeId on creation - officialName: ibExchange.name || `Exchange ${ibExchange.id}`, - country: ibExchange.country_code || 'UNKNOWN', - currency: ibExchange.currency || 'USD', - timezone: inferTimezone(ibExchange), - active: false, // Set active to false only on creation - - sourceMappings: { - ib: { - id: ibExchange.id || ibExchange._id?.toString() || 'unknown', - name: ibExchange.name || `Exchange ${ibExchange.id}`, - code: ibExchange.code || ibExchange.id || '', - aliases: generateAliases(ibExchange), - lastUpdated: now, - }, - }, - - confidence: 1.0, // High confidence for direct IB mapping - verified: true, // Mark as verified since it's direct from IB - - // DocumentBase fields - source: 'ib-exchange-sync', - created_at: now, - updated_at: now, - }; - - await collection.insertOne(masterExchange); - logger.debug('Created new master exchange', { masterExchangeId }); - } -} - -/** - * Generate master exchange ID from IB exchange - */ -function generateMasterExchangeId(ibExchange: IBExchange): string { - // Use code if available, otherwise use ID, otherwise generate from name - if (ibExchange.code) { - return ibExchange.code.toUpperCase().replace(/[^A-Z0-9]/g, ''); - } - - if (ibExchange.id) { - return ibExchange.id.toUpperCase().replace(/[^A-Z0-9]/g, ''); - } - - if (ibExchange.name) { - return ibExchange.name - .toUpperCase() - .split(' ') - .slice(0, 2) - .join('_') - .replace(/[^A-Z0-9_]/g, ''); - } - - return 'UNKNOWN_EXCHANGE'; -} - -/** - * Generate aliases for the exchange - */ -function generateAliases(ibExchange: IBExchange): string[] { - const aliases: string[] = []; - - if (ibExchange.name && ibExchange.name.includes(' ')) { - // Add abbreviated version - aliases.push( - ibExchange.name - .split(' ') - .map(w => w[0]) - .join('') - .toUpperCase() - ); - } - - if (ibExchange.code) { - aliases.push(ibExchange.code.toUpperCase()); - } - - return aliases; -} - -/** - * Infer timezone from exchange name/location - */ -function inferTimezone(ibExchange: IBExchange): string { - if (!ibExchange.name) { - return 'UTC'; - } - - const name = ibExchange.name.toUpperCase(); - - if (name.includes('NEW YORK') || name.includes('NYSE') || name.includes('NASDAQ')) { - return 'America/New_York'; - } - if (name.includes('LONDON')) { - return 'Europe/London'; - } - if (name.includes('TOKYO')) { - return 'Asia/Tokyo'; - } - if (name.includes('SHANGHAI')) { - return 'Asia/Shanghai'; - } - if (name.includes('TORONTO')) { - return 'America/Toronto'; - } - if (name.includes('FRANKFURT')) { - return 'Europe/Berlin'; - } - - return 'UTC'; // Default -} diff --git a/apps/stock/web-api/src/routes/pipeline.routes.ts b/apps/stock/web-api/src/routes/pipeline.routes.ts index e7677147..f640c211 100644 --- a/apps/stock/web-api/src/routes/pipeline.routes.ts +++ b/apps/stock/web-api/src/routes/pipeline.routes.ts @@ -73,16 +73,6 @@ export function createPipelineRoutes(container: IServiceContainer) { } }); - pipeline.post('/provider-mappings/ib', async c => { - try { - const result = await pipelineService.syncIBExchanges(); - return c.json(result, result.success ? 200 : 503); - } catch (error) { - logger.error('Error in POST /provider-mappings/ib', { error }); - return c.json({ success: false, error: 'Internal server error' }, 500); - } - }); - // Status endpoint pipeline.get('/status', async c => { try { diff --git a/apps/stock/web-api/src/services/pipeline.service.ts b/apps/stock/web-api/src/services/pipeline.service.ts index 1bc4a8b6..29a5fb4d 100644 --- a/apps/stock/web-api/src/services/pipeline.service.ts +++ b/apps/stock/web-api/src/services/pipeline.service.ts @@ -182,38 +182,6 @@ export class PipelineService { } } - /** - * Queue a job to sync IB exchanges - */ - async syncIBExchanges(): Promise { - try { - const queueManager = this.container.queueManager; - if (!queueManager) { - return { success: false, error: 'Queue manager not available' }; - } - - const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges')); - const job = await exchangesQueue.add('sync-ib-exchanges', { - handler: 'exchanges', - operation: 'sync-ib-exchanges', - payload: {}, - }); - - logger.info('IB exchanges sync job queued', { jobId: job.id }); - return { - success: true, - jobId: job.id, - message: 'IB exchanges sync job queued', - }; - } catch (error) { - logger.error('Failed to queue IB exchanges sync job', { error }); - return { - success: false, - error: error instanceof Error ? error.message : 'Failed to queue sync job', - }; - } - } - /** * Get sync status */ diff --git a/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx b/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx index 412aa3f6..2cee3147 100644 --- a/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx +++ b/apps/stock/web-app/src/features/pipeline/PipelinePage.tsx @@ -59,14 +59,6 @@ const operations: PipelineOperation[] = [ method: 'POST', category: 'sync', }, - { - id: 'sync-ib-exchanges', - name: 'Sync IB Exchanges', - description: 'Sync exchanges from Interactive Brokers', - endpoint: '/provider-mappings/ib', - method: 'POST', - category: 'sync', - }, // Maintenance operations { id: 'clear-postgresql', @@ -89,7 +81,6 @@ export function PipelinePage() { syncQMExchanges, syncAllExchanges, syncQMProviderMappings, - syncIBExchanges, clearPostgreSQLData, getExchangeStats, getProviderMappingStats, @@ -136,9 +127,6 @@ export function PipelinePage() { case 'sync-qm-provider-mappings': await syncQMProviderMappings(); break; - case 'sync-ib-exchanges': - await syncIBExchanges(); - break; case 'clear-postgresql': { const expected = `DELETE STOCK REFERENCE DATA:${clearDataType}`; diff --git a/apps/stock/web-app/src/features/pipeline/hooks/usePipeline.ts b/apps/stock/web-app/src/features/pipeline/hooks/usePipeline.ts index dc874aa3..eac46d03 100644 --- a/apps/stock/web-app/src/features/pipeline/hooks/usePipeline.ts +++ b/apps/stock/web-app/src/features/pipeline/hooks/usePipeline.ts @@ -65,11 +65,6 @@ export function usePipeline() { [executeOperation] ); - const syncIBExchanges = useCallback( - () => executeOperation(() => pipelineApi.syncIBExchanges()), - [executeOperation] - ); - // Maintenance operations const clearPostgreSQLData = useCallback( (dataType: DataClearType, confirmation: string) => @@ -148,7 +143,6 @@ export function usePipeline() { // Provider mapping operations syncQMProviderMappings, - syncIBExchanges, // Maintenance operations clearPostgreSQLData, diff --git a/apps/stock/web-app/src/features/pipeline/services/pipelineApi.ts b/apps/stock/web-app/src/features/pipeline/services/pipelineApi.ts index 81124529..dbca4f61 100644 --- a/apps/stock/web-app/src/features/pipeline/services/pipelineApi.ts +++ b/apps/stock/web-app/src/features/pipeline/services/pipelineApi.ts @@ -46,10 +46,6 @@ class PipelineApiService { return this.request('/provider-mappings/qm', { method: 'POST' }); } - async syncIBExchanges(): Promise { - return this.request('/provider-mappings/ib', { method: 'POST' }); - } - // Status and maintenance operations async getSyncStatus(): Promise { return this.request('/status'); diff --git a/scripts/test/pipeline-legacy-removal.test.ts b/scripts/test/pipeline-legacy-removal.test.ts new file mode 100644 index 00000000..6d307eaa --- /dev/null +++ b/scripts/test/pipeline-legacy-removal.test.ts @@ -0,0 +1,79 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'bun:test'; +import { Hono } from 'hono'; +import type { IServiceContainer } from '@stock-bot/handlers'; +import { createPipelineRoutes } from '../../apps/stock/web-api/src/routes/pipeline.routes'; + +const repository = fileURLToPath(new URL('../../', import.meta.url)); + +function scanSourceFiles(relativeDir: string): string[] { + const dir = join(repository, relativeDir); + return [...new Bun.Glob('**/*.{ts,tsx}').scanSync({ cwd: dir })].map(file => join(dir, file)); +} + +describe('legacy sync-ib-exchanges removal', () => { + it('legacy MongoDB-writing sync-ib-exchanges operations file does not exist', () => { + const legacyFile = join( + repository, + 'apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts' + ); + expect(existsSync(legacyFile)).toBe(false); + }); + + it('no source file in data-pipeline, web-api, or web-app references sync-ib-exchanges or syncIBExchanges', () => { + const trees = [ + 'apps/stock/data-pipeline/src', + 'apps/stock/web-api/src', + 'apps/stock/web-app/src', + ]; + const forbiddenSymbols = ['sync-ib-exchanges', 'syncIBExchanges']; + const hits: string[] = []; + + for (const tree of trees) { + for (const file of scanSourceFiles(tree)) { + const content = readFileSync(file, 'utf8'); + for (const token of forbiddenSymbols) { + if (content.includes(token)) { + hits.push(`${file}: ${token}`); + } + } + if (tree !== 'apps/stock/data-pipeline/src' && content.includes('/provider-mappings/ib')) { + hits.push(`${file}: /provider-mappings/ib`); + } + } + } + + expect(hits).toEqual([]); + }); + + it('POST /api/pipeline/provider-mappings/ib returns 404 without enqueueing jobs while QM mapping route stays active', async () => { + const jobs: unknown[] = []; + const services = { + queueManager: { + getQueue() { + return { + async add(_name: string, data: unknown) { + jobs.push(data); + return { id: 'fixture' }; + }, + }; + }, + }, + } as unknown as IServiceContainer; + + const app = new Hono(); + app.route('/api/pipeline', createPipelineRoutes(services)); + + const removed = await app.request('/api/pipeline/provider-mappings/ib', { method: 'POST' }); + expect(removed.status).toBe(404); + expect(jobs).toHaveLength(0); + + const active = await app.request('/api/pipeline/provider-mappings/qm', { method: 'POST' }); + expect(active.status).toBe(200); + expect(jobs).toEqual([ + { handler: 'exchanges', operation: 'sync-qm-provider-mappings', payload: {} }, + ]); + }); +}); From 654782a6a169a7959b0ddc24697671ad127abff0 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 10:33:27 -0500 Subject: [PATCH 02/20] =?UTF-8?q?T-2:=20M0.2=20=E2=80=94=20Finish=20shared?= =?UTF-8?q?=20Postgres=20migrations:=20`bun=20run=20db:migrate`=20+=20fres?= =?UTF-8?q?h-database=20schema=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- database/postgres/init/02-master-schema.sql | 8 +- .../04-provider-exchange-mapping-schema.sql | 2 +- package.json | 1 + scripts/db-migrate.ts | 139 +++++++++++ scripts/test/db-migrate.test.ts | 143 ++++++++++++ test/postgres/fresh-database-schema.test.ts | 220 ++++++++++++++++++ 6 files changed, 508 insertions(+), 5 deletions(-) create mode 100644 scripts/db-migrate.ts create mode 100644 scripts/test/db-migrate.test.ts create mode 100644 test/postgres/fresh-database-schema.test.ts diff --git a/database/postgres/init/02-master-schema.sql b/database/postgres/init/02-master-schema.sql index 80ba8b3f..818a45da 100644 --- a/database/postgres/init/02-master-schema.sql +++ b/database/postgres/init/02-master-schema.sql @@ -2,7 +2,7 @@ -- Exchanges Table CREATE TABLE IF NOT EXISTS exchanges ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), code VARCHAR(10) UNIQUE NOT NULL, -- NASDAQ, NYSE, TSX, etc. name VARCHAR(255) NOT NULL, -- Full exchange name country CHAR(2) NOT NULL, -- US, CA, GB @@ -14,7 +14,7 @@ CREATE TABLE IF NOT EXISTS exchanges ( -- Symbols Table CREATE TABLE IF NOT EXISTS symbols ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), symbol VARCHAR(20) NOT NULL, -- AAPL, SHOP, etc. exchange_id UUID REFERENCES exchanges(id), company_name VARCHAR(255), @@ -29,7 +29,7 @@ CREATE TABLE IF NOT EXISTS symbols ( -- Provider Symbol Mappings (How each provider refers to our symbols) CREATE TABLE IF NOT EXISTS provider_mappings ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), symbol_id UUID REFERENCES symbols(id), provider VARCHAR(50) NOT NULL, -- 'qm', 'yahoo', 'ib', etc. provider_symbol VARCHAR(100) NOT NULL, -- How provider names it: "AAPL:NASDAQ", "SHOP.TO" @@ -43,7 +43,7 @@ CREATE TABLE IF NOT EXISTS provider_mappings ( -- Simple sync tracking table CREATE TABLE IF NOT EXISTS sync_status ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), provider VARCHAR(50) NOT NULL, data_type VARCHAR(50) NOT NULL, -- 'symbols', 'exchanges' last_sync_at TIMESTAMP, diff --git a/database/postgres/init/04-provider-exchange-mapping-schema.sql b/database/postgres/init/04-provider-exchange-mapping-schema.sql index 66f3f835..4abd9586 100644 --- a/database/postgres/init/04-provider-exchange-mapping-schema.sql +++ b/database/postgres/init/04-provider-exchange-mapping-schema.sql @@ -19,7 +19,7 @@ END $$; -- Provider Exchange Mappings Table -- Maps provider-specific exchange codes to our master exchanges CREATE TABLE IF NOT EXISTS provider_exchange_mappings ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), provider VARCHAR(50) NOT NULL, -- 'qm', 'eod', 'ib', etc. provider_exchange_code VARCHAR(50) NOT NULL, -- Provider's exchange code: 'NYE', 'US', 'NASDAQ' provider_exchange_name VARCHAR(255), -- Provider's exchange name diff --git a/package.json b/package.json index 91ddb4be..0b86adce 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "test:integration": "bun test test/integration/", "test:native": "cargo test -p engine --lib --offline", "test:postgres": "bun run scripts/test-postgres.ts", + "db:migrate": "bun run scripts/db-migrate.ts", "audit:secrets": "bun run scripts/audit-secrets.ts", "test:e2e": "bun run scripts/test-e2e.ts", "test:e2e:install": "playwright install chromium", diff --git a/scripts/db-migrate.ts b/scripts/db-migrate.ts new file mode 100644 index 00000000..d8f6434f --- /dev/null +++ b/scripts/db-migrate.ts @@ -0,0 +1,139 @@ +import { getLogger } from '@stock-bot/logger'; +import { + PostgreSQLClient, + runPostgresMigrations, + type MigrationTrack, + type PostgreSQLClientConfig, +} from '@stock-bot/postgres'; +import { + assertEnvironmentSafety, + initializeStockConfig, + type StockAppConfig, +} from '@stock-bot/stock-config'; + +const VALID_TRACKS = new Set(['master', 'research', 'all']); +const TRACK_USAGE = 'Valid tracks: master|research|all'; + +export interface DbMigrateArgs { + track: MigrationTrack; +} + +export interface MigrationTarget { + clientConfig: PostgreSQLClientConfig; + targetLabel: string; +} + +function isValidTrack(value: string): value is MigrationTrack { + return VALID_TRACKS.has(value as MigrationTrack); +} + +export function parseDbMigrateArgs(argv: readonly string[]): DbMigrateArgs { + let track: MigrationTrack = 'all'; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--track') { + const value = argv[i + 1]; + if (!value || value.startsWith('-')) { + throw new Error(`Missing value for --track. ${TRACK_USAGE}`); + } + if (!isValidTrack(value)) { + throw new Error(`Invalid --track value "${value}". ${TRACK_USAGE}`); + } + track = value; + i += 1; + continue; + } + + if (arg.startsWith('--track=')) { + const value = arg.slice('--track='.length); + if (!isValidTrack(value)) { + throw new Error(`Invalid --track value "${value}". ${TRACK_USAGE}`); + } + track = value; + continue; + } + + throw new Error(`Unknown argument "${arg}". Usage: db:migrate [--track master|research|all]`); + } + + return { track }; +} + +export function resolveMigrationTarget( + config: StockAppConfig, + env: Record = process.env +): MigrationTarget { + const pg = config.database.postgres; + if (!pg.enabled) { + throw new Error('PostgreSQL is disabled in the active configuration.'); + } + + // Disable unrelated MongoDB checks so Postgres migrations only enforce PostgreSQL/environment guards. + assertEnvironmentSafety( + { + ...config, + database: { + ...config.database, + mongodb: { + ...config.database.mongodb, + enabled: false, + }, + }, + }, + 'dataPipeline', + env + ); + + const clientConfig: PostgreSQLClientConfig = { + host: pg.host, + port: pg.port, + database: pg.database, + username: pg.user, + password: pg.password, + ssl: { enabled: pg.ssl, rejectUnauthorized: true }, + poolSettings: { + min: 0, + max: pg.poolSize, + idleTimeoutMillis: pg.idleTimeout, + }, + timeouts: { connection: pg.connectionTimeout }, + }; + + return { + clientConfig, + targetLabel: `${pg.host}:${pg.port}/${pg.database}`, + }; +} + +async function main(argv: readonly string[]): Promise { + const { track } = parseDbMigrateArgs(argv); + const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); + const { clientConfig, targetLabel } = resolveMigrationTarget(config, process.env); + const logger = getLogger('db-migrate'); + const client = new PostgreSQLClient(clientConfig, logger); + + try { + await client.connect(); + const applied = await runPostgresMigrations(client, { track }); + console.log(`Target: ${targetLabel} (track: ${track})`); + if (applied.length === 0) { + console.log('nothing to apply'); + } else { + console.log(`Applied ${applied.length} migration(s):`); + for (const filename of applied) { + console.log(` - ${filename}`); + } + } + } finally { + await client.disconnect(); + } +} + +if (import.meta.main) { + main(process.argv.slice(2)).catch(error => { + const message = error instanceof Error ? error.message : String(error); + console.error(`db:migrate failed: ${message}`); + process.exit(1); + }); +} diff --git a/scripts/test/db-migrate.test.ts b/scripts/test/db-migrate.test.ts new file mode 100644 index 00000000..2d5793a5 --- /dev/null +++ b/scripts/test/db-migrate.test.ts @@ -0,0 +1,143 @@ +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config'; +import { parseDbMigrateArgs, resolveMigrationTarget } from '../db-migrate'; + +const root = fileURLToPath(new URL('../../', import.meta.url)); + +function makeConfig(overrides: { + environment?: StockAppConfig['environment']; + postgres?: Partial; +}): StockAppConfig { + return stockAppSchema.parse({ + name: 'stock-bot', + version: '1.0.0', + environment: overrides.environment ?? 'development', + service: { + name: 'data-pipeline', + port: 2002, + }, + log: {}, + database: { + postgres: { + enabled: true, + host: 'localhost', + port: 5433, + database: 'trading_bot_dev', + user: 'dev_user', + password: 'dev_pass', + ssl: false, + poolSize: 10, + connectionTimeout: 30000, + idleTimeout: 10000, + ...overrides.postgres, + }, + mongodb: { + enabled: true, + uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin', + database: 'stock_dev', + poolSize: 10, + }, + questdb: {}, + dragonfly: {}, + }, + providers: {}, + features: {}, + }); +} + +describe('parseDbMigrateArgs', () => { + test('defaults to track "all" when no arguments are passed', () => { + expect(parseDbMigrateArgs([])).toEqual({ track: 'all' }); + }); + + test('accepts each valid track with space or equals syntax', () => { + for (const track of ['master', 'research', 'all'] as const) { + expect(parseDbMigrateArgs(['--track', track])).toEqual({ track }); + expect(parseDbMigrateArgs([`--track=${track}`])).toEqual({ track }); + } + }); + + test('rejects invalid track values with message listing valid tracks', () => { + expect(() => parseDbMigrateArgs(['--track', 'bogus'])).toThrow(/master\|research\|all/); + expect(() => parseDbMigrateArgs(['--track=bogus'])).toThrow(/master\|research\|all/); + }); + + test('rejects missing track value and unknown arguments', () => { + expect(() => parseDbMigrateArgs(['--track'])).toThrow(/master\|research\|all/); + expect(() => parseDbMigrateArgs(['--track', '--other'])).toThrow(/master\|research\|all/); + expect(() => parseDbMigrateArgs(['--unknown'])).toThrow(/master\|research\|all/); + expect(() => parseDbMigrateArgs(['positional'])).toThrow(/master\|research\|all/); + }); +}); + +describe('resolveMigrationTarget', () => { + test('rejects development targeting QA PostgreSQL on localhost:5432/trading_bot', () => { + const config = makeConfig({ + environment: 'development', + postgres: { host: 'localhost', port: 5432, database: 'trading_bot' }, + }); + expect(() => resolveMigrationTarget(config, {})).toThrow(/QA PostgreSQL/i); + }); + + test('rejects development targeting QA PostgreSQL on 127.0.0.1:5432/trading_bot', () => { + const config = makeConfig({ + environment: 'development', + postgres: { host: '127.0.0.1', port: 5432, database: 'trading_bot' }, + }); + expect(() => resolveMigrationTarget(config, {})).toThrow(/QA PostgreSQL/i); + }); + + test('accepts development targeting isolated dev PostgreSQL on localhost:5433/trading_bot_dev', () => { + const config = makeConfig({ + environment: 'development', + postgres: { + host: 'localhost', + port: 5433, + database: 'trading_bot_dev', + user: 'dev_user', + password: 'dev_pass', + }, + }); + const resolved = resolveMigrationTarget(config, {}); + expect(resolved.targetLabel).toBe('localhost:5433/trading_bot_dev'); + expect(resolved.clientConfig).toEqual({ + host: 'localhost', + port: 5433, + database: 'trading_bot_dev', + username: 'dev_user', + password: 'dev_pass', + ssl: { enabled: false, rejectUnauthorized: true }, + poolSettings: { min: 0, max: 10, idleTimeoutMillis: 10000 }, + timeouts: { connection: 30000 }, + }); + }); + + test('rejects qa targeting a _dev database', () => { + const config = makeConfig({ + environment: 'qa', + postgres: { host: 'localhost', port: 5433, database: 'trading_bot_dev' }, + }); + expect(() => resolveMigrationTarget(config, {})).toThrow(/dev PostgreSQL/i); + }); + + test('rejects disabled PostgreSQL configuration', () => { + const config = makeConfig({ + environment: 'development', + postgres: { enabled: false }, + }); + expect(() => resolveMigrationTarget(config, {})).toThrow(/disabled/i); + }); +}); + +describe('db-migrate CLI subprocess', () => { + test('exits non-zero with valid tracks on stderr for --track bogus without connecting to DB', () => { + const result = Bun.spawnSync( + [process.execPath, 'run', 'scripts/db-migrate.ts', '--track', 'bogus'], + { cwd: root } + ); + expect(result.exitCode).not.toBe(0); + const stderr = new TextDecoder().decode(result.stderr); + expect(stderr).toMatch(/master\|research\|all/); + }); +}); diff --git a/test/postgres/fresh-database-schema.test.ts b/test/postgres/fresh-database-schema.test.ts new file mode 100644 index 00000000..d67a2faf --- /dev/null +++ b/test/postgres/fresh-database-schema.test.ts @@ -0,0 +1,220 @@ +import { randomUUID } from 'node:crypto'; +import { copyFileSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('fresh-database-schema-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init', import.meta.url)); + +const MASTER_FILES = [ + '01-init-database.sql', + '02-master-schema.sql', + '03-initial-data.sql', + '04-provider-exchange-mapping-schema.sql', + '05-add-visible-column.sql', +]; + +const BOOTSTRAP_FILES = [ + '06-create-backtest-tables.sql', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', +]; + +const RESEARCH_FILES = [ + '09-backtest-run-contract.sql', + '10-durable-backtest-dispatch.sql', + '11-simulation-execution-ledger.sql', + '12-historical-datasets.sql', + '13-strategy-recovery.sql', + '14-backtest-submission.sql', + '15-canonical-paper-intents.sql', + '16-strategy-catalog.sql', + '17-research-retention.sql', + '18-backtest-strategy-versions.sql', + '19-canonical-research.sql', + '20-research-workspace.sql', + '21-run-reproduction.sql', + '22-experiments.sql', + '23-experiment-retries.sql', + '24-chronological-validation.sql', + '25-walk-forward.sql', + '26-cost-sensitivity.sql', + '27-research-evidence-sources.sql', + '28-research-agents.sql', + '29-isolated-candidates.sql', + '30-paper-deployments.sql', + '31-research-agent-project-links.sql', + '32-candidate-parameter-defaults.sql', + '33-candidate-decimal-normalization.sql', +]; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +async function createIsolatedFixture() { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + + const tables = async () => + ( + await pool.query('SELECT tablename FROM pg_tables WHERE schemaname = $1 ORDER BY tablename', [ + schema, + ]) + ).rows.map(row => row.tablename as string); + + const recorded = async () => + (await pool.query('SELECT filename FROM migrations ORDER BY filename')).rows.map( + row => row.filename as string + ); + + const hasColumn = async (tableName: string, columnName: string) => + ( + await pool.query( + 'SELECT 1 FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 AND column_name = $3', + [schema, tableName, columnName] + ) + ).rowCount === 1; + + return { pool, schema, postgres, tables, recorded, hasColumn }; +} + +describe.skipIf(!url)('fresh PostgreSQL database schema', () => { + test('Case A: init SQL 01-33 contain no CREATE DATABASE/\\c and create all master and research tables', async () => { + const f = await createIsolatedFixture(); + const sqlFiles = readdirSync(initDir) + .filter(file => file.endsWith('.sql')) + .sort(); + + expect(sqlFiles.length).toBeGreaterThanOrEqual(33); + + for (const file of sqlFiles) { + const sql = readFileSync(join(initDir, file), 'utf8'); + expect(sql).not.toMatch(/\bCREATE\s+DATABASE\b/i); + expect(sql).not.toMatch(/^\s*\\c(?:\s|$)/m); + await f.pool.query(sql); + } + + const createdTables = new Set(await f.tables()); + for (const expectedTable of [ + // Master tables (02-05) + 'exchanges', + 'symbols', + 'provider_exchange_mappings', + 'provider_mappings', + 'sync_status', + // Research tables (06-33, including representatives from 12, 16, 20, 22, 28, 30) + 'backtests', + 'backtest_results', + 'runs', + 'backtest_datasets', + 'strategies', + 'research_projects', + 'research_experiments', + 'research_agents', + 'paper_deployments', + ]) { + expect(createdTables.has(expectedTable)).toBe(true); + } + + // 05-add-visible-column.sql & 19-canonical-research.sql add columns to existing tables + expect(await f.hasColumn('exchanges', 'visible')).toBe(true); + expect(await f.hasColumn('backtest_results', 'canonical_result')).toBe(true); + }); + + test('Case B: master track creates master tables, records exact 5 files, and is idempotent', async () => { + const f = await createIsolatedFixture(); + + const first = await runPostgresMigrations(f.postgres, { track: 'master' }); + expect(first).toEqual(MASTER_FILES); + expect(await f.recorded()).toEqual(MASTER_FILES); + + const createdTables = new Set(await f.tables()); + for (const table of [ + 'exchanges', + 'symbols', + 'provider_exchange_mappings', + 'provider_mappings', + 'sync_status', + ]) { + expect(createdTables.has(table)).toBe(true); + } + expect(await f.hasColumn('exchanges', 'visible')).toBe(true); + + const second = await runPostgresMigrations(f.postgres, { track: 'master' }); + expect(second).toEqual([]); + expect(await f.recorded()).toEqual(MASTER_FILES); + }); + + test('Case C: all track with 06-08 pre-applied records master + 09-33 and never records 06-08', async () => { + const f = await createIsolatedFixture(); + + for (const file of BOOTSTRAP_FILES) { + await f.pool.query(readFileSync(join(initDir, file), 'utf8')); + } + + const expected = [...MASTER_FILES, ...RESEARCH_FILES]; + const first = await runPostgresMigrations(f.postgres, { track: 'all' }); + expect(first).toEqual(expected); + + const recorded = await f.recorded(); + expect(recorded).toEqual(expected); + for (const excluded of BOOTSTRAP_FILES) { + expect(recorded).not.toContain(excluded); + } + + const second = await runPostgresMigrations(f.postgres, { track: 'all' }); + expect(second).toEqual([]); + }); + + test('Case D: failing master migration rolls back all DDL and leaves no migrations row', async () => { + const f = await createIsolatedFixture(); + const tempDir = mkdtempSync(join(tmpdir(), 'stock-bot-migrate-fail-')); + cleanup.push(() => { + rmSync(tempDir, { recursive: true, force: true }); + }); + + copyFileSync(join(initDir, '01-init-database.sql'), join(tempDir, '01-init-database.sql')); + copyFileSync(join(initDir, '02-master-schema.sql'), join(tempDir, '02-master-schema.sql')); + writeFileSync(join(tempDir, '03-initial-data.sql'), 'SELECT 1 / 0;\n', 'utf8'); + + await expect( + runPostgresMigrations(f.postgres, { track: 'master', migrationsDir: tempDir }) + ).rejects.toThrow(/division by zero/i); + + expect(await f.tables()).toEqual([]); + }); +}); From b82fc7c905e26ec1ed02894787d20b01babdad11 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 10:39:55 -0500 Subject: [PATCH 03/20] =?UTF-8?q?T-2:=20M0.2=20=E2=80=94=20Finish=20shared?= =?UTF-8?q?=20Postgres=20migrations:=20`bun=20run=20db:migrate`=20+=20fres?= =?UTF-8?q?h-database=20schema=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/stock/config/src/config-instance.ts | 6 +- scripts/db-migrate.ts | 12 ++- scripts/test/db-migrate.test.ts | 103 ++++++++++++++++++++++- 3 files changed, 114 insertions(+), 7 deletions(-) diff --git a/apps/stock/config/src/config-instance.ts b/apps/stock/config/src/config-instance.ts index b5eda87a..d949c8f8 100644 --- a/apps/stock/config/src/config-instance.ts +++ b/apps/stock/config/src/config-instance.ts @@ -13,6 +13,7 @@ const __dirname = path.dirname(__filename); export interface InitializeStockConfigOptions { mongoReadOnly?: boolean; + postgresOnly?: boolean; } /** @@ -33,14 +34,15 @@ export function initializeStockConfig( const rawConfig = configInstance.initialize(stockAppSchema); const config: StockAppConfig = - options?.mongoReadOnly === true + options?.mongoReadOnly === true || options?.postgresOnly === true ? { ...rawConfig, database: { ...rawConfig.database, mongodb: { ...rawConfig.database.mongodb, - readOnly: true, + ...(options?.mongoReadOnly === true ? { readOnly: true } : {}), + ...(options?.postgresOnly === true ? { enabled: false } : {}), }, }, } diff --git a/scripts/db-migrate.ts b/scripts/db-migrate.ts index d8f6434f..3ef20669 100644 --- a/scripts/db-migrate.ts +++ b/scripts/db-migrate.ts @@ -60,6 +60,10 @@ export function parseDbMigrateArgs(argv: readonly string[]): DbMigrateArgs { return { track }; } +export function loadMigrationConfig(): StockAppConfig { + return initializeStockConfig('dataPipeline', { postgresOnly: true }); +} + export function resolveMigrationTarget( config: StockAppConfig, env: Record = process.env @@ -69,7 +73,9 @@ export function resolveMigrationTarget( throw new Error('PostgreSQL is disabled in the active configuration.'); } - // Disable unrelated MongoDB checks so Postgres migrations only enforce PostgreSQL/environment guards. + // Never allow the shared dev-on-QA override to bypass the PostgreSQL guard in db:migrate, + // and disable unrelated MongoDB checks so Postgres migrations only enforce PostgreSQL/environment guards. + const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _ignored, ...safeEnv } = env; assertEnvironmentSafety( { ...config, @@ -82,7 +88,7 @@ export function resolveMigrationTarget( }, }, 'dataPipeline', - env + safeEnv ); const clientConfig: PostgreSQLClientConfig = { @@ -108,7 +114,7 @@ export function resolveMigrationTarget( async function main(argv: readonly string[]): Promise { const { track } = parseDbMigrateArgs(argv); - const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); + const config = loadMigrationConfig(); const { clientConfig, targetLabel } = resolveMigrationTarget(config, process.env); const logger = getLogger('db-migrate'); const client = new PostgreSQLClient(clientConfig, logger); diff --git a/scripts/test/db-migrate.test.ts b/scripts/test/db-migrate.test.ts index 2d5793a5..d7b05d52 100644 --- a/scripts/test/db-migrate.test.ts +++ b/scripts/test/db-migrate.test.ts @@ -1,7 +1,7 @@ import { fileURLToPath } from 'node:url'; import { describe, expect, test } from 'bun:test'; -import { stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config'; -import { parseDbMigrateArgs, resolveMigrationTarget } from '../db-migrate'; +import { resetStockConfig, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config'; +import { loadMigrationConfig, parseDbMigrateArgs, resolveMigrationTarget } from '../db-migrate'; const root = fileURLToPath(new URL('../../', import.meta.url)); @@ -121,6 +121,16 @@ describe('resolveMigrationTarget', () => { expect(() => resolveMigrationTarget(config, {})).toThrow(/dev PostgreSQL/i); }); + test('rejects development targeting QA PostgreSQL even when STOCK_BOT_ALLOW_DEV_ON_QA_DB=true', () => { + const config = makeConfig({ + environment: 'development', + postgres: { host: 'localhost', port: 5432, database: 'trading_bot' }, + }); + expect(() => + resolveMigrationTarget(config, { STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true' }) + ).toThrow(/QA PostgreSQL/i); + }); + test('rejects disabled PostgreSQL configuration', () => { const config = makeConfig({ environment: 'development', @@ -130,6 +140,95 @@ describe('resolveMigrationTarget', () => { }); }); +function withEnv(overrides: Record, fn: () => void): void { + const previous = new Map(); + for (const [key, value] of Object.entries(overrides)) { + previous.set(key, process.env[key]); + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } + resetStockConfig(); + try { + fn(); + } finally { + resetStockConfig(); + for (const [key, value] of previous.entries()) { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } + } +} + +describe('loadMigrationConfig (real initialization path)', () => { + test('succeeds for dev PostgreSQL even when QA MongoDB admin URI is set without MONGODB_READ_URI', () => { + withEnv( + { + NODE_ENV: 'development', + POSTGRES_HOST: 'localhost', + POSTGRES_PORT: '5433', + POSTGRES_DATABASE: 'trading_bot_dev', + POSTGRES_USERNAME: 'dev_user', + POSTGRES_PASSWORD: 'dev_pass', + DATABASE_POSTGRES_HOST: 'localhost', + DATABASE_POSTGRES_PORT: '5433', + DATABASE_POSTGRES_DATABASE: 'trading_bot_dev', + MONGODB_URI: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', + MONGODB_READ_URI: undefined, + STOCK_BOT_ALLOW_DEV_ON_QA_DB: undefined, + }, + () => { + const config = loadMigrationConfig(); + expect(config.database.mongodb.enabled).toBe(false); + const resolved = resolveMigrationTarget(config, process.env); + expect(resolved.targetLabel).toBe('localhost:5433/trading_bot_dev'); + } + ); + }); + + test('rejects development targeting QA PostgreSQL during real config initialization', () => { + withEnv( + { + NODE_ENV: 'development', + POSTGRES_HOST: 'localhost', + POSTGRES_PORT: '5432', + POSTGRES_DATABASE: 'trading_bot', + DATABASE_POSTGRES_HOST: 'localhost', + DATABASE_POSTGRES_PORT: '5432', + DATABASE_POSTGRES_DATABASE: 'trading_bot', + STOCK_BOT_ALLOW_DEV_ON_QA_DB: undefined, + }, + () => { + expect(() => loadMigrationConfig()).toThrow(/QA PostgreSQL/i); + } + ); + }); + + test('rejects development targeting QA PostgreSQL even when STOCK_BOT_ALLOW_DEV_ON_QA_DB=true in real env', () => { + withEnv( + { + NODE_ENV: 'development', + POSTGRES_HOST: 'localhost', + POSTGRES_PORT: '5432', + POSTGRES_DATABASE: 'trading_bot', + DATABASE_POSTGRES_HOST: 'localhost', + DATABASE_POSTGRES_PORT: '5432', + DATABASE_POSTGRES_DATABASE: 'trading_bot', + STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true', + }, + () => { + const config = loadMigrationConfig(); + expect(() => resolveMigrationTarget(config, process.env)).toThrow(/QA PostgreSQL/i); + } + ); + }); +}); + describe('db-migrate CLI subprocess', () => { test('exits non-zero with valid tracks on stderr for --track bogus without connecting to DB', () => { const result = Bun.spawnSync( From f36bdbd6bd9eeafb983c919dec64f71e44bf1eaa Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 10:43:36 -0500 Subject: [PATCH 04/20] =?UTF-8?q?T-2:=20M0.2=20=E2=80=94=20Finish=20shared?= =?UTF-8?q?=20Postgres=20migrations:=20`bun=20run=20db:migrate`=20+=20fres?= =?UTF-8?q?h-database=20schema=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/stock/config/src/config-instance.ts | 9 +- scripts/db-migrate.ts | 3 + scripts/test/db-migrate.test.ts | 181 ++++++++++++++--------- 3 files changed, 125 insertions(+), 68 deletions(-) diff --git a/apps/stock/config/src/config-instance.ts b/apps/stock/config/src/config-instance.ts index d949c8f8..04187ff1 100644 --- a/apps/stock/config/src/config-instance.ts +++ b/apps/stock/config/src/config-instance.ts @@ -42,7 +42,14 @@ export function initializeStockConfig( mongodb: { ...rawConfig.database.mongodb, ...(options?.mongoReadOnly === true ? { readOnly: true } : {}), - ...(options?.postgresOnly === true ? { enabled: false } : {}), + ...(options?.postgresOnly === true + ? { + enabled: false, + uri: 'mongodb://disabled', + readUri: undefined, + password: undefined, + } + : {}), }, }, } diff --git a/scripts/db-migrate.ts b/scripts/db-migrate.ts index 3ef20669..c5e2b3e5 100644 --- a/scripts/db-migrate.ts +++ b/scripts/db-migrate.ts @@ -84,6 +84,9 @@ export function resolveMigrationTarget( mongodb: { ...config.database.mongodb, enabled: false, + uri: 'mongodb://disabled', + readUri: undefined, + password: undefined, }, }, }, diff --git a/scripts/test/db-migrate.test.ts b/scripts/test/db-migrate.test.ts index d7b05d52..37218d5b 100644 --- a/scripts/test/db-migrate.test.ts +++ b/scripts/test/db-migrate.test.ts @@ -1,9 +1,13 @@ -import { fileURLToPath } from 'node:url'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; import { describe, expect, test } from 'bun:test'; -import { resetStockConfig, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config'; -import { loadMigrationConfig, parseDbMigrateArgs, resolveMigrationTarget } from '../db-migrate'; +import { stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config'; +import { parseDbMigrateArgs, resolveMigrationTarget } from '../db-migrate'; const root = fileURLToPath(new URL('../../', import.meta.url)); +const dbMigrateModuleUrl = pathToFileURL(join(root, 'scripts/db-migrate.ts')).href; function makeConfig(overrides: { environment?: StockAppConfig['environment']; @@ -140,59 +144,64 @@ describe('resolveMigrationTarget', () => { }); }); -function withEnv(overrides: Record, fn: () => void): void { - const previous = new Map(); - for (const [key, value] of Object.entries(overrides)) { - previous.set(key, process.env[key]); - if (value === undefined) { - delete process.env[key]; - } else { - process.env[key] = value; - } - } - resetStockConfig(); +function runInitInIsolatedSubprocess( + env: Record, + mode: 'load-and-resolve' | 'load-only' = 'load-and-resolve' +): { exitCode: number; stdout: string; stderr: string } { + const isolatedDir = mkdtempSync(join(tmpdir(), 'stock-bot-db-migrate-env-')); + const script = + mode === 'load-only' + ? `import { loadMigrationConfig } from ${JSON.stringify(dbMigrateModuleUrl)}; +const config = loadMigrationConfig(); +console.log(JSON.stringify({ mongoEnabled: config.database.mongodb.enabled }));` + : `import { loadMigrationConfig, resolveMigrationTarget } from ${JSON.stringify(dbMigrateModuleUrl)}; +const config = loadMigrationConfig(); +const resolved = resolveMigrationTarget(config, process.env); +console.log(JSON.stringify({ mongoEnabled: config.database.mongodb.enabled, targetLabel: resolved.targetLabel }));`; + try { - fn(); + const result = Bun.spawnSync([process.execPath, '-e', script], { + cwd: isolatedDir, + env: { + PATH: process.env.PATH ?? '', + HOME: isolatedDir, + ...env, + }, + }); + return { + exitCode: result.exitCode, + stdout: new TextDecoder().decode(result.stdout).trim(), + stderr: new TextDecoder().decode(result.stderr).trim(), + }; } finally { - resetStockConfig(); - for (const [key, value] of previous.entries()) { - if (value === undefined) { - delete process.env[key]; - } else { - process.env[key] = value; - } - } + rmSync(isolatedDir, { recursive: true, force: true }); } } -describe('loadMigrationConfig (real initialization path)', () => { +describe('loadMigrationConfig (real initialization path, isolated subprocess)', () => { test('succeeds for dev PostgreSQL even when QA MongoDB admin URI is set without MONGODB_READ_URI', () => { - withEnv( - { - NODE_ENV: 'development', - POSTGRES_HOST: 'localhost', - POSTGRES_PORT: '5433', - POSTGRES_DATABASE: 'trading_bot_dev', - POSTGRES_USERNAME: 'dev_user', - POSTGRES_PASSWORD: 'dev_pass', - DATABASE_POSTGRES_HOST: 'localhost', - DATABASE_POSTGRES_PORT: '5433', - DATABASE_POSTGRES_DATABASE: 'trading_bot_dev', - MONGODB_URI: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', - MONGODB_READ_URI: undefined, - STOCK_BOT_ALLOW_DEV_ON_QA_DB: undefined, - }, - () => { - const config = loadMigrationConfig(); - expect(config.database.mongodb.enabled).toBe(false); - const resolved = resolveMigrationTarget(config, process.env); - expect(resolved.targetLabel).toBe('localhost:5433/trading_bot_dev'); - } - ); + const result = runInitInIsolatedSubprocess({ + NODE_ENV: 'development', + POSTGRES_HOST: 'localhost', + POSTGRES_PORT: '5433', + POSTGRES_DATABASE: 'trading_bot_dev', + POSTGRES_USERNAME: 'dev_user', + POSTGRES_PASSWORD: 'dev_pass', + DATABASE_POSTGRES_HOST: 'localhost', + DATABASE_POSTGRES_PORT: '5433', + DATABASE_POSTGRES_DATABASE: 'trading_bot_dev', + MONGODB_URI: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', + }); + + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + mongoEnabled: false, + targetLabel: 'localhost:5433/trading_bot_dev', + }); }); test('rejects development targeting QA PostgreSQL during real config initialization', () => { - withEnv( + const result = runInitInIsolatedSubprocess( { NODE_ENV: 'development', POSTGRES_HOST: 'localhost', @@ -201,31 +210,69 @@ describe('loadMigrationConfig (real initialization path)', () => { DATABASE_POSTGRES_HOST: 'localhost', DATABASE_POSTGRES_PORT: '5432', DATABASE_POSTGRES_DATABASE: 'trading_bot', - STOCK_BOT_ALLOW_DEV_ON_QA_DB: undefined, }, - () => { - expect(() => loadMigrationConfig()).toThrow(/QA PostgreSQL/i); - } + 'load-only' ); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toMatch(/QA PostgreSQL/i); }); test('rejects development targeting QA PostgreSQL even when STOCK_BOT_ALLOW_DEV_ON_QA_DB=true in real env', () => { - withEnv( - { - NODE_ENV: 'development', - POSTGRES_HOST: 'localhost', - POSTGRES_PORT: '5432', - POSTGRES_DATABASE: 'trading_bot', - DATABASE_POSTGRES_HOST: 'localhost', - DATABASE_POSTGRES_PORT: '5432', - DATABASE_POSTGRES_DATABASE: 'trading_bot', - STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true', - }, - () => { - const config = loadMigrationConfig(); - expect(() => resolveMigrationTarget(config, process.env)).toThrow(/QA PostgreSQL/i); - } - ); + const result = runInitInIsolatedSubprocess({ + NODE_ENV: 'development', + POSTGRES_HOST: 'localhost', + POSTGRES_PORT: '5432', + POSTGRES_DATABASE: 'trading_bot', + DATABASE_POSTGRES_HOST: 'localhost', + DATABASE_POSTGRES_PORT: '5432', + DATABASE_POSTGRES_DATABASE: 'trading_bot', + STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true', + }); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toMatch(/QA PostgreSQL/i); + }); + + test('succeeds in production with unused MongoDB placeholder credential while still rejecting dev Postgres password', () => { + const okResult = runInitInIsolatedSubprocess({ + NODE_ENV: 'production', + POSTGRES_HOST: 'pg.prod.internal', + POSTGRES_PORT: '5432', + POSTGRES_DATABASE: 'trading_bot', + POSTGRES_USERNAME: 'prod_user', + POSTGRES_PASSWORD: 'strong_prod_pg_secret_987', + DATABASE_POSTGRES_HOST: 'pg.prod.internal', + DATABASE_POSTGRES_PORT: '5432', + DATABASE_POSTGRES_DATABASE: 'trading_bot', + DATABASE_POSTGRES_PASSWORD: 'strong_prod_pg_secret_987', + MONGODB_URI: 'mongodb://prod:trading_mongo_dev@mongo.internal:27017/stock?authSource=admin', + DRAGONFLY_PASSWORD: 'strong_prod_redis_secret_987', + }); + + expect(okResult.exitCode).toBe(0); + expect(JSON.parse(okResult.stdout)).toEqual({ + mongoEnabled: false, + targetLabel: 'pg.prod.internal:5432/trading_bot', + }); + + const badPgResult = runInitInIsolatedSubprocess({ + NODE_ENV: 'production', + POSTGRES_HOST: 'pg.prod.internal', + POSTGRES_PORT: '5432', + POSTGRES_DATABASE: 'trading_bot', + POSTGRES_USERNAME: 'prod_user', + POSTGRES_PASSWORD: 'trading_pass_dev', + DATABASE_POSTGRES_HOST: 'pg.prod.internal', + DATABASE_POSTGRES_PORT: '5432', + DATABASE_POSTGRES_DATABASE: 'trading_bot', + DATABASE_POSTGRES_PASSWORD: 'trading_pass_dev', + MONGODB_URI: 'mongodb://prod:trading_mongo_dev@mongo.internal:27017/stock?authSource=admin', + DRAGONFLY_PASSWORD: 'strong_prod_redis_secret_987', + }); + + expect(badPgResult.exitCode).not.toBe(0); + expect(badPgResult.stderr).toMatch(/production PostgreSQL password/i); }); }); From 2a28c402e8a71aa3177b9d47842258a8c13a243a Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 11:08:34 -0500 Subject: [PATCH 05/20] T-9: Multi-host MongoDB URI bypasses the dev QA-Mongo guard --- apps/stock/config/src/env-safety.ts | 187 ++++++++++++++++++++++---- test/unit/environment-safety.test.ts | 190 ++++++++++++++++++++++++++- 2 files changed, 346 insertions(+), 31 deletions(-) diff --git a/apps/stock/config/src/env-safety.ts b/apps/stock/config/src/env-safety.ts index d4187560..66df53ec 100644 --- a/apps/stock/config/src/env-safety.ts +++ b/apps/stock/config/src/env-safety.ts @@ -2,7 +2,25 @@ import type { StockAppConfig } from './schemas'; export type StockServiceName = 'dataIngestion' | 'dataPipeline' | 'webApi' | 'orchestrator'; -const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0']); +interface MongoTargetHost { + host: string; + port?: number; +} + +interface ParsedMongoTarget { + hosts: MongoTargetHost[]; + host?: string; + database?: string; + username?: string; +} + +const LOOPBACK_HOSTS = new Set([ + 'localhost', + '0.0.0.0', + '::1', + '0:0:0:0:0:0:0:1', + '::ffff:127.0.0.1', +]); const FORBIDDEN_PROD_SECRETS = new Set([ 'trading_pass_dev', 'trading_mongo_dev', @@ -12,41 +30,162 @@ const FORBIDDEN_PROD_SECRETS = new Set([ 'admin123', ]); +function isIpv4Loopback(host: string): boolean { + const octets = host.split('.'); + if (octets.length !== 4 || octets[0] !== '127') { + return false; + } + return octets.every(part => { + if (!/^\d{1,3}$/.test(part)) { + return false; + } + const value = Number(part); + return value >= 0 && value <= 255; + }); +} + function isLoopbackHost(host?: string): boolean { if (!host) { return false; } - const normalized = host.replace(/^\[|\]$/g, '').toLowerCase(); - return LOOPBACK_HOSTS.has(normalized); + const normalized = host + .trim() + .replace(/^\[|\]$/g, '') + .replace(/\.+$/, '') + .toLowerCase(); + if (LOOPBACK_HOSTS.has(normalized) || isIpv4Loopback(normalized)) { + return true; + } + return normalized.startsWith('::ffff:') && isIpv4Loopback(normalized.slice(7)); } -function parseMongoTarget(uri?: string): { - host?: string; - port?: number; - database?: string; - username?: string; -} { - if (!uri) { - return {}; +function parseMongoHostPort( + segment: string, + defaultPort: number | undefined +): MongoTargetHost | null { + const trimmed = segment.trim(); + if (!trimmed) { + return null; } - try { - const parsed = new URL(uri); - const database = parsed.pathname.replace(/^\/+/, '').split('/')[0] || undefined; - const port = parsed.port ? Number(parsed.port) : parsed.protocol === 'mongodb:' ? 27017 : undefined; - return { - host: parsed.hostname || undefined, - port: Number.isFinite(port) ? port : undefined, - database, - username: parsed.username ? decodeURIComponent(parsed.username) : undefined, - }; - } catch { - return {}; + + if (trimmed.startsWith('[')) { + const closeIdx = trimmed.indexOf(']'); + if (closeIdx <= 1) { + return null; + } + const host = trimmed.slice(1, closeIdx).trim(); + if (!host) { + return null; + } + const after = trimmed.slice(closeIdx + 1).trim(); + if (after === '' || after === ':') { + return { host, port: defaultPort }; + } + if (!after.startsWith(':')) { + return null; + } + const portStr = after.slice(1).trim(); + if (!/^\d+$/.test(portStr)) { + return null; + } + const port = Number(portStr); + if (port < 1 || port > 65535) { + return null; + } + return { host, port }; } + + const colonIdx = trimmed.indexOf(':'); + if (colonIdx === -1) { + return { host: trimmed, port: defaultPort }; + } + if (trimmed.indexOf(':', colonIdx + 1) !== -1) { + return null; + } + + const host = trimmed.slice(0, colonIdx).trim(); + const portStr = trimmed.slice(colonIdx + 1).trim(); + if (!host) { + return null; + } + if (portStr === '') { + return { host, port: defaultPort }; + } + if (!/^\d+$/.test(portStr)) { + return null; + } + const port = Number(portStr); + if (port < 1 || port > 65535) { + return null; + } + return { host, port }; +} + +function parseMongoTarget(uri?: string): ParsedMongoTarget { + const trimmed = uri?.trim(); + if (!trimmed) { + return { hosts: [] }; + } + + const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/i.exec(trimmed); + const rawScheme = schemeMatch?.[1]; + const rest = schemeMatch?.[2]; + if (!rawScheme || rest === undefined) { + return { hosts: [] }; + } + + const scheme = rawScheme.toLowerCase(); + const defaultPort = scheme === 'mongodb' ? 27017 : undefined; + + const delimiterMatch = /[/?#]/.exec(rest); + const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest; + const remainder = delimiterMatch ? rest.slice(delimiterMatch.index) : ''; + + let database: string | undefined; + if (remainder.startsWith('/')) { + const pathPart = remainder.split(/[?#]/, 1)[0] ?? ''; + const firstSegment = pathPart.replace(/^\/+/, '').split('/')[0]; + database = firstSegment || undefined; + } + + const atIndex = authority.lastIndexOf('@'); + const userinfo = atIndex >= 0 ? authority.slice(0, atIndex) : ''; + const hostList = atIndex >= 0 ? authority.slice(atIndex + 1) : authority; + + let username: string | undefined; + if (userinfo) { + const colonIndex = userinfo.indexOf(':'); + const rawUsername = colonIndex >= 0 ? userinfo.slice(0, colonIndex) : userinfo; + if (rawUsername) { + try { + username = decodeURIComponent(rawUsername); + } catch { + username = rawUsername; + } + } + } + + const hosts: MongoTargetHost[] = []; + for (const segment of hostList.split(',')) { + const parsedHost = parseMongoHostPort(segment, defaultPort); + if (parsedHost) { + hosts.push(parsedHost); + } + } + + return { + hosts, + host: hosts[0]?.host, + database, + username, + }; } function isQaMongoTarget(uri: string | undefined): boolean { const target = parseMongoTarget(uri); - return isLoopbackHost(target.host) && target.port === 27017; + return target.hosts.some( + entry => isLoopbackHost(entry.host) && (entry.port === undefined || entry.port === 27017) + ); } function isQaPostgresTarget(pg: StockAppConfig['database']['postgres']): boolean { diff --git a/test/unit/environment-safety.test.ts b/test/unit/environment-safety.test.ts index bc0bc88d..84e057a7 100644 --- a/test/unit/environment-safety.test.ts +++ b/test/unit/environment-safety.test.ts @@ -25,7 +25,7 @@ function makeConfig(overrides: { mongoDatabase?: string; dragonflyPassword?: string; } = {}): StockAppConfig { - return stockAppSchema.parse({ + const parsed = stockAppSchema.parse({ name: 'stock-bot', version: '1.0.0', environment: overrides.environment ?? 'development', @@ -50,12 +50,8 @@ function makeConfig(overrides: { }, mongodb: { enabled: true, - uri: - overrides.mongoUri ?? - 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin', - readUri: - overrides.mongoReadUri ?? - 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock', + uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin', + readUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock', readOnly: overrides.mongoReadOnly ?? false, database: overrides.mongoDatabase ?? 'stock_dev', }, @@ -81,6 +77,15 @@ function makeConfig(overrides: { }, features: {}, }); + + if (overrides.mongoUri !== undefined) { + parsed.database.mongodb.uri = overrides.mongoUri; + } + if (overrides.mongoReadUri !== undefined) { + parsed.database.mongodb.readUri = overrides.mongoReadUri; + } + + return parsed; } describe('Environment safety & multi-env isolation', () => { @@ -247,6 +252,177 @@ describe('Environment safety & multi-env isolation', () => { ); }); + test('blocks multi-host MongoDB seed lists targeting QA loopback :27017 for dataIngestion and dataPipeline', () => { + const qaFirstIngestion = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://u:p@localhost:27017,localhost:27018/stock', + mongoDatabase: 'stock', + }); + expect(() => assertEnvironmentSafety(qaFirstIngestion, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + expect(() => + assertEnvironmentSafety(qaFirstIngestion, 'dataIngestion', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).not.toThrow(); + + const qaSecondIngestion = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://u:p@localhost:27018,localhost:27017/stock_dev', + mongoDatabase: 'stock_dev', + }); + expect(() => assertEnvironmentSafety(qaSecondIngestion, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + expect(() => + assertEnvironmentSafety(qaSecondIngestion, 'dataIngestion', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).not.toThrow(); + + const qaPipelineNonReadOnly = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27018,localhost:27017/stock_dev', + mongoReadOnly: false, + }); + expect(() => assertEnvironmentSafety(qaPipelineNonReadOnly, 'dataPipeline', {})).toThrow( + /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ + ); + + const qaPipelineFallbackUri = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://studio_stock_bot_read:secret@localhost:27018,localhost:27017/stock', + mongoReadOnly: false, + }); + qaPipelineFallbackUri.database.mongodb.readUri = undefined; + expect(() => assertEnvironmentSafety(qaPipelineFallbackUri, 'dataPipeline', {})).toThrow( + /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ + ); + + const qaPipelineAdmin = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://trading_admin:pass@localhost:27017,localhost:27018/stock', + mongoReadOnly: true, + }); + expect(() => + assertEnvironmentSafety(qaPipelineAdmin, 'dataPipeline', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/); + + const qaPipelineEncodedAdmin = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://trading%5Fadmin:pass@localhost:27018,localhost:27017/stock', + mongoReadOnly: true, + }); + expect(() => + assertEnvironmentSafety(qaPipelineEncodedAdmin, 'dataPipeline', { + STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true', + }) + ).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/); + + const qaPipelineReadOnlyAllowed = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock', + mongoReadOnly: true, + }); + expect(() => assertEnvironmentSafety(qaPipelineReadOnlyAllowed, 'dataPipeline', {})).not.toThrow(); + }); + + test('blocks omitted port, loopback variants, and mongodb+srv loopback URIs', () => { + const qaLoopbackUris = [ + 'mongodb://u:p@localhost:27018,localhost/stock_dev', + 'mongodb://u:p@localhost:27018,127.0.0.1/stock_dev', + 'mongodb://u:p@localhost:27018,[::1]:27017/stock_dev', + 'mongodb://u:p@localhost:27018,[::1]/stock_dev', + 'mongodb://u:p@localhost:27018,LOCALHOST.:27017/stock_dev', + 'mongodb://u:p@127.0.0.2:27017/stock_dev', + 'mongodb+srv://u:p@localhost/stock', + ]; + + for (const mongoUri of qaLoopbackUris) { + const cfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock_dev', + }); + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + } + }); + + test('handles multi-host MongoDB URI parsing edge cases without failing open', () => { + const unencodedAtPipeline = makeConfig({ + environment: 'development', + mongoReadUri: 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock', + mongoReadOnly: true, + }); + expect(() => assertEnvironmentSafety(unencodedAtPipeline, 'dataPipeline', {})).toThrow( + /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/ + ); + + const edgeCaseUris = [ + 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock', + 'mongodb://u:p@localhost:/stock', + 'mongodb://localhost:27017,localhost:27018/stock', + 'mongodb://u:p@bad:port,localhost:27017/stock', + ]; + + for (const mongoUri of edgeCaseUris) { + const cfg = makeConfig({ + environment: 'development', + mongoUri, + mongoDatabase: 'stock', + }); + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + } + }); + + test('allows non-QA multi-host dev seed lists and validates production multi-host URIs', () => { + const devMultiHostUri = + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin'; + + const devIngestion = makeConfig({ + environment: 'development', + mongoUri: devMultiHostUri, + mongoDatabase: 'stock_dev', + }); + expect(() => assertEnvironmentSafety(devIngestion, 'dataIngestion', {})).not.toThrow(); + + const devPipeline = makeConfig({ + environment: 'development', + mongoUri: devMultiHostUri, + mongoReadUri: devMultiHostUri, + mongoReadOnly: false, + mongoDatabase: 'stock_dev', + }); + expect(() => assertEnvironmentSafety(devPipeline, 'dataPipeline', {})).not.toThrow(); + + const prodMultiHostSafe = makeConfig({ + environment: 'production', + pgHost: 'pg.prod.internal', + pgDatabase: 'trading_bot_prod', + pgPassword: 'super-strong-prod-password', + mongoUri: 'mongodb://prod:strongpass@mongo1.prod.internal:27017,mongo2.prod.internal:27017/stock', + }); + expect(() => assertEnvironmentSafety(prodMultiHostSafe, 'webApi', {})).not.toThrow(); + + const prodMultiHostDevSecret = makeConfig({ + environment: 'production', + pgHost: 'pg.prod.internal', + pgDatabase: 'trading_bot_prod', + pgPassword: 'super-strong-prod-password', + mongoUri: 'mongodb://prod:trading_mongo_dev@mongo1.prod.internal:27017,mongo2.prod.internal:27017/stock', + }); + expect(() => assertEnvironmentSafety(prodMultiHostDevSecret, 'webApi', {})).toThrow( + /production MongoDB \(mongo1\.prod\.internal\) cannot use a default dev\/qa credential/ + ); + }); + test('blocks qa environment from targeting *_dev databases', () => { const cfg = makeConfig({ environment: 'qa', From 677658a32fd7ecdbd4c747cae57ad088b8c17cdd Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 11:13:53 -0500 Subject: [PATCH 06/20] T-9: Multi-host MongoDB URI bypasses the dev QA-Mongo guard --- apps/stock/config/src/env-safety.ts | 139 +++++++++++++++--- .../config/src/schemas/database.schema.ts | 87 ++++++++++- libs/core/config/test/schemas.test.ts | 36 ++++- test/unit/environment-safety.test.ts | 119 +++++++++++++-- 4 files changed, 348 insertions(+), 33 deletions(-) diff --git a/apps/stock/config/src/env-safety.ts b/apps/stock/config/src/env-safety.ts index 66df53ec..fda0dad9 100644 --- a/apps/stock/config/src/env-safety.ts +++ b/apps/stock/config/src/env-safety.ts @@ -14,13 +14,7 @@ interface ParsedMongoTarget { username?: string; } -const LOOPBACK_HOSTS = new Set([ - 'localhost', - '0.0.0.0', - '::1', - '0:0:0:0:0:0:0:1', - '::ffff:127.0.0.1', -]); +const LOOPBACK_HOSTS = new Set(['localhost', '0.0.0.0']); const FORBIDDEN_PROD_SECRETS = new Set([ 'trading_pass_dev', 'trading_mongo_dev', @@ -30,18 +24,126 @@ const FORBIDDEN_PROD_SECRETS = new Set([ 'admin123', ]); -function isIpv4Loopback(host: string): boolean { +function parseIpv4Octets(host: string): [number, number, number, number] | null { const octets = host.split('.'); - if (octets.length !== 4 || octets[0] !== '127') { - return false; + if (octets.length !== 4) { + return null; } - return octets.every(part => { + const values: number[] = []; + for (const part of octets) { if (!/^\d{1,3}$/.test(part)) { - return false; + return null; } const value = Number(part); - return value >= 0 && value <= 255; - }); + if (value < 0 || value > 255) { + return null; + } + values.push(value); + } + const [a, b, c, d] = values; + if (a === undefined || b === undefined || c === undefined || d === undefined) { + return null; + } + return [a, b, c, d]; +} + +function isIpv4Loopback(host: string): boolean { + const octets = parseIpv4Octets(host); + return octets !== null && octets[0] === 127; +} + +function parseIpv6Side(side: string, allowIpv4Tail: boolean): number[] | null { + if (side === '') { + return []; + } + const parts = side.split(':'); + const groups: number[] = []; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + if (part === undefined) { + return null; + } + if (i === parts.length - 1 && allowIpv4Tail && part.includes('.')) { + const octets = parseIpv4Octets(part); + if (!octets) { + return null; + } + groups.push((octets[0] << 8) | octets[1], (octets[2] << 8) | octets[3]); + continue; + } + if (!/^[0-9a-f]{1,4}$/i.test(part)) { + return null; + } + groups.push(parseInt(part, 16)); + } + return groups; +} + +function parseIpv6Hextets(host: string): number[] | null { + if (!host.includes(':')) { + return null; + } + const zoneIdx = host.indexOf('%'); + const addr = zoneIdx >= 0 ? host.slice(0, zoneIdx) : host; + const halves = addr.split('::'); + if (halves.length > 2) { + return null; + } + + const firstHalf = halves[0]; + if (firstHalf === undefined) { + return null; + } + + if (halves.length === 1) { + const groups = parseIpv6Side(firstHalf, true); + return groups && groups.length === 8 ? groups : null; + } + + const secondHalf = halves[1]; + if (secondHalf === undefined) { + return null; + } + + const left = parseIpv6Side(firstHalf, false); + const right = parseIpv6Side(secondHalf, true); + if (!left || !right) { + return null; + } + const missing = 8 - left.length - right.length; + if (missing < 1) { + return null; + } + return [...left, ...Array(missing).fill(0), ...right]; +} + +function isIpv6Loopback(host: string): boolean { + const hextets = parseIpv6Hextets(host); + if (!hextets) { + return false; + } + const [h0, h1, h2, h3, h4, h5, h6, h7] = hextets; + if ( + h0 === undefined || + h1 === undefined || + h2 === undefined || + h3 === undefined || + h4 === undefined || + h5 === undefined || + h6 === undefined || + h7 === undefined + ) { + return false; + } + if (h0 === 0 && h1 === 0 && h2 === 0 && h3 === 0 && h4 === 0 && h5 === 0 && h6 === 0) { + return h7 === 0 || h7 === 1; + } + // IPv4-mapped IPv6 (::ffff:0:0/96): match 127.0.0.0/8 and 0.0.0.0 in both dotted and hex forms + if (h0 === 0 && h1 === 0 && h2 === 0 && h3 === 0 && h4 === 0 && h5 === 0xffff) { + const firstOctet = (h6 >> 8) & 0xff; + return firstOctet === 127 || (h6 === 0 && h7 === 0); + } + return false; } function isLoopbackHost(host?: string): boolean { @@ -53,10 +155,11 @@ function isLoopbackHost(host?: string): boolean { .replace(/^\[|\]$/g, '') .replace(/\.+$/, '') .toLowerCase(); - if (LOOPBACK_HOSTS.has(normalized) || isIpv4Loopback(normalized)) { - return true; - } - return normalized.startsWith('::ffff:') && isIpv4Loopback(normalized.slice(7)); + return ( + LOOPBACK_HOSTS.has(normalized) || + isIpv4Loopback(normalized) || + isIpv6Loopback(normalized) + ); } function parseMongoHostPort( diff --git a/libs/core/config/src/schemas/database.schema.ts b/libs/core/config/src/schemas/database.schema.ts index 72c255d3..c9f08c8c 100644 --- a/libs/core/config/src/schemas/database.schema.ts +++ b/libs/core/config/src/schemas/database.schema.ts @@ -33,11 +33,94 @@ export const questdbConfigSchema = z.object({ .describe('Deprecated: no effect on QuestDB client/writer'), }); +function isValidMongoHostSegment(segment: string, allowPort: boolean): boolean { + if (!segment || /\s/.test(segment)) { + return false; + } + + if (segment.startsWith('[')) { + const closeIdx = segment.indexOf(']'); + if (closeIdx <= 1) { + return false; + } + const host = segment.slice(1, closeIdx); + if (!host || host.includes('[') || host.includes(']')) { + return false; + } + const after = segment.slice(closeIdx + 1); + if (after === '') { + return true; + } + if (!allowPort || !after.startsWith(':')) { + return false; + } + const portStr = after.slice(1); + if (!/^\d+$/.test(portStr)) { + return false; + } + const port = Number(portStr); + return port >= 1 && port <= 65535; + } + + const colonIdx = segment.indexOf(':'); + if (colonIdx === -1) { + return true; + } + if (!allowPort || segment.indexOf(':', colonIdx + 1) !== -1) { + return false; + } + + const host = segment.slice(0, colonIdx); + const portStr = segment.slice(colonIdx + 1); + if (!host || !/^\d+$/.test(portStr)) { + return false; + } + const port = Number(portStr); + return port >= 1 && port <= 65535; +} + +function isValidMongoUri(uri: string): boolean { + if (!uri || /\s/.test(uri)) { + return false; + } + + const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/i.exec(uri); + const rawScheme = schemeMatch?.[1]; + const rest = schemeMatch?.[2]; + if (!rawScheme || !rest) { + return false; + } + + const isSrv = rawScheme.toLowerCase() === 'mongodb+srv'; + const delimiterMatch = /[/?#]/.exec(rest); + const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest; + if (!authority) { + return false; + } + + const atIndex = authority.lastIndexOf('@'); + const hostList = atIndex >= 0 ? authority.slice(atIndex + 1) : authority; + if (!hostList) { + return false; + } + + const segments = hostList.split(','); + if (isSrv && segments.length !== 1) { + return false; + } + + return segments.every(segment => isValidMongoHostSegment(segment, !isSrv)); +} + +const mongodbUriSchema = z.string().refine(isValidMongoUri, { + message: 'Invalid MongoDB connection URI', +}); + // MongoDB configuration export const mongodbConfigSchema = z.object({ enabled: z.boolean().default(true), - uri: z.string().url(), // URI is required and contains all connection info - readUri: z.string().url().optional(), // Optional read-only URI (e.g. dev data-pipeline reading QA MongoDB) + uri: mongodbUriSchema, // URI is required and contains all connection info + readUri: mongodbUriSchema.optional(), // Optional read-only URI (e.g. dev data-pipeline reading QA MongoDB) readOnly: z.boolean().default(false).optional(), database: z.string(), // Database name for reference poolSize: z.number().min(1).max(100).default(10), diff --git a/libs/core/config/test/schemas.test.ts b/libs/core/config/test/schemas.test.ts index 4cee74d2..01568b95 100644 --- a/libs/core/config/test/schemas.test.ts +++ b/libs/core/config/test/schemas.test.ts @@ -584,10 +584,44 @@ describe('Config Schemas', () => { expect(config).toEqual(input); }); + it('should accept multi-host MongoDB seed lists for uri and readUri', () => { + const config = mongodbConfigSchema.parse({ + uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin', + readUri: + 'mongodb://studio_stock_bot_read:secret@localhost:27017,[::1]:27018/stock?authSource=stock', + database: 'stock_dev', + }); + expect(config.uri).toBe( + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin' + ); + expect(config.readUri).toBe( + 'mongodb://studio_stock_bot_read:secret@localhost:27017,[::1]:27018/stock?authSource=stock' + ); + }); + it('should validate URI format', () => { + const invalidUris = [ + 'invalid-uri', + 'http://localhost:27017/stock', + 'mongodb://', + 'mongodb://u:p@', + 'mongodb://u:p@localhost:27017,', + 'mongodb://u:p@localhost:99999/stock', + 'mongodb+srv://u:p@localhost:27017/stock', + 'mongodb+srv://u:p@host1.example.com,host2.example.com/stock', + ]; + for (const uri of invalidUris) { + expect(() => + mongodbConfigSchema.parse({ + uri, + database: 'testdb', + }) + ).toThrow(); + } expect(() => mongodbConfigSchema.parse({ - uri: 'invalid-uri', + uri: 'mongodb://localhost:27018/stock_dev', + readUri: 'not-a-mongo-uri', database: 'testdb', }) ).toThrow(); diff --git a/test/unit/environment-safety.test.ts b/test/unit/environment-safety.test.ts index 84e057a7..ab3b7948 100644 --- a/test/unit/environment-safety.test.ts +++ b/test/unit/environment-safety.test.ts @@ -24,7 +24,13 @@ function makeConfig(overrides: { mongoReadOnly?: boolean; mongoDatabase?: string; dragonflyPassword?: string; + bypassSchemaValidation?: boolean; } = {}): StockAppConfig { + const defaultMongoUri = + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin'; + const defaultMongoReadUri = + 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock'; + const parsed = stockAppSchema.parse({ name: 'stock-bot', version: '1.0.0', @@ -50,8 +56,12 @@ function makeConfig(overrides: { }, mongodb: { enabled: true, - uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin', - readUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock', + uri: overrides.bypassSchemaValidation + ? defaultMongoUri + : (overrides.mongoUri ?? defaultMongoUri), + readUri: overrides.bypassSchemaValidation + ? defaultMongoReadUri + : (overrides.mongoReadUri ?? defaultMongoReadUri), readOnly: overrides.mongoReadOnly ?? false, database: overrides.mongoDatabase ?? 'stock_dev', }, @@ -78,11 +88,13 @@ function makeConfig(overrides: { features: {}, }); - if (overrides.mongoUri !== undefined) { - parsed.database.mongodb.uri = overrides.mongoUri; - } - if (overrides.mongoReadUri !== undefined) { - parsed.database.mongodb.readUri = overrides.mongoReadUri; + if (overrides.bypassSchemaValidation) { + if (overrides.mongoUri !== undefined) { + parsed.database.mongodb.uri = overrides.mongoUri; + } + if (overrides.mongoReadUri !== undefined) { + parsed.database.mongodb.readUri = overrides.mongoReadUri; + } } return parsed; @@ -336,6 +348,12 @@ describe('Environment safety & multi-env isolation', () => { 'mongodb://u:p@localhost:27018,127.0.0.1/stock_dev', 'mongodb://u:p@localhost:27018,[::1]:27017/stock_dev', 'mongodb://u:p@localhost:27018,[::1]/stock_dev', + 'mongodb://u:p@[0:0:0:0:0:0:0:0001]:27017/stock', + 'mongodb://u:p@[::ffff:7f00:1]:27017/stock', + 'mongodb://u:p@[::ffff:7f00:0001]/stock', + 'mongodb://u:p@[::ffff:7f01:0203]:27017/stock', + 'mongodb://u:p@[0:0:0:0:0:ffff:7f00:1]:27017/stock', + 'mongodb://u:p@[::ffff:127.0.0.2]:27017/stock', 'mongodb://u:p@localhost:27018,LOCALHOST.:27017/stock_dev', 'mongodb://u:p@127.0.0.2:27017/stock_dev', 'mongodb+srv://u:p@localhost/stock', @@ -351,6 +369,14 @@ describe('Environment safety & multi-env isolation', () => { /cannot open a writable MongoDB connection to QA MongoDB/ ); } + + // Non-loopback IPv4-mapped IPv6 addresses must not false-positive as QA loopback + const nonLoopbackMappedCfg = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://u:p@[::ffff:0a00:1]:27017/stock_dev', + mongoDatabase: 'stock_dev', + }); + expect(() => assertEnvironmentSafety(nonLoopbackMappedCfg, 'dataIngestion', {})).not.toThrow(); }); test('handles multi-host MongoDB URI parsing edge cases without failing open', () => { @@ -364,17 +390,18 @@ describe('Environment safety & multi-env isolation', () => { ); const edgeCaseUris = [ - 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock', - 'mongodb://u:p@localhost:/stock', - 'mongodb://localhost:27017,localhost:27018/stock', - 'mongodb://u:p@bad:port,localhost:27017/stock', + { uri: 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock', malformed: false }, + { uri: 'mongodb://localhost:27017,localhost:27018/stock', malformed: false }, + { uri: 'mongodb://u:p@localhost:/stock', malformed: true }, + { uri: 'mongodb://u:p@bad:port,localhost:27017/stock', malformed: true }, ]; - for (const mongoUri of edgeCaseUris) { + for (const { uri: mongoUri, malformed } of edgeCaseUris) { const cfg = makeConfig({ environment: 'development', mongoUri, mongoDatabase: 'stock', + bypassSchemaValidation: malformed, }); expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow( /cannot open a writable MongoDB connection to QA MongoDB/ @@ -423,6 +450,74 @@ describe('Environment safety & multi-env isolation', () => { ); }); + test('initializeStockConfig validates and guards multi-host MongoDB seed lists end-to-end', () => { + const envKeys = [ + 'NODE_ENV', + 'POSTGRES_HOST', + 'POSTGRES_PORT', + 'POSTGRES_DB', + 'POSTGRES_USER', + 'POSTGRES_PASSWORD', + 'MONGODB_URI', + 'MONGODB_READ_URI', + 'MONGODB_DATABASE', + 'HTTP_PROXY', + 'HTTPS_PROXY', + 'http_proxy', + 'https_proxy', + ] as const; + const savedEnv: Partial> = {}; + for (const key of envKeys) { + savedEnv[key] = process.env[key]; + } + + try { + process.env.NODE_ENV = 'development'; + process.env.POSTGRES_HOST = 'localhost'; + process.env.POSTGRES_PORT = '5433'; + process.env.POSTGRES_DB = 'trading_bot_dev'; + process.env.POSTGRES_USER = 'dev_user'; + process.env.POSTGRES_PASSWORD = 'dev_pass'; + process.env.MONGODB_URI = + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin'; + process.env.MONGODB_READ_URI = + 'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock'; + process.env.MONGODB_DATABASE = 'stock_dev'; + delete process.env.HTTP_PROXY; + delete process.env.HTTPS_PROXY; + delete process.env.http_proxy; + delete process.env.https_proxy; + + // Approved dev seed list passes schema validation and guard for dataIngestion + resetStockConfig(); + const ingestionCfg = initializeStockConfig('dataIngestion'); + expect(ingestionCfg.database.mongodb.uri).toBe(process.env.MONGODB_URI); + + // Approved QA read-only seed list passes schema validation and guard for dataPipeline + resetStockConfig(); + const pipelineCfg = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); + expect(pipelineCfg.database.mongodb.readUri).toBe(process.env.MONGODB_READ_URI); + expect(pipelineCfg.database.mongodb.readOnly).toBe(true); + + // Guarded QA seed list passes schema validation and is blocked by the safety guard + process.env.MONGODB_URI = + 'mongodb://trading_admin:trading_mongo_dev@[::ffff:7f00:1]:27017/stock?authSource=admin'; + resetStockConfig(); + expect(() => initializeStockConfig('dataIngestion')).toThrow( + /cannot open a writable MongoDB connection to QA MongoDB/ + ); + } finally { + for (const key of envKeys) { + if (savedEnv[key] === undefined) { + delete process.env[key]; + } else { + process.env[key] = savedEnv[key]; + } + } + resetStockConfig(); + } + }); + test('blocks qa environment from targeting *_dev databases', () => { const cfg = makeConfig({ environment: 'qa', From 4b46e809beeeb61c1cba3ef1465ba0c4ff06447d Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 11:17:59 -0500 Subject: [PATCH 07/20] T-9: Multi-host MongoDB URI bypasses the dev QA-Mongo guard --- .../config/src/schemas/database.schema.ts | 11 ++++- libs/core/config/test/schemas.test.ts | 22 ++++++++++ libs/core/di/src/container/builder.ts | 28 +++++++++--- libs/core/di/test/container-builder.test.ts | 43 +++++++++++++++++++ test/unit/environment-safety.test.ts | 37 +++++++++++++++- 5 files changed, 134 insertions(+), 7 deletions(-) diff --git a/libs/core/config/src/schemas/database.schema.ts b/libs/core/config/src/schemas/database.schema.ts index c9f08c8c..f68f4aa7 100644 --- a/libs/core/config/src/schemas/database.schema.ts +++ b/libs/core/config/src/schemas/database.schema.ts @@ -55,6 +55,9 @@ function isValidMongoHostSegment(segment: string, allowPort: boolean): boolean { return false; } const portStr = after.slice(1); + if (portStr === '') { + return true; + } if (!/^\d+$/.test(portStr)) { return false; } @@ -72,7 +75,13 @@ function isValidMongoHostSegment(segment: string, allowPort: boolean): boolean { const host = segment.slice(0, colonIdx); const portStr = segment.slice(colonIdx + 1); - if (!host || !/^\d+$/.test(portStr)) { + if (!host) { + return false; + } + if (portStr === '') { + return true; + } + if (!/^\d+$/.test(portStr)) { return false; } const port = Number(portStr); diff --git a/libs/core/config/test/schemas.test.ts b/libs/core/config/test/schemas.test.ts index 01568b95..bfa6c8a9 100644 --- a/libs/core/config/test/schemas.test.ts +++ b/libs/core/config/test/schemas.test.ts @@ -599,6 +599,22 @@ describe('Config Schemas', () => { ); }); + it('should accept empty port spellings for mongodb:// in hostname and bracketed IPv6 forms', () => { + const hostEmptyPort = mongodbConfigSchema.parse({ + uri: 'mongodb://mongo.prod.internal:/stock', + readUri: 'mongodb://[::1]:/stock', + database: 'stock', + }); + expect(hostEmptyPort.uri).toBe('mongodb://mongo.prod.internal:/stock'); + expect(hostEmptyPort.readUri).toBe('mongodb://[::1]:/stock'); + + const seedListEmptyPort = mongodbConfigSchema.parse({ + uri: 'mongodb://u:p@mongo1.prod.internal:,[::1]:/stock', + database: 'stock', + }); + expect(seedListEmptyPort.uri).toBe('mongodb://u:p@mongo1.prod.internal:,[::1]:/stock'); + }); + it('should validate URI format', () => { const invalidUris = [ 'invalid-uri', @@ -606,7 +622,13 @@ describe('Config Schemas', () => { 'mongodb://', 'mongodb://u:p@', 'mongodb://u:p@localhost:27017,', + 'mongodb://u:p@:27017/stock', + 'mongodb://u:p@localhost:0/stock', 'mongodb://u:p@localhost:99999/stock', + 'mongodb://u:p@[::1]:0/stock', + 'mongodb://u:p@[::1]:99999/stock', + 'mongodb://u:p@localhost:abc/stock', + 'mongodb+srv://u:p@localhost:/stock', 'mongodb+srv://u:p@localhost:27017/stock', 'mongodb+srv://u:p@host1.example.com,host2.example.com/stock', ]; diff --git a/libs/core/di/src/container/builder.ts b/libs/core/di/src/container/builder.ts index 4cd9b5d9..421e0342 100644 --- a/libs/core/di/src/container/builder.ts +++ b/libs/core/di/src/container/builder.ts @@ -35,15 +35,33 @@ export type ContainerRegistrar = ( ) => void; function extractMongoDatabaseFromUri(uri?: string): string | undefined { - if (!uri) { + const trimmed = uri?.trim(); + if (!trimmed) { return undefined; } - try { - const db = new URL(uri).pathname.replace(/^\/+/, '').split('/')[0]; - return db || undefined; - } catch { + + const schemeMatch = /^mongodb(?:\+srv)?:\/\/(.*)$/i.exec(trimmed); + const rest = schemeMatch?.[1]; + if (!rest) { return undefined; } + + const delimiterMatch = /[/?#]/.exec(rest); + if (!delimiterMatch || delimiterMatch[0] !== '/') { + return undefined; + } + + const pathPart = rest.slice(delimiterMatch.index).split(/[?#]/, 1)[0] ?? ''; + const rawDb = pathPart.replace(/^\/+/, '').split('/')[0]; + if (!rawDb) { + return undefined; + } + + try { + return decodeURIComponent(rawDb); + } catch { + return rawDb; + } } function getInfluxPort(config: { influxPort?: number; ilpPort?: number }): number { diff --git a/libs/core/di/test/container-builder.test.ts b/libs/core/di/test/container-builder.test.ts index e630b16a..6f72f326 100644 --- a/libs/core/di/test/container-builder.test.ts +++ b/libs/core/di/test/container-builder.test.ts @@ -120,6 +120,49 @@ describe('ServiceContainerBuilder production configuration', () => { } }); + it('extracts database from multi-host readUri when mongoReadOnly is enabled', async () => { + const config = { + ...configuration(), + database: { + ...configuration().database, + mongodb: { + enabled: true, + uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin', + readUri: + 'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock', + database: 'stock_dev', + }, + }, + }; + const container = await new ServiceContainerBuilder() + .withConfig(config) + .withOptions({ + enableMongoDB: true, + mongoReadOnly: true, + enablePostgres: false, + enableQuestDB: false, + enableCache: false, + enableQueue: false, + enableBrowser: false, + enableProxy: false, + }) + .skipInitialization() + .build(); + + try { + const resolvedConfig = container.resolve('config'); + expect(resolvedConfig.mongodb.readOnly).toBe(true); + expect(resolvedConfig.mongodb.database).toBe('stock'); + + const mongo = container.resolve('mongoClient'); + expect(mongo).not.toBeNull(); + expect(mongo!.isReadOnly()).toBe(true); + expect(mongo!.getDefaultDatabase()).toBe('stock'); + } finally { + await container.dispose(); + } + }); + it('rejects invalid settings and missing required app fields with schema errors', () => { expect(() => new ServiceContainerBuilder().withConfig({ diff --git a/test/unit/environment-safety.test.ts b/test/unit/environment-safety.test.ts index ab3b7948..4a45a3b5 100644 --- a/test/unit/environment-safety.test.ts +++ b/test/unit/environment-safety.test.ts @@ -392,7 +392,8 @@ describe('Environment safety & multi-env isolation', () => { const edgeCaseUris = [ { uri: 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock', malformed: false }, { uri: 'mongodb://localhost:27017,localhost:27018/stock', malformed: false }, - { uri: 'mongodb://u:p@localhost:/stock', malformed: true }, + { uri: 'mongodb://u:p@localhost:/stock', malformed: false }, + { uri: 'mongodb://u:p@[::1]:/stock', malformed: false }, { uri: 'mongodb://u:p@bad:port,localhost:27017/stock', malformed: true }, ]; @@ -668,4 +669,38 @@ describe('MongoDBClient read-only enforcement', () => { await shutdown(); } }); + + test('ServiceContainerBuilder extracts database from multi-host readUri when mongoReadOnly=true', async () => { + const cfg = makeConfig({ + environment: 'development', + mongoUri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin', + mongoReadUri: + 'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock', + mongoDatabase: 'stock_dev', + mongoReadOnly: true, + }); + const { container, shutdown } = await new ServiceContainerBuilder() + .withConfig(cfg) + .withOptions({ + enableMongoDB: true, + mongoReadOnly: true, + enablePostgres: false, + enableQuestDB: false, + enableCache: false, + enableQueue: false, + enableBrowser: false, + enableProxy: false, + skipInitialization: true, + }) + .buildOwned(); + + try { + const mongo = container.resolve('mongoClient'); + expect(mongo).not.toBeNull(); + expect(mongo!.isReadOnly()).toBe(true); + expect(mongo!.getDefaultDatabase()).toBe('stock'); + } finally { + await shutdown(); + } + }); }); From 20498802f75595d258ea9ed31695242f3d136ea3 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 11:25:39 -0500 Subject: [PATCH 08/20] T-9: tests --- .../environment-safety-multi-host.test.ts | 208 ++++++++++++++++++ 1 file changed, 208 insertions(+) create mode 100644 test/unit/environment-safety-multi-host.test.ts diff --git a/test/unit/environment-safety-multi-host.test.ts b/test/unit/environment-safety-multi-host.test.ts new file mode 100644 index 00000000..d9d2dd0a --- /dev/null +++ b/test/unit/environment-safety-multi-host.test.ts @@ -0,0 +1,208 @@ +import { describe, expect, test } from 'bun:test'; +import { MongoClient } from 'mongodb'; +import { ServiceContainerBuilder } from '@stock-bot/di'; +import { setLoggerConfig } from '@stock-bot/logger'; +import { assertEnvironmentSafety, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config'; + +// T-9 QA: multi-host (seed list) MongoDB URIs and the dev QA-Mongo guard. +// The installed MongoDB driver is used only as a parsing oracle (new MongoClient +// parses the URI without connecting). 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 WRITE_ERROR = /cannot open a writable MongoDB connection to QA MongoDB/; +const PIPELINE_ERROR = /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/; + +function makeConfig(o: { + mongoUri?: string; + mongoReadUri?: string | null; + mongoReadOnly?: boolean; + mongoDatabase?: string; +} = {}): StockAppConfig { + const mongodb: Record = { + enabled: true, + uri: o.mongoUri ?? DEV_MONGO_URI, + readOnly: o.mongoReadOnly ?? false, + database: o.mongoDatabase ?? 'stock_dev', + }; + if (o.mongoReadUri !== null && o.mongoReadUri !== undefined) { + mongodb.readUri = o.mongoReadUri; + } + return stockAppSchema.parse({ + name: 'stock-bot', + version: '1.0.0', + 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: '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: {}, + }); +} + +/** Independent oracle: does the real driver resolve any seed to a plain loopback :27017 address? */ +function driverSeesQaSeed(uri: string): boolean { + const client = new MongoClient(uri); + return client.options.hosts.some(h => { + const host = (h.host ?? '').toLowerCase(); + const loopback = host === 'localhost' || host === '::1' || host === '0.0.0.0' || /^127\.\d+\.\d+\.\d+$/.test(host); + return loopback && h.port === 27017; + }); +} + +describe('T-9 guard verdict matches the driver for seed lists that pass schema validation', () => { + const qaSeedLists = [ + 'mongodb://u:p@localhost:27017,localhost:27018/stock', + 'mongodb://u:p@localhost:27018,localhost:27017/stock_dev', + 'mongodb://u:p@db1.dev.internal:27018,db2.dev.internal:27018,127.0.0.1:27017/stock_dev', + 'mongodb://u:p@localhost:27018,localhost:27019,localhost/stock_dev?replicaSet=rs0', + 'mongodb://u:p@localhost:27018,0.0.0.0:27017/stock_dev', + 'mongodb://u:p@localhost:27018,localhost:027017/stock_dev', + 'mongodb://u:p,w@localhost:27018,localhost:27017/stock', + 'mongodb://localhost:27018,localhost:27017', + ]; + const safeSeedLists = [ + 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin', + // localhost:27017 only inside the query string is not a seed host. + 'mongodb://u:p@localhost:27018,localhost:27019/stock_dev?appName=localhost:27017', + 'mongodb://u:p@10.0.0.51:27017,10.0.0.52:27017/stock', + ]; + + for (const uri of qaSeedLists) { + test(`blocks writable dataIngestion and non-readOnly dataPipeline on ${uri}`, () => { + expect(driverSeesQaSeed(uri)).toBe(true); + + const ingestion = makeConfig({ mongoUri: uri, mongoDatabase: 'stock' }); + expect(() => assertEnvironmentSafety(ingestion, 'dataIngestion', {})).toThrow(WRITE_ERROR); + + const pipeline = makeConfig({ mongoReadUri: uri, mongoReadOnly: false }); + expect(() => assertEnvironmentSafety(pipeline, 'dataPipeline', {})).toThrow(PIPELINE_ERROR); + }); + } + + for (const uri of safeSeedLists) { + test(`allows dev dataIngestion and dataPipeline on ${uri}`, () => { + expect(driverSeesQaSeed(uri)).toBe(false); + + const ingestion = makeConfig({ mongoUri: uri }); + expect(() => assertEnvironmentSafety(ingestion, 'dataIngestion', {})).not.toThrow(); + + const pipeline = makeConfig({ mongoReadUri: uri, mongoReadOnly: false }); + expect(() => assertEnvironmentSafety(pipeline, 'dataPipeline', {})).not.toThrow(); + }); + } +}); + +describe('T-9 guard: every non-pipeline dev service is covered for seed lists', () => { + const qaSeedList = 'mongodb://u:p@localhost:27018,localhost:27017/stock'; + + test('webApi, orchestrator and an unnamed service are blocked from writing', () => { + const cfg = makeConfig({ mongoUri: qaSeedList, mongoDatabase: 'stock' }); + expect(() => assertEnvironmentSafety(cfg, 'webApi', {})).toThrow(/"webApi"/); + expect(() => assertEnvironmentSafety(cfg, 'orchestrator', {})).toThrow(/"orchestrator"/); + expect(() => assertEnvironmentSafety(cfg, undefined, {})).toThrow(/"app"/); + }); + + test('pipeline without readUri falls back to a seed-list uri and blocks trading_admin', () => { + const cfg = makeConfig({ + mongoUri: 'mongodb://trading_admin:pw@localhost:27018,localhost:27017/stock', + mongoReadUri: null, + mongoReadOnly: true, + mongoDatabase: 'stock', + }); + expect(cfg.database.mongodb.readUri).toBeUndefined(); + expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR); + }); + + test('pipeline without readUri allows the read user on a seed-list uri in readOnly mode', () => { + const cfg = makeConfig({ + mongoUri: 'mongodb://studio_stock_bot_read:pw@localhost:27018,localhost:27017/stock', + mongoReadUri: null, + mongoReadOnly: true, + mongoDatabase: 'stock', + }); + expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow(); + }); +}); + +describe('T-9 guard: seed lists the driver accepts but the schema rejects still fail closed', () => { + // The driver tolerates empty seed entries; the guard must not treat them as a + // reason to drop the QA seed. + const driverAcceptedSchemaRejected = [ + 'mongodb://u:p@localhost:27018,,localhost:27017/stock', + 'mongodb://u:p@localhost:27018,localhost:27017,/stock', + ]; + + for (const uri of driverAcceptedSchemaRejected) { + test(`schema rejects but guard still blocks ${uri}`, () => { + expect(driverSeesQaSeed(uri)).toBe(true); + expect(() => makeConfig({ mongoUri: uri })).toThrow(/Invalid MongoDB connection URI/); + + const cfg = makeConfig(); + cfg.database.mongodb.uri = uri; + expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow(WRITE_ERROR); + }); + } +}); + +describe('T-9 container: read-only database selection agrees with the driver', () => { + const cases: Array<{ readUri: string; expected: string }> = [ + { readUri: 'mongodb://r:pw@localhost:27017,localhost:27018/stock?authSource=stock', expected: 'stock' }, + { readUri: 'mongodb://r:pw@h1.internal:27017,h2.internal/stock%5Fqa?authSource=admin', expected: 'stock_qa' }, + { readUri: 'mongodb://r:pw@h1.internal,h2.internal/stock#frag', expected: 'stock' }, + // No database in the URI: the container keeps the configured database. + { readUri: 'mongodb://r:pw@h1.internal:27017,h2.internal:27018/?replicaSet=rs0', expected: 'stock_dev' }, + { readUri: 'mongodb://r:pw@h1.internal,h2.internal', expected: 'stock_dev' }, + ]; + + for (const { readUri, expected } of cases) { + test(`selects "${expected}" for ${readUri}`, async () => { + const driverDb = new MongoClient(readUri).options.dbName; + // The driver defaults to "test" when the URI has no database; the container uses config. + expect(driverDb === 'test' ? 'stock_dev' : driverDb).toBe(expected); + + const cfg = makeConfig({ mongoReadUri: readUri, mongoReadOnly: true }); + const { container, shutdown } = await new ServiceContainerBuilder() + .withConfig(cfg) + .withOptions({ + enableMongoDB: true, + mongoReadOnly: true, + enablePostgres: false, + enableQuestDB: false, + enableCache: false, + enableQueue: false, + enableBrowser: false, + enableProxy: false, + skipInitialization: true, + }) + .buildOwned(); + try { + const mongo = container.resolve('mongoClient'); + expect(mongo).not.toBeNull(); + expect(mongo!.isReadOnly()).toBe(true); + expect(mongo!.getDefaultDatabase()).toBe(expected); + } finally { + await shutdown(); + } + }); + } +}); From 55629edb1399d7309d59dc2c54e8cfe70e1f8e21 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 11:48:35 -0500 Subject: [PATCH 09/20] T-10: tests --- scripts/test/pipeline-legacy-removal.test.ts | 63 ++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/scripts/test/pipeline-legacy-removal.test.ts b/scripts/test/pipeline-legacy-removal.test.ts index 6d307eaa..e96c5bb2 100644 --- a/scripts/test/pipeline-legacy-removal.test.ts +++ b/scripts/test/pipeline-legacy-removal.test.ts @@ -4,7 +4,9 @@ import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'bun:test'; import { Hono } from 'hono'; import type { IServiceContainer } from '@stock-bot/handlers'; +import { ExchangesHandler } from '../../apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler'; import { createPipelineRoutes } from '../../apps/stock/web-api/src/routes/pipeline.routes'; +import { PipelineService } from '../../apps/stock/web-api/src/services/pipeline.service'; const repository = fileURLToPath(new URL('../../', import.meta.url)); @@ -77,3 +79,64 @@ describe('legacy sync-ib-exchanges removal', () => { ]); }); }); + +describe('exchanges handler after sync-ib-exchanges removal', () => { + it('registers exactly the remaining exchange operations and no IB operation', () => { + const metadata = ExchangesHandler.extractMetadata(); + + expect(metadata?.name).toBe('exchanges'); + // @Operation + @ScheduledOperation on one method registers the name twice, so compare the set. + expect([...new Set(metadata?.operations ?? [])].sort()).toEqual([ + 'clear-postgresql-data', + 'get-exchange-stats', + 'get-provider-mapping-stats', + 'sync-all-exchanges', + 'sync-qm-exchanges', + 'sync-qm-provider-mappings', + ]); + }); + + it('keeps the other nightly schedules but drops the 03:00 IB exchange schedule', () => { + const metadata = ExchangesHandler.extractMetadata(); + + const schedules = (metadata?.scheduledJobs ?? []) + .map(job => ({ operation: job.operation, cronPattern: job.cronPattern })) + .sort((a, b) => a.operation.localeCompare(b.operation)); + + expect(schedules).toEqual([ + { operation: 'sync-all-exchanges', cronPattern: '0 0 * * 0' }, + { operation: 'sync-qm-exchanges', cronPattern: '0 1 * * *' }, + { operation: 'sync-qm-provider-mappings', cronPattern: '0 3 * * *' }, + ]); + }); + + it('rejects a leftover queued sync-ib-exchanges job without touching MongoDB', async () => { + const mongoCalls: string[] = []; + const mongodb = new Proxy( + {}, + { + get(_target, property) { + mongoCalls.push(String(property)); + return () => { + throw new Error('MongoDB must not be used'); + }; + }, + } + ); + const handler = new ExchangesHandler({ mongodb } as unknown as IServiceContainer); + + await expect( + handler.execute('sync-ib-exchanges', {}, { type: 'queue', metadata: {} } as never) + ).rejects.toThrow('Unknown operation: sync-ib-exchanges'); + expect(mongoCalls).toEqual([]); + }); +}); + +describe('web-api pipeline service after sync-ib-exchanges removal', () => { + it('no longer exposes a method that enqueues sync-ib-exchanges', () => { + const service = new PipelineService({} as IServiceContainer); + + expect('syncIBExchanges' in service).toBe(false); + expect(typeof service.syncQMProviderMappings).toBe('function'); + }); +}); From b098bda4621b6d01c83890f26aa2236521b7c659 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 11:54:48 -0500 Subject: [PATCH 10/20] =?UTF-8?q?T-10:=20M0.3b=20=E2=80=94=20Delete=20lega?= =?UTF-8?q?cy=20MongoDB-writing=20sync-ib-exchanges=20operation=20and=20it?= =?UTF-8?q?s=20web-api/web-app=20hooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handlers/test/create-job-handler.test.ts | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/libs/core/handlers/test/create-job-handler.test.ts b/libs/core/handlers/test/create-job-handler.test.ts index b97e681d..50fccfaf 100644 --- a/libs/core/handlers/test/create-job-handler.test.ts +++ b/libs/core/handlers/test/create-job-handler.test.ts @@ -96,9 +96,16 @@ describe('createJobHandler', () => { }); it('should support async operations', async () => { + let resolveAsyncWork!: () => void; + let asyncWorkCompleted = false; + const handler = createJobHandler(async job => { - // Simulate async operation - await new Promise(resolve => setTimeout(resolve, 10)); + await new Promise(resolve => { + resolveAsyncWork = () => { + asyncWorkCompleted = true; + resolve(); + }; + }); return { success: true, @@ -120,12 +127,15 @@ describe('createJobHandler', () => { updateProgress: async () => {}, }; - const startTime = Date.now(); - const result = await handler(mockJob as any); - const endTime = Date.now(); + const resultPromise = handler(mockJob as any); + expect(asyncWorkCompleted).toBe(false); + resolveAsyncWork(); + const result = await resultPromise; + + expect(asyncWorkCompleted).toBe(true); expect(result.success).toBe(true); - expect(endTime - startTime).toBeGreaterThanOrEqual(10); + expect(result.processedBy).toBe('user-789'); }); it('should maintain type safety for complex payloads', () => { From 888813450383ad56c6fe94cd450e1334f72e1db0 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 11:58:20 -0500 Subject: [PATCH 11/20] T-10: tests --- .../handlers/test/create-job-handler.test.ts | 38 +++++++++++-------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/libs/core/handlers/test/create-job-handler.test.ts b/libs/core/handlers/test/create-job-handler.test.ts index 50fccfaf..ecd947e3 100644 --- a/libs/core/handlers/test/create-job-handler.test.ts +++ b/libs/core/handlers/test/create-job-handler.test.ts @@ -96,21 +96,20 @@ describe('createJobHandler', () => { }); it('should support async operations', async () => { - let resolveAsyncWork!: () => void; - let asyncWorkCompleted = false; + // Gate created before the wrapper runs, so the test does not assume synchronous invocation. + let releaseAsyncWork!: () => void; + const asyncWorkGate = new Promise(resolve => { + releaseAsyncWork = resolve; + }); + let callbackFinished = false; const handler = createJobHandler(async job => { - await new Promise(resolve => { - resolveAsyncWork = () => { - asyncWorkCompleted = true; - resolve(); - }; - }); - + await asyncWorkGate; + callbackFinished = true; return { success: true, processedBy: job.data.userId, - timestamp: new Date(), + timestamp: new Date(0), }; }); @@ -127,15 +126,22 @@ describe('createJobHandler', () => { updateProgress: async () => {}, }; - const resultPromise = handler(mockJob as any); - expect(asyncWorkCompleted).toBe(false); + let wrapperSettled = false; + const resultPromise = handler(mockJob as any).finally(() => { + wrapperSettled = true; + }); - resolveAsyncWork(); + // Drain microtasks: the wrapper must still be waiting on the callback. + await Promise.resolve(); + await Promise.resolve(); + expect(wrapperSettled).toBe(false); + expect(callbackFinished).toBe(false); + + releaseAsyncWork(); const result = await resultPromise; - expect(asyncWorkCompleted).toBe(true); - expect(result.success).toBe(true); - expect(result.processedBy).toBe('user-789'); + expect(callbackFinished).toBe(true); + expect(result).toEqual({ success: true, processedBy: 'user-789', timestamp: new Date(0) }); }); it('should maintain type safety for complex payloads', () => { From 9c4e87cdfda789df20a44dfbf4451111a420d470 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 12:01:06 -0500 Subject: [PATCH 12/20] =?UTF-8?q?T-16:=20M0.1b=20=E2=80=94=20Make=20repo-w?= =?UTF-8?q?ide=20`bun=20test`=20green:=20fix=20queue,=20shutdown-signal=20?= =?UTF-8?q?and=20research-workflow=20test=20failures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/core/cache/test/redis-cache.test.ts | 56 ++++++++--- libs/core/config/test/config-manager.test.ts | 31 +++--- libs/core/config/test/env.loader.test.ts | 33 +++---- libs/core/config/test/file.loader.test.ts | 22 ++--- libs/core/di/test/handler-scanner.test.ts | 10 +- libs/core/di/test/registration.test.ts | 90 ++++------------- libs/core/di/test/service-application.test.ts | 96 ++++++++++--------- .../handlers/test/create-job-handler.test.ts | 20 ++-- libs/core/queue/src/queue-manager.ts | 8 ++ libs/core/queue/src/queue.ts | 16 +++- libs/core/queue/test/queue-class.test.ts | 46 ++++++--- libs/core/queue/test/queue.test.ts | 61 ++++++------ libs/core/shutdown/src/shutdown.ts | 39 +++++++- .../test/shutdown-comprehensive.test.ts | 21 ++-- .../shutdown/test/shutdown-signals.test.ts | 36 +++---- libs/core/shutdown/test/shutdown.test.ts | 33 ++++--- test/setup.ts | 14 ++- 17 files changed, 366 insertions(+), 266 deletions(-) diff --git a/libs/core/cache/test/redis-cache.test.ts b/libs/core/cache/test/redis-cache.test.ts index 601ae57c..ba28ba89 100644 --- a/libs/core/cache/test/redis-cache.test.ts +++ b/libs/core/cache/test/redis-cache.test.ts @@ -1,21 +1,48 @@ -import { beforeEach, describe, expect, it } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; import { RedisCache } from '../src/redis-cache'; -import type { CacheOptions } from '../src/types'; +import type { CacheOptions, RedisConfig } from '../src/types'; -const hasTestRedis = Boolean(process.env.BACKTEST_TEST_REDIS_URL); +const testRedisUrl = process.env.BACKTEST_TEST_REDIS_URL; -describe.skipIf(!hasTestRedis)('RedisCache', () => { +function parseTestRedisConfig(rawUrl: string): RedisConfig { + const parsed = new URL(rawUrl); + if (parsed.pathname !== '/15') { + throw new Error('BACKTEST_TEST_REDIS_URL must point to dedicated Redis database /15'); + } + return { + host: parsed.hostname, + port: parsed.port ? Number(parsed.port) : 6379, + db: 15, + ...(parsed.username ? { username: decodeURIComponent(parsed.username) } : {}), + ...(parsed.password ? { password: decodeURIComponent(parsed.password) } : {}), + }; +} + +if (!testRedisUrl) { + process.stderr.write( + 'Skipping RedisCache integration tests: set BACKTEST_TEST_REDIS_URL to a dedicated Redis fixture using database /15\n' + ); +} + +describe.skipIf(!testRedisUrl)('RedisCache', () => { let cache: RedisCache; + let redisConfig: RedisConfig; beforeEach(() => { + redisConfig = parseTestRedisConfig(testRedisUrl!); const options: CacheOptions = { keyPrefix: 'test:', ttl: 3600, - redisConfig: { host: 'localhost', port: 6379 }, + shared: false, + redisConfig, }; cache = new RedisCache(options); }); + afterEach(async () => { + await cache?.disconnect().catch(() => {}); + }); + describe('Core functionality', () => { it('should create cache instance', () => { expect(cache).toBeDefined(); @@ -148,16 +175,21 @@ describe.skipIf(!hasTestRedis)('RedisCache', () => { // Force an error by using invalid JSON const badCache = new RedisCache({ keyPrefix: 'bad:', - redisConfig: { host: 'localhost', port: 6379 }, + shared: false, + redisConfig, }); - // This would normally throw but should return null - const result = await badCache.get('non-existent'); - expect(result).toBeNull(); + try { + // This would normally throw but should return null + const result = await badCache.get('non-existent'); + expect(result).toBeNull(); - // Check stats updated - const stats = badCache.getStats(); - expect(stats.misses).toBe(1); + // Check stats updated + const stats = badCache.getStats(); + expect(stats.misses).toBe(1); + } finally { + await badCache.disconnect().catch(() => {}); + } }); }); diff --git a/libs/core/config/test/config-manager.test.ts b/libs/core/config/test/config-manager.test.ts index 1ec94406..e2be9463 100644 --- a/libs/core/config/test/config-manager.test.ts +++ b/libs/core/config/test/config-manager.test.ts @@ -1,19 +1,10 @@ -import { beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; +import * as loggerModule from '@stock-bot/logger'; import { z } from 'zod'; import { ConfigManager } from '../src/config-manager'; import { ConfigError, ConfigValidationError } from '../src/errors'; import type { ConfigLoader, Environment } from '../src/types'; -// Mock the logger -mock.module('@stock-bot/logger', () => ({ - getLogger: () => ({ - info: mock(() => {}), - error: mock(() => {}), - warn: mock(() => {}), - debug: mock(() => {}), - }), -})); - // Mock loader class class MockLoader implements ConfigLoader { constructor( @@ -28,10 +19,28 @@ class MockLoader implements ConfigLoader { describe('ConfigManager', () => { let manager: ConfigManager; + let getLoggerSpy: ReturnType; + const originalNodeEnv = process.env.NODE_ENV; beforeEach(() => { // Reset environment delete process.env.NODE_ENV; + getLoggerSpy = spyOn(loggerModule, 'getLogger').mockReturnValue({ + info: mock(() => {}), + error: mock(() => {}), + warn: mock(() => {}), + debug: mock(() => {}), + trace: mock(() => {}), + } as any); + }); + + afterEach(() => { + getLoggerSpy?.mockRestore(); + if (originalNodeEnv === undefined) { + delete process.env.NODE_ENV; + } else { + process.env.NODE_ENV = originalNodeEnv; + } }); describe('constructor', () => { diff --git a/libs/core/config/test/env.loader.test.ts b/libs/core/config/test/env.loader.test.ts index b6c37589..0d51fae8 100644 --- a/libs/core/config/test/env.loader.test.ts +++ b/libs/core/config/test/env.loader.test.ts @@ -1,16 +1,12 @@ -import { readFileSync } from 'fs'; -import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; +import * as fs from 'fs'; +import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test'; import { ConfigLoaderError } from '../src/errors'; import { EnvLoader } from '../src/loaders/env.loader'; import { queueConfigSchema } from '../src/schemas'; -// Mock fs module -mock.module('fs', () => ({ - readFileSync: mock(() => ''), -})); - describe('EnvLoader', () => { let loader: EnvLoader; + let readFileSync: ReturnType; const originalEnv = { ...process.env }; beforeEach(() => { @@ -18,9 +14,11 @@ describe('EnvLoader', () => { for (const key in process.env) { delete process.env[key]; } + readFileSync = spyOn(fs, 'readFileSync').mockReturnValue('' as any); }); afterEach(() => { + readFileSync?.mockRestore(); // Restore original environment for (const key in process.env) { delete process.env[key]; @@ -371,17 +369,20 @@ KEY_WITHOUT_VALUE= it('should warn on other file errors', () => { const consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {}); + try { + (readFileSync as any).mockImplementation(() => { + const error: any = new Error('Permission denied'); + error.code = 'EACCES'; + throw error; + }); - (readFileSync as any).mockImplementation(() => { - const error: any = new Error('Permission denied'); - error.code = 'EACCES'; - throw error; - }); + loader = new EnvLoader(); + loader.load(); - loader = new EnvLoader(); - loader.load(); - - expect(consoleWarnSpy).toHaveBeenCalled(); + expect(consoleWarnSpy).toHaveBeenCalled(); + } finally { + consoleWarnSpy.mockRestore(); + } }); it('should try multiple env file paths', () => { diff --git a/libs/core/config/test/file.loader.test.ts b/libs/core/config/test/file.loader.test.ts index 27da55fd..47cada57 100644 --- a/libs/core/config/test/file.loader.test.ts +++ b/libs/core/config/test/file.loader.test.ts @@ -1,23 +1,23 @@ -import { existsSync, readFileSync } from 'fs'; -import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import * as fs from 'fs'; +import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test'; import { ConfigLoaderError } from '../src/errors'; import { FileLoader } from '../src/loaders/file.loader'; -// Mock fs module -mock.module('fs', () => ({ - existsSync: mock(() => false), - readFileSync: mock(() => ''), -})); - describe('FileLoader', () => { let loader: FileLoader; + let existsSync: ReturnType; + let readFileSync: ReturnType; const configPath = '/app/config'; const environment = 'development'; beforeEach(() => { - // Reset mocks - (existsSync as any).mockReset(); - (readFileSync as any).mockReset(); + existsSync = spyOn(fs, 'existsSync').mockReturnValue(false); + readFileSync = spyOn(fs, 'readFileSync').mockReturnValue('' as any); + }); + + afterEach(() => { + existsSync?.mockRestore(); + readFileSync?.mockRestore(); }); describe('constructor', () => { diff --git a/libs/core/di/test/handler-scanner.test.ts b/libs/core/di/test/handler-scanner.test.ts index ce8b1dea..a468bf18 100644 --- a/libs/core/di/test/handler-scanner.test.ts +++ b/libs/core/di/test/handler-scanner.test.ts @@ -1,5 +1,5 @@ import { asFunction, createContainer, type AwilixContainer } from 'awilix'; -import { beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import type { HandlerRegistry } from '@stock-bot/handler-registry'; import * as logger from '@stock-bot/logger'; import type { ExecutionContext, IHandler } from '@stock-bot/types'; @@ -55,6 +55,7 @@ describe('HandlerScanner', () => { let mockRegistry: HandlerRegistry; let container: AwilixContainer; let mockLogger: any; + let getLoggerSpy: ReturnType; beforeEach(() => { // Create mock logger @@ -63,10 +64,11 @@ describe('HandlerScanner', () => { debug: mock(() => {}), error: mock(() => {}), warn: mock(() => {}), + trace: mock(() => {}), }; // Mock getLogger to return our mock logger - spyOn(logger, 'getLogger').mockReturnValue(mockLogger); + getLoggerSpy = spyOn(logger, 'getLogger').mockReturnValue(mockLogger); // Create mock registry mockRegistry = { @@ -87,6 +89,10 @@ describe('HandlerScanner', () => { }); }); + afterEach(() => { + getLoggerSpy?.mockRestore(); + }); + describe('scanHandlers', () => { it('should handle empty patterns gracefully', async () => { await scanner.scanHandlers([]); diff --git a/libs/core/di/test/registration.test.ts b/libs/core/di/test/registration.test.ts index d61e404f..ce644248 100644 --- a/libs/core/di/test/registration.test.ts +++ b/libs/core/di/test/registration.test.ts @@ -1,21 +1,28 @@ import { asFunction, asValue, createContainer } from 'awilix'; -import { describe, expect, it, mock } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; +import * as queueModule from '@stock-bot/queue'; import { registerApplicationServices, registerCacheServices, registerDatabaseServices, } from '../src/registrations'; -// Mock the queue module -mock.module('@stock-bot/queue', () => ({ - createServiceCache: mock(() => ({ - get: mock(() => Promise.resolve(null)), - set: mock(() => Promise.resolve()), - del: mock(() => Promise.resolve()), - })), -})); - describe('DI Registrations', () => { + let createServiceCacheSpy: ReturnType; + + beforeEach(() => { + createServiceCacheSpy = spyOn(queueModule, 'createServiceCache').mockImplementation( + (() => ({ + get: mock(() => Promise.resolve(null)), + set: mock(() => Promise.resolve()), + del: mock(() => Promise.resolve()), + })) as any + ); + }); + + afterEach(() => { + createServiceCacheSpy?.mockRestore(); + }); describe('registerCacheServices', () => { it('should register null cache when redis disabled', () => { const container = createContainer(); @@ -108,22 +115,6 @@ describe('DI Registrations', () => { it('should register MongoDB when config exists', () => { const container = createContainer(); - // Mock MongoDB client - const mockMongoClient = { - connect: mock(() => Promise.resolve()), - disconnect: mock(() => Promise.resolve()), - getDb: mock(() => ({})), - }; - - // Mock the MongoDB factory - mock.module('@stock-bot/mongodb', () => ({ - MongoDBClient: class { - constructor() { - return mockMongoClient; - } - }, - })); - const config = { mongodb: { enabled: true, @@ -140,22 +131,6 @@ describe('DI Registrations', () => { it('should register PostgreSQL when config exists', () => { const container = createContainer(); - // Mock Postgres client - const mockPostgresClient = { - connect: mock(() => Promise.resolve()), - disconnect: mock(() => Promise.resolve()), - query: mock(() => Promise.resolve({ rows: [] })), - }; - - // Mock the Postgres factory - mock.module('@stock-bot/postgres', () => ({ - PostgresClient: class { - constructor() { - return mockPostgresClient; - } - }, - })); - const config = { postgres: { enabled: true, @@ -175,22 +150,6 @@ describe('DI Registrations', () => { it('should register QuestDB when config exists', () => { const container = createContainer(); - // Mock QuestDB client - const mockQuestdbClient = { - connect: mock(() => Promise.resolve()), - disconnect: mock(() => Promise.resolve()), - query: mock(() => Promise.resolve({ data: [] })), - }; - - // Mock the QuestDB factory - mock.module('@stock-bot/questdb', () => ({ - QuestDBClient: class { - constructor() { - return mockQuestdbClient; - } - }, - })); - const config = { questdb: { enabled: true, @@ -281,21 +240,6 @@ describe('DI Registrations', () => { }), }); - // Mock queue manager - const mockQueueManager = { - getQueue: mock(() => ({})), - startAllWorkers: mock(() => {}), - shutdown: mock(() => Promise.resolve()), - }; - - mock.module('@stock-bot/queue', () => ({ - QueueManager: class { - constructor() { - return mockQueueManager; - } - }, - })); - const config = { service: { name: 'test-service', diff --git a/libs/core/di/test/service-application.test.ts b/libs/core/di/test/service-application.test.ts index 472f4281..c76525e5 100644 --- a/libs/core/di/test/service-application.test.ts +++ b/libs/core/di/test/service-application.test.ts @@ -1,25 +1,23 @@ -import { afterEach, describe, expect, it, mock } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import type { BaseAppConfig } from '@stock-bot/config'; +import * as loggerModule from '@stock-bot/logger'; +import { Shutdown } from '@stock-bot/shutdown'; import { ServiceApplication } from '../src/service-application'; import type { ServiceApplicationConfig, ServiceLifecycleHooks } from '../src/service-application'; -// Mock logger module -const mockLogger = { +// Mock logger object used via spyOn in beforeEach (restored in afterEach) +const mockLogger: any = { info: mock(() => {}), error: mock(() => {}), warn: mock(() => {}), debug: mock(() => {}), - child: mock(() => mockLogger), + trace: mock(() => {}), }; +mockLogger.child = mock(() => mockLogger); -mock.module('@stock-bot/logger', () => ({ - getLogger: () => mockLogger, - setLoggerConfig: mock(() => {}), - shutdownLoggers: mock(() => Promise.resolve()), -})); - -// Mock shutdown module +// Mock shutdown instance used via spyOn(Shutdown, 'getInstance') in beforeEach const mockShutdownInstance = { + shutdown: mock(() => Promise.resolve()), onShutdown: mock(() => {}), onShutdownHigh: mock(() => {}), onShutdownMedium: mock(() => {}), @@ -30,24 +28,13 @@ const mockShutdownInstance = { executeCallbacks: mock(() => Promise.resolve()), }; -const mockShutdown = { - getInstance: mock(() => mockShutdownInstance), -}; - -mock.module('@stock-bot/shutdown', () => ({ - Shutdown: mockShutdown, -})); - -// Mock Bun.serve +// Mock server returned by spyOn(Bun, 'serve') const mockServer = { stop: mock(() => {}), port: 3000, hostname: '0.0.0.0', }; -const _originalBunServe = Bun.serve; -Bun.serve = mock(() => mockServer); - const mockConfig: BaseAppConfig = { name: 'test-service', version: '1.0.0', @@ -75,13 +62,44 @@ const mockConfig: BaseAppConfig = { describe('ServiceApplication', () => { let app: ServiceApplication; + let getLoggerSpy: ReturnType; + let setLoggerConfigSpy: ReturnType; + let shutdownLoggersSpy: ReturnType; + let shutdownGetInstanceSpy: ReturnType; + let bunServeSpy: ReturnType; + + beforeEach(() => { + getLoggerSpy = spyOn(loggerModule, 'getLogger').mockReturnValue(mockLogger); + setLoggerConfigSpy = spyOn(loggerModule, 'setLoggerConfig').mockImplementation(() => {}); + shutdownLoggersSpy = spyOn(loggerModule, 'shutdownLoggers').mockResolvedValue(undefined); + shutdownGetInstanceSpy = spyOn(Shutdown, 'getInstance').mockReturnValue( + mockShutdownInstance as any + ); + bunServeSpy = spyOn(Bun, 'serve').mockImplementation((() => mockServer) as any); + }); afterEach(() => { + // Clean up app if it exists before restoring spies + if (app) { + app.stop().catch(() => {}); + app = null as any; + } + + // Restore module/global spies so no state leaks to other test files + getLoggerSpy?.mockRestore(); + setLoggerConfigSpy?.mockRestore(); + shutdownLoggersSpy?.mockRestore(); + shutdownGetInstanceSpy?.mockRestore(); + bunServeSpy?.mockRestore(); + // Reset mocks mockLogger.info.mockReset(); mockLogger.error.mockReset(); mockLogger.warn.mockReset(); mockLogger.debug.mockReset(); + mockLogger.trace.mockReset(); + mockShutdownInstance.shutdown.mockReset(); + mockShutdownInstance.shutdown.mockImplementation(() => Promise.resolve()); mockShutdownInstance.onShutdown.mockReset(); mockShutdownInstance.onShutdownHigh.mockReset(); mockShutdownInstance.onShutdownMedium.mockReset(); @@ -90,12 +108,6 @@ describe('ServiceApplication', () => { mockShutdownInstance.registerAsync.mockReset(); mockShutdownInstance.handleTermination.mockReset(); mockShutdownInstance.executeCallbacks.mockReset(); - - // Clean up app if it exists - if (app) { - app.stop().catch(() => {}); - app = null as any; - } }); describe('constructor', () => { @@ -136,7 +148,7 @@ describe('ServiceApplication', () => { }; app = new ServiceApplication(mockConfig, serviceConfig); - expect(mockShutdown.getInstance).toHaveBeenCalledWith({ + expect(shutdownGetInstanceSpy).toHaveBeenCalledWith({ timeout: 30000, }); }); @@ -605,19 +617,14 @@ describe('ServiceApplication', () => { describe('stop method', () => { it('should trigger shutdown', async () => { - const mockShutdownInstance = { + const localShutdownInstance = { shutdown: mock(() => Promise.resolve()), onShutdown: mock(() => {}), onShutdownHigh: mock(() => {}), onShutdownMedium: mock(() => {}), onShutdownLow: mock(() => {}), }; - - mock.module('@stock-bot/shutdown', () => ({ - Shutdown: { - getInstance: () => mockShutdownInstance, - }, - })); + shutdownGetInstanceSpy.mockReturnValue(localShutdownInstance as any); const serviceConfig: ServiceApplicationConfig = { serviceName: 'test-service', @@ -627,7 +634,7 @@ describe('ServiceApplication', () => { await app.stop(); - expect(mockShutdownInstance.shutdown).toHaveBeenCalled(); + expect(localShutdownInstance.shutdown).toHaveBeenCalled(); expect(mockLogger.info).toHaveBeenCalledWith('Stopping test-service service...'); }); }); @@ -665,19 +672,14 @@ describe('ServiceApplication', () => { describe('shutdown handlers', () => { it('should register all shutdown handlers during start', async () => { - const mockShutdownInstance = { + const localShutdownInstance = { shutdown: mock(() => Promise.resolve()), onShutdown: mock(() => {}), onShutdownHigh: mock(() => {}), onShutdownMedium: mock(() => {}), onShutdownLow: mock(() => {}), }; - - mock.module('@stock-bot/shutdown', () => ({ - Shutdown: { - getInstance: () => mockShutdownInstance, - }, - })); + shutdownGetInstanceSpy.mockReturnValue(localShutdownInstance as any); const serviceConfig: ServiceApplicationConfig = { serviceName: 'test-service', @@ -731,10 +733,10 @@ describe('ServiceApplication', () => { ); // Should have registered shutdown handlers - expect(mockShutdownInstance.onShutdown).toHaveBeenCalledTimes(5); // Queue, HTTP, Custom, Services, Loggers + expect(localShutdownInstance.onShutdown).toHaveBeenCalledTimes(5); // Queue, HTTP, Custom, Services, Loggers // Test the handlers by calling them - const shutdownHandlers = (mockShutdownInstance.onShutdown as any).mock.calls; + const shutdownHandlers = (localShutdownInstance.onShutdown as any).mock.calls; // Find and execute queue shutdown handler (priority 9) const queueHandler = shutdownHandlers.find(call => call[2] === 'Queue System'); diff --git a/libs/core/handlers/test/create-job-handler.test.ts b/libs/core/handlers/test/create-job-handler.test.ts index b97e681d..fc6ddae3 100644 --- a/libs/core/handlers/test/create-job-handler.test.ts +++ b/libs/core/handlers/test/create-job-handler.test.ts @@ -96,9 +96,15 @@ describe('createJobHandler', () => { }); it('should support async operations', async () => { + let resolveStep!: () => void; + let asyncStepCompleted = false; + const stepGate = new Promise(resolve => { + resolveStep = resolve; + }); + const handler = createJobHandler(async job => { - // Simulate async operation - await new Promise(resolve => setTimeout(resolve, 10)); + await stepGate; + asyncStepCompleted = true; return { success: true, @@ -120,12 +126,14 @@ describe('createJobHandler', () => { updateProgress: async () => {}, }; - const startTime = Date.now(); - const result = await handler(mockJob as any); - const endTime = Date.now(); + const pending = handler(mockJob as any); + expect(asyncStepCompleted).toBe(false); + resolveStep(); + const result = await pending; + expect(asyncStepCompleted).toBe(true); expect(result.success).toBe(true); - expect(endTime - startTime).toBeGreaterThanOrEqual(10); + expect(result.processedBy).toBe('user-789'); }); it('should maintain type safety for complex payloads', () => { diff --git a/libs/core/queue/src/queue-manager.ts b/libs/core/queue/src/queue-manager.ts index 983270ab..31f6a07f 100644 --- a/libs/core/queue/src/queue-manager.ts +++ b/libs/core/queue/src/queue-manager.ts @@ -99,6 +99,14 @@ export class QueueManager { this.ioredisConnection = deps?.createRedis ? deps.createRedis(ioredisOptions) : new Redis(ioredisOptions); + if (typeof this.ioredisConnection.on === 'function') { + this.ioredisConnection.on('error', error => { + this.logger.error('QueueManager Redis connection error', { + service: this.serviceName, + error, + }); + }); + } // Rate limiter will be initialized when rules are added dynamically // No longer initialized from config diff --git a/libs/core/queue/src/queue.ts b/libs/core/queue/src/queue.ts index 46ac78f7..650613d0 100644 --- a/libs/core/queue/src/queue.ts +++ b/libs/core/queue/src/queue.ts @@ -123,7 +123,7 @@ export class Queue { // Initialize queue events if workers will be used if (config.workers && config.workers > 0) { - this.queueEvents = new QueueEvents(queueName, { connection }); + this.queueEvents = this.createQueueEvents(connection); } // Start workers if requested and not explicitly disabled @@ -262,12 +262,18 @@ export class Queue { return await this.bullQueue.getJob(jobId); } + private createQueueEvents(connection: ReturnType): QueueEvents { + const queueEvents = new QueueEvents(this.queueName, { connection }); + queueEvents.on('error', error => + this.logger.error('QueueEvents connection error', { queueName: this.queueName, error }) + ); + return queueEvents; + } + /** Wait for a result using a QueueEvents connection owned by this queue. */ async waitForJob(job: Job, timeout = 30000): Promise { if (!this.queueEvents) { - this.queueEvents = new QueueEvents(this.queueName, { - connection: getRedisConnection(this.redisConfig), - }); + this.queueEvents = this.createQueueEvents(getRedisConnection(this.redisConfig)); } await this.queueEvents.waitUntilReady(); return job.waitUntilFinished(this.queueEvents, timeout); @@ -589,7 +595,7 @@ export class Queue { // Initialize queue events if not already done if (!this.queueEvents) { const connection = getRedisConnection(this.redisConfig); - this.queueEvents = new QueueEvents(this.queueName, { connection }); + this.queueEvents = this.createQueueEvents(connection); } this.startWorkers(workerCount, concurrency); diff --git a/libs/core/queue/test/queue-class.test.ts b/libs/core/queue/test/queue-class.test.ts index 43b886fe..2433ba3b 100644 --- a/libs/core/queue/test/queue-class.test.ts +++ b/libs/core/queue/test/queue-class.test.ts @@ -1,17 +1,37 @@ -import { describe, expect, it, mock } from 'bun:test'; +import { afterEach, describe, expect, it, mock } from 'bun:test'; import { Queue, removeScheduledJobsFromBullQueue } from '../src/queue'; import { QueueManager } from '../src/queue-manager'; import type { QueueWorkerConfig, RedisConfig } from '../src/types'; describe('Queue Class', () => { + // Use a non-QA isolated loopback port so unit tests never touch QA Dragonfly (localhost:6379) const mockRedisConfig: RedisConfig = { - host: 'localhost', - port: 6379, + host: '127.0.0.1', + port: 16379, + maxRetriesPerRequest: 1, + retryDelay: 50, }; + const createdQueues: Queue[] = []; + + function trackQueue(queue: Queue): Queue { + createdQueues.push(queue); + return queue; + } + + afterEach(async () => { + await Promise.all( + createdQueues.splice(0).map(async queue => { + // Stop reconnect timers on unreachable test sockets before awaiting BullMQ close() + (queue.getBullQueue() as any).connection?._client?.disconnect(false); + (queue as any).queueEvents?.connection?._client?.disconnect(false); + await queue.close().catch(() => {}); + }) + ); + }); describe('basic functionality', () => { it('should create queue with minimal config', () => { - const queue = new Queue('test-queue', mockRedisConfig); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig)); expect(queue).toBeDefined(); expect(queue.getName()).toBe('test-queue'); }); @@ -22,7 +42,7 @@ describe('Queue Class', () => { backoff: { type: 'exponential' as const, delay: 2000 }, }; - const queue = new Queue('test-queue', mockRedisConfig, defaultJobOptions); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig, defaultJobOptions)); expect(queue).toBeDefined(); expect(queue.getName()).toBe('test-queue'); }); @@ -36,7 +56,7 @@ describe('Queue Class', () => { trace: mock(() => {}), }; - const queue = new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger)); expect(queue).toBeDefined(); }); @@ -48,19 +68,19 @@ describe('Queue Class', () => { serviceName: 'test-service', }; - const queue = new Queue('test-queue', mockRedisConfig, {}, workerConfig); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, workerConfig)); expect(queue).toBeDefined(); }); }); describe('queue naming and utilities', () => { it('should return queue name', () => { - const queue = new Queue('my-test-queue', mockRedisConfig); + const queue = trackQueue(new Queue('my-test-queue', mockRedisConfig)); expect(queue.getName()).toBe('my-test-queue'); }); it('should get bull queue instance', () => { - const queue = new Queue('test-queue', mockRedisConfig); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig)); const bullQueue = queue.getBullQueue(); expect(bullQueue).toBeDefined(); }); @@ -83,7 +103,7 @@ describe('Queue Class', () => { child: mock(() => mockChildLogger), }; - const queue = new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger)); const childLogger = queue.createChildLogger('batch', { batchId: '123' }); expect(childLogger).toBe(mockChildLogger); @@ -99,7 +119,7 @@ describe('Queue Class', () => { trace: mock(() => {}), }; - const queue = new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger)); const childLogger = queue.createChildLogger('batch', { batchId: '123' }); expect(childLogger).toBe(mockLogger); @@ -108,7 +128,7 @@ describe('Queue Class', () => { describe('worker count methods', () => { it('should get worker count when no workers', () => { - const queue = new Queue('test-queue', mockRedisConfig); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig)); expect(queue.getWorkerCount()).toBe(0); }); @@ -118,7 +138,7 @@ describe('Queue Class', () => { startWorker: false, // Don't actually start }; - const queue = new Queue('test-queue', mockRedisConfig, {}, workerConfig); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, workerConfig)); // Workers aren't actually started with startWorker: false expect(queue.getWorkerCount()).toBe(0); }); diff --git a/libs/core/queue/test/queue.test.ts b/libs/core/queue/test/queue.test.ts index bd9d6f77..4f2c25c6 100644 --- a/libs/core/queue/test/queue.test.ts +++ b/libs/core/queue/test/queue.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'bun:test'; +import { afterEach, describe, expect, it } from 'bun:test'; import { createServiceCache, ServiceCache } from '../src/service-cache'; import { generateCachePrefix, @@ -78,39 +78,40 @@ describe('Service Utilities', () => { }); describe('ServiceCache', () => { - it('should create service cache', () => { - const mockRedisConfig = { - host: 'localhost', - port: 6379, - }; + // Use a non-QA isolated loopback port and non-shared clients so unit tests never touch QA Dragonfly (localhost:6379) + const mockRedisConfig = { + host: '127.0.0.1', + port: 16379, + maxRetriesPerRequest: 1, + retryDelay: 50, + }; + const createdCaches: ServiceCache[] = []; - // Since ServiceCache constructor internally creates a real cache, - // we can't easily test it without mocking the createCache function - // For now, just test that the function exists and returns something - const serviceCache = createServiceCache('myservice', mockRedisConfig); + afterEach(async () => { + await Promise.all(createdCaches.splice(0).map(cache => cache.disconnect().catch(() => {}))); + }); + + it('should create service cache', () => { + const serviceCache = createServiceCache('myservice', mockRedisConfig, { shared: false }); + createdCaches.push(serviceCache); expect(serviceCache).toBeDefined(); expect(serviceCache).toBeInstanceOf(ServiceCache); }); it('should handle cache prefix correctly', () => { - const mockRedisConfig = { - host: 'localhost', - port: 6379, - }; - - const serviceCache = createServiceCache('webApi', mockRedisConfig); + const serviceCache = createServiceCache('webApi', mockRedisConfig, { shared: false }); + createdCaches.push(serviceCache); expect(serviceCache).toBeDefined(); // The prefix is set internally as cache:web-api expect(serviceCache.getKey('test')).toBe('cache:web-api:test'); }); it('should support global cache option', () => { - const mockRedisConfig = { - host: 'localhost', - port: 6379, - }; - - const globalCache = createServiceCache('myservice', mockRedisConfig, { global: true }); + const globalCache = createServiceCache('myservice', mockRedisConfig, { + global: true, + shared: false, + }); + createdCaches.push(globalCache); expect(globalCache).toBeDefined(); // Global cache uses a different prefix expect(globalCache.getKey('test')).toBe('stock-bot:shared:test'); @@ -120,16 +121,16 @@ describe('ServiceCache', () => { describe('Batch Processing', () => { it('should handle batch job data types', () => { const batchJob: BatchJobData = { - items: [1, 2, 3], - options: { - batchSize: 10, - concurrency: 2, - }, + payloadKey: 'batch:payload:1', + batchIndex: 0, + totalBatches: 3, + itemCount: 10, + totalDelayHours: 1, }; - expect(batchJob.items).toHaveLength(3); - expect(batchJob.options.batchSize).toBe(10); - expect(batchJob.options.concurrency).toBe(2); + expect(batchJob.payloadKey).toBe('batch:payload:1'); + expect(batchJob.totalBatches).toBe(3); + expect(batchJob.itemCount).toBe(10); }); it('should process batch results', () => { diff --git a/libs/core/shutdown/src/shutdown.ts b/libs/core/shutdown/src/shutdown.ts index fbf8c6d9..4ffe4fba 100644 --- a/libs/core/shutdown/src/shutdown.ts +++ b/libs/core/shutdown/src/shutdown.ts @@ -15,6 +15,7 @@ export class Shutdown { private shutdownTimeout: number; private callbacks: CallbackEntry[] = []; private signalHandlersRegistered = false; + private registeredSignalHandlers = new Map void>(); private shutdownPromise: Promise | null = null; private triggerSignal: string | null = null; @@ -33,6 +34,37 @@ export class Shutdown { return Shutdown.instance; } + /** + * Dispose the singleton instance and remove its signal listeners. + */ + static reset(): void { + if (Shutdown.instance) { + Shutdown.instance.dispose(); + Shutdown.instance = null; + } + } + + /** + * Remove process signal handlers registered by this instance. + */ + removeSignalHandlers(): void { + for (const [signal, listener] of this.registeredSignalHandlers) { + process.off(signal, listener); + } + this.registeredSignalHandlers.clear(); + this.signalHandlersRegistered = false; + } + + /** + * Clean up signal listeners and clear singleton reference if this is the active singleton. + */ + dispose(): void { + this.removeSignalHandlers(); + if (Shutdown.instance === this) { + Shutdown.instance = null; + } + } + /** * Get current shutdown status */ @@ -153,7 +185,7 @@ export class Shutdown { signals.forEach(signal => { // Use process.on instead of process.once to handle multiple signals - process.on(signal, async () => { + const listener = async () => { this.logger.info(`Received ${signal} signal`); // If already shutting down, ignore the signal @@ -178,7 +210,10 @@ export class Shutdown { process.exit(1); } - }); + }; + + this.registeredSignalHandlers.set(signal, listener); + process.on(signal, listener); this.logger.debug(`Registered handler for ${signal}`); }); diff --git a/libs/core/shutdown/test/shutdown-comprehensive.test.ts b/libs/core/shutdown/test/shutdown-comprehensive.test.ts index e0d434f7..a3d8f6c2 100644 --- a/libs/core/shutdown/test/shutdown-comprehensive.test.ts +++ b/libs/core/shutdown/test/shutdown-comprehensive.test.ts @@ -6,14 +6,15 @@ describe('Shutdown Comprehensive Tests', () => { beforeEach(() => { // Reset singleton instance for each test - (Shutdown as any).instance = null; + Shutdown.reset(); // Create a fresh instance for each test shutdownInstance = new Shutdown({ autoRegister: false }); }); afterEach(() => { - // Clean up singleton - (Shutdown as any).instance = null; + // Clean up singleton and any signal listeners + shutdownInstance?.dispose(); + Shutdown.reset(); }); describe('Basic Functionality', () => { @@ -250,10 +251,18 @@ describe('Shutdown Comprehensive Tests', () => { }); it('should use default timeout', () => { - const _defaultShutdown = new Shutdown(); + const defaultShutdown = new Shutdown(); + let secondShutdown: Shutdown | undefined; - // Can't directly test timeout value, but we can verify it doesn't throw - expect(() => new Shutdown()).not.toThrow(); + try { + // Can't directly test timeout value, but we can verify it doesn't throw + expect(() => { + secondShutdown = new Shutdown(); + }).not.toThrow(); + } finally { + defaultShutdown.dispose(); + secondShutdown?.dispose(); + } }); }); }); diff --git a/libs/core/shutdown/test/shutdown-signals.test.ts b/libs/core/shutdown/test/shutdown-signals.test.ts index be3f4118..22fca3f0 100644 --- a/libs/core/shutdown/test/shutdown-signals.test.ts +++ b/libs/core/shutdown/test/shutdown-signals.test.ts @@ -1,46 +1,46 @@ -import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import { Shutdown } from '../src/shutdown'; describe('Shutdown Signal Handlers', () => { - let shutdown: Shutdown; - let processOnceSpy: any; - let processExitSpy: any; - const originalOn = process.on; - const originalExit = process.exit; + let shutdown: Shutdown | undefined; + let processOnceSpy: ReturnType; + let processExitSpy: ReturnType; beforeEach(() => { // Reset singleton instance - (Shutdown as any).instance = null; + Shutdown.reset(); + shutdown = undefined; // Mock process.on to capture signal handlers const listeners: Record = {}; - processOnceSpy = mock((event: string, handler: Function) => { + processOnceSpy = spyOn(process, 'on').mockImplementation(((event: string, handler: Function) => { if (!listeners[event]) { listeners[event] = []; } listeners[event].push(handler); return process; - }); - process.on = processOnceSpy as any; + }) as any); // Mock process.exit - processExitSpy = mock((_code?: number) => { + processExitSpy = spyOn(process, 'exit').mockImplementation(((_code?: number) => { // Just record the call, don't actually exit return undefined as never; - }); - process.exit = processExitSpy as any; + }) as any); // Store listeners for manual triggering (global as any).__testListeners = listeners; }); afterEach(() => { - // Restore original methods - process.on = originalOn; - process.exit = originalExit; + // Clean up any registered listeners and singleton before restoring process spies + shutdown?.dispose(); + shutdown = undefined; + Shutdown.reset(); + + // Restore original methods + processOnceSpy?.mockRestore(); + processExitSpy?.mockRestore(); - // Clean up - (Shutdown as any).instance = null; delete (global as any).__testListeners; }); diff --git a/libs/core/shutdown/test/shutdown.test.ts b/libs/core/shutdown/test/shutdown.test.ts index 6e4e5964..0faeb0bf 100644 --- a/libs/core/shutdown/test/shutdown.test.ts +++ b/libs/core/shutdown/test/shutdown.test.ts @@ -5,14 +5,14 @@ describe('Shutdown', () => { let shutdown: Shutdown; beforeEach(() => { - // Reset singleton instance for each test - (Shutdown as any).instance = null; - shutdown = Shutdown.getInstance({ timeout: 1000 }); + // Reset singleton instance and remove any prior signal listeners + Shutdown.reset(); + shutdown = Shutdown.getInstance({ timeout: 1000, autoRegister: false }); }); afterEach(() => { - // Clean up - (Shutdown as any).instance = null; + // Clean up listeners and singleton + Shutdown.reset(); }); describe('getInstance', () => { @@ -24,7 +24,8 @@ describe('Shutdown', () => { }); it('should use provided config on first call', () => { - const instance = Shutdown.getInstance({ timeout: 5000 }); + Shutdown.reset(); + const instance = Shutdown.getInstance({ timeout: 5000, autoRegister: false }); expect(instance).toBeDefined(); }); }); @@ -125,20 +126,28 @@ describe('Shutdown', () => { }); it('should respect timeout', async () => { + let slowTimer: ReturnType | undefined; const slowHandler = mock(async () => { - await new Promise(resolve => setTimeout(resolve, 2000)); + await new Promise(resolve => { + slowTimer = setTimeout(resolve, 2000); + }); }); - shutdown = Shutdown.getInstance({ timeout: 100 }); + Shutdown.reset(); + shutdown = Shutdown.getInstance({ timeout: 100, autoRegister: false }); shutdown.onShutdown(slowHandler, 10, 'Slow Handler'); const start = Date.now(); - await expect(shutdown.shutdown()).rejects.toThrow('Shutdown timeout'); + try { + await expect(shutdown.shutdown()).rejects.toThrow('Shutdown timeout'); + } finally { + clearTimeout(slowTimer); + } const duration = Date.now() - start; // Shutdown waits for timeout (100ms) plus some processing time expect(duration).toBeGreaterThan(90); - expect(duration).toBeLessThan(1500); // But not the full 2000ms + expect(duration).toBeLessThan(500); }); }); @@ -161,8 +170,8 @@ describe('Shutdown', () => { await shutdown.shutdown(); // Reset by creating new instance - (Shutdown as any).instance = null; - shutdown = Shutdown.getInstance({ timeout: 1000 }); + Shutdown.reset(); + shutdown = Shutdown.getInstance({ timeout: 1000, autoRegister: false }); shutdown.onShutdown(handler, 10, 'Handler'); await shutdown.shutdown(); diff --git a/test/setup.ts b/test/setup.ts index 9c786868..b145a4f7 100644 --- a/test/setup.ts +++ b/test/setup.ts @@ -9,7 +9,13 @@ // Bun.timeout = 30000; // Store original console methods to allow restoration -const originalConsole = global.console; +const originalConsoleMethods = { + log: console.log.bind(console), + debug: console.debug.bind(console), + info: console.info.bind(console), + warn: console.warn.bind(console), + error: console.error.bind(console), +}; // Mock console methods to reduce noise during tests // These can be restored with testHelpers.restoreConsole() @@ -98,7 +104,11 @@ global.testHelpers = { * Restore console methods */ restoreConsole: () => { - global.console = originalConsole; + console.log = originalConsoleMethods.log; + console.debug = originalConsoleMethods.debug; + console.info = originalConsoleMethods.info; + console.warn = originalConsoleMethods.warn; + console.error = originalConsoleMethods.error; } }; From 7814f834fb5366402a6efaaf6c62a3282feff912 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 12:03:37 -0500 Subject: [PATCH 13/20] T-11: audit-secrets skips any match containing `${`, so a hardcoded user:pass with an interpolated host is missed --- scripts/audit-secrets.ts | 6 +++-- scripts/test/security.test.ts | 43 +++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/scripts/audit-secrets.ts b/scripts/audit-secrets.ts index c57435f8..ff757830 100644 --- a/scripts/audit-secrets.ts +++ b/scripts/audit-secrets.ts @@ -43,11 +43,13 @@ export function findEmbeddedHttpCredentials(content: string): number[] { for (let index = 0; index < lines.length; index++) { const line = lines[index] ?? ''; for (const match of line.matchAll(httpCredentialPattern)) { - const fullMatch = match[0] ?? ''; + const user = match[1] ?? ''; + const password = match[2] ?? ''; const host = match[3] ?? ''; const normalizedHost = host.replace(/\.$/, ''); if ( - fullMatch.includes('${') || + user.includes('${') || + password.includes('${') || !normalizedHost || normalizedHost.startsWith('.') || isPlaceholderHost(normalizedHost) diff --git a/scripts/test/security.test.ts b/scripts/test/security.test.ts index 9b5f9756..26061c44 100644 --- a/scripts/test/security.test.ts +++ b/scripts/test/security.test.ts @@ -425,6 +425,49 @@ test('embedded HTTP(S) credential audit catches real credentials with line numbe expect(serialized).not.toContain('proxy-user'); }); +test('embedded HTTP(S) credential audit reports hardcoded credentials with interpolated hosts and skips interpolated credentials', () => { + const buildUrl = (scheme: string, user: string, pass: string, host: string) => + `${scheme}://${user}:${pass}@${host}`; + + const interpHost = buildUrl('http', 'realuser', 'realpass', '${proxyHost}:80'); + const partialInterpHost = buildUrl('https', 'realuser', 'realpass', 'sub.${domain}/v1'); + const ipv6InterpHost = buildUrl('http', 'realuser', 'realpass', '[${ipv6Host}]:80'); + const placeholderSubInterp = buildUrl('http', 'realuser', 'realpass', '${sub}.example.com:80'); + + const lines = [ + 'const bothInterpDocHost = `http://${user}:${pass}@host:80`;', + 'const bothInterpRealHost = `http://${user}:${pass}@proxy.vendor.io:80`;', + 'const allInterp = `http://${user}:${pass}@${proxyHost}:80`;', + 'const userOnlyInterp = `http://${user}:realpass@proxy.vendor.io:80`;', + 'const userOnlyInterpHost = `http://${user}:realpass@${proxyHost}:80`;', + 'const passOnlyInterp = `http://realuser:${pass}@proxy.vendor.io:80`;', + 'const passOnlyInterpHost = `http://realuser:${pass}@${proxyHost}:80`;', + `const placeholderSub = \`${placeholderSubInterp}\`;`, + `const leakedInterpHost = \`${interpHost}\`;`, + `const leakedPartialInterpHost = \`${partialInterpHost}\`;`, + `const leakedIpv6InterpHost = \`${ipv6InterpHost}\`;`, + `const mixedSameLine = [\`http://\${user}:\${pass}@proxy.vendor.io:80\`, \`${interpHost}\`];`, + ].join('\n'); + + expect(findEmbeddedHttpCredentials(lines)).toEqual([9, 10, 11, 12]); + + const files = new Map([ + ['apps/stock/proxy.ts', Buffer.from(`const url = \`${interpHost}\`;\n`)], + ]); + const findings = scanTrackedFilesForHttpCredentials( + ['apps/stock/proxy.ts'], + path => files.get(path) ?? null + ); + expect(findings).toEqual([{ path: 'apps/stock/proxy.ts', line: 1 }]); + const serialized = JSON.stringify(findings); + expect(serialized).not.toContain('realuser'); + expect(serialized).not.toContain('realpass'); + + expect( + scanTrackedFilesForHttpCredentials(['scripts/audit-secrets.ts', 'scripts/test/security.test.ts']) + ).toEqual([]); +}); + function isolatedGitEnv(baseEnv: NodeJS.ProcessEnv = process.env): Record { const env: Record = {}; for (const [key, value] of Object.entries(baseEnv)) { From dfb43ef5d03a877ea2d4bc6d522869b8265db8bf Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 12:10:01 -0500 Subject: [PATCH 14/20] T-11: tests --- scripts/test/security.test.ts | 64 +++++++++++++++++++++++++++++++++-- 1 file changed, 62 insertions(+), 2 deletions(-) diff --git a/scripts/test/security.test.ts b/scripts/test/security.test.ts index 26061c44..8e8a99fe 100644 --- a/scripts/test/security.test.ts +++ b/scripts/test/security.test.ts @@ -468,6 +468,52 @@ test('embedded HTTP(S) credential audit reports hardcoded credentials with inter ).toEqual([]); }); +test('embedded HTTP(S) credential audit handles interpolated-host edge cases per line', () => { + const buildUrl = (scheme: string, user: string, pass: string, host: string) => + `${scheme}://${user}:${pass}@${host}`; + + const interpHost = buildUrl('http', 'edgeuser', 'edgepass', '${proxyHost}:80'); + const interpHostNoPort = buildUrl('https', 'edgeuser', 'edgepass', '${proxyHost}/v1'); + const upperScheme = buildUrl('HTTPS', 'edgeuser', 'edgepass', '${proxyHost}'); + const interpFqdnDot = buildUrl('https', 'edgeuser', 'edgepass', '${region}.vendor.io.:8443'); + const interpTestTld = buildUrl('http', 'edgeuser', 'edgepass', '${sub}.proxy.test:80'); + const interpLocalhost = buildUrl('http', 'edgeuser', 'edgepass', 'localhost'); + + const lines = [ + `const reportedFirst = [\`${interpHost}\`, \`http://\${user}:\${pass}@proxy.vendor.io:80\`];`, + `const twoLeaks = [\`${interpHost}\`, \`${interpHostNoPort}\`];`, + 'const partialUser = `http://real${suffix}:realpass@proxy.vendor.io:80`;', + 'const partialPass = `http://realuser:pre${secret}post@${proxyHost}:80`;', + `const upper = \`${upperScheme}\`;`, + `const fqdnDot = \`${interpFqdnDot}\`;`, + `const testTld = \`${interpTestTld}\`;`, + `const local = \`${interpLocalhost}\`;`, + ].join('\r\n'); + + // Line 2 holds two leaks but is reported once; CRLF must not shift line numbers. + expect(findEmbeddedHttpCredentials(lines)).toEqual([1, 2, 5, 6]); +}); + +test('embedded HTTP(S) credential audit self-scan reads both edited sources regardless of cwd', () => { + const sources = new Map([ + ['scripts/audit-secrets.ts', fileURLToPath(new URL('../audit-secrets.ts', import.meta.url))], + ['scripts/test/security.test.ts', fileURLToPath(import.meta.url)], + ]); + const read: string[] = []; + + const findings = scanTrackedFilesForHttpCredentials([...sources.keys()], path => { + const absolute = sources.get(path); + if (!absolute) throw new Error(`unexpected path ${path}`); + const content = readFileSync(absolute); + expect(content.length).toBeGreaterThan(0); + read.push(path); + return content; + }); + + expect(read).toEqual([...sources.keys()]); + expect(findings).toEqual([]); +}); + function isolatedGitEnv(baseEnv: NodeJS.ProcessEnv = process.env): Record { const env: Record = {}; for (const [key, value] of Object.entries(baseEnv)) { @@ -478,12 +524,15 @@ function isolatedGitEnv(baseEnv: NodeJS.ProcessEnv = process.env): Record { + const result = runAuditSecretsCliFixture(process.env, '${proxyHost}:80'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('leaked.ts:2'); + expect(result.stdout).not.toContain(result.fakeUser); + expect(result.stdout).not.toContain(result.fakePass); + expect(result.stderr).not.toContain(result.fakeUser); + expect(result.stderr).not.toContain(result.fakePass); +}); + test('audit-secrets CLI fixture ignores inherited Git repository and index env vars', () => { const callerDir = mkdtempSync(join(tmpdir(), 'audit-secrets-caller-')); const cleanEnv = isolatedGitEnv(); From 512be9d95a6187e7d513ec666abfd895a0e4148c Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 12:14:24 -0500 Subject: [PATCH 15/20] =?UTF-8?q?T-16:=20M0.1b=20=E2=80=94=20Make=20repo-w?= =?UTF-8?q?ide=20`bun=20test`=20green:=20fix=20queue,=20shutdown-signal=20?= =?UTF-8?q?and=20research-workflow=20test=20failures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/core/cache/test/redis-cache.test.ts | 16 +++++-- libs/core/shutdown/test/shutdown.test.ts | 55 ++++++++++++++++-------- 2 files changed, 49 insertions(+), 22 deletions(-) diff --git a/libs/core/cache/test/redis-cache.test.ts b/libs/core/cache/test/redis-cache.test.ts index ba28ba89..19c6fcff 100644 --- a/libs/core/cache/test/redis-cache.test.ts +++ b/libs/core/cache/test/redis-cache.test.ts @@ -27,11 +27,13 @@ if (!testRedisUrl) { describe.skipIf(!testRedisUrl)('RedisCache', () => { let cache: RedisCache; let redisConfig: RedisConfig; + let testPrefix: string; beforeEach(() => { redisConfig = parseTestRedisConfig(testRedisUrl!); + testPrefix = `test:${crypto.randomUUID()}:`; const options: CacheOptions = { - keyPrefix: 'test:', + keyPrefix: testPrefix, ttl: 3600, shared: false, redisConfig, @@ -40,7 +42,14 @@ describe.skipIf(!testRedisUrl)('RedisCache', () => { }); afterEach(async () => { - await cache?.disconnect().catch(() => {}); + if (!cache) return; + try { + await cache.clear(); + } catch { + // Ignore cleanup errors if Redis is unreachable or already disconnected + } finally { + await cache.disconnect().catch(() => {}); + } }); describe('Core functionality', () => { @@ -174,7 +183,7 @@ describe.skipIf(!testRedisUrl)('RedisCache', () => { it('should handle errors gracefully in get', async () => { // Force an error by using invalid JSON const badCache = new RedisCache({ - keyPrefix: 'bad:', + keyPrefix: `bad:${crypto.randomUUID()}:`, shared: false, redisConfig, }); @@ -188,6 +197,7 @@ describe.skipIf(!testRedisUrl)('RedisCache', () => { const stats = badCache.getStats(); expect(stats.misses).toBe(1); } finally { + await badCache.clear().catch(() => {}); await badCache.disconnect().catch(() => {}); } }); diff --git a/libs/core/shutdown/test/shutdown.test.ts b/libs/core/shutdown/test/shutdown.test.ts index 0faeb0bf..55e5af60 100644 --- a/libs/core/shutdown/test/shutdown.test.ts +++ b/libs/core/shutdown/test/shutdown.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import { Shutdown } from '../src/shutdown'; describe('Shutdown', () => { @@ -126,28 +126,45 @@ describe('Shutdown', () => { }); it('should respect timeout', async () => { - let slowTimer: ReturnType | undefined; - const slowHandler = mock(async () => { - await new Promise(resolve => { - slowTimer = setTimeout(resolve, 2000); - }); - }); + let releaseHandler!: () => void; + const slowHandler = mock( + () => + new Promise(resolve => { + releaseHandler = resolve; + }) + ); - Shutdown.reset(); - shutdown = Shutdown.getInstance({ timeout: 100, autoRegister: false }); - shutdown.onShutdown(slowHandler, 10, 'Slow Handler'); + let scheduledCallback: (() => void) | undefined; + let scheduledDelay: number | undefined; + const fakeTimer = {} as ReturnType; + const setTimeoutSpy = spyOn(globalThis, 'setTimeout').mockImplementation((( + cb: (...args: unknown[]) => void, + delay?: number + ) => { + scheduledCallback = () => cb(); + scheduledDelay = delay; + return fakeTimer; + }) as unknown as typeof setTimeout); + const clearTimeoutSpy = spyOn(globalThis, 'clearTimeout').mockImplementation(() => {}); - const start = Date.now(); try { - await expect(shutdown.shutdown()).rejects.toThrow('Shutdown timeout'); - } finally { - clearTimeout(slowTimer); - } - const duration = Date.now() - start; + Shutdown.reset(); + shutdown = Shutdown.getInstance({ timeout: 100, autoRegister: false }); + shutdown.onShutdown(slowHandler, 10, 'Slow Handler'); - // Shutdown waits for timeout (100ms) plus some processing time - expect(duration).toBeGreaterThan(90); - expect(duration).toBeLessThan(500); + const shutdownPromise = shutdown.shutdown(); + expect(scheduledDelay).toBe(100); + expect(scheduledCallback).toBeDefined(); + + scheduledCallback!(); + + await expect(shutdownPromise).rejects.toThrow('Shutdown timeout'); + expect(clearTimeoutSpy).toHaveBeenCalledWith(fakeTimer); + } finally { + releaseHandler?.(); + setTimeoutSpy.mockRestore(); + clearTimeoutSpy.mockRestore(); + } }); }); From 6fc3f8cd5c795629374dc97286ee67eb03297019 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 12:21:58 -0500 Subject: [PATCH 16/20] T-16: edits made in the worktree --- libs/core/cache/test/redis-cache.test.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/libs/core/cache/test/redis-cache.test.ts b/libs/core/cache/test/redis-cache.test.ts index 19c6fcff..e93ce530 100644 --- a/libs/core/cache/test/redis-cache.test.ts +++ b/libs/core/cache/test/redis-cache.test.ts @@ -45,10 +45,8 @@ describe.skipIf(!testRedisUrl)('RedisCache', () => { if (!cache) return; try { await cache.clear(); - } catch { - // Ignore cleanup errors if Redis is unreachable or already disconnected } finally { - await cache.disconnect().catch(() => {}); + await cache.disconnect(); } }); @@ -197,8 +195,11 @@ describe.skipIf(!testRedisUrl)('RedisCache', () => { const stats = badCache.getStats(); expect(stats.misses).toBe(1); } finally { - await badCache.clear().catch(() => {}); - await badCache.disconnect().catch(() => {}); + try { + await badCache.clear(); + } finally { + await badCache.disconnect(); + } } }); }); From c2e4f3b2bd84decaecd8b1f5484c996b8b62070e Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 12:33:45 -0500 Subject: [PATCH 17/20] T-16: tests --- .../test/queue-connection-errors.test.ts | 122 ++++++++++++++++ .../shutdown/test/shutdown-dispose.test.ts | 136 ++++++++++++++++++ test/unit/in-process-test-isolation.test.ts | 54 +++++++ 3 files changed, 312 insertions(+) create mode 100644 libs/core/queue/test/queue-connection-errors.test.ts create mode 100644 libs/core/shutdown/test/shutdown-dispose.test.ts create mode 100644 test/unit/in-process-test-isolation.test.ts diff --git a/libs/core/queue/test/queue-connection-errors.test.ts b/libs/core/queue/test/queue-connection-errors.test.ts new file mode 100644 index 00000000..aa980067 --- /dev/null +++ b/libs/core/queue/test/queue-connection-errors.test.ts @@ -0,0 +1,122 @@ +import { EventEmitter } from 'events'; +import { afterEach, describe, expect, it, mock } from 'bun:test'; +import { Queue } from '../src/queue'; +import { QueueManager } from '../src/queue-manager'; +import type { RedisConfig } from '../src/types'; + +// Regression: an EventEmitter that emits 'error' with no listener throws synchronously, +// so an unreachable Redis used to surface as an unhandled error mid-suite. +// Non-QA loopback port; nothing is expected to listen here. +const unreachableRedis: RedisConfig = { + host: '127.0.0.1', + port: 16379, + maxRetriesPerRequest: 1, + retryDelay: 50, +}; + +function createLogger() { + return { + info: mock(() => {}), + error: mock(() => {}), + warn: mock(() => {}), + debug: mock(() => {}), + trace: mock(() => {}), + }; +} + +describe('Queue connection error handling', () => { + const queues: Queue[] = []; + + afterEach(async () => { + await Promise.all( + queues.splice(0).map(async queue => { + // Stop reconnect timers on the unreachable socket before awaiting close() + (queue.getBullQueue() as any).connection?._client?.disconnect(false); + (queue as any).queueEvents?.connection?._client?.disconnect(false); + await queue.close().catch(() => {}); + }) + ); + }); + + it('logs QueueEvents connection errors instead of throwing', () => { + const logger = createLogger(); + const queue = new Queue( + 'conn-error-queue', + unreachableRedis, + {}, + { workers: 1, startWorker: false }, + logger as any + ); + queues.push(queue); + const queueEvents = (queue as any).queueEvents as EventEmitter; + expect(queueEvents).toBeDefined(); + expect(queueEvents.listenerCount('error')).toBeGreaterThanOrEqual(1); + + const failure = new Error('connect ECONNREFUSED 127.0.0.1:16379'); + expect(() => queueEvents.emit('error', failure)).not.toThrow(); + + expect(logger.error).toHaveBeenCalledWith('QueueEvents connection error', { + queueName: 'conn-error-queue', + error: failure, + }); + }); + + it('does not create QueueEvents for a producer-only queue', () => { + const queue = new Queue('producer-only', unreachableRedis, {}, {}, createLogger() as any); + queues.push(queue); + + expect((queue as any).queueEvents).toBeUndefined(); + }); +}); + +describe('QueueManager connection error handling', () => { + function createFakeRedis() { + const redis = new EventEmitter() as EventEmitter & { + quit: ReturnType; + disconnect: ReturnType; + }; + redis.quit = mock(async () => 'OK'); + redis.disconnect = mock(() => {}); + return redis; + } + + it('logs rate-limiter Redis errors instead of throwing', async () => { + const logger = createLogger(); + const redis = createFakeRedis(); + const manager = new QueueManager( + { serviceName: 'conn-error-svc', redis: unreachableRedis }, + undefined, + logger as any, + { createRedis: () => redis as any } + ); + + try { + expect(redis.listenerCount('error')).toBe(1); + const failure = new Error('connect ECONNREFUSED 127.0.0.1:16379'); + + expect(() => redis.emit('error', failure)).not.toThrow(); + + expect(logger.error).toHaveBeenCalledWith('QueueManager Redis connection error', { + service: 'conn-error-svc', + error: failure, + }); + } finally { + await manager.shutdown(); + } + expect(redis.quit).toHaveBeenCalledTimes(1); + }); + + it('accepts an injected Redis client without an event API', async () => { + const quit = mock(async () => 'OK'); + const manager = new QueueManager( + { serviceName: 'no-events-svc', redis: unreachableRedis }, + undefined, + createLogger() as any, + { createRedis: () => ({ quit, disconnect: mock(() => {}) }) as any } + ); + + await manager.shutdown(); + + expect(quit).toHaveBeenCalledTimes(1); + }); +}); diff --git a/libs/core/shutdown/test/shutdown-dispose.test.ts b/libs/core/shutdown/test/shutdown-dispose.test.ts new file mode 100644 index 00000000..0e9c02ba --- /dev/null +++ b/libs/core/shutdown/test/shutdown-dispose.test.ts @@ -0,0 +1,136 @@ +import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; +import { Shutdown } from '../src/shutdown'; + +// These tests use the real `process` listener registry (no stubs) because the +// regression being guarded is listeners leaking across test files in one bun process. +const SIGNALS = ['SIGTERM', 'SIGINT'] as const; + +function listenerCounts(): Record<(typeof SIGNALS)[number], number> { + return { + SIGTERM: process.listenerCount('SIGTERM'), + SIGINT: process.listenerCount('SIGINT'), + }; +} + +describe('Shutdown signal listener cleanup', () => { + const created: Shutdown[] = []; + let baseline: ReturnType; + + function track(instance: Shutdown): Shutdown { + created.push(instance); + return instance; + } + + beforeEach(() => { + Shutdown.reset(); + baseline = listenerCounts(); + }); + + afterEach(() => { + for (const instance of created.splice(0)) { + instance.dispose(); + } + Shutdown.reset(); + }); + + it('autoRegister adds exactly one SIGTERM and one SIGINT listener and dispose removes them', () => { + const shutdown = track(new Shutdown()); + + expect(listenerCounts()).toEqual({ + SIGTERM: baseline.SIGTERM + 1, + SIGINT: baseline.SIGINT + 1, + }); + + shutdown.dispose(); + + expect(listenerCounts()).toEqual(baseline); + }); + + it('autoRegister: false adds no process listeners', () => { + track(new Shutdown({ autoRegister: false })); + + expect(listenerCounts()).toEqual(baseline); + }); + + it('removeSignalHandlers leaves listeners owned by other code in place', () => { + const foreign = () => {}; + process.on('SIGTERM', foreign); + try { + const shutdown = track(new Shutdown()); + shutdown.removeSignalHandlers(); + + expect(process.listeners('SIGTERM')).toContain(foreign); + expect(listenerCounts()).toEqual({ SIGTERM: baseline.SIGTERM + 1, SIGINT: baseline.SIGINT }); + } finally { + process.off('SIGTERM', foreign); + } + }); + + it('dispose and reset are idempotent', () => { + const shutdown = track(new Shutdown()); + + shutdown.dispose(); + shutdown.dispose(); + Shutdown.reset(); + Shutdown.reset(); + + expect(listenerCounts()).toEqual(baseline); + }); + + it('repeatedly creating and disposing instances never accumulates listeners', () => { + for (let i = 0; i < 25; i++) { + new Shutdown().dispose(); + } + + expect(listenerCounts()).toEqual(baseline); + }); + + it('Shutdown.reset removes singleton listeners and the next getInstance builds a fresh instance', () => { + const first = Shutdown.getInstance(); + expect(listenerCounts().SIGTERM).toBe(baseline.SIGTERM + 1); + + Shutdown.reset(); + + expect(listenerCounts()).toEqual(baseline); + const second = Shutdown.getInstance({ autoRegister: false }); + track(second); + expect(second).not.toBe(first); + expect(listenerCounts()).toEqual(baseline); + }); + + it('disposing a non-singleton instance keeps the active singleton and its listeners', () => { + const singleton = Shutdown.getInstance(); + const other = track(new Shutdown()); + + other.dispose(); + + expect(Shutdown.getInstance()).toBe(singleton); + expect(listenerCounts()).toEqual({ + SIGTERM: baseline.SIGTERM + 1, + SIGINT: baseline.SIGINT + 1, + }); + }); + + it('disposing the singleton directly clears it so getInstance returns a new one', () => { + const singleton = Shutdown.getInstance({ autoRegister: false }); + + singleton.dispose(); + + const next = Shutdown.getInstance({ autoRegister: false }); + expect(next).not.toBe(singleton); + }); + + it('a disposed instance keeps its shutdown callbacks usable without process listeners', async () => { + const shutdown = track(new Shutdown({ timeout: 1000 })); + const calls: string[] = []; + shutdown.onShutdown(() => { + calls.push('ran'); + }, 10, 'probe'); + + shutdown.dispose(); + await shutdown.shutdown(); + + expect(calls).toEqual(['ran']); + expect(listenerCounts()).toEqual(baseline); + }); +}); diff --git a/test/unit/in-process-test-isolation.test.ts b/test/unit/in-process-test-isolation.test.ts new file mode 100644 index 00000000..9e71995c --- /dev/null +++ b/test/unit/in-process-test-isolation.test.ts @@ -0,0 +1,54 @@ +import { readdirSync, readFileSync } from 'fs'; +import { join, relative } from 'path'; +import { describe, expect, it } from 'bun:test'; + +// Guards T-16: all test files share one bun process, so process-global mocks in one +// file silently change the modules and globals other files see. Restorable `spyOn` +// is the supported pattern; child-process harnesses (test/integration) are exempt. +const root = join(import.meta.dir, '..', '..'); +const scannedRoots = ['libs']; +const forbidden: Array<{ label: string; pattern: RegExp }> = [ + { label: 'mock.module(', pattern: /\bmock\.module\s*\(/ }, + { label: 'Bun.serve assignment', pattern: /\bBun\.serve\s*=(?!=)/ }, + { label: 'process.on assignment', pattern: /\bprocess\.(on|once|off)\s*=(?!=)/ }, + { label: 'process.exit assignment', pattern: /\bprocess\.exit\s*=(?!=)/ }, + { label: 'global console assignment', pattern: /\b(global|globalThis)\.console\s*=(?!=)/ }, +]; + +function collectTestFiles(dir: string, out: string[]): void { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name.startsWith('.')) { + continue; + } + const full = join(dir, entry.name); + if (entry.isDirectory()) { + collectTestFiles(full, out); + } else if (/\.(test|spec)\.tsx?$/.test(entry.name)) { + out.push(full); + } + } +} + +describe('in-process test isolation', () => { + it('library tests never install process-global mocks or overwrite process/Bun globals', () => { + const files: string[] = []; + for (const dir of scannedRoots) { + collectTestFiles(join(root, dir), files); + } + expect(files.length).toBeGreaterThan(0); + + const violations: string[] = []; + for (const file of files) { + const lines = readFileSync(file, 'utf8').split('\n'); + lines.forEach((line, index) => { + for (const { label, pattern } of forbidden) { + if (pattern.test(line)) { + violations.push(`${relative(root, file)}:${index + 1} ${label}`); + } + } + }); + } + + expect(violations).toEqual([]); + }); +}); From b9536a774053ac0868b425e55920290876a1f63a Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 12:43:30 -0500 Subject: [PATCH 18/20] T-23: Benchmark self-tests hash every untracked file in the worktree and fail on unreadable ones --- scripts/benchmark-research.ts | 54 +++++-- scripts/test/benchmark-research.test.ts | 180 ++++++++++++++++++++++++ 2 files changed, 223 insertions(+), 11 deletions(-) diff --git a/scripts/benchmark-research.ts b/scripts/benchmark-research.ts index 5c4f571f..1cefeadb 100644 --- a/scripts/benchmark-research.ts +++ b/scripts/benchmark-research.ts @@ -247,25 +247,57 @@ async function child(workload: Workload) { }; } -function command(args: string[]): string { - const result = Bun.spawnSync(args, { cwd: root, stdout: 'pipe', stderr: 'pipe' }); +function command(args: string[], cwd: string = root): string { + const result = Bun.spawnSync(args, { cwd, stdout: 'pipe', stderr: 'pipe' }); if (result.exitCode !== 0) { throw new Error(`${args[0]} failed: ${result.stderr.toString()}`); } return result.stdout.toString().trimEnd(); } -export function identity() { - const paths = command(['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z']) +function errorCode(error: unknown): string | undefined { + if (typeof error === 'object' && error !== null && 'code' in error) { + const code = (error as { code?: unknown }).code; + return typeof code === 'string' ? code : undefined; + } + return undefined; +} + +export function identity( + options: { + sourceRoot?: string; + readSourceFile?: (path: string) => Uint8Array; + } = {} +) { + const sourceRoot = options.sourceRoot ?? root; + const readSourceFile = options.readSourceFile ?? readFileSync; + const tracked = new Set( + command(['git', 'ls-files', '--cached', '-z'], sourceRoot).split('\0').filter(Boolean) + ); + const paths = command( + ['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z'], + sourceRoot + ) .split('\0') .filter(Boolean) .sort(); const source = createHash('sha256'); for (const path of paths) { - const absolute = join(root, path); - source.update( - JSON.stringify([path, existsSync(absolute) ? sha256(readFileSync(absolute)) : 'deleted']) - ); + const absolute = join(sourceRoot, path); + let entry: string; + try { + entry = sha256(readSourceFile(absolute)); + } catch (error) { + const code = errorCode(error); + if (code === 'ENOENT') { + entry = 'deleted'; + } else if ((code === 'EACCES' || code === 'EPERM') && !tracked.has(path)) { + entry = 'unreadable'; + } else { + throw error; + } + } + source.update(JSON.stringify([path, entry])); } const addon = join(root, 'apps/stock/engine/dist/engine.node'); const nativeSha256 = sha256(readFileSync(addon)); @@ -285,12 +317,12 @@ export function identity() { }; return { source: { - commit: command(['git', 'rev-parse', 'HEAD']), - dirty: command(['git', 'status', '--porcelain']).length > 0, + commit: command(['git', 'rev-parse', 'HEAD'], sourceRoot), + dirty: command(['git', 'status', '--porcelain'], sourceRoot).length > 0, contentSha256: source.digest('hex'), files: paths.length, scope: - 'Tracked and nonignored untracked file paths/content, including dirty changes; generated ignored artifacts excluded.', + 'Tracked and nonignored untracked file paths/content, including dirty changes; unreadable untracked files are hashed by path with an unreadable marker; generated ignored artifacts excluded.', }, native: { path: addon, diff --git a/scripts/test/benchmark-research.test.ts b/scripts/test/benchmark-research.test.ts index a4ed2b11..0d98fd7b 100644 --- a/scripts/test/benchmark-research.test.ts +++ b/scripts/test/benchmark-research.test.ts @@ -1,13 +1,71 @@ import { describe, expect, test } from 'bun:test'; +import { chmodSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { prepareDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset'; import { economicHash, + identity, parameters, researchFixture, unavailable, verifyRepeats, } from '../benchmark-research'; +function runGit(cwd: string, args: string[]): void { + const result = Bun.spawnSync(['git', ...args], { + cwd, + stdout: 'pipe', + stderr: 'pipe', + env: { + ...process.env, + GIT_CONFIG_NOSYSTEM: '1', + GIT_CONFIG_GLOBAL: '/dev/null', + }, + }); + if (result.exitCode !== 0) { + throw new Error(`git ${args.join(' ')} failed: ${result.stderr.toString()}`); + } +} + +function withTempGitRepo(fn: (repoDir: string, protectForCleanup: (path: string) => void) => T): T { + const repoDir = mkdtempSync(join(tmpdir(), 'stock-bot-benchmark-identity-')); + const chmodPaths: string[] = []; + const protectForCleanup = (path: string) => { + chmodPaths.push(path); + }; + try { + runGit(repoDir, ['init']); + writeFileSync(join(repoDir, 'tracked.txt'), 'tracked-v1\n'); + runGit(repoDir, ['add', 'tracked.txt']); + runGit(repoDir, [ + '-c', + 'user.name=Test User', + '-c', + 'user.email=test@example.com', + 'commit', + '-m', + 'initial', + ]); + return fn(repoDir, protectForCleanup); + } finally { + for (const path of chmodPaths) { + try { + chmodSync(path, 0o600); + } catch { + // Ignore if file was removed during the test. + } + } + rmSync(repoDir, { recursive: true, force: true }); + } +} + +function fsError(code: string, path: string): NodeJS.ErrnoException { + const error = new Error(`${code}: ${path}`) as NodeJS.ErrnoException; + error.code = code; + return error; +} + describe('existing-path research benchmark', () => { test('fixture is seeded, ordered, hash-verified and detached by real dataset preparation', async () => { for (const assets of [1, 10]) { @@ -142,4 +200,126 @@ describe('existing-path research benchmark', () => { } } }); + + test('identity hashes unreadable untracked files deterministically while throwing on tracked or non-permission errors', () => { + withTempGitRepo(repoDir => { + const untrackedPath = join(repoDir, '.bash_profile'); + const trackedPath = join(repoDir, 'tracked.txt'); + writeFileSync(untrackedPath, 'placeholder\n'); + + for (const code of ['EACCES', 'EPERM'] as const) { + const readSourceFile = (path: string) => { + if (path === untrackedPath) { + throw fsError(code, path); + } + return readFileSync(path); + }; + + const first = identity({ sourceRoot: repoDir, readSourceFile }); + const second = identity({ sourceRoot: repoDir, readSourceFile }); + expect(Object.keys(first)).toEqual(['source', 'native', 'runtime', 'host']); + expect(first.source.contentSha256).toBe(second.source.contentSha256); + expect(first.source.files).toBe(2); + expect(first.source.dirty).toBe(true); + expect(first.source.scope).toContain('unreadable'); + + // Changing a readable file changes contentSha256. + writeFileSync(trackedPath, `tracked-${code}\n`); + const afterReadableEdit = identity({ sourceRoot: repoDir, readSourceFile }); + expect(afterReadableEdit.source.contentSha256).not.toBe(first.source.contentSha256); + + // Tracked files still throw EACCES / EPERM. + expect(() => + identity({ + sourceRoot: repoDir, + readSourceFile: path => { + if (path === trackedPath) { + throw fsError(code, path); + } + return readFileSync(path); + }, + }) + ).toThrow(code); + } + + // Non-permission errors on untracked files still throw. + expect(() => + identity({ + sourceRoot: repoDir, + readSourceFile: path => { + if (path === untrackedPath) { + throw fsError('EIO', path); + } + return readFileSync(path); + }, + }) + ).toThrow('EIO'); + + // Renaming or removing the unreadable untracked file changes contentSha256. + const beforeRename = identity({ + sourceRoot: repoDir, + readSourceFile: path => { + if (path === untrackedPath) { + throw fsError('EACCES', path); + } + return readFileSync(path); + }, + }); + const renamedPath = join(repoDir, '.bash_profile_renamed'); + renameSync(untrackedPath, renamedPath); + const afterRename = identity({ + sourceRoot: repoDir, + readSourceFile: path => { + if (path === renamedPath) { + throw fsError('EACCES', path); + } + return readFileSync(path); + }, + }); + expect(afterRename.source.contentSha256).not.toBe(beforeRename.source.contentSha256); + + rmSync(renamedPath); + const afterRemove = identity({ sourceRoot: repoDir }); + expect(afterRemove.source.contentSha256).not.toBe(afterRename.source.contentSha256); + expect(afterRemove.source.files).toBe(1); + }); + }); + + test('identity handles real chmod 000 untracked files and rejects chmod 000 tracked files', () => { + if (process.getuid?.() === 0) { + return; + } + withTempGitRepo((repoDir, protectForCleanup) => { + const trackedPath = join(repoDir, 'tracked.txt'); + const untrackedPath = join(repoDir, 'unreadable-untracked.txt'); + writeFileSync(untrackedPath, 'secret\n'); + chmodSync(untrackedPath, 0o000); + protectForCleanup(untrackedPath); + + const first = identity({ sourceRoot: repoDir }); + const second = identity({ sourceRoot: repoDir }); + expect(first.source.contentSha256).toBe(second.source.contentSha256); + expect(first.source.files).toBe(2); + + writeFileSync(trackedPath, 'tracked-v2\n'); + const afterEdit = identity({ sourceRoot: repoDir }); + expect(afterEdit.source.contentSha256).not.toBe(first.source.contentSha256); + + chmodSync(trackedPath, 0o000); + protectForCleanup(trackedPath); + expect(() => identity({ sourceRoot: repoDir })).toThrow(/EACCES|permission denied/i); + }); + }); + + test('identity hashes deleted unstaged tracked files with the deleted marker', () => { + withTempGitRepo(repoDir => { + const trackedPath = join(repoDir, 'tracked.txt'); + const beforeDelete = identity({ sourceRoot: repoDir }); + rmSync(trackedPath); + const afterDelete = identity({ sourceRoot: repoDir }); + expect(afterDelete.source.contentSha256).not.toBe(beforeDelete.source.contentSha256); + expect(afterDelete.source.files).toBe(1); + expect(afterDelete.source.dirty).toBe(true); + }); + }); }); From f3fc80daa5d093119ee13828cdfb0cf16cda8e0d Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 12:48:31 -0500 Subject: [PATCH 19/20] T-23: Benchmark self-tests hash every untracked file in the worktree and fail on unreadable ones --- scripts/test/benchmark-research.test.ts | 31 +++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/scripts/test/benchmark-research.test.ts b/scripts/test/benchmark-research.test.ts index 0d98fd7b..26f26e22 100644 --- a/scripts/test/benchmark-research.test.ts +++ b/scripts/test/benchmark-research.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from 'bun:test'; +import { createHash } from 'node:crypto'; import { chmodSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -36,6 +37,9 @@ function withTempGitRepo(fn: (repoDir: string, protectForCleanup: (path: stri }; try { runGit(repoDir, ['init']); + const emptyExcludesPath = join(repoDir, '.git', 'info', 'exclude'); + writeFileSync(emptyExcludesPath, ''); + runGit(repoDir, ['config', 'core.excludesFile', emptyExcludesPath]); writeFileSync(join(repoDir, 'tracked.txt'), 'tracked-v1\n'); runGit(repoDir, ['add', 'tracked.txt']); runGit(repoDir, [ @@ -66,6 +70,18 @@ function fsError(code: string, path: string): NodeJS.ErrnoException { return error; } +function sha256(data: Uint8Array | string): string { + return createHash('sha256').update(data).digest('hex'); +} + +function expectedSourceSha256(entries: [string, string][]): string { + const hash = createHash('sha256'); + for (const [path, entry] of [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) { + hash.update(JSON.stringify([path, entry])); + } + return hash.digest('hex'); +} + describe('existing-path research benchmark', () => { test('fixture is seeded, ordered, hash-verified and detached by real dataset preparation', async () => { for (const assets of [1, 10]) { @@ -219,6 +235,12 @@ describe('existing-path research benchmark', () => { const second = identity({ sourceRoot: repoDir, readSourceFile }); expect(Object.keys(first)).toEqual(['source', 'native', 'runtime', 'host']); expect(first.source.contentSha256).toBe(second.source.contentSha256); + expect(first.source.contentSha256).toBe( + expectedSourceSha256([ + ['.bash_profile', 'unreadable'], + ['tracked.txt', sha256(readFileSync(trackedPath))], + ]) + ); expect(first.source.files).toBe(2); expect(first.source.dirty).toBe(true); expect(first.source.scope).toContain('unreadable'); @@ -299,6 +321,12 @@ describe('existing-path research benchmark', () => { const first = identity({ sourceRoot: repoDir }); const second = identity({ sourceRoot: repoDir }); expect(first.source.contentSha256).toBe(second.source.contentSha256); + expect(first.source.contentSha256).toBe( + expectedSourceSha256([ + ['tracked.txt', sha256(readFileSync(trackedPath))], + ['unreadable-untracked.txt', 'unreadable'], + ]) + ); expect(first.source.files).toBe(2); writeFileSync(trackedPath, 'tracked-v2\n'); @@ -318,6 +346,9 @@ describe('existing-path research benchmark', () => { rmSync(trackedPath); const afterDelete = identity({ sourceRoot: repoDir }); expect(afterDelete.source.contentSha256).not.toBe(beforeDelete.source.contentSha256); + expect(afterDelete.source.contentSha256).toBe( + expectedSourceSha256([['tracked.txt', 'deleted']]) + ); expect(afterDelete.source.files).toBe(1); expect(afterDelete.source.dirty).toBe(true); }); From f712c3619bda5c2aaf6fc7bacbce838d5c032b2c Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 12:57:44 -0500 Subject: [PATCH 20/20] T-23: tests --- .../benchmark-identity-edge-cases.test.ts | 242 ++++++++++++++++++ 1 file changed, 242 insertions(+) create mode 100644 test/unit/benchmark-identity-edge-cases.test.ts diff --git a/test/unit/benchmark-identity-edge-cases.test.ts b/test/unit/benchmark-identity-edge-cases.test.ts new file mode 100644 index 00000000..5f03c911 --- /dev/null +++ b/test/unit/benchmark-identity-edge-cases.test.ts @@ -0,0 +1,242 @@ +import { createHash } from 'node:crypto'; +import { + chmodSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { describe, expect, test } from 'bun:test'; +import { identity } from '../../scripts/benchmark-research'; + +// Guards T-23: benchmark provenance must tolerate unreadable *untracked* files (sandbox +// placeholder dotfiles) without masking read failures on tracked sources, and must keep +// readable/deleted digests identical to the pre-fix algorithm. + +const runningAsRoot = process.getuid?.() === 0; + +function git(cwd: string, args: string[]): string { + const result = Bun.spawnSync( + ['git', '-c', 'user.name=QA', '-c', 'user.email=qa@example.com', ...args], + { + cwd, + stdout: 'pipe', + stderr: 'pipe', + env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' }, + } + ); + if (result.exitCode !== 0) { + throw new Error(`git ${args.join(' ')} failed: ${result.stderr.toString()}`); + } + return result.stdout.toString().trim(); +} + +function sha256(data: Uint8Array | string): string { + return createHash('sha256').update(data).digest('hex'); +} + +// Mirrors the digest identity() builds: sorted paths, each hashed as JSON [path, entry]. +function expectedDigest(entries: Array<[string, string]>): string { + const hash = createHash('sha256'); + for (const pair of [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) { + hash.update(JSON.stringify(pair)); + } + return hash.digest('hex'); +} + +function withRepo( + files: Record, + fn: (repo: string, restoreLater: (path: string, mode: number) => void) => void +): void { + const repo = mkdtempSync(join(tmpdir(), 'stock-bot-identity-edge-')); + const restores: Array<[string, number]> = []; + try { + git(repo, ['init', '-q']); + const excludes = join(repo, '.git', 'info', 'exclude'); + writeFileSync(excludes, ''); + git(repo, ['config', 'core.excludesFile', excludes]); + for (const [path, content] of Object.entries(files)) { + mkdirSync(join(repo, path, '..'), { recursive: true }); + writeFileSync(join(repo, path), content); + } + git(repo, ['add', '-A']); + git(repo, ['commit', '-qm', 'fixture']); + fn(repo, (path, mode) => restores.push([path, mode])); + } finally { + for (const [path, mode] of restores.reverse()) { + try { + chmodSync(path, mode); + } catch { + // Already removed by the test. + } + } + rmSync(repo, { recursive: true, force: true }); + } +} + +describe('benchmark identity() edge cases (T-23)', () => { + test('readable-only repo digest is byte-for-byte the pre-fix algorithm, including awkward names', () => { + const files = { 'name with space.txt': 'a\n', 'ünïcode.txt': 'b\n', 'dir/nested.txt': 'c\n' }; + withRepo(files, repo => { + writeFileSync(join(repo, 'untracked.txt'), 'u\n'); + + const result = identity({ sourceRoot: repo }); + + expect(result.source.contentSha256).toBe( + expectedDigest([ + ...Object.entries(files).map(([p, c]): [string, string] => [p, sha256(c)]), + ['untracked.txt', sha256('u\n')], + ]) + ); + expect(result.source.files).toBe(4); + }); + }); + + test('sourceRoot drives every git query, so commit and dirty describe the temp repo', () => { + withRepo({ 'a.txt': 'a\n' }, repo => { + const head = git(repo, ['rev-parse', 'HEAD']); + + const clean = identity({ sourceRoot: repo }); + writeFileSync(join(repo, 'a.txt'), 'changed\n'); + const dirty = identity({ sourceRoot: repo }); + + expect(clean.source.commit).toBe(head); + expect(clean.source.dirty).toBe(false); + expect(dirty.source.commit).toBe(head); + expect(dirty.source.dirty).toBe(true); + }); + }); + + test('dangling untracked symlink still hashes as deleted, as before the fix', () => { + withRepo({ 'a.txt': 'a\n' }, repo => { + symlinkSync('missing-target', join(repo, 'dangling')); + + const result = identity({ sourceRoot: repo }); + + expect(result.source.contentSha256).toBe( + expectedDigest([ + ['a.txt', sha256('a\n')], + ['dangling', 'deleted'], + ]) + ); + }); + }); + + test.skipIf(runningAsRoot)( + 'untracked symlink to an unreadable target hashes as unreadable instead of throwing', + () => { + withRepo({ 'a.txt': 'a\n' }, (repo, restoreLater) => { + const secret = join(repo, 'secret'); + writeFileSync(secret, 's\n'); + chmodSync(secret, 0o000); + restoreLater(secret, 0o600); + symlinkSync('secret', join(repo, 'link')); + + const first = identity({ sourceRoot: repo }); + const second = identity({ sourceRoot: repo }); + + const expected = expectedDigest([ + ['a.txt', sha256('a\n')], + ['link', 'unreadable'], + ['secret', 'unreadable'], + ]); + expect(first.source.contentSha256).toBe(expected); + expect(second.source.contentSha256).toBe(expected); + }); + } + ); + + test.skipIf(runningAsRoot)( + 'unreadable untracked directory does not break identity (git cannot list its contents)', + () => { + withRepo({ 'a.txt': 'a\n' }, (repo, restoreLater) => { + const dir = join(repo, 'locked'); + mkdirSync(dir); + writeFileSync(join(dir, 'inside.txt'), 'x\n'); + chmodSync(dir, 0o000); + restoreLater(dir, 0o755); + + const result = identity({ sourceRoot: repo }); + + expect(result.source.contentSha256).toBe(expectedDigest([['a.txt', sha256('a\n')]])); + expect(result.source.files).toBe(1); + }); + } + ); + + test.skipIf(runningAsRoot)( + 'tracked file under a non-searchable directory throws EACCES instead of hashing as deleted', + () => { + withRepo({ 'a.txt': 'a\n', 'src/core.ts': 'export {};\n' }, (repo, restoreLater) => { + const dir = join(repo, 'src'); + chmodSync(dir, 0o600); + restoreLater(dir, 0o755); + + expect(() => identity({ sourceRoot: repo })).toThrow(/EACCES.*src\/core\.ts/); + }); + } + ); + + test.skipIf(runningAsRoot)( + 'file removed from the index with git rm --cached is treated as untracked and tolerated when unreadable', + () => { + withRepo({ 'a.txt': 'a\n', 'was-tracked.txt': 'w\n' }, (repo, restoreLater) => { + const path = join(repo, 'was-tracked.txt'); + git(repo, ['rm', '-q', '--cached', 'was-tracked.txt']); + chmodSync(path, 0o000); + restoreLater(path, 0o600); + + const result = identity({ sourceRoot: repo }); + + expect(result.source.contentSha256).toBe( + expectedDigest([ + ['a.txt', sha256('a\n')], + ['was-tracked.txt', 'unreadable'], + ]) + ); + }); + } + ); + + test('staged-but-uncommitted file counts as tracked, so a permission error on it still throws', () => { + withRepo({ 'a.txt': 'a\n' }, repo => { + const staged = join(repo, 'staged.txt'); + writeFileSync(staged, 's\n'); + git(repo, ['add', 'staged.txt']); + + const readSourceFile = (path: string): Uint8Array => { + if (path === staged) { + throw Object.assign(new Error(`EACCES: ${path}`), { code: 'EACCES' }); + } + return readFileSync(path); + }; + + expect(() => identity({ sourceRoot: repo, readSourceFile })).toThrow('EACCES'); + }); + }); + + test('errors without a string code are rethrown, never mapped to a marker', () => { + withRepo({ 'a.txt': 'a\n' }, repo => { + writeFileSync(join(repo, 'untracked.txt'), 'u\n'); + const target = join(repo, 'untracked.txt'); + + for (const thrown of [ + new Error('plain failure'), + Object.assign(new Error('numeric'), { code: 13 }), + ]) { + const readSourceFile = (path: string): Uint8Array => { + if (path === target) { + throw thrown; + } + return readFileSync(path); + }; + + expect(() => identity({ sourceRoot: repo, readSourceFile })).toThrow(thrown.message); + } + }); + }); +});