Skip to content

Make the Candid depth guard comment-aware (CWE-674) - #82

Merged
aterga merged 2 commits into
mainfrom
claude/recursion-guard-comment-quote-zayn9b
Jul 27, 2026
Merged

aterga merged 2 commits into
mainfrom
claude/recursion-guard-comment-quote-zayn9b

Conversation

@aterga

@aterga aterga commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

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 depth count, but knew nothing about Candid's // and /* */ comments — which the parser's shared logos 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.

Reachable from the caller-supplied args / candid fields of canister_query and canister_update_call (via encode_args, decode_bytes_with_did, has_oql, is_query_method, api_doc_method, decode_args_with_did) and from the install arg in management.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

  • Add 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.
  • Run it at the top of guard_candid_text's scan loop, so a " inside a comment can never be mistaken for the start of a string literal.
  • Run it inside peek_significant too: a comment between a keyword and its brace (opt /* c */ record { … }) must not hide the { and cause the pending opt prefix 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_stack runs a parse of untrusted Candid, plus everything done with the resulting AST before it is dropped (so the recursive Drop runs 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 a None.
  • Caveat worth stating plainly: with input capped at MAX_CANDID_TEXT_BYTES this is a wide margin, not a proof. The depth guard is still what actually holds the line.
  • Following review (8a72234), on_deep_stack takes 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_aware first pins the premise against candid_parser itself (it really does skip //", /*"*/, and nested /* /* " */ */, then parses what follows), then checks each of those hides neither an opt-chain nor bracket nesting from the guard, plus the opt-comment-record prefix case. Also covers no false positives: comments are still trivia, and // / /* inside a string is still string content.
  • encode_args_refuses_comment_hidden_deep_nesting covers the reported vector end to end, and checks legitimately nested values still encode.
  • deep_stack_parses_are_capped_but_all_complete covers 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-targets
  • cargo test --locked --all-targets — 146 passed, 0 failed
  • cargo clippy --all-targets — no new warnings from this change (the tree already carries 8 pre-existing ones: tool_router never read, ok never used, 5 map_or, 1 redundant closure, 1 repeat().take()). cargo fmt --all was 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

  • I have read the Contributing guidelines.
  • Docs (README / comments) updated for any user-visible change — the doc comments on guard_candid_text, skip_trivia, and on_deep_stack spell out the invariant the scanner has to hold against the lexer. No user-visible behavior change beyond hostile input now being refused.
  • No secrets, credentials, or internal-only information are included.

`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

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_text comment-aware via skip_trivia (skips whitespace, // line comments, and nested /* … */ block comments) and use it both in the main scan loop and peek_significant.
  • Add on_deep_stack to 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_args refusal 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.

Comment thread src/calls.rs Resolved
@aterga
aterga marked this pull request as ready for review July 27, 2026 16:29
@aterga
aterga requested a review from a team as a code owner 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
Copilot AI review requested due to automatic review settings July 27, 2026 16:34

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

@aterga
aterga merged commit cee3713 into main Jul 27, 2026
2 checks passed
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants