stock-bot/test/unit/mongodb-read-only.test.ts

470 lines
20 KiB
TypeScript

import { describe, expect, mock, test } from 'bun:test';
import { MongoClient } from 'mongodb';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { MongoDBClient } from '@stock-bot/mongodb';
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',
namespace: 'stock.eodPrices',
// Safe read methods
find: mock(() => ({ toArray: async () => [{ symbol: 'AAPL', close: 200 }] })),
findOne: mock(async () => ({ symbol: 'AAPL', close: 200 })),
countDocuments: mock(async () => 42),
estimatedDocumentCount: mock(async () => 100),
distinct: mock(async () => ['AAPL', 'MSFT']),
listIndexes: mock(() => ({ toArray: async () => [{ name: '_id_' }] })),
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' } })),
updateOne: mock(async () => ({ matchedCount: 1, modifiedCount: 1, upsertedCount: 0, upsertedId: null })),
updateMany: mock(async () => ({ matchedCount: 1, modifiedCount: 1, upsertedCount: 0, upsertedId: null })),
deleteOne: mock(async () => ({ deletedCount: 1 })),
deleteMany: mock(async () => ({ deletedCount: 1 })),
bulkWrite: mock(async () => ({ upsertedCount: 1, modifiedCount: 0 })),
createIndex: mock(async () => 'symbol_1'),
dropIndex: mock(async () => ({})),
drop: mock(async () => true),
rename: mock(async () => ({})),
};
const dbStub = {
databaseName: 'stock',
namespace: 'stock',
collection: mock(() => collectionStub),
listCollections: mock(() => ({ toArray: async () => [{ name: 'eodPrices' }] })),
stats: mock(async () => ({ ok: 1 })),
createCollection: mock(async () => collectionStub),
dropCollection: mock(async () => true),
dropDatabase: mock(async () => true),
command: mock(async () => ({ ok: 1 })),
};
const client = new MongoDBClient(
{
host: 'localhost',
port: 27017,
database: 'stock',
readOnly,
},
logger
);
// Inject stubbed driver objects directly so zero network sockets are opened
Object.assign(client, {
client: { db: mock(() => dbStub) },
db: dbStub,
isConnected: true,
});
return {
client,
dbStub,
collectionStub,
driverClientSymbol,
getLastCursorStub: () => lastCursorStub,
};
}
function assertZeroMutationCalls(
dbStub: ReturnType<typeof createStubbedClient>['dbStub'],
collectionStub: ReturnType<typeof createStubbedClient>['collectionStub']
) {
expect(collectionStub.insertOne).not.toHaveBeenCalled();
expect(collectionStub.insertMany).not.toHaveBeenCalled();
expect(collectionStub.updateOne).not.toHaveBeenCalled();
expect(collectionStub.updateMany).not.toHaveBeenCalled();
expect(collectionStub.deleteOne).not.toHaveBeenCalled();
expect(collectionStub.deleteMany).not.toHaveBeenCalled();
expect(collectionStub.bulkWrite).not.toHaveBeenCalled();
expect(collectionStub.createIndex).not.toHaveBeenCalled();
expect(collectionStub.dropIndex).not.toHaveBeenCalled();
expect(collectionStub.drop).not.toHaveBeenCalled();
expect(collectionStub.rename).not.toHaveBeenCalled();
expect(dbStub.createCollection).not.toHaveBeenCalled();
expect(dbStub.dropCollection).not.toHaveBeenCalled();
expect(dbStub.dropDatabase).not.toHaveBeenCalled();
expect(dbStub.command).not.toHaveBeenCalled();
}
describe('MongoDBClient read-only mode (offline)', () => {
test('blocks all direct client write and DDL methods without calling driver stubs', async () => {
const { client, dbStub, collectionStub } = createStubbedClient(true);
expect(client.isReadOnly()).toBe(true);
await expect(client.insertOne('x', { symbol: 'AAPL' } as never)).rejects.toThrow(/read-only mode/);
await expect(client.insertMany('x', [{ symbol: 'AAPL' }])).rejects.toThrow(/read-only mode/);
await expect(client.updateOne('x', { symbol: 'AAPL' }, { $set: { close: 1 } })).rejects.toThrow(
/read-only mode/
);
await expect(client.updateMany('x', {}, { $set: { close: 1 } })).rejects.toThrow(/read-only mode/);
await expect(client.deleteOne('x', { symbol: 'AAPL' })).rejects.toThrow(/read-only mode/);
await expect(client.deleteMany('x', {})).rejects.toThrow(/read-only mode/);
await expect(client.batchUpsert('x', [{ symbol: 'AAPL' } as never], 'symbol')).rejects.toThrow(
/read-only mode/
);
await expect(client.createIndex('x', { symbol: 1 })).rejects.toThrow(/read-only mode/);
await expect(client.dropIndex('x', 'symbol_1')).rejects.toThrow(/read-only mode/);
await expect(client.createCollection('x')).rejects.toThrow(/read-only mode/);
await expect(client.dropCollection('x')).rejects.toThrow(/read-only mode/);
assertZeroMutationCalls(dbStub, collectionStub);
});
test('blocks mutations through getDatabase, getDb, database, getCollection, and collection proxies', () => {
const { client, dbStub, collectionStub } = createStubbedClient(true);
// Collection write paths through every accessor
expect(() => client.getDatabase().collection('x').insertOne({ a: 1 })).toThrow(/read-only mode/);
expect(() => client.getDb().collection('x').updateOne({ a: 1 }, { $set: { b: 2 } })).toThrow(
/read-only mode/
);
expect(() => client.database!.collection('x').deleteMany({})).toThrow(/read-only mode/);
expect(() => client.getCollection('x').insertOne({ a: 1 })).toThrow(/read-only mode/);
expect(() => client.collection('x').bulkWrite([])).toThrow(/read-only mode/);
// Collection DDL paths
expect(() => client.getCollection('x').createIndex({ symbol: 1 })).toThrow(/read-only mode/);
expect(() => client.collection('x').dropIndex('symbol_1')).toThrow(/read-only mode/);
expect(() => client.getDatabase().collection('x').drop()).toThrow(/read-only mode/);
expect(() => client.getDb().collection('x').rename('y')).toThrow(/read-only mode/);
// Database DDL/admin paths
expect(() => client.getDatabase().createCollection('x')).toThrow(/read-only mode/);
expect(() => client.getDb().dropCollection('x')).toThrow(/read-only mode/);
expect(() => client.database!.dropDatabase()).toThrow(/read-only mode/);
expect(() => client.getDatabase().command({ dropDatabase: 1 })).toThrow(/read-only mode/);
assertZeroMutationCalls(dbStub, collectionStub);
});
test('blocks $out and $merge aggregation stages (including nested) on client and proxied collections', async () => {
const { client, collectionStub } = createStubbedClient(true);
const outPipeline = [{ $match: { symbol: 'AAPL' } }, { $out: 'hijacked' }];
const mergePipeline = [{ $merge: { into: 'hijacked' } }];
const nestedUnionWith = [
{ $unionWith: { coll: 'other', pipeline: [{ $out: 'hijacked' }] } },
];
const nestedFacet = [
{ $facet: { branch: [{ $merge: { into: 'hijacked' } }] } },
];
await expect(client.aggregate('x', outPipeline)).rejects.toThrow(/read-only mode/);
await expect(client.aggregate('x', mergePipeline)).rejects.toThrow(/read-only mode/);
await expect(client.aggregate('x', nestedUnionWith)).rejects.toThrow(/read-only mode/);
await expect(client.aggregate('x', nestedFacet)).rejects.toThrow(/read-only mode/);
expect(() => client.getCollection('x').aggregate(outPipeline)).toThrow(/read-only mode/);
expect(() => client.collection('x').aggregate(mergePipeline)).toThrow(/read-only mode/);
expect(() => client.getDatabase().collection('x').aggregate(nestedUnionWith)).toThrow(
/read-only mode/
);
expect(() => client.database!.collection('x').aggregate(nestedFacet)).toThrow(/read-only mode/);
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('builds aggregation stream from guarded iteration without exposing pinned driver cursor and preserves safe event listeners', async () => {
const logger = getLogger('mongodb-read-only-stream-test');
// Unconnected real driver client — zero sockets opened
const realMongoClient = new MongoClient('mongodb://127.0.0.1:1/stock');
const realDb = realMongoClient.db('stock');
const realCollection = realDb.collection('eodPrices');
const realCursor = realCollection.aggregate([{ $match: { symbol: 'AAPL' } }]);
// Confirm the pinned driver's raw stream exposes the unwrapped cursor via `_cursor`
const rawStream = realCursor.stream() as unknown as Record<string, unknown>;
expect(rawStream._cursor).toBe(realCursor);
// Stub next() and close() on the real AggregationCursor so no network I/O occurs
const docs = [
{ _id: 'AAPL', close: 200 },
{ _id: 'MSFT', close: 400 },
];
let index = 0;
const closeMock = mock(async () => {});
realCursor.next = mock(async () => (index < docs.length ? docs[index++] : null)) as never;
realCursor.close = closeMock as never;
const fakeDb = {
databaseName: 'stock',
collection: mock(() => ({
collectionName: 'eodPrices',
aggregate: mock(() => realCursor),
})),
};
const client = new MongoDBClient(
{ host: '127.0.0.1', port: 1, database: 'stock', readOnly: true },
logger
);
Object.assign(client, {
client: { db: mock(() => fakeDb) },
db: fakeDb,
isConnected: true,
});
const wrappedCursor = client
.getDatabase()
.collection('eodPrices')
.aggregate([{ $match: { symbol: 'AAPL' } }]);
// Safe EventEmitter methods bind `this` to `wrappedCursor` (never raw `realCursor`),
// track caller references for `listeners()` / `off()` / `removeListener()`, and
// keep the raw driver cursor inaccessible inside regular function listeners.
let closeEvents = 0;
let onceEvents = 0;
const onReceivers: unknown[] = [];
const onceReceivers: unknown[] = [];
function onCloseListener(this: unknown) {
closeEvents++;
onReceivers.push(this);
expect(this).toBe(wrappedCursor);
expect(this).not.toBe(realCursor);
expect((this as Record<string, unknown>).client).toBeUndefined();
expect(() => (this as { out: (target: string) => unknown }).out('hijacked')).toThrow(
/read-only mode/
);
}
function onceCloseListener(this: unknown) {
onceEvents++;
onceReceivers.push(this);
expect(this).toBe(wrappedCursor);
expect(this).not.toBe(realCursor);
expect((this as Record<string, unknown>).client).toBeUndefined();
expect(() => (this as { out: (target: string) => unknown }).out('hijacked')).toThrow(
/read-only mode/
);
}
const onReturn = wrappedCursor.on('close', onCloseListener);
const onceReturn = wrappedCursor.once('close', onceCloseListener);
expect(onReturn).toBe(wrappedCursor);
expect(onceReturn).toBe(wrappedCursor);
expect(wrappedCursor.listeners('close')).toEqual([onCloseListener, onceCloseListener]);
expect(wrappedCursor.listenerCount('close')).toBe(2);
expect(wrappedCursor.eventNames()).toEqual(['close']);
realCursor.emit('close');
expect(closeEvents).toBe(1);
expect(onceEvents).toBe(1);
expect(onReceivers).toEqual([wrappedCursor]);
expect(onceReceivers).toEqual([wrappedCursor]);
expect(wrappedCursor.listeners('close')).toEqual([onCloseListener]);
realCursor.emit('close');
expect(closeEvents).toBe(2);
expect(onceEvents).toBe(1);
// `off` / `removeListener` unregisters using the caller function reference
expect(wrappedCursor.off('close', onCloseListener)).toBe(wrappedCursor);
expect(wrappedCursor.listeners('close')).toEqual([]);
expect(wrappedCursor.listenerCount('close')).toBe(0);
realCursor.emit('close');
expect(closeEvents).toBe(2);
// Also verify `removeListener` unregisters a listener registered via `on`
wrappedCursor.on('close', onCloseListener);
expect(wrappedCursor.removeListener('close', onCloseListener)).toBe(wrappedCursor);
expect(wrappedCursor.listeners('close')).toEqual([]);
realCursor.emit('close');
expect(closeEvents).toBe(2);
// Wrapped stream must not expose the raw AggregationCursor or MongoClient
const guardedStream = wrappedCursor.stream({
transform: doc => ({ symbol: doc._id, doubled: Number(doc.close) * 2 }),
});
const streamRecord = guardedStream as unknown as Record<PropertyKey, unknown>;
expect(streamRecord._cursor).toBeUndefined();
for (const key of Reflect.ownKeys(guardedStream)) {
expect(streamRecord[key]).not.toBe(realCursor);
expect(streamRecord[key]).not.toBe(realMongoClient);
}
const streamed: unknown[] = [];
for await (const chunk of guardedStream) {
streamed.push(chunk);
}
expect(streamed).toEqual([
{ symbol: 'AAPL', doubled: 400 },
{ symbol: 'MSFT', doubled: 800 },
]);
// Destroying a guarded stream closes the underlying cursor
index = 0;
const destroyStream = wrappedCursor.stream();
destroyStream.destroy();
await new Promise(resolve => setImmediate(resolve));
expect(closeMock).toHaveBeenCalledTimes(1);
});
test('passes through safe read operations on client and proxies', async () => {
const { client, dbStub, collectionStub } = createStubbedClient(true);
expect(await client.find('eodPrices', { symbol: 'AAPL' })).toEqual([
{ symbol: 'AAPL', close: 200 },
]);
expect(await client.findOne('eodPrices', { symbol: 'AAPL' })).toEqual({
symbol: 'AAPL',
close: 200,
});
expect(await client.countDocuments('eodPrices', {})).toBe(42);
expect(await client.listIndexes('eodPrices')).toEqual([{ name: '_id_' }]);
expect(await client.listCollections()).toEqual([{ name: 'eodPrices' }]);
expect(await client.aggregate('eodPrices', [{ $match: { symbol: 'AAPL' } }])).toEqual([
{ _id: 'AAPL', count: 5 },
]);
// Proxied read methods
expect(await client.getCollection('eodPrices').estimatedDocumentCount()).toBe(100);
expect(await client.collection('eodPrices').distinct('symbol')).toEqual(['AAPL', 'MSFT']);
expect(
await client.getDatabase().collection('eodPrices').find({ symbol: 'AAPL' }).toArray()
).toEqual([{ symbol: 'AAPL', close: 200 }]);
expect(
await client
.getDb()
.collection('eodPrices')
.aggregate([{ $group: { _id: '$symbol' } }])
.toArray()
).toEqual([{ _id: 'AAPL', count: 5 }]);
expect(collectionStub.find).toHaveBeenCalledTimes(2);
expect(collectionStub.findOne).toHaveBeenCalledTimes(1);
expect(collectionStub.countDocuments).toHaveBeenCalledTimes(1);
expect(collectionStub.estimatedDocumentCount).toHaveBeenCalledTimes(1);
expect(collectionStub.distinct).toHaveBeenCalledTimes(1);
expect(collectionStub.listIndexes).toHaveBeenCalledTimes(1);
expect(collectionStub.aggregate).toHaveBeenCalledTimes(2);
expect(dbStub.listCollections).toHaveBeenCalledTimes(1);
});
test('allows writes when readOnly is false (control check)', async () => {
const { client, dbStub, collectionStub } = createStubbedClient(false);
expect(client.isReadOnly()).toBe(false);
const inserted = await client.insertOne('eodPrices', { symbol: 'AAPL' } as never);
expect((inserted as Record<string, unknown>)._id).toBe('id-1');
await client.getDatabase().collection('eodPrices').insertOne({ symbol: 'MSFT' });
await client.getDatabase().createCollection('tmp');
expect(collectionStub.insertOne).toHaveBeenCalledTimes(2);
expect(dbStub.createCollection).toHaveBeenCalledTimes(1);
});
});