Skip to content
Open
78 changes: 77 additions & 1 deletion bridge/src/mcp/dynamic-value-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ import {isV1ProtocolVersion} from '../protocol/bridge-protocol-strategy.js';
/** Maximum recursion depth when resolving nested dynamic values to prevent infinite loops. */
export const MAX_RESOLUTION_DEPTH = 100;

const MAX_NODE_VISITS = 10_000;

interface VisitBudget {
remaining: number;
}

/** Minimal context interface for evaluating dynamic values. */
export interface DynamicValueContext {
resolveDynamicValue<T = unknown>(value: unknown): T;
Expand All @@ -32,6 +38,61 @@ export function isPrototypePollutionKey(key: string): boolean {
return key === '__proto__' || key === 'constructor' || key === 'prototype';
}

/**
* Checks whether a value or any of its nested structures contains prototype
* pollution keys ('__proto__', 'constructor', 'prototype'), non-plain object prototypes,
* or nesting exceeding `maxDepth`.
*
* @param val The value to inspect.
* @param maxDepth Maximum recursion depth to guard against circular or deeply nested structures.
* @returns `true` if prototype pollution or excessive depth is detected, `false` otherwise.
*/
export function hasPrototypePollution(val: unknown, maxDepth = 64): boolean {
return hasPrototypePollutionInternal(val, maxDepth, new WeakSet<object>(), {
remaining: MAX_NODE_VISITS,
});
}

function hasPrototypePollutionInternal(
val: unknown,
maxDepth: number,
visited: WeakSet<object>,
budget: VisitBudget,
): boolean {
if (!val || typeof val !== 'object') {
return false;
}
if (maxDepth <= 0 || budget.remaining <= 0 || visited.has(val)) {
return true;
}
budget.remaining--;
const expectedProto = Array.isArray(val) ? Array.prototype : Object.prototype;
const proto = Object.getPrototypeOf(val);
if (proto !== expectedProto && proto !== null) {
return true;
}
visited.add(val);
try {
const record = val as Record<string, unknown>;
for (const prop of Object.getOwnPropertyNames(val)) {
if (isPrototypePollutionKey(prop)) {
return true;
}
const child = record[prop];
if (
child &&
typeof child === 'object' &&
hasPrototypePollutionInternal(child, maxDepth - 1, visited, budget)
) {
return true;
}
}
return false;
} finally {
visited.delete(val);
}
}

/** Checks whether a value is a non-null, non-array object. */
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
Expand All @@ -43,6 +104,13 @@ function isRecord(value: unknown): value is Record<string, unknown> {
export type DynamicExpressionResult =
{resolved: true; value: unknown; unchanged?: boolean} | {resolved: false};

/**
* Expression evaluator that skips dynamic resolution, used on unchanged
* passthrough results to sanitize prototype-pollution keys and enforce
* `MAX_RESOLUTION_DEPTH` without re-evaluating expressions.
*/
const NO_OP_RESOLVE_EXPRESSION = (): DynamicExpressionResult => ({resolved: false});

/**
* Recursively resolves dynamic values within arrays, objects, and nested nodes
* using the provided resolution callback while guarding against prototype pollution and stack overflows.
Expand All @@ -58,6 +126,12 @@ export function resolveDynamicTree<T = unknown>(
depth = 0,
): T {
if (depth >= MAX_RESOLUTION_DEPTH) {
if (Array.isArray(value)) {
return [] as unknown as T;
}
if (typeof value === 'object' && value !== null) {
return {} as unknown as T;
}
return value as T;
}
if (!isRecord(value) && !Array.isArray(value)) {
Expand All @@ -74,7 +148,9 @@ export function resolveDynamicTree<T = unknown>(
const exprResult = resolveExpression(value);
if (exprResult.resolved) {
if (exprResult.unchanged || exprResult.value === value) {
return exprResult.value as unknown as T;
// Skip expression re-evaluation while still stripping prototype-pollution keys
// and enforcing MAX_RESOLUTION_DEPTH across nested args/extra properties.
return resolveDynamicTree<T>(exprResult.value, NO_OP_RESOLVE_EXPRESSION, depth);
}
return resolveDynamicTree(exprResult.value, resolveExpression, depth + 1);
}
Expand Down
81 changes: 80 additions & 1 deletion bridge/src/mcp/v0-9-dynamic-value-strategy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ import {
isFunctionCall,
resolveDynamicValueDeep,
} from './v0-9-dynamic-value-strategy.js';
import type {DynamicValueContext} from './dynamic-value-strategy.js';
import {
hasPrototypePollution,
MAX_RESOLUTION_DEPTH,
type DynamicValueContext,
} from './dynamic-value-strategy.js';

describe('V09DynamicValueStrategy', () => {
const strategy = new V09DynamicValueStrategy();
Expand Down Expand Up @@ -149,6 +153,44 @@ describe('V09DynamicValueStrategy', () => {
expect(resolved).toBeDefined();
});

it('fails closed on structures at or exceeding maximum recursion depth with prototype pollution keys', () => {
const pollutedLeaf = JSON.parse(
'{"__proto__":{"polluted":true},"constructor":{"x":1},"prototype":{"y":1},"safe":1}',
);
let deepObj: unknown = pollutedLeaf;
for (let i = 0; i < MAX_RESOLUTION_DEPTH + 5; i++) {
deepObj = {child: deepObj};
}
const resolvedObj = strategy.resolveDynamicValueDeep(deepObj, mockContext);
expect(hasPrototypePollution(resolvedObj, 200)).toBe(false);

let cursor = resolvedObj as Record<string, unknown>;
for (let i = 0; i < MAX_RESOLUTION_DEPTH; i++) {
cursor = cursor['child'] as Record<string, unknown>;
}
expect(cursor).toEqual({});

let deepArr: unknown = [pollutedLeaf];
for (let i = 0; i < MAX_RESOLUTION_DEPTH; i++) {
deepArr = {child: deepArr};
}
const resolvedArr = strategy.resolveDynamicValueDeep(deepArr, mockContext);
expect(hasPrototypePollution(resolvedArr, 200)).toBe(false);

let arrCursor = resolvedArr as Record<string, unknown>;
for (let i = 0; i < MAX_RESOLUTION_DEPTH; i++) {
arrCursor = arrCursor['child'] as Record<string, unknown>;
}
expect(arrCursor).toEqual([]);

expect(
strategy.resolveDynamicValueDeep(pollutedLeaf, mockContext, MAX_RESOLUTION_DEPTH),
).toEqual({});
expect(
strategy.resolveDynamicValueDeep([pollutedLeaf], mockContext, MAX_RESOLUTION_DEPTH),
).toEqual([]);
});

it('passes through Promises without blocking', () => {
const promise = Promise.resolve('async');
expect(strategy.resolveDynamicValueDeep(promise, mockContext)).toBe(promise);
Expand All @@ -163,5 +205,42 @@ describe('V09DynamicValueStrategy', () => {
expect(result).toEqual({call: 'passthroughFn', args: {}, returnType: 'any'});
expect(resolveSpy).toHaveBeenCalledTimes(1);
});

it('strips prototype pollution keys from unchanged passthrough calls and extra v0.9 properties while calling resolveDynamicValue once', () => {
const resolveSpy = vi.fn((v: unknown) => v);
const inputWithDefaults = JSON.parse(
'{"call":"passthroughFn","args":{"__proto__":{"polluted":true},"constructor":{"x":1},"nested":[{"prototype":"bad","ok":2}],"ok":1}}',
);
const resultWithDefaults = strategy.resolveDynamicValueDeep(inputWithDefaults, {
resolveDynamicValue: resolveSpy,
});
expect(resolveSpy).toHaveBeenCalledTimes(1);
expect(hasPrototypePollution(resultWithDefaults)).toBe(false);
expect(resultWithDefaults).toEqual({
call: 'passthroughFn',
args: {nested: [{ok: 2}], ok: 1},
returnType: 'any',
});

const inputWithExtraOwnKeys = JSON.parse(
'{"call":"passthroughFn","args":{"__proto__":{"polluted":true},"ok":1},"returnType":"string","__proto__":{"topPolluted":true},"constructor":{"z":3},"extra":{"prototype":{"y":2},"kept":true}}',
);
const resultWithExtra = strategy.resolveDynamicValueDeep(inputWithExtraOwnKeys, {
resolveDynamicValue: resolveSpy,
});
expect(resolveSpy).toHaveBeenCalledTimes(2);
expect(hasPrototypePollution(resultWithExtra)).toBe(false);
expect(resultWithExtra).toEqual({
call: 'passthroughFn',
args: {ok: 1},
returnType: 'string',
extra: {kept: true},
});
const resultRecord = resultWithExtra as Record<string, unknown>;
const argsRecord = resultRecord['args'] as Record<string, unknown>;
expect(Object.prototype.hasOwnProperty.call(resultRecord, '__proto__')).toBe(false);
expect(Object.prototype.hasOwnProperty.call(resultRecord, 'constructor')).toBe(false);
expect(Object.prototype.hasOwnProperty.call(argsRecord, '__proto__')).toBe(false);
});
});
});
Loading
Loading