220 lines
10 KiB
TypeScript
220 lines
10 KiB
TypeScript
import { describe, expect, mock, test } from 'bun:test';
|
|
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 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(() => ({ toArray: async () => [{ _id: 'AAPL', count: 5 }] })),
|
|
// 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 };
|
|
}
|
|
|
|
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('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);
|
|
});
|
|
});
|