stock-bot/test/unit/environment-safety-multi-host.test.ts
2026-11-27 11:48:28 -05:00

208 lines
9 KiB
TypeScript

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();
}
});
}
});