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
75e459f50b
commit
3bbf25ca25
3 changed files with 551 additions and 137 deletions
|
|
@ -24,6 +24,29 @@ import type {
|
|||
PoolMetrics,
|
||||
} from './types';
|
||||
|
||||
const READ_ONLY_CURSOR_FLUENT_MODIFIERS = [
|
||||
'filter',
|
||||
'hint',
|
||||
'min',
|
||||
'max',
|
||||
'returnKey',
|
||||
'showRecordId',
|
||||
'addQueryModifier',
|
||||
'comment',
|
||||
'maxAwaitTimeMS',
|
||||
'maxTimeMS',
|
||||
'project',
|
||||
'sort',
|
||||
'allowDiskUse',
|
||||
'collation',
|
||||
'limit',
|
||||
'skip',
|
||||
'batchSize',
|
||||
'withReadPreference',
|
||||
'withReadConcern',
|
||||
'addCursorFlag',
|
||||
] as const;
|
||||
|
||||
const READ_ONLY_COLLECTION_METHODS = new Set<string | symbol>([
|
||||
'find',
|
||||
'findOne',
|
||||
|
|
@ -187,15 +210,88 @@ export class MongoDBClient {
|
|||
return this.client.db(databaseName || this.defaultDatabase);
|
||||
}
|
||||
|
||||
private wrapReadOnlyAggregationCursor<T extends Document>(
|
||||
cursor: AggregationCursor<T>
|
||||
): AggregationCursor<T> {
|
||||
const assertCursorPipelineSafe = (): void => {
|
||||
if (Array.isArray(cursor.pipeline)) {
|
||||
this.assertReadOnlyPipeline(cursor.pipeline);
|
||||
}
|
||||
};
|
||||
private createGuardedCursorStream(
|
||||
cursor: {
|
||||
next: () => Promise<unknown>;
|
||||
close?: () => Promise<unknown>;
|
||||
},
|
||||
options?: { transform?: (doc: never) => unknown },
|
||||
beforeRead?: () => void
|
||||
): Readable {
|
||||
beforeRead?.();
|
||||
const transform = options?.transform;
|
||||
const closeCursor = (): Promise<unknown> =>
|
||||
typeof cursor.close === 'function' ? cursor.close() : Promise.resolve();
|
||||
let readInProgress = false;
|
||||
|
||||
return new Readable({
|
||||
objectMode: true,
|
||||
autoDestroy: false,
|
||||
highWaterMark: 1,
|
||||
read() {
|
||||
if (readInProgress) {
|
||||
return;
|
||||
}
|
||||
readInProgress = true;
|
||||
const readNext = (): void => {
|
||||
try {
|
||||
beforeRead?.();
|
||||
} catch (err) {
|
||||
readInProgress = false;
|
||||
this.destroy(err instanceof Error ? err : new Error(String(err)));
|
||||
return;
|
||||
}
|
||||
|
||||
cursor.next().then(
|
||||
doc => {
|
||||
if (doc == null) {
|
||||
readInProgress = false;
|
||||
this.push(null);
|
||||
return;
|
||||
}
|
||||
if (this.destroyed) {
|
||||
readInProgress = false;
|
||||
closeCursor().catch(() => {});
|
||||
return;
|
||||
}
|
||||
let output: unknown = doc;
|
||||
if (transform) {
|
||||
try {
|
||||
output = transform(doc as never);
|
||||
} catch (err) {
|
||||
readInProgress = false;
|
||||
this.destroy(err instanceof Error ? err : new Error(String(err)));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (this.push(output)) {
|
||||
readNext();
|
||||
} else {
|
||||
readInProgress = false;
|
||||
}
|
||||
},
|
||||
err => {
|
||||
readInProgress = false;
|
||||
this.destroy(err instanceof Error ? err : new Error(String(err)));
|
||||
}
|
||||
);
|
||||
};
|
||||
readNext();
|
||||
},
|
||||
destroy(error, callback) {
|
||||
closeCursor().then(
|
||||
() => callback(error),
|
||||
closeError =>
|
||||
callback(closeError instanceof Error ? closeError : new Error(String(closeError)))
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private createTrackedCursorEventMethods(
|
||||
cursor: Record<PropertyKey, unknown>,
|
||||
wrapped: Record<PropertyKey, unknown>
|
||||
): Record<string, unknown> {
|
||||
type CursorListener = (...args: unknown[]) => void;
|
||||
interface TrackedListener {
|
||||
original: CursorListener;
|
||||
|
|
@ -204,11 +300,16 @@ export class MongoDBClient {
|
|||
}
|
||||
const trackedListeners = new Map<string | symbol, TrackedListener[]>();
|
||||
|
||||
const invokeCursorEventMethod = (method: string, ...args: unknown[]): unknown => {
|
||||
const fn = cursor[method];
|
||||
return typeof fn === 'function' ? fn.apply(cursor, args) : undefined;
|
||||
};
|
||||
|
||||
const detachFromCursor = (event: string | symbol, bound: CursorListener): void => {
|
||||
if (typeof cursor.removeListener === 'function') {
|
||||
cursor.removeListener(event as never, bound as never);
|
||||
invokeCursorEventMethod('removeListener', event, bound);
|
||||
} else if (typeof cursor.off === 'function') {
|
||||
cursor.off(event as never, bound as never);
|
||||
invokeCursorEventMethod('off', event, bound);
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -252,18 +353,14 @@ export class MongoDBClient {
|
|||
|
||||
if (options.prepend) {
|
||||
if (options.once) {
|
||||
if (typeof cursor.prependOnceListener === 'function') {
|
||||
cursor.prependOnceListener(event as never, entry.bound as never);
|
||||
}
|
||||
} else if (typeof cursor.prependListener === 'function') {
|
||||
cursor.prependListener(event as never, entry.bound as never);
|
||||
invokeCursorEventMethod('prependOnceListener', event, entry.bound);
|
||||
} else {
|
||||
invokeCursorEventMethod('prependListener', event, entry.bound);
|
||||
}
|
||||
} else if (options.once) {
|
||||
if (typeof cursor.once === 'function') {
|
||||
cursor.once(event as never, entry.bound as never);
|
||||
}
|
||||
} else if (typeof cursor.on === 'function') {
|
||||
cursor.on(event as never, entry.bound as never);
|
||||
invokeCursorEventMethod('once', event, entry.bound);
|
||||
} else {
|
||||
invokeCursorEventMethod('on', event, entry.bound);
|
||||
}
|
||||
|
||||
return wrapped;
|
||||
|
|
@ -293,6 +390,178 @@ export class MongoDBClient {
|
|||
return wrapped;
|
||||
};
|
||||
|
||||
return {
|
||||
on: (event: string | symbol, listener: CursorListener) =>
|
||||
registerTrackedListener(event, listener, { once: false, prepend: false }),
|
||||
once: (event: string | symbol, listener: CursorListener) =>
|
||||
registerTrackedListener(event, listener, { once: true, prepend: false }),
|
||||
off: (event: string | symbol, listener: CursorListener) =>
|
||||
unregisterTrackedListener(event, listener),
|
||||
addListener: (event: string | symbol, listener: CursorListener) =>
|
||||
registerTrackedListener(event, listener, { once: false, prepend: false }),
|
||||
removeListener: (event: string | symbol, listener: CursorListener) =>
|
||||
unregisterTrackedListener(event, listener),
|
||||
removeAllListeners: (event?: string | symbol) => {
|
||||
if (event !== undefined) {
|
||||
const entries = trackedListeners.get(event);
|
||||
if (entries) {
|
||||
for (const entry of entries) {
|
||||
detachFromCursor(event, entry.bound);
|
||||
}
|
||||
trackedListeners.delete(event);
|
||||
}
|
||||
} else {
|
||||
for (const [ev, entries] of trackedListeners) {
|
||||
for (const entry of entries) {
|
||||
detachFromCursor(ev, entry.bound);
|
||||
}
|
||||
}
|
||||
trackedListeners.clear();
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
prependListener: (event: string | symbol, listener: CursorListener) =>
|
||||
registerTrackedListener(event, listener, { once: false, prepend: true }),
|
||||
prependOnceListener: (event: string | symbol, listener: CursorListener) =>
|
||||
registerTrackedListener(event, listener, { once: true, prepend: true }),
|
||||
setMaxListeners: (n: number) => {
|
||||
invokeCursorEventMethod('setMaxListeners', n);
|
||||
return wrapped;
|
||||
},
|
||||
getMaxListeners: () =>
|
||||
typeof cursor.getMaxListeners === 'function'
|
||||
? (invokeCursorEventMethod('getMaxListeners') as number)
|
||||
: 10,
|
||||
listeners: (event: string | symbol) =>
|
||||
(trackedListeners.get(event) ?? []).map(entry => entry.original),
|
||||
rawListeners: (event: string | symbol) =>
|
||||
(trackedListeners.get(event) ?? []).map(entry => entry.original),
|
||||
listenerCount: (event: string | symbol) => trackedListeners.get(event)?.length ?? 0,
|
||||
eventNames: () => Array.from(trackedListeners.keys()),
|
||||
};
|
||||
}
|
||||
|
||||
private wrapReadOnlyCursor<TCursor extends object>(cursor: TCursor): TCursor {
|
||||
const rawCursor = cursor as Record<PropertyKey, unknown>;
|
||||
|
||||
const delegate = (method: string) => (...args: unknown[]) => {
|
||||
const fn = rawCursor[method];
|
||||
if (typeof fn !== 'function') {
|
||||
throw new TypeError(`Cursor does not implement "${method}"`);
|
||||
}
|
||||
return fn.apply(cursor, args);
|
||||
};
|
||||
|
||||
const wrapped: Record<PropertyKey, unknown> = {
|
||||
get id() {
|
||||
return rawCursor.id;
|
||||
},
|
||||
get namespace() {
|
||||
return rawCursor.namespace;
|
||||
},
|
||||
get readPreference() {
|
||||
return rawCursor.readPreference;
|
||||
},
|
||||
get readConcern() {
|
||||
return rawCursor.readConcern;
|
||||
},
|
||||
get closed() {
|
||||
return rawCursor.closed;
|
||||
},
|
||||
get killed() {
|
||||
return rawCursor.killed;
|
||||
},
|
||||
get loadBalanced() {
|
||||
return rawCursor.loadBalanced;
|
||||
},
|
||||
toArray: delegate('toArray'),
|
||||
next: delegate('next'),
|
||||
tryNext: delegate('tryNext'),
|
||||
hasNext: delegate('hasNext'),
|
||||
forEach: delegate('forEach'),
|
||||
count: delegate('count'),
|
||||
explain: delegate('explain'),
|
||||
close: delegate('close'),
|
||||
rewind: delegate('rewind'),
|
||||
bufferedCount: delegate('bufferedCount'),
|
||||
readBufferedDocuments: delegate('readBufferedDocuments'),
|
||||
stream: (options?: { transform?: (doc: never) => unknown }) =>
|
||||
this.createGuardedCursorStream(
|
||||
rawCursor as unknown as {
|
||||
next: () => Promise<unknown>;
|
||||
close?: () => Promise<unknown>;
|
||||
},
|
||||
options
|
||||
),
|
||||
[Symbol.asyncIterator]: () => {
|
||||
const iterator = rawCursor[Symbol.asyncIterator];
|
||||
if (typeof iterator !== 'function') {
|
||||
throw new TypeError('Cursor is not async iterable');
|
||||
}
|
||||
return iterator.call(cursor);
|
||||
},
|
||||
[Symbol.asyncDispose]: () => {
|
||||
const dispose = rawCursor[Symbol.asyncDispose];
|
||||
if (typeof dispose === 'function') {
|
||||
return dispose.call(cursor);
|
||||
}
|
||||
const close = rawCursor.close;
|
||||
return typeof close === 'function' ? close.call(cursor) : Promise.resolve();
|
||||
},
|
||||
map: (transform: (doc: unknown) => unknown) => {
|
||||
const fn = rawCursor.map;
|
||||
if (typeof fn !== 'function') {
|
||||
throw new TypeError('Cursor does not implement "map"');
|
||||
}
|
||||
const mapped = fn.call(cursor, transform);
|
||||
return mapped === cursor
|
||||
? wrapped
|
||||
: mapped && typeof mapped === 'object'
|
||||
? this.wrapReadOnlyCursor(mapped as object)
|
||||
: mapped;
|
||||
},
|
||||
clone: () => {
|
||||
const fn = rawCursor.clone;
|
||||
if (typeof fn !== 'function') {
|
||||
throw new TypeError('Cursor does not implement "clone"');
|
||||
}
|
||||
const cloned = fn.call(cursor);
|
||||
return cloned && typeof cloned === 'object'
|
||||
? this.wrapReadOnlyCursor(cloned as object)
|
||||
: cloned;
|
||||
},
|
||||
};
|
||||
|
||||
for (const modifier of READ_ONLY_CURSOR_FLUENT_MODIFIERS) {
|
||||
if (typeof rawCursor[modifier] === 'function') {
|
||||
wrapped[modifier] = (...args: unknown[]) => {
|
||||
const fn = rawCursor[modifier] as (...modifierArgs: unknown[]) => unknown;
|
||||
const result = fn.apply(cursor, args);
|
||||
if (result === cursor) {
|
||||
return wrapped;
|
||||
}
|
||||
if (result && typeof result === 'object') {
|
||||
return this.wrapReadOnlyCursor(result as object);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Object.assign(wrapped, this.createTrackedCursorEventMethods(rawCursor, wrapped));
|
||||
|
||||
return wrapped as unknown as TCursor;
|
||||
}
|
||||
|
||||
private wrapReadOnlyAggregationCursor<T extends Document>(
|
||||
cursor: AggregationCursor<T>
|
||||
): AggregationCursor<T> {
|
||||
const assertCursorPipelineSafe = (): void => {
|
||||
if (Array.isArray(cursor.pipeline)) {
|
||||
this.assertReadOnlyPipeline(cursor.pipeline);
|
||||
}
|
||||
};
|
||||
|
||||
const wrapped: Record<PropertyKey, unknown> = {
|
||||
get id() {
|
||||
return cursor.id;
|
||||
|
|
@ -339,76 +608,15 @@ export class MongoDBClient {
|
|||
assertCursorPipelineSafe();
|
||||
return cursor.forEach(iterator);
|
||||
},
|
||||
stream: (options?: Parameters<AggregationCursor<T>['stream']>[0]) => {
|
||||
assertCursorPipelineSafe();
|
||||
const transform = options?.transform;
|
||||
let readInProgress = false;
|
||||
|
||||
const readable = new Readable({
|
||||
objectMode: true,
|
||||
autoDestroy: false,
|
||||
highWaterMark: 1,
|
||||
read() {
|
||||
if (readInProgress) {
|
||||
return;
|
||||
}
|
||||
readInProgress = true;
|
||||
const readNext = (): void => {
|
||||
try {
|
||||
assertCursorPipelineSafe();
|
||||
} catch (err) {
|
||||
readInProgress = false;
|
||||
this.destroy(err instanceof Error ? err : new Error(String(err)));
|
||||
return;
|
||||
}
|
||||
|
||||
cursor.next().then(
|
||||
doc => {
|
||||
if (doc == null) {
|
||||
readInProgress = false;
|
||||
this.push(null);
|
||||
return;
|
||||
}
|
||||
if (this.destroyed) {
|
||||
readInProgress = false;
|
||||
cursor.close().catch(() => {});
|
||||
return;
|
||||
}
|
||||
let output: unknown = doc;
|
||||
if (transform) {
|
||||
try {
|
||||
output = transform(doc);
|
||||
} catch (err) {
|
||||
readInProgress = false;
|
||||
this.destroy(err instanceof Error ? err : new Error(String(err)));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (this.push(output)) {
|
||||
readNext();
|
||||
} else {
|
||||
readInProgress = false;
|
||||
}
|
||||
},
|
||||
err => {
|
||||
readInProgress = false;
|
||||
this.destroy(err instanceof Error ? err : new Error(String(err)));
|
||||
}
|
||||
);
|
||||
};
|
||||
readNext();
|
||||
stream: (options?: Parameters<AggregationCursor<T>['stream']>[0]) =>
|
||||
this.createGuardedCursorStream(
|
||||
cursor as unknown as {
|
||||
next: () => Promise<unknown>;
|
||||
close?: () => Promise<unknown>;
|
||||
},
|
||||
destroy(error, callback) {
|
||||
cursor.close().then(
|
||||
() => callback(error),
|
||||
closeError =>
|
||||
callback(closeError instanceof Error ? closeError : new Error(String(closeError)))
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
return readable as ReturnType<AggregationCursor<T>['stream']>;
|
||||
},
|
||||
options as { transform?: (doc: never) => unknown } | undefined,
|
||||
assertCursorPipelineSafe
|
||||
) as ReturnType<AggregationCursor<T>['stream']>,
|
||||
explain: (...args: Parameters<AggregationCursor<T>['explain']>) => {
|
||||
assertCursorPipelineSafe();
|
||||
return cursor.explain(...args);
|
||||
|
|
@ -509,56 +717,13 @@ export class MongoDBClient {
|
|||
: this.wrapReadOnlyAggregationCursor(mapped as unknown as AggregationCursor<Document>);
|
||||
},
|
||||
clone: () => this.wrapReadOnlyAggregationCursor(cursor.clone()),
|
||||
// Safe EventEmitter delegation: bind `this` to `wrapped` and track caller listeners
|
||||
// so regular function callbacks never receive the raw driver cursor.
|
||||
on: (event: string | symbol, listener: (...args: unknown[]) => void) =>
|
||||
registerTrackedListener(event, listener, { once: false, prepend: false }),
|
||||
once: (event: string | symbol, listener: (...args: unknown[]) => void) =>
|
||||
registerTrackedListener(event, listener, { once: true, prepend: false }),
|
||||
off: (event: string | symbol, listener: (...args: unknown[]) => void) =>
|
||||
unregisterTrackedListener(event, listener),
|
||||
addListener: (event: string | symbol, listener: (...args: unknown[]) => void) =>
|
||||
registerTrackedListener(event, listener, { once: false, prepend: false }),
|
||||
removeListener: (event: string | symbol, listener: (...args: unknown[]) => void) =>
|
||||
unregisterTrackedListener(event, listener),
|
||||
removeAllListeners: (event?: string | symbol) => {
|
||||
if (event !== undefined) {
|
||||
const entries = trackedListeners.get(event);
|
||||
if (entries) {
|
||||
for (const entry of entries) {
|
||||
detachFromCursor(event, entry.bound);
|
||||
}
|
||||
trackedListeners.delete(event);
|
||||
}
|
||||
} else {
|
||||
for (const [ev, entries] of trackedListeners) {
|
||||
for (const entry of entries) {
|
||||
detachFromCursor(ev, entry.bound);
|
||||
}
|
||||
}
|
||||
trackedListeners.clear();
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
prependListener: (event: string | symbol, listener: (...args: unknown[]) => void) =>
|
||||
registerTrackedListener(event, listener, { once: false, prepend: true }),
|
||||
prependOnceListener: (event: string | symbol, listener: (...args: unknown[]) => void) =>
|
||||
registerTrackedListener(event, listener, { once: true, prepend: true }),
|
||||
setMaxListeners: (n: number) => {
|
||||
if (typeof cursor.setMaxListeners === 'function') {
|
||||
cursor.setMaxListeners(n);
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
getMaxListeners: () => (typeof cursor.getMaxListeners === 'function' ? cursor.getMaxListeners() : 10),
|
||||
listeners: (event: string | symbol) =>
|
||||
(trackedListeners.get(event) ?? []).map(entry => entry.original),
|
||||
rawListeners: (event: string | symbol) =>
|
||||
(trackedListeners.get(event) ?? []).map(entry => entry.original),
|
||||
listenerCount: (event: string | symbol) => trackedListeners.get(event)?.length ?? 0,
|
||||
eventNames: () => Array.from(trackedListeners.keys()),
|
||||
};
|
||||
|
||||
Object.assign(
|
||||
wrapped,
|
||||
this.createTrackedCursorEventMethods(cursor as unknown as Record<PropertyKey, unknown>, wrapped)
|
||||
);
|
||||
|
||||
return wrapped as unknown as AggregationCursor<T>;
|
||||
}
|
||||
|
||||
|
|
@ -580,6 +745,18 @@ export class MongoDBClient {
|
|||
);
|
||||
};
|
||||
}
|
||||
if (prop === 'find' || prop === 'listIndexes') {
|
||||
const fn: unknown = Reflect.get(target, prop, target);
|
||||
if (typeof fn === 'function') {
|
||||
return (...args: unknown[]) => {
|
||||
const cursor = (fn as (...methodArgs: unknown[]) => unknown).apply(target, args);
|
||||
return cursor && typeof cursor === 'object'
|
||||
? this.wrapReadOnlyCursor(cursor as object)
|
||||
: cursor;
|
||||
};
|
||||
}
|
||||
return fn;
|
||||
}
|
||||
if (READ_ONLY_COLLECTION_METHODS.has(prop)) {
|
||||
const fn = Reflect.get(target, prop, target);
|
||||
return typeof fn === 'function' ? fn.bind(target) : fn;
|
||||
|
|
@ -603,6 +780,18 @@ export class MongoDBClient {
|
|||
return <T extends Document = Document>(name: string) =>
|
||||
this.wrapReadOnlyCollection(target.collection<T>(name));
|
||||
}
|
||||
if (prop === 'listCollections') {
|
||||
const fn: unknown = Reflect.get(target, prop, target);
|
||||
if (typeof fn === 'function') {
|
||||
return (...args: unknown[]) => {
|
||||
const cursor = (fn as (...methodArgs: unknown[]) => unknown).apply(target, args);
|
||||
return cursor && typeof cursor === 'object'
|
||||
? this.wrapReadOnlyCursor(cursor as object)
|
||||
: cursor;
|
||||
};
|
||||
}
|
||||
return fn;
|
||||
}
|
||||
if (READ_ONLY_DB_METHODS.has(prop)) {
|
||||
const fn = Reflect.get(target, prop, target);
|
||||
return typeof fn === 'function' ? fn.bind(target) : fn;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue