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:
parent
7cf940afce
commit
abbab4b5a8
10 changed files with 644 additions and 18 deletions
|
|
@ -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 });
|
||||
|
||||
|
|
@ -121,6 +127,61 @@ describe('Environment safety & multi-env isolation', () => {
|
|||
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',
|
||||
] 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;
|
||||
|
||||
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',
|
||||
|
|
|
|||
|
|
@ -7,6 +7,61 @@ setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
|||
function createStubbedClient(readOnly: boolean) {
|
||||
const logger = getLogger('mongodb-read-only-unit-test');
|
||||
|
||||
const driverClientSymbol = Symbol('kClient');
|
||||
const createCursorStub = (initialPipeline: Record<string, unknown>[] = []) => {
|
||||
const pipeline = [...initialPipeline];
|
||||
const docs = [{ _id: 'AAPL', count: 5 }];
|
||||
let nextIndex = 0;
|
||||
|
||||
const cursorStub: Record<PropertyKey, unknown> = {
|
||||
pipeline,
|
||||
client: { db: mock(() => dbStub) },
|
||||
[driverClientSymbol]: { db: mock(() => dbStub) },
|
||||
out: mock((target: unknown) => {
|
||||
pipeline.push({ $out: target });
|
||||
return cursorStub;
|
||||
}),
|
||||
addStage: mock((stage: Record<string, unknown>) => {
|
||||
pipeline.push(stage);
|
||||
return cursorStub;
|
||||
}),
|
||||
lookup: mock((stage: Record<string, unknown>) => {
|
||||
pipeline.push({ $lookup: stage });
|
||||
return cursorStub;
|
||||
}),
|
||||
match: mock((stage: Record<string, unknown>) => {
|
||||
pipeline.push({ $match: stage });
|
||||
return cursorStub;
|
||||
}),
|
||||
project: mock((stage: Record<string, unknown>) => {
|
||||
pipeline.push({ $project: stage });
|
||||
return cursorStub;
|
||||
}),
|
||||
group: mock((stage: Record<string, unknown>) => {
|
||||
pipeline.push({ $group: stage });
|
||||
return cursorStub;
|
||||
}),
|
||||
limit: mock((n: number) => {
|
||||
pipeline.push({ $limit: n });
|
||||
return cursorStub;
|
||||
}),
|
||||
batchSize: mock(() => cursorStub),
|
||||
map: mock(() => cursorStub),
|
||||
clone: mock(() => createCursorStub(pipeline)),
|
||||
toArray: mock(async () => docs),
|
||||
next: mock(async () => (nextIndex < docs.length ? docs[nextIndex++] : null)),
|
||||
[Symbol.asyncIterator]: async function* () {
|
||||
for (const doc of docs) {
|
||||
yield doc;
|
||||
}
|
||||
},
|
||||
[Symbol.asyncDispose]: mock(async () => {}),
|
||||
};
|
||||
return cursorStub;
|
||||
};
|
||||
|
||||
let lastCursorStub: ReturnType<typeof createCursorStub> | null = null;
|
||||
|
||||
const collectionStub = {
|
||||
collectionName: 'eodPrices',
|
||||
dbName: 'stock',
|
||||
|
|
@ -18,7 +73,10 @@ function createStubbedClient(readOnly: boolean) {
|
|||
estimatedDocumentCount: mock(async () => 100),
|
||||
distinct: mock(async () => ['AAPL', 'MSFT']),
|
||||
listIndexes: mock(() => ({ toArray: async () => [{ name: '_id_' }] })),
|
||||
aggregate: mock(() => ({ toArray: async () => [{ _id: 'AAPL', count: 5 }] })),
|
||||
aggregate: mock((pipeline: Record<string, unknown>[] = []) => {
|
||||
lastCursorStub = createCursorStub(pipeline);
|
||||
return lastCursorStub;
|
||||
}),
|
||||
// Write & DDL methods
|
||||
insertOne: mock(async () => ({ insertedId: 'id-1' })),
|
||||
insertMany: mock(async () => ({ insertedCount: 1, insertedIds: { 0: 'id-1' } })),
|
||||
|
|
@ -62,7 +120,13 @@ function createStubbedClient(readOnly: boolean) {
|
|||
isConnected: true,
|
||||
});
|
||||
|
||||
return { client, dbStub, collectionStub };
|
||||
return {
|
||||
client,
|
||||
dbStub,
|
||||
collectionStub,
|
||||
driverClientSymbol,
|
||||
getLastCursorStub: () => lastCursorStub,
|
||||
};
|
||||
}
|
||||
|
||||
function assertZeroMutationCalls(
|
||||
|
|
@ -164,6 +228,55 @@ describe('MongoDBClient read-only mode (offline)', () => {
|
|||
expect(collectionStub.aggregate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('wraps aggregation cursor in a read-only interface blocking fluent write stages and driver client access', async () => {
|
||||
const { client, driverClientSymbol, getLastCursorStub } = createStubbedClient(true);
|
||||
|
||||
const initialPipeline: Record<string, unknown>[] = [{ $match: { symbol: 'AAPL' } }];
|
||||
const cursor = client.getDatabase().collection('eodPrices').aggregate(initialPipeline);
|
||||
const rawCursor = getLastCursorStub()!;
|
||||
|
||||
// Underlying driver client and internal symbols are not exposed
|
||||
expect((cursor as unknown as Record<string, unknown>).client).toBeUndefined();
|
||||
expect(Object.getOwnPropertySymbols(cursor)).not.toContain(driverClientSymbol);
|
||||
|
||||
// Mutating caller's input pipeline array or frozen cursor.pipeline cannot inject write stages
|
||||
initialPipeline.push({ $out: 'hijacked' });
|
||||
expect(rawCursor.pipeline).toEqual([{ $match: { symbol: 'AAPL' } }]);
|
||||
expect(() => (cursor.pipeline as unknown as Record<string, unknown>[]).push({ $out: 'hijacked' })).toThrow();
|
||||
|
||||
// Direct fluent write stages fail closed without touching the underlying cursor
|
||||
expect(() => cursor.out('hijacked')).toThrow(/read-only mode/);
|
||||
expect(() => cursor.addStage({ $out: 'hijacked' })).toThrow(/read-only mode/);
|
||||
expect(() => cursor.addStage({ $merge: { into: 'hijacked' } })).toThrow(/read-only mode/);
|
||||
expect(() =>
|
||||
cursor.addStage({ $unionWith: { coll: 'other', pipeline: [{ $out: 'hijacked' }] } })
|
||||
).toThrow(/read-only mode/);
|
||||
expect(() =>
|
||||
cursor.lookup({ from: 'other', pipeline: [{ $merge: { into: 'hijacked' } }], as: 'x' })
|
||||
).toThrow(/read-only mode/);
|
||||
|
||||
// Chained read-only stages, clone(), and map() preserve read-only enforcement
|
||||
const chained = cursor
|
||||
.match({ close: { $gt: 100 } })
|
||||
.addStage({ $limit: 10 })
|
||||
.project({ symbol: 1 })
|
||||
.batchSize(100);
|
||||
expect(() => chained.out('hijacked')).toThrow(/read-only mode/);
|
||||
expect(() => chained.addStage({ $merge: { into: 'hijacked' } })).toThrow(/read-only mode/);
|
||||
expect(() => chained.clone().out('hijacked')).toThrow(/read-only mode/);
|
||||
expect(() => chained.map(doc => doc).addStage({ $out: 'hijacked' })).toThrow(/read-only mode/);
|
||||
expect(rawCursor.out).not.toHaveBeenCalled();
|
||||
|
||||
// Safe read iteration (toArray, next, for-await) still works
|
||||
expect(await chained.toArray()).toEqual([{ _id: 'AAPL', count: 5 }]);
|
||||
expect(await chained.next()).toEqual({ _id: 'AAPL', count: 5 });
|
||||
const iterated: unknown[] = [];
|
||||
for await (const doc of chained) {
|
||||
iterated.push(doc);
|
||||
}
|
||||
expect(iterated).toEqual([{ _id: 'AAPL', count: 5 }]);
|
||||
});
|
||||
|
||||
test('passes through safe read operations on client and proxies', async () => {
|
||||
const { client, dbStub, collectionStub } = createStubbedClient(true);
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue