T-7: M0.3a — Harden dev Mongo safety: env-safety throws on unsafe data-pipeline QA reads, scheduled jobs default off, read-only bypass tests
This commit is contained in:
commit
39f6f1fdfe
25 changed files with 3016 additions and 71 deletions
239
test/unit/environment-safety-edge-cases.test.ts
Normal file
239
test/unit/environment-safety-edge-cases.test.ts
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
import { readFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { queueConfigSchema as coreQueueConfigSchema } from '../../libs/core/config/src/schemas';
|
||||
import { queueConfigSchema as diQueueConfigSchema } from '@stock-bot/di';
|
||||
import { setLoggerConfig } from '@stock-bot/logger';
|
||||
import { assertEnvironmentSafety, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config';
|
||||
|
||||
// T-7 edge cases for the dev QA-Mongo guard and the scheduled-jobs default.
|
||||
// Pure config objects only: 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 READ_URI = 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock';
|
||||
const PIPELINE_ERROR = /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/;
|
||||
const WRITE_ERROR = /cannot open a writable MongoDB connection to QA MongoDB/;
|
||||
|
||||
function makeConfig(o: {
|
||||
environment?: 'development' | 'qa' | 'test' | 'production';
|
||||
mongoEnabled?: boolean;
|
||||
mongoUri?: string;
|
||||
mongoReadUri?: string | null;
|
||||
mongoReadOnly?: boolean;
|
||||
mongoDatabase?: string;
|
||||
pgDatabase?: string;
|
||||
} = {}): StockAppConfig {
|
||||
const mongodb: Record<string, unknown> = {
|
||||
enabled: o.mongoEnabled ?? true,
|
||||
uri: o.mongoUri ?? DEV_MONGO_URI,
|
||||
readOnly: o.mongoReadOnly ?? false,
|
||||
database: o.mongoDatabase ?? 'stock_dev',
|
||||
};
|
||||
if (o.mongoReadUri !== null) {
|
||||
mongodb.readUri = o.mongoReadUri ?? READ_URI;
|
||||
}
|
||||
return stockAppSchema.parse({
|
||||
name: 'stock-bot',
|
||||
version: '1.0.0',
|
||||
environment: o.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: o.pgDatabase ?? '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: {},
|
||||
});
|
||||
}
|
||||
|
||||
describe('dev QA-Mongo guard: loopback :27017 host variants', () => {
|
||||
const qaVariants = [
|
||||
'mongodb://studio_stock_bot_read:secret@127.0.0.1:27017/stock',
|
||||
'mongodb://studio_stock_bot_read:secret@0.0.0.0:27017/stock',
|
||||
'mongodb://studio_stock_bot_read:secret@[::1]:27017/stock',
|
||||
'mongodb://studio_stock_bot_read:secret@LOCALHOST:27017/stock',
|
||||
// No explicit port: the driver defaults to 27017.
|
||||
'mongodb://studio_stock_bot_read:secret@localhost/stock',
|
||||
// No db path and no trailing slash.
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017',
|
||||
// Different db name on the same QA server is still the QA server.
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017/other',
|
||||
];
|
||||
|
||||
for (const uri of qaVariants) {
|
||||
test(`non-readOnly dataPipeline reading ${uri} throws with fix guidance`, () => {
|
||||
const cfg = makeConfig({ mongoReadUri: uri, mongoReadOnly: false });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR);
|
||||
});
|
||||
|
||||
test(`readOnly dataPipeline reading ${uri} as the read user passes`, () => {
|
||||
const cfg = makeConfig({ mongoReadUri: uri, mongoReadOnly: true });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test(`writable dataIngestion on ${uri} throws`, () => {
|
||||
const cfg = makeConfig({ mongoUri: uri, mongoReadUri: null, mongoDatabase: 'other' });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow(WRITE_ERROR);
|
||||
});
|
||||
}
|
||||
|
||||
test('non-loopback host on :27017 is not treated as local QA Mongo', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoUri: 'mongodb://writer:pw@10.0.0.51:27017/stock',
|
||||
mongoReadUri: 'mongodb://reader:pw@10.0.0.51:27017/stock',
|
||||
mongoReadOnly: false,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow();
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('dev QA-Mongo guard: dataPipeline credential and target rules', () => {
|
||||
test('percent-encoded trading_admin username is still recognised and blocked', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoReadUri: 'mongodb://trading%5Fadmin:pw@localhost:27017/stock',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR);
|
||||
});
|
||||
|
||||
test('without readUri the pipeline falls back to uri, so trading_admin@27017 in uri throws', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoUri: 'mongodb://trading_admin:pw@localhost:27017/stock',
|
||||
mongoReadUri: null,
|
||||
mongoReadOnly: true,
|
||||
mongoDatabase: 'stock',
|
||||
});
|
||||
expect(cfg.database.mongodb.readUri).toBeUndefined();
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR);
|
||||
});
|
||||
|
||||
test('without readUri, a non-readOnly pipeline on uri localhost:27017 throws', () => {
|
||||
const cfg = makeConfig({ mongoUri: READ_URI, mongoReadUri: null, mongoReadOnly: false });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR);
|
||||
});
|
||||
|
||||
test('readUri wins over uri: a dev :27018 readUri passes even when uri points at QA :27017', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoUri: 'mongodb://trading_admin:pw@localhost:27017/stock',
|
||||
mongoReadUri: DEV_MONGO_URI,
|
||||
mongoReadOnly: false,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE does not unlock a non-readOnly pipeline', () => {
|
||||
const cfg = makeConfig({ mongoReadOnly: false });
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(cfg, 'dataPipeline', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true' })
|
||||
).toThrow(PIPELINE_ERROR);
|
||||
});
|
||||
|
||||
test('only the literal string "true" opens the ingestion escape hatch', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoUri: 'mongodb://trading_admin:pw@localhost:27017',
|
||||
mongoReadUri: null,
|
||||
});
|
||||
for (const value of ['1', 'TRUE', 'yes', '']) {
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(cfg, 'dataIngestion', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: value })
|
||||
).toThrow(WRITE_ERROR);
|
||||
}
|
||||
});
|
||||
|
||||
test('readOnly ingestion-style service on QA :27017 keeps the pre-existing allowance', () => {
|
||||
const cfg = makeConfig({ mongoUri: READ_URI, mongoReadUri: null, mongoReadOnly: true });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow();
|
||||
expect(() => assertEnvironmentSafety(cfg, 'webApi', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('unnamed development service writing to QA :27017 is blocked', () => {
|
||||
const cfg = makeConfig({ mongoUri: READ_URI, mongoReadUri: null });
|
||||
expect(() => assertEnvironmentSafety(cfg, undefined, {})).toThrow(/development service "app"/);
|
||||
});
|
||||
|
||||
test('disabled MongoDB skips the Mongo guard for the pipeline', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoEnabled: false,
|
||||
mongoReadUri: 'mongodb://trading_admin:pw@localhost:27017/stock',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('qa and test environments never apply the dev Mongo guard to the pipeline', () => {
|
||||
for (const environment of ['qa', 'test'] as const) {
|
||||
const cfg = makeConfig({
|
||||
environment,
|
||||
mongoUri: 'mongodb://trading_admin:pw@localhost:27017/stock',
|
||||
mongoReadUri: 'mongodb://trading_admin:pw@localhost:27017/stock',
|
||||
mongoReadOnly: false,
|
||||
mongoDatabase: 'stock',
|
||||
pgDatabase: 'trading_bot',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('enableScheduledJobs defaults off', () => {
|
||||
test('core queueConfigSchema: unset -> false, explicit true -> true', () => {
|
||||
expect(coreQueueConfigSchema.parse({ redis: {} }).enableScheduledJobs).toBe(false);
|
||||
expect(
|
||||
coreQueueConfigSchema.parse({ redis: {}, enableScheduledJobs: true }).enableScheduledJobs
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test('DI queueConfigSchema: unset -> false, explicit true -> true', () => {
|
||||
expect(diQueueConfigSchema.parse({}).enableScheduledJobs).toBe(false);
|
||||
expect(diQueueConfigSchema.parse({ enableScheduledJobs: true }).enableScheduledJobs).toBe(true);
|
||||
});
|
||||
|
||||
test('stock default.json ships enableScheduledJobs=false', () => {
|
||||
const defaults = JSON.parse(
|
||||
readFileSync(path.resolve(import.meta.dir, '../../apps/stock/config/config/default.json'), 'utf8')
|
||||
);
|
||||
expect(defaults.queue.enableScheduledJobs).toBe(false);
|
||||
});
|
||||
|
||||
test('pipeline and ingestion entrypoints fall back to false, and the pipeline requests mongoReadOnly', () => {
|
||||
for (const app of ['data-pipeline', 'data-ingestion']) {
|
||||
const src = readFileSync(
|
||||
path.resolve(import.meta.dir, `../../apps/stock/${app}/src/index.ts`),
|
||||
'utf8'
|
||||
);
|
||||
expect(src).toContain('enableScheduledJobs: config.queue?.enableScheduledJobs ?? false');
|
||||
expect(src).not.toMatch(/enableScheduledJobs\s*\?\?\s*true/);
|
||||
}
|
||||
const pipelineSrc = readFileSync(
|
||||
path.resolve(import.meta.dir, '../../apps/stock/data-pipeline/src/index.ts'),
|
||||
'utf8'
|
||||
);
|
||||
expect(pipelineSrc).toContain("initializeStockConfig('dataPipeline', { mongoReadOnly: true })");
|
||||
});
|
||||
|
||||
test('env-safety no longer warns on the pipeline admin case', () => {
|
||||
const src = readFileSync(
|
||||
path.resolve(import.meta.dir, '../../apps/stock/config/src/env-safety.ts'),
|
||||
'utf8'
|
||||
);
|
||||
expect(src).not.toContain('logger.warn');
|
||||
});
|
||||
});
|
||||
|
|
@ -3,7 +3,13 @@ import { ConfigManager } from '@stock-bot/config';
|
|||
import { ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { MongoDBClient } from '@stock-bot/mongodb';
|
||||
import { assertEnvironmentSafety, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config';
|
||||
import {
|
||||
assertEnvironmentSafety,
|
||||
initializeStockConfig,
|
||||
resetStockConfig,
|
||||
stockAppSchema,
|
||||
type StockAppConfig,
|
||||
} from '@stock-bot/stock-config';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
|
||||
|
|
@ -116,11 +122,131 @@ describe('Environment safety & multi-env isolation', () => {
|
|||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('allows development dataPipeline to read QA MongoDB via readUri while writing dev Postgres', () => {
|
||||
const cfg = makeConfig({ environment: 'development' });
|
||||
test('allows development dataPipeline to read QA MongoDB via readUri when readOnly=true', () => {
|
||||
const cfg = makeConfig({ environment: 'development', mongoReadOnly: true });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('initializeStockConfig applies mongoReadOnly override before safety validation for dev dataPipeline', () => {
|
||||
const envKeys = [
|
||||
'NODE_ENV',
|
||||
'POSTGRES_HOST',
|
||||
'POSTGRES_PORT',
|
||||
'POSTGRES_DB',
|
||||
'POSTGRES_USER',
|
||||
'POSTGRES_PASSWORD',
|
||||
'MONGODB_URI',
|
||||
'MONGODB_READ_URI',
|
||||
'MONGODB_DATABASE',
|
||||
'QUEUE_ENABLE_SCHEDULED_JOBS',
|
||||
'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/stock_dev?authSource=admin';
|
||||
process.env.MONGODB_READ_URI =
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock';
|
||||
process.env.MONGODB_DATABASE = 'stock_dev';
|
||||
delete process.env.QUEUE_ENABLE_SCHEDULED_JOBS;
|
||||
delete process.env.HTTP_PROXY;
|
||||
delete process.env.HTTPS_PROXY;
|
||||
delete process.env.http_proxy;
|
||||
delete process.env.https_proxy;
|
||||
|
||||
resetStockConfig();
|
||||
const cfg = initializeStockConfig('dataPipeline', { mongoReadOnly: true });
|
||||
expect(cfg.database.mongodb.readOnly).toBe(true);
|
||||
expect(cfg.service.serviceName).toBe('data-pipeline');
|
||||
expect(cfg.queue?.enableScheduledJobs).toBe(false);
|
||||
|
||||
// Omitting { mongoReadOnly: true } must fail closed during initializeStockConfig
|
||||
resetStockConfig();
|
||||
expect(() => initializeStockConfig('dataPipeline')).toThrow(
|
||||
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
|
||||
);
|
||||
} finally {
|
||||
for (const key of envKeys) {
|
||||
if (savedEnv[key] === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = savedEnv[key];
|
||||
}
|
||||
}
|
||||
resetStockConfig();
|
||||
}
|
||||
});
|
||||
|
||||
test('blocks development dataPipeline from reading QA MongoDB with trading_admin even when readOnly=true or escape hatch is set', () => {
|
||||
const cfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(cfg, 'dataPipeline', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true' })
|
||||
).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/);
|
||||
});
|
||||
|
||||
test('blocks development dataPipeline from reading QA MongoDB when readOnly is false', () => {
|
||||
const cfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock',
|
||||
mongoReadOnly: false,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(
|
||||
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
|
||||
);
|
||||
});
|
||||
|
||||
test('blocks loopback :27017 URI omitting /stock for both dataIngestion and non-readOnly dataPipeline', () => {
|
||||
const ingestionCfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: 'mongodb://trading_admin:pass@localhost:27017',
|
||||
mongoDatabase: 'other_db',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {
|
||||
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
|
||||
})
|
||||
).not.toThrow();
|
||||
|
||||
const ipv6IngestionCfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: 'mongodb://trading_admin:pass@[::1]:27017',
|
||||
mongoDatabase: 'other_db',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(ipv6IngestionCfg, 'dataIngestion', {})).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
|
||||
const pipelineCfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017',
|
||||
mongoReadOnly: false,
|
||||
mongoDatabase: 'other_db',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow(
|
||||
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
|
||||
);
|
||||
});
|
||||
|
||||
test('blocks qa environment from targeting *_dev databases', () => {
|
||||
const cfg = makeConfig({
|
||||
environment: 'qa',
|
||||
|
|
|
|||
1133
test/unit/mongodb-read-only.test.ts
Normal file
1133
test/unit/mongodb-read-only.test.ts
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue