Repository navigation
fix(web_core): stop parsing array items once maxItems fails - #4399
pierreespitia wants to merge 4 commits into
Conversation
|
Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). View this failed invocation of the CLA check for more information. For the most up to date status, view the checks section at the bottom of the pull request. |
There was a problem hiding this comment.
Code Review
This pull request addresses a validation vulnerability (GHSA-mrhx-c7xc-m3w5) by ensuring that arrays exceeding maxItems fail validation on their length before their items are parsed or checked for uniqueness. This is achieved by introducing a rejectOversizedArray preprocessor function in schema_loader.ts that adds a fatal too_big issue early. A corresponding unit test using a Proxy has been added to schema_loader.test.ts to verify that array items are not accessed when the limit is exceeded. There are no review comments, and the changes look solid, so I have no feedback to provide.
2a047b5 to
b37f294
Compare
|
From triage bot, analysis: For humansTL;DR Summary: Targeted issues: Why flagged for triage: Suggestion: What I checked:
The expert needs to decide whether to take this fix for the zod 3 code now, or wait for the direction of #4352. The PR works on #4192 but does not close it. #4192 first proposed to depend on zod
Reply:
To adjust the analysis and apply its suggestion, open it in the hosted triage UI, or run in your a2ui checkout: tools/internal/triage/triage_ui.sh https://github.com/a2ui-project/a2ui/pull/4399For softwareThis analysis is auto-created to help humans to triage this item. Please, do not treat it as a team decision. |
b37f294 to
b1fc745
Compare
|
From triage bot, analysis: For humansTL;DR Summary: Targeted issues: Why flagged for triage: Suggestion: What I checked:
The expert needs to decide whether to take this fix for the zod 3 code now, or wait for the direction of #4352. The PR works on #4192 but does not close it. #4192 first proposed to depend on zod
Reply:
To adjust the analysis and apply its suggestion, open it in the hosted triage UI, or run in your a2ui checkout: tools/internal/triage/triage_ui.sh https://github.com/a2ui-project/a2ui/pull/4399For softwareThis analysis is auto-created to help humans to triage this item. Please, do not treat it as a team decision. |
gspencergoog
left a comment
There was a problem hiding this comment.
This PR adds rejectOversizedArray in typescript/core/web_core/src/catalog/schema_loader.ts so array properties declaring maxItems fail fast via a fatal z.preprocess too_big issue before Zod 3 parses elements or runs uniqueItems refinements. The approach stays compatible with zod-to-json-schema, getDeclaredSchemaKeys, getKnownSchemaKeys, unwrapZodField, and Catalog.toJson(). Two medium and two low refinements remain: finalizePropertyZod wraps not outside rejectOversizedArray, CHANGELOG.md overstates Zod 4 behavior, the synthetic too_big issue hardcodes message and omits exact: false, and the new test uses valid unique items.
🤖 Agent-generated
| ); | ||
| } | ||
| if (typeof propSchema.maxItems === 'number') { | ||
| arr = rejectOversizedArray(arr, propSchema.maxItems); |
There was a problem hiding this comment.
Applying rejectOversizedArray before finalizePropertyZod places propSchema.not's z.preprocess outside the length guard. When a schema declares both maxItems and not, notSchema.safeParse(val) executes before rejectOversizedArray can abort. Oversized arrays still trigger full item traversal inside notSchema and emit an extra custom issue when not matches, violating the length-check bound and single-issue contract.
--- a/typescript/core/web_core/src/catalog/schema_loader.ts
+++ b/typescript/core/web_core/src/catalog/schema_loader.ts
@@ -160,6 +160,7 @@ function finalizePropertyZod(
rootDoc?: Record<string, unknown>,
visitedPointers?: Set<string>,
defCache?: Map<string, z.ZodTypeAny>,
+ maxItems?: number,
): z.ZodTypeAny {
let result = baseZod;
if (propSchema.not && typeof propSchema.not === 'object') {
@@ -181,6 +182,9 @@ function finalizePropertyZod(
return val;
}, result);
}
+ if (typeof maxItems === 'number') {
+ result = rejectOversizedArray(result, maxItems);
+ }
if (propSchema.default !== undefined) {
result = result.default(propSchema.default);
}
@@ -519,9 +523,7 @@ function convertPropertyToZod(
{message: 'Array items must be unique'},
);
}
- if (typeof propSchema.maxItems === 'number') {
- arr = rejectOversizedArray(arr, propSchema.maxItems);
- }
- return finalizePropertyZod(arr, propSchema, rootDoc, visitedPointers, defCache);
+ const maxItems = typeof propSchema.maxItems === 'number' ? propSchema.maxItems : undefined;
+ return finalizePropertyZod(arr, propSchema, rootDoc, visitedPointers, defCache, maxItems);
}Details
Impact: Oversized arrays still trigger full item traversal inside notSchema and emit an extra custom issue when not matches, violating the length-check bound and single-issue contract.
Evidence (Deduction): convertPropertyToZod (typescript/core/web_core/src/catalog/schema_loader.ts:522-525) wraps arr in rejectOversizedArray before calling finalizePropertyZod; finalizePropertyZod (typescript/core/web_core/src/catalog/schema_loader.ts:165-182) then wraps result in an outer z.preprocess calling notSchema.safeParse(val), which traverses every item via ZodArray._parse (zod/v3/types.js:1808-1810).
Putting rejectOversizedArray between not and .default() preserves not's precondition because rejectOversizedArray returns val unchanged without filling defaults, keeps ZodDefault outermost so zodField instanceof z.ZodDefault at schema_loader.ts:709 still works, and leaves zod-to-json-schema output unchanged.
🤖 Agent-generated
| - **BREAKING CHANGE**: Remove the limit of 5 on nested function calls from `validateRecursionAndPaths`, and remove the `MAX_FUNC_CALL_DEPTH` export. Function call nesting is bounded only by the global depth limit (`MAX_GLOBAL_DEPTH`), so payloads that failed with `functionCall depth > 5` are now accepted. Recommended migration: drop references to `MAX_FUNC_CALL_DEPTH` ([#4296](https://github.com/a2ui-project/a2ui/pull/4296)). | ||
| - **BREAKING CHANGE**: `MessageProcessor` rejects a payload whose batch arrays and `{"messages": [...]}` wrappers nest deeper than `MAX_GLOBAL_DEPTH` with `A2uiRecursionError`, with or without a `validationConfig`. With a `validationConfig`, each message's depth counts from `0` inside those containers, and keys beside `messages` on a wrapper are checked for depth and `path` syntax. Recommended migration: send messages in one array or wrapper, and remove invalid values beside `messages` ([#4296](https://github.com/a2ui-project/a2ui/pull/4296)). | ||
| - Add an optional `startDepth` parameter to `validateRecursionAndPaths`, a non-negative integer that defaults to `0`, for checking a value held by a container whose depth is already counted ([#4296](https://github.com/a2ui-project/a2ui/pull/4296)). | ||
| - An array property declared with `maxItems` in JSON Schema (by `Catalog.fromJson` or an `AgentFunction` `schema`) now fails on its length before its items are parsed or checked for `uniqueItems`, so a value over `maxItems` reports a single `too_big` issue and costs no more to validate than its length check, on Zod 3 as on Zod 4 (GHSA-mrhx-c7xc-m3w5, [#4192](https://github.com/a2ui-project/a2ui/issues/4192), [#4399](https://github.com/a2ui-project/a2ui/pull/4399)). |
There was a problem hiding this comment.
@a2ui/web_core pins Zod 3 (^3.25.76) and rejectOversizedArray uses Zod 3 z.preprocess and fatal issue fields. Unpatched Zod 4 releases also iterate every item before running .max(). Readers can mistakenly infer that @a2ui/web_core runs on Zod 4 or that every Zod 4 release already blocks GHSA-mrhx-c7xc-m3w5.
| - An array property declared with `maxItems` in JSON Schema (by `Catalog.fromJson` or an `AgentFunction` `schema`) now fails on its length before its items are parsed or checked for `uniqueItems`, so a value over `maxItems` reports a single `too_big` issue and costs no more to validate than its length check, on Zod 3 as on Zod 4 (GHSA-mrhx-c7xc-m3w5, [#4192](https://github.com/a2ui-project/a2ui/issues/4192), [#4399](https://github.com/a2ui-project/a2ui/pull/4399)). | |
| - An array property declared with `maxItems` in JSON Schema (by `Catalog.fromJson` or an `AgentFunction` `schema`) now fails on its length before its items are parsed or checked for `uniqueItems`, so a value over `maxItems` reports a single `too_big` issue and costs no more to validate than its length check under Zod 3 (GHSA-mrhx-c7xc-m3w5, [#4192](https://github.com/a2ui-project/a2ui/issues/4192), [#4399](https://github.com/a2ui-project/a2ui/pull/4399)). |
Details
Impact: Readers can mistakenly infer that @a2ui/web_core runs on Zod 4 or that every Zod 4 release already blocks GHSA-mrhx-c7xc-m3w5.
Evidence (Read): "on Zod 3 as on Zod 4" (typescript/core/web_core/CHANGELOG.md:7) vs "zod": "^3.25.76" (typescript/core/web_core/package.json:313) and $ZodArray iterating all elements before checks in for (let i = 0; i < input.length; i++) (node_modules/zod/v4/core/schemas.js:637-649).
🤖 Agent-generated
| ctx.addIssue({ | ||
| code: 'too_big', | ||
| maximum: maxItems, | ||
| inclusive: true, | ||
| type: 'array', | ||
| message: `Array must contain at most ${maxItems} element(s)`, | ||
| fatal: true, | ||
| }); |
There was a problem hiding this comment.
Passing a hardcoded message in ctx.addIssue skips Zod's error-map chain, and omitting exact: false differs from ZodArray.max(). Omitting message lets defaultErrorMap generate the identical English text. Consumers with a custom ZodErrorMap or code inspecting issue.exact see inconsistent too_big issues compared to z.array().max().
| ctx.addIssue({ | |
| code: 'too_big', | |
| maximum: maxItems, | |
| inclusive: true, | |
| type: 'array', | |
| message: `Array must contain at most ${maxItems} element(s)`, | |
| fatal: true, | |
| }); | |
| ctx.addIssue({ | |
| code: z.ZodIssueCode.too_big, | |
| maximum: maxItems, | |
| inclusive: true, | |
| exact: false, | |
| type: 'array', | |
| fatal: true, | |
| }); |
Details
Impact: Consumers with a custom ZodErrorMap or code inspecting issue.exact see inconsistent too_big issues compared to z.array().max().
Evidence (Read): ctx.addIssue({ code: 'too_big', maximum: maxItems, inclusive: true, type: 'array', message: ..., fatal: true }) (typescript/core/web_core/src/catalog/schema_loader.ts:211-218) vs ZodArray._parse (node_modules/zod/v3/types.js:1790-1797) setting exact: false with message: undefined, and makeIssue (node_modules/zod/v3/helpers/parseUtil.js:10-16) returning early when issueData.message !== undefined.
🤖 Agent-generated
| // Counts reads of array elements, so the test notices if the items are | ||
| // parsed (or passed to the `uniqueItems` check) after `maxItems` fails. | ||
| let itemReads = 0; | ||
| const tags = new Proxy(['a', 'b', 'c'], { |
There was a problem hiding this comment.
Every element in ['a', 'b', 'c'] already satisfies ^[a-z]+$ and is unique. Even without fast-fail, result.error.issues would still contain only ['too_big', ['tags']]. Using invalid duplicate items tests both zero element reads and suppression of item-level and uniqueItems errors on oversized arrays.
| const tags = new Proxy(['a', 'b', 'c'], { | |
| const tags = new Proxy(['A', 'A', 'A'], { |
Details
Impact: Using invalid duplicate items tests both zero element reads and suppression of item-level and uniqueItems errors on oversized arrays.
Evidence (Read): const tags = new Proxy(['a', 'b', 'c'], { (typescript/core/web_core/src/catalog/schema_loader.test.ts:616) against items: {type: 'string', pattern: '^[a-z]+$'}, uniqueItems: true (schema_loader.test.ts:603-605) and result.error.issues.map(issue => [issue.code, issue.path]) (schema_loader.test.ts:625-628).
🤖 Agent-generated
`Catalog.fromJson` and `AgentFunction` schemas turn a JSON Schema `maxItems` into `z.array().max()`. Zod 3 records the failed check but still parses every item and runs the `uniqueItems` refinement, so the cost of validating a value is not bounded by `maxItems` (GHSA-mrhx-c7xc-m3w5). Check the length first in a fatal preprocess step, which works the same on Zod 3 and Zod 4 and leaves the generated JSON Schema unchanged. Refs a2ui-project#4192
- Run the length check outside the `not` check, so an oversized array is rejected before `not` parses its items, and keep `.default()` outermost. - Build the `too_big` issue like `ZodArray.max()` does: no fixed message, and `exact: false`. - Say in the CHANGELOG that the guarantee holds under Zod 3. - Test with invalid duplicate items, and add a case with both `maxItems` and `not`. Refs a2ui-project#4192
0.17.0 was released while this PR was open, so the entry belongs under Unreleased.
5a61d2d to
264272c
Compare
|
Thanks for the review. I applied the four suggestions and rebased on current The Web and Node.js CI and the other workflows are waiting for approval on the latest commit, since this is a first contribution from this account. Could a maintainer approve them so the checks run? Once they are green, it should be ready to merge. |
Description
Catalog.fromJsonandAgentFunctionschemas turn a JSON SchemamaxItemsintoz.array().max()(schema_loader.ts). On Zod 3, a failed.max()is recorded but every item is still parsed, and theuniqueItemsrefinement then runs over the whole array. So an over-long array prop costs as much to validate as if there were nomaxItemsat all. That is the behaviour behind GHSA-mrhx-c7xc-m3w5, and it is reachable fromweb_corethrough catalogmaxItems, not only from user-level zod code.This PR checks the length first, in a fatal
z.preprocessstep, so parsing stops before the array schema sees the value:zod/v3stopgap discussed in [FEATURE]: Stopgap for GHSA-mrhx-c7xc-m3w5: depend on zod ^4.6.6 and import from "zod/v3" #4192, which keeps the unfixed v3 code path.z.preprocessfornot.zod-to-json-schemadescribes a preprocess by its inner schema, so the generated JSON Schema still carriesmaxItems.too_bigissue instead oftoo_bigplus item errors.Related: #4192 (stopgap discussion), #3825 (Zod 4 error shapes), #2753 (version-agnostic
GenericBinder), #4352 (drop zod), #2160 / #2002 (Zod 4 support). This change is independent of all of them.Test
New test in
schema_loader.test.ts: a component withmaxItems: 2anduniqueItemsgets a 3-item array wrapped in aProxythat counts element reads.Before (
main, zod 3.25.76):After:
Full
yarn testintypescript/core/web_core(build + conformance + unit): 1659 / 1659 pass. Prettier is clean, and eslint reports no new warnings.Pre-launch Checklist
One time:
For this PR:
🤖 Generated with Claude Code