@devries-cameron20 / composio-1 / commits / 64aceaed0
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(core): defensive polish in dereferenceJsonSchema

Three follow-ups from the security/pattern reviewers — all small. - **Prototype-pollution defense**: filter `__proto__`/`constructor`/`prototype` keys in `cloneChildren`. The global prototype is already safe (`{}` literals protect us), but a malicious `$defs` entry with `__proto__: {…}` would yield an output node whose prototype is the attacker's object — breaking downstream `Object.keys` / `in` checks (e.g. in AJV). - **External `$ref` audit signal**: log `logger.warn(\`Leaving external $ref untouched: \${ref}\`)` whenever a non-internal ref (`http://`, `https://`, `file://`, …) passes through. Behavior unchanged — security-sensitive deployments now have a log line they can grep for. - **`possibleFixes` on `JsonSchemaRefResolutionError`**: every error now carries the same two fix hints, matching the convention in `ts/packages/core/src/errors/ToolErrors.ts`. Two new red-then-green tests cover the proto filter and the warn behavior. All 855 core tests + 43 mastra tests pass. Note on the fourth review item (extract `containsRef` test helper across packages): kept the duplication — sharing test utilities across workspace packages requires either a `./test-utils` exports entry on `@composio/core` or relative cross-package imports, both of which add more friction than the 6 LOC of duplication save. Leaving as-is.

jkomyno committed Apr 30, 2026 at 01:54 UTC 64aceaed012eca08624305f7c8a0087ad3fef6aa
2 files changed +56 -10
ts/packages/core/src/utils/jsonSchema.ts
+22 -3
@@ -1,11 +1,17 @@
1 import { z } from 'zod/v3';
2 import { JsonSchemaRefResolutionError, JsonSchemaToZodError } from '../errors';
3 import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
4 +import logger from './logger';
5 import { isPlainObject } from './modifiers/FileToolModifier.utils.neutral';
6
7 const MAX_REF_CHAIN_DEPTH = 100;
8 const MAX_NODE_DEPTH = 512;
9 const CYCLE_BREAK_SENTINEL = { type: 'object', additionalProperties: true } as const;
10 +const POLLUTING_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
11 +const REF_RESOLUTION_FIXES = [
12 + 'Ensure the $ref pointer matches a path in $defs or definitions',
13 + 'External $ref pointers (http://, https://, file://, …) are not resolved by the SDK',
14 +];
15
16 const decodePointerSegment = (segment: string): string =>
17 segment.replace(/~1/g, '/').replace(/~0/g, '~');
@@ -13,6 +19,7 @@ const decodePointerSegment = (segment: string): string =>
19 const failResolution = (pointer: string, segment: string): never => {
20 throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
21 meta: { ref: pointer, failedAt: segment },
22 + possibleFixes: REF_RESOLUTION_FIXES,
23 });
24 };
25
@@ -33,6 +40,7 @@ const resolvePointer = (root: Record<string, unknown>, pointer: string): unknown
40 if (!pointer.startsWith('#/')) {
41 throw new JsonSchemaRefResolutionError(`Unsupported $ref pointer: ${pointer}`, {
42 meta: { ref: pointer },
43 + possibleFixes: REF_RESOLUTION_FIXES,
44 });
45 }
46 return pointer
@@ -93,6 +101,9 @@ export function dereferenceJsonSchema<T = unknown>(schema: T): T {
101 const root = schema as Record<string, unknown>;
102 const visiting = new WeakSet<object>();
103
104 + // Filter `__proto__`/`constructor`/`prototype` keys to avoid altering the
105 + // prototype of the cloned output node (which can break downstream
106 + // `Object.keys` / `in` checks even though the global prototype is safe).
107 const cloneChildren = (
108 obj: Record<string, unknown>,
109 visitedRefs: ReadonlySet<string>,
@@ -100,7 +111,9 @@ export function dereferenceJsonSchema<T = unknown>(schema: T): T {
111 nodeDepth: number
112 ): Record<string, unknown> =>
113 Object.fromEntries(
103 - Object.entries(obj).map(([k, v]) => [k, walk(v, visitedRefs, chainDepth, nodeDepth + 1)])
114 + Object.entries(obj)
115 + .filter(([k]) => !POLLUTING_KEYS.has(k))
116 + .map(([k, v]) => [k, walk(v, visitedRefs, chainDepth, nodeDepth + 1)])
117 );
118
119 // Function declaration so `cloneChildren` can reference `walk` despite being
@@ -113,7 +126,8 @@ export function dereferenceJsonSchema<T = unknown>(schema: T): T {
126 ): unknown {
127 if (nodeDepth >= MAX_NODE_DEPTH) {
128 throw new JsonSchemaRefResolutionError(
116 - `JSON Schema node depth exceeded cap (${MAX_NODE_DEPTH})`
129 + `JSON Schema node depth exceeded cap (${MAX_NODE_DEPTH})`,
130 + { possibleFixes: REF_RESOLUTION_FIXES }
131 );
132 }
133 if (Array.isArray(node)) {
@@ -132,13 +146,18 @@ export function dereferenceJsonSchema<T = unknown>(schema: T): T {
146 const ref = typeof node.$ref === 'string' ? node.$ref : null;
147 // External refs and non-$ref nodes both pass through the same clone path.
148 if (ref === null || !ref.startsWith('#')) {
149 + if (ref !== null) {
150 + // Audit signal for security-sensitive deployments: a downstream
151 + // resolver may fetch this and trigger SSRF or local-file disclosure.
152 + logger.warn(`Leaving external $ref untouched: ${ref}`);
153 + }
154 return cloneChildren(node, visitedRefs, chainDepth, nodeDepth);
155 }
156
157 if (chainDepth >= MAX_REF_CHAIN_DEPTH) {
158 throw new JsonSchemaRefResolutionError(
159 `JSON Schema $ref chain exceeded depth cap (${MAX_REF_CHAIN_DEPTH}): ${ref}`,
141 - { meta: { ref } }
160 + { meta: { ref }, possibleFixes: REF_RESOLUTION_FIXES }
161 );
162 }
163 if (visitedRefs.has(ref)) return { ...CYCLE_BREAK_SENTINEL };
ts/packages/core/test/utils/jsonSchema.test.ts
+34 -7
@@ -1,6 +1,7 @@
1 -import { describe, it, expect } from 'vitest';
1 +import { describe, it, expect, vi } from 'vitest';
2 import { dereferenceJsonSchema } from '../../src/utils/jsonSchema';
3 import { JsonSchemaRefResolutionError } from '../../src/errors/ValidationErrors';
4 +import logger from '../../src/utils/logger';
5
6 const containsRef = (value: unknown): boolean => {
7 if (value === null || typeof value !== 'object') return false;
@@ -198,15 +199,41 @@ describe('dereferenceJsonSchema', () => {
199 expect(out.properties.self).toEqual({ type: 'object', additionalProperties: true });
200 });
201
201 - it('leaves external $ref pointers untouched', () => {
202 + it('leaves external $ref pointers untouched and warns once for audit', () => {
203 + const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => {});
204 + try {
205 + const out = dereferenceJsonSchema({
206 + type: 'object',
207 + properties: { v: { $ref: 'https://example.com/Foo' } },
208 + });
209 +
210 + expect((out as { properties: { v: { $ref: string } } }).properties.v.$ref).toBe(
211 + 'https://example.com/Foo'
212 + );
213 + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('https://example.com/Foo'));
214 + } finally {
215 + warnSpy.mockRestore();
216 + }
217 + });
218 +
219 + it('filters prototype-pollution keys when cloning', () => {
220 const out = dereferenceJsonSchema({
221 type: 'object',
204 - properties: { v: { $ref: 'https://example.com/Foo' } },
205 - });
222 + properties: {
223 + v: { $ref: '#/$defs/User' },
224 + },
225 + $defs: {
226 + // eslint-disable-next-line @typescript-eslint/no-explicit-any
227 + User: { type: 'object', __proto__: { polluted: true } } as any,
228 + },
229 + } as Record<string, unknown>);
230
207 - expect((out as { properties: { v: { $ref: string } } }).properties.v.$ref).toBe(
208 - 'https://example.com/Foo'
209 - );
231 + const v = (out as { properties: { v: Record<string, unknown> } }).properties.v;
232 + expect('__proto__' in v && (v as Record<string, unknown>).__proto__).not.toEqual({
233 + polluted: true,
234 + });
235 + // The cloned node's prototype should remain Object.prototype.
236 + expect(Object.getPrototypeOf(v)).toBe(Object.prototype);
237 });
238
239 it('does not mutate the input schema', () => {