Skip to content

Harden untrusted-input handling: Candid recursion, discovery buffering, terminal escapes - #37

Merged
aterga merged 3 commits into
mainfrom
claude/mcp-spec-compliance-9202ka
Jul 5, 2026
Merged

aterga merged 3 commits into
mainfrom
claude/mcp-spec-compliance-9202ka

Conversation

@aterga

@aterga aterga commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator

Fixes three related "untrusted input reaches a sink without a bound or guard" security findings in a single change.

CWE-674 — Uncontrolled recursion in Candid parsing

Caller-supplied textual Candid — call_canister args, canister .did interfaces, and install-time init args — was passed straight to candid_parser, which recurses (parse → typecheck → Display) with no depth guard. Deeply nested untrusted input such as opt opt … 1 thousands deep drives an unrecoverable stack-overflow process abort, taking down every concurrent session.

Fix: guard_candid_text (in src/main.rs) runs a pre-parse structural check before any candid_parser call:

  • Byte cap (1 MiB) and nesting-depth cap (128).
  • Counts both bracket groups (( { [) and bracket-less opt/vec keyword nesting — bracket-counting alone misses the finding's exact vector.
  • Skips string literals so their contents can't inflate the count.
  • Safe over-approximation: it may over- but never under-count real nesting.

Oversized/over-deep values are a hard reject; an over-limit interface falls back to type-less encode/decode rather than failing the call. Wired into encode_args and decode_bytes_with_did (src/main.rs) and encode_textual_arg (src/management.rs).

CWE-770 — Unbounded allocation in discovery

discover() buffered fully user-controlled response bodies via reqwest::text(), which has no size ceiling — a hostile (or gzip-bomb-inflated) site could exhaust memory.

Fix: read_capped (in src/discover.rs) reads bodies chunk-by-chunk with per-document and aggregate caps (2 MiB per document, 256 KiB for env.json, 8 MiB total bundle scan). A truncated read drops the connection instead of draining it.

CWE-150 — Terminal escape injection in the monitoring CLI

report.js rendered probe-derived text (raw response bytes, error messages) to the operator's terminal verbatim, so a crafted probe response could inject ANSI escapes / CR to forge or overwrite dashboard lines.

Fix: a clean() sanitizer strips control characters at the render boundary, mirroring server.js's sanitizeForLog. The tool's own styling is applied after sanitization, so legitimate color output is unaffected.

Tests

  • candid_guard_rejects_deep_and_oversized (Rust): rejects deep opt-chains, deep brackets, and oversized input; no false positives on realistic values, string contents, or many sibling opts.
  • report.test.js (JS): asserts no ESC/CR/BEL survives rendering and that an embedded newline is flattened rather than forging a new line, while deliberate styling is preserved.
  • Full suite green: 48 Rust tests, 17 JS tests.

🤖 Generated with Claude Code

https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym


Generated by Claude Code

…g, terminal escapes

Three related "untrusted input reaches a sink without a bound/guard" findings,
fixed together:

CWE-674 (uncontrolled recursion): caller-supplied textual Candid (call args,
canister `.did` interfaces, and install-time init args) was handed straight to
candid_parser, which recurses with no depth guard. Deeply nested input such as
`opt opt … 1` thousands deep drives an unrecoverable stack-overflow *process
abort*, taking down every concurrent session. Add `guard_candid_text`, a
pre-parse structural check (byte cap + nesting-depth cap of 128) that counts
both bracket groups and bracket-less `opt`/`vec` keyword nesting, skips string
literals, and over- but never under-approximates real depth. Oversized/over-deep
*values* are a hard reject; an over-limit *interface* falls back to type-less
encode/decode rather than failing the call.

CWE-770 (unbounded allocation): `discover()` buffered fully user-controlled
response bodies via `reqwest::text()`, which has no ceiling — a hostile (or
gzip-bomb-inflated) site could exhaust memory. Read bodies chunk-by-chunk with
per-document and aggregate caps (2 MiB per doc, 256 KiB for env.json, 8 MiB
total bundle scan); a truncated read drops the connection instead of draining.

CWE-150 (terminal escape injection): the monitoring CLI rendered probe-derived
text (raw response bytes, error messages) to the operator's terminal verbatim,
so a crafted probe response could inject ANSI escapes / CR to forge or overwrite
dashboard lines. Sanitize control characters at the render boundary in
report.js, mirroring server.js's `sanitizeForLog`; the tool's own styling is
applied after sanitization so it is unaffected.

Adds Rust and JS unit tests covering each guard.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym

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

This PR hardens multiple untrusted-input paths to prevent denial-of-service via Candid parser recursion, unbounded memory growth during discovery fetches, and terminal escape injection in the monitoring CLI output.

Changes:

  • Add a pre-parse guard_candid_text with byte and structural depth caps and apply it to Candid value/interface parsing.
  • Replace reqwest::text() buffering in discovery with a capped, chunked reader to bound allocations.
  • Sanitize probe-derived fields in monitoring/mcp-status CLI rendering and add JS tests for terminal-injection safety.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/management.rs Applies the new Candid text guard before parsing install/init textual args.
src/main.rs Introduces guard_candid_text + caps, wires guards into encode/decode paths, and adds Rust tests.
src/discover.rs Adds chunked capped body reads and aggregate scan caps to prevent unbounded buffering.
monitoring/mcp-status/report.js Adds render-boundary sanitization (clean()) for terminal safety.
monitoring/mcp-status/report.test.js Adds unit tests asserting control characters are stripped during rendering.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread monitoring/mcp-status/report.js Resolved
Comment thread src/discover.rs Resolved
Comment thread src/main.rs Resolved
… wording

Follow-up to the untrusted-input hardening, addressing PR review:

- guard_candid_text no longer under-counts nesting. An `opt`/`vec` prefix now
  survives until the value it wraps completes (a leaf, string, or matching
  bracket closer) rather than being popped by the next word — so `opt record
  { … }` correctly counts as two levels, not one. Uses a small lookahead to tell
  a group-introducing keyword (record/variant) from a leaf. Adds a mixed
  opt-record nesting test that would previously have slipped past the depth cap.

- Terminal-escape sanitizers (report.js `clean`, server.js `sanitizeForLog`) now
  also neutralize the C1 control range (U+0080–U+009F, incl. U+009B the 8-bit
  CSI) and the Unicode line/paragraph separators (U+2028/U+2029), which can move
  the cursor or start a new line. Test payload extended to cover them.

- Corrected the read_capped doc comment: it stops at the cap and drops the
  connection rather than "discarding the rest".

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym
@aterga
aterga marked this pull request as ready for review July 5, 2026 19:36
Copilot AI review requested due to automatic review settings July 5, 2026 19:36

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 6 out of 6 changed files in this pull request and generated 2 comments.

Comment thread src/discover.rs Resolved
Comment thread monitoring/mcp-status/report.test.js Resolved
- discover.rs: the bundle-scan aggregate cap could overshoot MAX_SCAN_BYTES by
  one byte because the always-pushed '\n' separator wasn't counted against the
  budget. Push the separator first, then size the read against the remaining
  space, so `blob` never exceeds the cap.

- report.test.js: build the control/separator characters from code points
  (String.fromCharCode) instead of embedding them raw. Raw U+2028/U+2029 are JS
  line terminators and can break some parsers/tooling; the file is now pure ASCII.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym
@aterga
aterga merged commit 80aa1eb into main Jul 5, 2026
1 check passed
aterga pushed a commit that referenced this pull request Jul 5, 2026
Resolve the conflict in src/main.rs: PRs #35/#37/#38 landed on main while this
branch was open. The only content conflict was the Candid encode/decode layer —
#37 added CWE-674 hardening (guard_candid_text + MAX_CANDID_DEPTH/size caps) to
the very functions this branch had moved into the new src/calls.rs module.

Resolution: keep this branch's structure (the functions live in calls.rs) and
port #37's hardening into calls.rs:
- guard_candid_text / MAX_CANDID_TEXT_BYTES / MAX_CANDID_DEPTH / depth_err now
  live in calls.rs (pub(crate)), used by encode_args + decode_bytes_with_did.
- management.rs's install-arg guard now calls crate::calls::guard_candid_text.
- the CWE-674 guard test moved to calls::tests alongside the function.

discover.rs (SSRF #35 + discovery buffering #37), management.rs, and the
monitoring/* changes auto-merged. Build clean, all 53 tests pass, no new clippy
warnings.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hv4cGJfD97SGxHM2myTAbA
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