Merge branch 'dev' into fix/red-bun-test
This commit is contained in:
commit
e89aa6cf2c
14 changed files with 1678 additions and 46 deletions
220
test/postgres/fresh-database-schema.test.ts
Normal file
220
test/postgres/fresh-database-schema.test.ts
Normal file
|
|
@ -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> | 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([]);
|
||||
});
|
||||
});
|
||||
208
test/unit/environment-safety-multi-host.test.ts
Normal file
208
test/unit/environment-safety-multi-host.test.ts
Normal file
|
|
@ -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<string, unknown> = {
|
||||
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();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
@ -24,8 +24,14 @@ function makeConfig(overrides: {
|
|||
mongoReadOnly?: boolean;
|
||||
mongoDatabase?: string;
|
||||
dragonflyPassword?: string;
|
||||
bypassSchemaValidation?: boolean;
|
||||
} = {}): StockAppConfig {
|
||||
return stockAppSchema.parse({
|
||||
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',
|
||||
environment: overrides.environment ?? 'development',
|
||||
|
|
@ -50,12 +56,12 @@ 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: overrides.bypassSchemaValidation
|
||||
? defaultMongoUri
|
||||
: (overrides.mongoUri ?? defaultMongoUri),
|
||||
readUri: overrides.bypassSchemaValidation
|
||||
? defaultMongoReadUri
|
||||
: (overrides.mongoReadUri ?? defaultMongoReadUri),
|
||||
readOnly: overrides.mongoReadOnly ?? false,
|
||||
database: overrides.mongoDatabase ?? 'stock_dev',
|
||||
},
|
||||
|
|
@ -81,6 +87,17 @@ function makeConfig(overrides: {
|
|||
},
|
||||
features: {},
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
describe('Environment safety & multi-env isolation', () => {
|
||||
|
|
@ -247,6 +264,261 @@ 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@[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',
|
||||
];
|
||||
|
||||
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/
|
||||
);
|
||||
}
|
||||
|
||||
// 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', () => {
|
||||
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 = [
|
||||
{ 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: false },
|
||||
{ uri: 'mongodb://u:p@[::1]:/stock', malformed: false },
|
||||
{ uri: 'mongodb://u:p@bad:port,localhost:27017/stock', malformed: true },
|
||||
];
|
||||
|
||||
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/
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
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('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<Record<(typeof envKeys)[number], string | undefined>> = {};
|
||||
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',
|
||||
|
|
@ -397,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();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue