Repository navigation
Make the Candid depth guard comment-aware (CWE-674) - #82
Merged
Merged
Conversation
`guard_candid_text` is the only thing standing between caller-supplied
textual Candid and an uncatchable stack-overflow process abort in
`candid_parser`, whose parse / type-check / `Display` / `Drop` passes all
recurse without a depth limit. The scanner skipped string literals so their
contents could not inflate the count, but knew nothing about Candid's `//`
and `/* */` comments — which the parser's lexer drops in both the value and
`.did` grammars.
That desynchronized the two on a quote inside a comment. Given `//"` the
guard opened a "string" and swallowed everything after it at depth 0,
returning Ok; the parser dropped the comment and went on to parse the
arbitrarily deep value behind it. A ~200 KB `args` value — well under the
1 MiB cap — was enough to overflow a 2 MiB tokio worker stack and take down
the whole process, dropping every concurrent session on both instances.
Add `skip_trivia`, which advances past whitespace and comments exactly as
the lexer does (line comments to the next `\n`; block comments nesting via
the same `/*` / `*/` counter), and run it both at the top of the scan loop
and inside `peek_significant` — a comment between `opt` and `record {` must
not hide the brace and drop the pending prefix either.
As defense in depth, parse untrusted Candid on a dedicated thread with a
64 MiB stack (`on_deep_stack`) instead of the caller's 2 MiB worker stack,
so a future guard miss needs orders of magnitude more depth before it can
reach a guard page. The whole parse-and-use-the-AST operation moves onto
that thread, so the recursive `Drop` runs there too; when the thread cannot
be spawned, callers degrade exactly as they do for unparseable input rather
than falling back to the small stack.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01EYzJbp5D2ngXWvrk39jfrZ
There was a problem hiding this comment.
Pull request overview
Hardens handling of caller-supplied textual Candid to prevent recursion/stack-overflow process aborts (CWE-674) by aligning the pre-parse depth guard with the parser’s lexer (including comment trivia) and adding a defense-in-depth “deep stack” parsing wrapper for untrusted parse sites.
Changes:
- Make
guard_candid_textcomment-aware viaskip_trivia(skips whitespace,//line comments, and nested/* … */block comments) and use it both in the main scan loop andpeek_significant. - Add
on_deep_stackto run untrusted Candid parsing + subsequent AST usage/drop on a dedicated thread with a larger stack, and apply it to untrusted parse sites (incl. install arg encoding). - Add regression tests covering comment-embedded quote bypass scenarios and an end-to-end
encode_argsrefusal case.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
| src/calls.rs | Adds skip_trivia + integrates it into guard_candid_text; introduces on_deep_stack and wraps untrusted Candid parse/type-check/decode paths; adds targeted tests for comment-bypass and deep-nesting refusal. |
| src/management.rs | Wraps install arg textual Candid parsing/encoding with on_deep_stack after guard_candid_text. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
aterga
marked this pull request as ready for review
July 27, 2026 16:29
`on_deep_stack` spawned an OS thread per parse with no ceiling. Parsing untrusted Candid is reachable from the caller-supplied `args`/`candid` fields, so request concurrency alone could multiply live threads — and their 64 MiB stack mappings — without bound. Running these parses inline on the tokio workers had implicitly capped them at roughly one per core; moving them onto dedicated threads removed that ceiling without replacing it. Gate `on_deep_stack` on a process-wide permit, one per core (min 4). The parses are CPU-bound, so this restores the ceiling that was already there rather than imposing a new one: a caller waiting for a permit blocks exactly as it used to block on a busy worker, and every parse is bounded by MAX_CANDID_TEXT_BYTES / MAX_CANDID_DEPTH, so the queue always drains. The permit is an RAII guard held by the calling thread, so it is returned even while unwinding from a parser panic. Test that far more concurrent callers than permits all complete with their own closure's result, that permits are reusable afterwards, and that a panicking parse both reaches its caller and hands its permit back. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01EYzJbp5D2ngXWvrk39jfrZ
6 of 7 tasks
aterga
added a commit
that referenced
this pull request
Aug 18, 2026
…ICPBB-438) (#132) Every canister-reply decode used candid's default `DecoderConfig` (no `decoding_quota`), so nothing bounded the number of decoded elements. A zero-byte element type lets a ~13-byte reply declare tens of millions of elements (`vec null` × 4e7, and far more via nesting); decoding it drives a multi-gigabyte allocation and an UNCATCHABLE `handle_alloc_error`/OOM abort that drops every concurrent user's session. `on_deep_stack` recovers panics, not aborts, so its CWE-674 depth guard does not catch this element-count axis (the reply is depth-1). Route all five reply-decode sites (`decode_reply`, the typed `decode_bytes_with_did`, `parse_execute_reply`, `decode_text_reply`, and `from_bytes_with_types`) through a shared `DecoderConfig` carrying a decoding and skipping quota. candid charges the quota per decoded value, so the bound is absolute (nesting/padding can't raise it) and an over-budget reply returns the ordinary "reply is not decodable" error instead of aborting. The quota is sized so a rejected bomb's transient allocation stays in the tens of MB while realistic replies are untouched. Completes the untrusted-reply hardening line of #37/#82/#87/#108 (which bounded the depth axis) along the element-count axis. Co-authored-by: Claude Opus 5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
guard_candid_textis the only thing standing between caller-supplied textual Candid and an uncatchable stack-overflow process abort incandid_parser, whose parse / type-check /Display/Droppasses all recurse without a depth limit. The scanner skipped string literals so their contents could not inflate the depth count, but knew nothing about Candid's//and/* */comments — which the parser's shared logos lexer drops in both the value and.didgrammars.That desynchronized the two on a quote inside a comment. Given
//", the guard opened a "string" and swallowed everything after it at depth 0, returningOk; the parser dropped the comment and went on to parse the arbitrarily deep value behind it. A ~200 KBargsvalue — well under the 1 MiB cap — was enough to overflow a 2 MiB tokio worker stack and take down the whole process, dropping every concurrent session on both instances.Reachable from the caller-supplied
args/candidfields ofcanister_queryandcanister_update_call(viaencode_args,decode_bytes_with_did,has_oql,is_query_method,api_doc_method,decode_args_with_did) and from the installarginmanagement.rs.Related issues
Addresses the "Untrusted-input recursion guard bypassable via a comment-embedded quote" finding (CWE-674, MEDIUM) at
src/calls.rs:414.Changes
The fix — make the guard read the input the way the lexer does
skip_trivia, which advances past everything the lexer treats as trivia — whitespace,//line comments (to the next\n, or EOF), and/* … */block comments, nesting via the same/*/*/counter the lexer uses.guard_candid_text's scan loop, so a"inside a comment can never be mistaken for the start of a string literal.peek_significanttoo: a comment between a keyword and its brace (opt /* c */ record { … }) must not hide the{and cause the pendingoptprefix to be dropped — the same class of under-count, and one a fix touching only the string arm would have left behind.Defense in depth — parse off the small stack
on_deep_stackruns a parse of untrusted Candid, plus everything done with the resulting AST before it is dropped (so the recursiveDropruns there too), on a dedicated thread with a 64 MiB stack instead of the caller's 2 MiB tokio worker stack. Applied at all seven untrusted-Candid parse sites. When the thread cannot be spawned, callers degrade exactly as they do for input they cannot parse; they never fall back to the small stack. A panic inside the closure is re-raised on the caller's thread rather than laundered into aNone.MAX_CANDID_TEXT_BYTESthis is a wide margin, not a proof. The depth guard is still what actually holds the line.on_deep_stacktakes a process-wide permit (one per core, min 4) before spawning. Running these parses inline had already capped them at roughly one per core, and moving them to dedicated threads removed that ceiling without replacing it — so the permit restores the prior concurrency posture rather than imposing a new limit. Live 64 MiB mappings are now bounded by core count instead of by request concurrency. The permit is an RAII guard held by the calling thread, returned even while unwinding from a parser panic.Tests
candid_guard_is_comment_awarefirst pins the premise againstcandid_parseritself (it really does skip//",/*"*/, and nested/* /* " */ */, then parses what follows), then checks each of those hides neither anopt-chain nor bracket nesting from the guard, plus theopt-comment-recordprefix case. Also covers no false positives: comments are still trivia, and////*inside a string is still string content.encode_args_refuses_comment_hidden_deep_nestingcovers the reported vector end to end, and checks legitimately nested values still encode.deep_stack_parses_are_capped_but_all_completecovers the two failure modes the cap could introduce: 64 concurrent callers against far fewer permits all complete with their own closure's result (no deadlock, no lost work), and a panicking parse both reaches its caller and hands its permit back.Testing
cargo build --locked --all-targetscargo test --locked --all-targets— 146 passed, 0 failedcargo clippy --all-targets— no new warnings from this change (the tree already carries 8 pre-existing ones:tool_routernever read,oknever used, 5map_or, 1 redundant closure, 1repeat().take()).cargo fmt --allwas not run: the tree does not currently conform to default rustfmt, so it would have produced a large unrelated diff; new code matches surrounding style instead.npm test --prefix monitoring/mcp-status(dashboard unchanged)Checklist
guard_candid_text,skip_trivia, andon_deep_stackspell out the invariant the scanner has to hold against the lexer. No user-visible behavior change beyond hostile input now being refused.