From 654782a6a169a7959b0ddc24697671ad127abff0 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 10:33:27 -0500 Subject: [PATCH 1/7] =?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 2/7] =?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 3/7] =?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 4/7] 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 5/7] 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 6/7] 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 7/7] 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(); + } + }); + } +});