Repository navigation
Harden untrusted-input handling: Candid recursion, discovery buffering, terminal escapes - #37
Merged
Merged
Conversation
…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
There was a problem hiding this comment.
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_textwith 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-statusCLI 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.
… 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
- 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
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]>
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.
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_canisterargs, canister.didinterfaces, and install-time init args — was passed straight tocandid_parser, which recurses (parse → typecheck →Display) with no depth guard. Deeply nested untrusted input such asopt opt … 1thousands deep drives an unrecoverable stack-overflow process abort, taking down every concurrent session.Fix:
guard_candid_text(insrc/main.rs) runs a pre-parse structural check before anycandid_parsercall:({[) and bracket-lessopt/veckeyword nesting — bracket-counting alone misses the finding's exact vector.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_argsanddecode_bytes_with_did(src/main.rs) andencode_textual_arg(src/management.rs).CWE-770 — Unbounded allocation in discovery
discover()buffered fully user-controlled response bodies viareqwest::text(), which has no size ceiling — a hostile (or gzip-bomb-inflated) site could exhaust memory.Fix:
read_capped(insrc/discover.rs) reads bodies chunk-by-chunk with per-document and aggregate caps (2 MiB per document, 256 KiB forenv.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.jsrendered 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, mirroringserver.js'ssanitizeForLog. The tool's own styling is applied after sanitization, so legitimate color output is unaffected.Tests
candid_guard_rejects_deep_and_oversized(Rust): rejects deepopt-chains, deep brackets, and oversized input; no false positives on realistic values, string contents, or many siblingopts.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.🤖 Generated with Claude Code
https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym
Generated by Claude Code