Skip to content

Commit a0ebf97

Browse files
authored
fix(v4): check array, set and map size bounds before parsing elements (#6652)
.max(), .length() and .size() ran after every element was walked, so an oversized input built one issue per bad element before the bound was reported. Leading size checks now reject the input first, both in the interpreter and in the compiled path. Fixes #6643
1 parent a2ba4a6 commit a0ebf97

6 files changed

Lines changed: 93 additions & 0 deletions

File tree

‎packages/zod/src/v4/classic/tests/array.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,33 @@ test("continue parsing despite array size error", () => {
140140
`);
141141
});
142142

143+
test("an upper size bound fails before any element is parsed", () => {
144+
let parsed = 0;
145+
const el = z.string().refine(() => ++parsed);
146+
let refined = 0;
147+
const schema = z
148+
.array(el)
149+
.max(2, "too many")
150+
.refine(() => ++refined);
151+
expect(schema.safeParse([1, 2, 3]).error!.issues).toMatchObject([{ code: "too_big", path: [], message: "too many" }]);
152+
expect(z.array(el).length(2).safeParse(["a", "b", "c"]).error!.issues).toMatchObject([
153+
{ code: "too_big", exact: true },
154+
]);
155+
expect(z.object({ a: z.array(el).max(1) }).safeParse({ a: [1, 2] }).error!.issues).toMatchObject([
156+
{ code: "too_big", path: ["a"] },
157+
]);
158+
expect([parsed, refined]).toEqual([0, 0]);
159+
160+
// a check that may rewrite the value ends the gate
161+
expect(
162+
z
163+
.array(z.number())
164+
.overwrite((a) => a.slice(0, 2))
165+
.max(2)
166+
.parse([1, 2, 3])
167+
).toEqual([1, 2]);
168+
});
169+
143170
test("parse should fail given sparse array", () => {
144171
const schema = z.array(z.string()).nonempty().min(1).max(3);
145172
const result = schema.safeParse(new Array(3));

‎packages/zod/src/v4/classic/tests/map.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,13 @@ test("failing when map is bigger than max() ", () => {
9797
expect(result.success).toEqual(false);
9898
expect(result.error!.issues.length).toEqual(1);
9999
expect(result.error!.issues[0].code).toEqual("too_big");
100+
const bad = new Map([
101+
[1, 1],
102+
[2, 2],
103+
]);
104+
const capped = z.map(z.string(), z.string()).max(1);
105+
expect(capped.safeParse(bad).error!.issues).toMatchObject([{ code: "too_big" }]);
106+
expect(capped.safeParse(new Set([1, 2])).error!.issues[0]).toMatchObject({ code: "invalid_type", expected: "map" });
100107
});
101108

102109
test("failing when map does not match size() ", () => {

‎packages/zod/src/v4/classic/tests/set.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,12 @@ test("failing when set is bigger than max() ", () => {
8383
expect(result.success).toEqual(false);
8484
expect(result.error!.issues.length).toEqual(1);
8585
expect(result.error!.issues[0].code).toEqual("too_big");
86+
expect(
87+
z
88+
.set(z.string())
89+
.max(1)
90+
.safeParse(new Set([1, 2])).error!.issues
91+
).toMatchObject([{ code: "too_big" }]);
8692
});
8793

8894
test("failing when set does not match size() ", () => {

‎packages/zod/src/v4/core/compile.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1551,6 +1551,12 @@ function generateNullableCheck(
15511551
return outputVar;
15521552
}
15531553

1554+
function generateSizeGate(doc: Doc, schema: SomeType, size: string): void {
1555+
for (const [max, check] of util.sizeCaps(schema._zod.def.checks)) {
1556+
doc.write(`if (${size} > ${numericOperand(max, check._zod.def.check)}) return INVALID;`);
1557+
}
1558+
}
1559+
15541560
function generateArrayCheck(
15551561
doc: Doc,
15561562
ctx: CompileContext,
@@ -1560,6 +1566,7 @@ function generateArrayCheck(
15601566
): string | null {
15611567
const def = schema._zod.def as unknown as { element: SomeType };
15621568
doc.write(`if (!Array.isArray(${accessor})) return INVALID;`);
1569+
generateSizeGate(doc, schema, `${accessor}.length`);
15631570

15641571
// Build a new array with validated/transformed elements.
15651572
const outputVar = buildsValue ? newVar(ctx) : null;
@@ -2094,6 +2101,7 @@ function generateMapCheck(doc: Doc, ctx: CompileContext, schema: SomeType, acces
20942101
const def = schema._zod.def as unknown as { keyType: SomeType; valueType: SomeType };
20952102

20962103
doc.write(`if (!(${accessor} instanceof Map)) return INVALID;`);
2104+
generateSizeGate(doc, schema, `${accessor}.size`);
20972105

20982106
const outputVar = newVar(ctx);
20992107
const kVar = newVar(ctx);
@@ -2115,6 +2123,7 @@ function generateSetCheck(doc: Doc, ctx: CompileContext, schema: SomeType, acces
21152123
const def = schema._zod.def as unknown as { valueType: SomeType };
21162124

21172125
doc.write(`if (!(${accessor} instanceof Set)) return INVALID;`);
2126+
generateSizeGate(doc, schema, `${accessor}.size`);
21182127

21192128
const outputVar = newVar(ctx);
21202129
const valVar = newVar(ctx);

‎packages/zod/src/v4/core/schemas.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1844,6 +1844,34 @@ export interface $ZodArrayInternals<T extends SomeType = $ZodType> extends _$Zod
18441844

18451845
export interface $ZodArray<T extends SomeType = $ZodType> extends $ZodType<any, any, $ZodArrayInternals<T>> {}
18461846

1847+
// an oversized container fails its leading size checks before any element is parsed
1848+
function capSize(inst: $ZodType, size: (input: any) => number): void {
1849+
const caps = util.sizeCaps(inst._zod.def.checks);
1850+
if (!caps.length) return;
1851+
const cap = Math.min(...caps.map((c) => c[0]));
1852+
const parse = inst._zod.parse;
1853+
inst._zod.parse = (payload, ctx) => {
1854+
const n = size(payload.value);
1855+
if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") {
1856+
for (const [max, ch] of util.sizeCaps(inst._zod.def.checks)) {
1857+
if (n > max && ch._zod.def.when!(payload)) {
1858+
const start = payload.issues.length;
1859+
ch._zod.check(payload as ParsePayload<never>);
1860+
// the value is still the raw input, so no later check may read it
1861+
(payload.issues[start] as { continue?: boolean }).continue = false;
1862+
util.attachSchema(payload.issues, start, inst);
1863+
return payload;
1864+
}
1865+
}
1866+
}
1867+
return parse(payload, ctx);
1868+
};
1869+
}
1870+
1871+
const arraySize = (input: unknown): number => (Array.isArray(input) ? input.length : -1);
1872+
const mapSize = (input: unknown): number => (input instanceof Map ? input.size : -1);
1873+
const setSize = (input: unknown): number => (input instanceof Set ? input.size : -1);
1874+
18471875
function handleArrayResult(result: ParsePayload<any>, final: ParsePayload<any[]>, index: number) {
18481876
if (result.issues.length) {
18491877
final.issues.push(...util.prefixIssues(index, result.issues));
@@ -1899,6 +1927,7 @@ export const $ZodArray: core.$constructor<$ZodArray> = /*@__PURE__*/ core.$const
18991927

19001928
return payload; //handleArrayResultsAsync(parseResults, final);
19011929
};
1930+
capSize(inst, arraySize);
19021931
});
19031932

19041933
//////////////////////////////////////////
@@ -3483,6 +3512,7 @@ export const $ZodMap: core.$constructor<$ZodMap> = /*@__PURE__*/ core.$construct
34833512
if (proms.length) return Promise.all(proms).then(() => payload);
34843513
return payload;
34853514
};
3515+
capSize(inst, mapSize);
34863516
});
34873517

34883518
function handleMapResult(
@@ -3585,6 +3615,7 @@ export const $ZodSet: core.$constructor<$ZodSet> = /*@__PURE__*/ core.$construct
35853615
if (proms.length) return Promise.all(proms).then(() => payload);
35863616
return payload;
35873617
};
3618+
capSize(inst, setSize);
35883619
});
35893620

35903621
function handleSetResult(result: ParsePayload, final: ParsePayload<Set<any>>) {

‎packages/zod/src/v4/core/util.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -935,6 +935,19 @@ export function unwrapMessage(message: string | { message: string } | undefined
935935
}
936936

937937
/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */
938+
/** The leading size checks of `defChecks` that set an upper bound, each paired with it. */
939+
export function sizeCaps(defChecks: checks.$ZodCheck<never>[] | undefined): [number, checks.$ZodCheck<never>][] {
940+
const caps: [number, checks.$ZodCheck<never>][] = [];
941+
for (const ch of defChecks ?? []) {
942+
const d = ch._zod.def as any;
943+
// a later check may rewrite the value
944+
if (!/_(length|size)$|_equals$/.test(d.check)) break;
945+
const max = d.maximum ?? d.length ?? d.size;
946+
if (max >= 0) caps.push([max, ch]);
947+
}
948+
return caps;
949+
}
950+
938951
export function attachSchema(issues: errors.$ZodRawIssue[], start: number, inst: schemas.$ZodType): void {
939952
for (let i = start; i < issues.length; i++) {
940953
(issues[i] as any).schema ??= inst;

0 commit comments

Comments
 (0)