diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index 929e9a3d..0f7d9d0c 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -154,22 +154,34 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/sto --out-dir ./tmp/security-master-report ``` +- **Scope of `--as-of `:** `--as-of` sets the calendar reference date for Pass 6 delisting classification (active grace window vs. delisted outcome). It does **not** take a historical point-in-time snapshot of MongoDB — source symbol records and bar spans are read from the current collections, so the report can incorporate provider observations recorded after `--as-of`. + ### Persist to isolated dev PostgreSQL (`localhost:5433/trading_bot_dev`) -Ensure the `master` track migrations have been applied to dev PostgreSQL first (`bun run db:migrate --track master`), then run with `--persist`: +Apply the `master` track migrations to isolated dev PostgreSQL first (passing the dev target variables explicitly so a QA-configured shell cannot migrate QA): + +```bash +NODE_ENV=development \ +POSTGRES_HOST=localhost \ +POSTGRES_PORT=5433 \ +POSTGRES_DATABASE=trading_bot_dev \ + bun run db:migrate --track master +``` + +Then run the CLI with `--persist` against the same isolated dev PostgreSQL target: ```bash NODE_ENV=development \ MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ POSTGRES_HOST=localhost \ POSTGRES_PORT=5433 \ -POSTGRES_DB=trading_bot_dev \ +POSTGRES_DATABASE=trading_bot_dev \ bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts \ --as-of 2026-01-15 \ --out-dir ./tmp/security-master-report \ --persist ``` -- **Safety guards:** MongoDB is always opened with `mongoReadOnly: true` via `MONGODB_READ_URI`. Without `--persist`, no PostgreSQL client is constructed. With `--persist`, `assertEnvironmentSafety()` runs before opening PostgreSQL (with `STOCK_BOT_ALLOW_DEV_ON_QA_DB` stripped) so `development` runs cannot write to QA PostgreSQL (`localhost:5432/trading_bot`). +- **Safety guards:** MongoDB is always opened with `mongoReadOnly: true` via `MONGODB_READ_URI`. Without `--persist`, no PostgreSQL client is constructed. With `--persist`, `assertSecurityMasterPersistSafety()` runs `assertEnvironmentSafety()` (with `STOCK_BOT_ALLOW_DEV_ON_QA_DB` stripped) and enforces `NODE_ENV=development` against an isolated dev PostgreSQL database (`*_dev` / `stock_bot_safety*`), blocking `NODE_ENV=qa` and QA PostgreSQL (`localhost:5432/trading_bot`) before any PostgreSQL client is created. - **Pass 4 status:** Pass 4 cross-sectional price cross-check input (`sampleCloses` / `fxRates`) is **not yet wired** into this CLI; `composeSecurityMasterRun` is invoked without sample closes and Pass 4 is explicitly reported as `skipped` (`pass4: null`). ### Output files (`--out-dir`) diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index c10ee95e..7fd47256 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -216,6 +216,7 @@ export { } from './run'; export { + assertSecurityMasterPersistSafety, formatRunSecurityMasterSummary, parseRunSecurityMasterArgs, RUN_SECURITY_MASTER_USAGE, diff --git a/apps/stock/data-pipeline/src/security-master/run-security-master.ts b/apps/stock/data-pipeline/src/security-master/run-security-master.ts index 1834900e..d8090a05 100644 --- a/apps/stock/data-pipeline/src/security-master/run-security-master.ts +++ b/apps/stock/data-pipeline/src/security-master/run-security-master.ts @@ -3,7 +3,11 @@ import { dirname, join } from 'node:path'; import { getLogger } from '@stock-bot/logger'; import { MongoDBClient } from '@stock-bot/mongodb'; import { PostgreSQLClient } from '@stock-bot/postgres'; -import { assertEnvironmentSafety, initializeStockConfig } from '@stock-bot/stock-config'; +import { + assertEnvironmentSafety, + initializeStockConfig, + type StockAppConfig, +} from '@stock-bot/stock-config'; import { computeBarSpans, normalizeBarDate, @@ -55,7 +59,7 @@ export const RUN_SECURITY_MASTER_USAGE = [ 'Options:', ' --as-of Required. Calendar reference date for Pass 6 delisting classification.', ' --out-dir Required. Output directory for match-report.md, conflicts.csv, override-template.sql, and run-stats.json.', - ' --persist Optional. Persist security-master rows to PostgreSQL after running assertEnvironmentSafety() (default: off).', + ' --persist Optional. Persist security-master rows to isolated dev PostgreSQL after running safety guards (default: off).', ' --help Show this help message and exit.', ].join('\n'); @@ -220,6 +224,40 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe }; } +export function assertSecurityMasterPersistSafety( + config: StockAppConfig, + env: Record = process.env +): void { + const pg = config.database.postgres; + if (!pg.enabled) { + throw new Error('PostgreSQL is disabled in configuration; cannot run with --persist'); + } + + const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _stripped, ...safeEnv } = env; + assertEnvironmentSafety(config, 'dataPipeline', safeEnv); + + if (config.environment !== 'development') { + throw new Error( + `Security master --persist is restricted to NODE_ENV=development targeting isolated dev PostgreSQL ` + + `(got environment "${config.environment}", target ${pg.host}:${pg.port}/${pg.database}).` + ); + } + + if (pg.database === 'trading_bot' || pg.port === 5432) { + throw new Error( + `Security master --persist cannot target QA PostgreSQL (${pg.host}:${pg.port}/${pg.database}); ` + + 'configure isolated dev PostgreSQL (localhost:5433/trading_bot_dev).' + ); + } + + if (!pg.database.endsWith('_dev') && !pg.database.startsWith('stock_bot_safety')) { + throw new Error( + `Security master --persist requires an isolated dev PostgreSQL database ` + + `(ending in "_dev" or "stock_bot_safety*"), got "${pg.database}".` + ); + } +} + export function formatRunSecurityMasterSummary( params: Pick< RunSecurityMasterOutput, @@ -471,7 +509,7 @@ export async function runSecurityMaster( } } - // Step 8: Emit concise one-screen summary after all steps succeed. + // Step 8: Build concise one-screen summary (emitted only after cleanup succeeds). const summary = formatRunSecurityMasterSummary({ asOfDate: options.asOfDate, outDir: options.outDir, @@ -479,12 +517,6 @@ export async function runSecurityMaster( filesWritten, composed, }); - const writeStdout = - deps.writeStdout ?? - ((text: string) => { - process.stdout.write(text); - }); - writeStdout(summary); output = { asOfDate: options.asOfDate, @@ -514,6 +546,13 @@ export async function runSecurityMaster( throw wrapStepError('close-mongo', mongoCloseError); } + const writeStdout = + deps.writeStdout ?? + ((text: string) => { + process.stdout.write(text); + }); + writeStdout(output.summary); + return output; } @@ -532,11 +571,7 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P await mongo.connect(); const assertSafety = (): void => { - if (!config.database.postgres.enabled) { - throw new Error('PostgreSQL is disabled in configuration; cannot run with --persist'); - } - const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _stripped, ...safeEnv } = process.env; - assertEnvironmentSafety(config, 'dataPipeline', safeEnv); + assertSecurityMasterPersistSafety(config, process.env); }; const createPostgresClient = async (): Promise => { diff --git a/test/unit/security-master-run-cli.test.ts b/test/unit/security-master-run-cli.test.ts index 22c151f9..01d9a32a 100644 --- a/test/unit/security-master-run-cli.test.ts +++ b/test/unit/security-master-run-cli.test.ts @@ -10,6 +10,7 @@ import { type GroupedBarSpanRow, } from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; import { + assertSecurityMasterPersistSafety, classifySourceExchanges, compareAscii, composeSecurityMasterRun, @@ -672,6 +673,150 @@ describe('runSecurityMaster', () => { expect(stdoutChunks).toHaveLength(0); }); + test('assertSecurityMasterPersistSafety rejects QA profile and non-dev PostgreSQL targets before opening PostgreSQL', async () => { + const buildConfig = (overrides: { + environment: 'development' | 'qa'; + host?: string; + port: number; + database: string; + }) => + stockAppSchema.parse({ + name: 'stock-bot', + version: '1.0.0', + environment: overrides.environment, + service: { + name: 'data-pipeline', + port: 2002, + }, + log: { + level: 'info', + }, + database: { + postgres: { + enabled: true, + host: overrides.host ?? 'localhost', + port: overrides.port, + database: overrides.database, + user: 'trading_user', + password: 'dev_password', + }, + mongodb: { + enabled: true, + uri: + overrides.environment === 'qa' + ? 'mongodb://localhost:27017/stock' + : 'mongodb://localhost:27018/stock_dev', + readUri: 'mongodb://studio_stock_bot_read:pass@localhost:27017/stock?authSource=stock', + readOnly: true, + database: overrides.environment === 'qa' ? 'stock' : 'stock_dev', + }, + questdb: { enabled: false }, + dragonfly: { enabled: false }, + }, + providers: {}, + features: {}, + }); + + // 1. QA profile targeting QA PostgreSQL (localhost:5432/trading_bot) must be rejected before PG factory runs + const qaConfig = buildConfig({ + environment: 'qa', + port: 5432, + database: 'trading_bot', + }); + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + let pgFactoryCalls = 0; + let mongoClosed = 0; + const stdoutChunks: string[] = []; + + let caught: unknown = null; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => assertSecurityMasterPersistSafety(qaConfig, {}), + createPostgresClient: () => { + pgFactoryCalls += 1; + throw new Error('PostgreSQL factory must not be called for QA profile'); + }, + writeStdout: text => stdoutChunks.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), persist: true } + ); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('env-safety'); + expect((caught as Error).message).toContain('NODE_ENV=development'); + expect(pgFactoryCalls).toBe(0); + expect(mongoClosed).toBe(1); + expect(stdoutChunks).toHaveLength(0); + + // 2. Development profile targeting QA PostgreSQL (even with STOCK_BOT_ALLOW_DEV_ON_QA_DB=true) is rejected + const devQaPgConfig = buildConfig({ + environment: 'development', + port: 5432, + database: 'trading_bot', + }); + expect(() => + assertSecurityMasterPersistSafety(devQaPgConfig, { STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true' }) + ).toThrow(/Safety guard: development environment cannot target QA PostgreSQL/); + + // 3. Development profile on port 5433 with non-dev database name is rejected + const devNonDevDbConfig = buildConfig({ + environment: 'development', + port: 5433, + database: 'trading_bot', + }); + expect(() => assertSecurityMasterPersistSafety(devNonDevDbConfig, {})).toThrow( + /cannot target QA PostgreSQL/ + ); + + // 4. Development profile targeting isolated dev PostgreSQL (localhost:5433/trading_bot_dev) passes + const devIsolatedConfig = buildConfig({ + environment: 'development', + port: 5433, + database: 'trading_bot_dev', + }); + expect(() => assertSecurityMasterPersistSafety(devIsolatedConfig, {})).not.toThrow(); + }); + + test('closeMongo failure after successful writes rejects with close-mongo and leaves stdout empty', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const outDir = createTempDir(); + const stdoutChunks: string[] = []; + const closeErr = new Error('Mongo disconnect timed out'); + + let caught: unknown = null; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + throw closeErr; + }, + writeStdout: text => { + stdoutChunks.push(text); + }, + }, + { asOfDate: '2026-01-15', outDir } + ); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('close-mongo'); + expect((caught as Error).cause).toBe(closeErr); + expect(stdoutChunks).toHaveLength(0); + }); + test('real assertEnvironmentSafety rejects development config targeting QA PostgreSQL 5432/trading_bot', () => { const devQaPgConfig = stockAppSchema.parse({ name: 'stock-bot',