镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Commit e7d430f

Browse files
committed
fix(json): guard recursive parsing depth (#515)
Charge object and array recursion to the existing logical/native stack guard so hostile valid JSON throws the standard RangeError before Zig stack exhaustion. Protect the reviver walk through the same contract and preserve OutOfMemory, Throw, and internal control failures instead of relabeling them as SyntaxError. Add a production-module subprocess gate for 50,000-level arrays and objects, 20,000 mixed containers, JSON.rawJSON, reviver traversal, a 96-level valid boundary, and malformed-syntax classification. Run it in CI normally and under TSan. Before: the 50,000-array witness exited 139. After: it returns OK 42. Debug, ReleaseSafe, and TSan runtime gates pass; full unit gate is 1,544 passed, 1 expected skip, 0 failed/leaked; JSON.parse test262 remains 77/77, flips 0 cases.
1 parent 4adcc0d commit e7d430f

4 files changed

Lines changed: 68 additions & 5 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,9 @@ jobs:
181181
# drifting while the sharded full root suite remains authoritative.
182182
- name: focused-engine-tests
183183
home_tool: true
184-
cmd: zig build test-jit test-vm test-concurrency gc-relocation-inventory-check optimizer-release-inventory-check
184+
cmd: |
185+
zig build test-jit test-vm test-runtime test-concurrency gc-relocation-inventory-check optimizer-release-inventory-check
186+
zig build test-runtime -Dtsan=true
185187
# Execute real generated instructions and require both sides of W^X:
186188
# unpublished pages fault on execute, and published pages fault on
187189
# write. This Linux x86-64 leg exercises the POSIX backend directly.

‎build.zig‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1688,6 +1688,7 @@ pub fn build(b: *std.Build) void {
16881688
for ([_]struct { step_name: []const u8, suite: []const u8, description: []const u8 }{
16891689
.{ .step_name = "test-frontend", .suite = "frontend", .description = "Run focused production lexer/parser semantic tests" },
16901690
.{ .step_name = "test-vm", .suite = "vm", .description = "Run focused production bytecode/VM semantic tests" },
1691+
.{ .step_name = "test-runtime", .suite = "runtime", .description = "Run focused production runtime security tests" },
16911692
.{ .step_name = "test-concurrency", .suite = "concurrency", .description = "Run focused production concurrency semantic tests" },
16921693
}) |spec| {
16931694
const run_focused_engine_tests = b.addRunArtifact(focused_engine_tests);

‎src/builtins.zig‎

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2983,7 +2983,12 @@ pub fn jsonRawJSON(ctx: *anyopaque, this: Value, args: []const Value) HostError!
29832983
return self.throwError("SyntaxError", "JSON.rawJSON text must be non-empty and not start or end with whitespace");
29842984
var p = JsonParser{ .s = s, .i = 0, .interp = self };
29852985
p.skipWs();
2986-
const parsed = p.parseValue() catch return self.throwError("SyntaxError", "JSON.rawJSON: invalid JSON");
2986+
const parsed = p.parseValue() catch |err| switch (err) {
2987+
error.Invalid => return self.throwError("SyntaxError", "JSON.rawJSON: invalid JSON"),
2988+
error.OutOfMemory => return error.OutOfMemory,
2989+
error.Throw => return error.Throw,
2990+
error.OptShortCircuit => return error.OptShortCircuit,
2991+
};
29872992
const v = parsed.value;
29882993
p.skipWs();
29892994
if (p.i != s.len) return self.throwError("SyntaxError", "JSON.rawJSON: trailing characters");
@@ -3019,7 +3024,12 @@ pub fn jsonParse(ctx: *anyopaque, this: Value, args: []const Value) HostError!Va
30193024
const text = try self.toStringWtf8(arg(args, 0));
30203025
var p = JsonParser{ .s = text, .i = 0, .interp = self };
30213026
p.skipWs();
3022-
const parsed = p.parseValue() catch return self.throwError("SyntaxError", "JSON.parse: invalid JSON");
3027+
const parsed = p.parseValue() catch |err| switch (err) {
3028+
error.Invalid => return self.throwError("SyntaxError", "JSON.parse: invalid JSON"),
3029+
error.OutOfMemory => return error.OutOfMemory,
3030+
error.Throw => return error.Throw,
3031+
error.OptShortCircuit => return error.OptShortCircuit,
3032+
};
30233033
const v = parsed.value;
30243034
p.skipWs();
30253035
if (p.i != text.len) return self.throwError("SyntaxError", "JSON.parse: trailing characters");
@@ -3041,6 +3051,12 @@ pub fn jsonParse(ctx: *anyopaque, this: Value, args: []const Value) HostError!Va
30413051
/// InternalizeJSONProperty: recursively apply `reviver` to `holder[key]` and its
30423052
/// nested elements/properties (children first), returning the reviver's result.
30433053
fn internalizeJson(self: *Interpreter, holder: Value, key: []const u8, reviver: Value, sources: []const JsonSourceEntry) HostError!Value {
3054+
// InternalizeJSONProperty is recursive even though parsing has completed.
3055+
// A reviver must not turn the parser's bounded-depth guarantee into a
3056+
// second native-stack overflow while walking the accepted result graph.
3057+
self.depth += 1;
3058+
defer self.depth -= 1;
3059+
try self.stackGuard();
30443060
const a = self.arena;
30453061
const val = try self.getProperty(holder, key);
30463062
if (val.isObject() and !val.asObj().isCallableObject()) {
@@ -3136,8 +3152,23 @@ const JsonParser = struct {
31363152
if (p.i >= p.s.len) return error.Invalid;
31373153
const c = p.s[p.i];
31383154
switch (c) {
3139-
'{' => return p.parseObject(),
3140-
'[' => return p.parseArray(),
3155+
// Only containers recurse back into parseValue. Charge their
3156+
// nesting to the engine's logical/native stack guard so hostile
3157+
// valid JSON fails with the normal catchable RangeError before the
3158+
// Zig call stack can overflow. Flat scalar arrays keep the shallow
3159+
// fast path and pay no per-element stack probe.
3160+
'{' => {
3161+
p.interp.depth += 1;
3162+
defer p.interp.depth -= 1;
3163+
try p.interp.stackGuard();
3164+
return p.parseObject();
3165+
},
3166+
'[' => {
3167+
p.interp.depth += 1;
3168+
defer p.interp.depth -= 1;
3169+
try p.interp.stackGuard();
3170+
return p.parseArray();
3171+
},
31413172
'"' => {
31423173
const start = p.i;
31433174
const s = try p.parseString();

‎tools/focused_engine_tests.zig‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,33 @@ const jit_cases = [_]Case{
122122
},
123123
};
124124

125+
const runtime_cases = [_]Case{
126+
.{
127+
.name = "JSON hostile nesting is catchable",
128+
.source =
129+
\\function rejectsDepth(text) {
130+
\\ try { JSON.parse(text); return false; }
131+
\\ catch (error) { return error instanceof RangeError && error.message === "Maximum call stack size exceeded"; }
132+
\\}
133+
\\let shallow = "[".repeat(96) + "7" + "]".repeat(96);
134+
\\let value = JSON.parse(shallow);
135+
\\for (let i = 0; i < 96; i++) value = value[0];
136+
\\let revived = JSON.parse(shallow, function (key, child) { return child; });
137+
\\for (let i = 0; i < 96; i++) revived = revived[0];
138+
\\let syntax = false;
139+
\\try { JSON.parse("[1,"); } catch (error) { syntax = error instanceof SyntaxError; }
140+
\\let arrays = rejectsDepth("[".repeat(50000) + "0" + "]".repeat(50000));
141+
\\let objects = rejectsDepth("{\"v\":".repeat(50000) + "0" + "}".repeat(50000));
142+
\\let mixed = rejectsDepth("[{\"v\":".repeat(20000) + "0" + "}]".repeat(20000));
143+
\\let raw = false;
144+
\\try { JSON.rawJSON("[".repeat(50000) + "0" + "]".repeat(50000)); }
145+
\\catch (error) { raw = error instanceof RangeError && error.message === "Maximum call stack size exceeded"; }
146+
\\value === 7 && revived === 7 && syntax && arrays && objects && mixed && raw ? 1 : 0
147+
,
148+
.expected = 1,
149+
},
150+
};
151+
125152
const concurrency_cases = [_]Case{
126153
.{
127154
.name = "atomic increments",
@@ -226,6 +253,8 @@ pub fn main(init: std.process.Init) !void {
226253
break :blk valid + invalid;
227254
} else if (std.mem.eql(u8, suite, "vm"))
228255
try runCases(gpa, &vm_cases, filter, false, false)
256+
else if (std.mem.eql(u8, suite, "runtime"))
257+
try runCases(gpa, &runtime_cases, filter, false, false)
229258
else if (std.mem.eql(u8, suite, "jit")) blk: {
230259
const interpreted = try runCases(gpa, &jit_cases, filter, false, false);
231260
const native = try runCases(gpa, &jit_cases, filter, true, false);

0 commit comments

Comments
 (0)