Repository navigation
Cherry pick #121693 to 26.3: Guard the JSON AST deserialization recursions with checkStackSize - #121851
Conversation
Deserializing an AST from JSON (formatQueryFromJSON, the clickhouse_json
dialect) recursed with no stack check. Its only bound was a counter compared
against effectiveJSONDeserializationMaxDepth(), i.e. max_ast_depth when set and
1000 otherwise. A count is not a stack budget: safety is
stack_size / per_level_frame_cost, and both factors move independently of any
setting. Measured per-level cost in a debug build is ~6.1 KiB for the AST node
descent, ~1.0 KiB for the structured Field descent and ~65 B per JSON container
level, so the 1000-level ceiling is only ~1.4x safe on an 8 MiB stack and is
unsafe at 4 MiB, while raising max_ast_depth removes the bound outright.
On v26.8.11.7-lts a 1500-level nested AST JSON document at
max_ast_depth = 100000 terminated the process with SIGSEGV, zero output and no
stack trace, the overflow having prevented the fault handler from running.
Three distinct recursions are involved and none checked the stack:
- createFromJSON(const Poco::JSON::Object &), the AST node descent;
- readFieldFromObjectImpl, the structured Field descent, which adds no AST
nodes and so is bounded only by its own limit;
- Poco::JSON::Parser's own descent over the JSON text, which completes before
a single AST node exists, so no check inside createFromJSON can observe it.
A valid one-node Literal carrying an ignored 200000-level array member was
enough to exit 139.
checkStackSize() is now called on each recursive entry, after that recursion's
existing bound check so that whenever a bound is the binding limit its own
message still wins. The check is unconditional because the stack, not a
setting, is the thing being bounded; gating it on the ceiling would leave the
default-settings 4 MiB crash reachable by construction.
DB::Exception derives from Poco::Exception, so the existing
catch (const Poco::Exception &) converted the handler's TOO_DEEP_RECURSION into
BAD_ARGUMENTS. A catch (const Exception &) { throw; } clause is ordered before
it. That was the failure mode which looks like a working guard.
Two stale comments are corrected: our Poco fork does enforce setDepth
(ParserImpl.cpp:145 in handleArray and :165 in handleObject both test
_currentDepth >= _depth, against a JSON_DEFAULT_DEPTH of 1000), so the claim
that the bracket pre-scan is the actual enforcement was wrong, and it was the
stated reason that pre-scan exists. One line records in its place what the
setDepth call does here, which the call alone does not show: it RAISES that
1000-level default to the pre-scan's budget, and that is what makes the deep
text descent reachable at all.
Rejected alternative: capping the ceiling with min(max_ast_depth, 1000). It
rejects input that works today (formatQueryFromJSON(parseQueryToJSON(...)) of a
600-nested-abs query, AST depth ~1204, returns 3016 bytes at
max_ast_depth = 200000 and is rejected at 1000), and it still would not bound
the stack: a depth-900 payload SIGSEGVs at default settings on a 4 MiB stack.
Deliberate consequence: accepted depth is now stack-bounded rather than
count-bounded. checkStackSize() permits 50% of the thread stack (5% under
TSAN), and the bisected trip depths sit at exactly that fraction of the
previous crash depth (711 against 1459 node levels, 4302 against 8565 Field
levels). In a debug build, node payloads deeper than ~690 are therefore
rejected where they previously succeeded up to 1000. Release frames are smaller
so that window sits deeper, which was not measured. A recursion bounded by the
stack cannot also promise a count.
Tests: three arms in 04056_ast_json_limits, one per guarded recursion, each
verified by its captured stack frames to trip the guard it names rather than a
neighbouring limit, and each exiting 139 on the unfixed binary. Every one of
those thresholds scales as 1 / per_level_frame_cost, which is a build property,
so the depths are placed with margin over the depth at which the UNFIXED binary
crashes (13.7x and 2.9x in a debug build) rather than over the guard's own trip
depth: that is what keeps the pre-fix failure reachable in a build whose frames
are cheaper. For the same reason the arms assert only that a controlled error
replaces the crash, never which of the three guards reports it. 04654 case 3
asserted which of two bounds rejects a payload; once the recursion is
stack-bounded that is a property of the build's stack budget (measured: the
Field bound's own message at 8 MiB, TOO_DEEP_RECURSION at a TSAN-parity 840 KiB
budget), so that arm now asserts the controlled rejection. It still fails on an
unrelated error.
Field::restoreFromDump is left alone: its dump parser is flat, so a nested dump
is rejected with CANNOT_RESTORE_FROM_FIELD_DUMP before it can recurse, measured
at depth 20000 for both Array_ and Tuple_ shapes.
Related: #120725
Co-Authored-By: Claude Opus 5 <[email protected]>
Delete the comment narrating the pre-scan/handler division of labour (the surviving lines below it already state the budget's semantics), and reduce the three property comments to one standalone line each. Drops the inaccurate claim that setDepth "raises" Poco's default: the budget is a multiple of the effective max_ast_depth, so it is lower than Poco's 1000 for max_ast_depth <= 125. Co-Authored-By: Claude Opus 5 <[email protected]>
Guard the JSON AST deserialization recursions with checkStackSize
Not applicable to 26.3: the code #121693 patches does not exist on this branchThe cherry-pick is
The JSON-to-AST deserialization path that #121693 guards is not on 26.3 at all. On both I think this PR should be closed as not applicable, together with the sibling for the other branch in the same position; I have not closed either myself. #121853 (26.8) and #121854 (26.9) do apply. Both fail to build on a missing |
…rypick/26.3/121693 # Conflicts: # src/Parsers/ASTFromJSON.cpp # src/Parsers/ASTJSONReadHelpers.cpp # tests/queries/0_stateless/04056_ast_json_limits.sql # tests/queries/0_stateless/04654_ast_json_depth_guard_max_ast_depth_zero.reference # tests/queries/0_stateless/04654_ast_json_depth_guard_max_ast_depth_zero.sh
Original pull-request #121693
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Before you resolve anything
Conflicts are often caused by a prerequisite change that has not been backported yet, rather than by a real divergence. The bot re-tries this cherry-pick against the release branch on every run, so if that is the case here it will merge itself as soon as the prerequisite lands, and you will see a comment saying so. Manual resolution is only needed while the conflict persists.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job