Skip to content

fix(server): bound Claude Desktop apply bodies - #1272

Closed
luvs01 wants to merge 3 commits into
lidge-jun:devfrom
luvs01:agent/fix-claude-apply-body-bound
Closed

fix(server): bound Claude Desktop apply bodies#1272
luvs01 wants to merge 3 commits into
lidge-jun:devfrom
luvs01:agent/fix-claude-apply-body-bound

Conversation

@luvs01

@luvs01 luvs01 commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Summary

  • route POST /api/claude-desktop/apply through the shared 4 MiB management JSON reader instead of unbounded req.text();
  • stop raw request streams at the caller's wire-byte cap even when Content-Length is missing, malformed, or dishonest;
  • enforce the decompressed-byte limit independently before JSON parsing;
  • preserve the existing empty-body behavior with an explicit optional-body fallback;
  • validate JSON, mode, and profile before writing the Claude Desktop desired state;
  • add regressions for malformed input, invalid mode/profile, compressed oversize, streaming oversize, abort/cancellation, and no-mutation failures.

Why

The Claude Desktop apply route was the remaining management endpoint that parsed its body with req.text(). A compressed or chunked request could bypass the management-body contract, and invalid input could set the persistent desired state to ON before the route returned 400.

A post-arrayBuffer() size check was still insufficient for absent or falsely low Content-Length: the platform could drain and allocate the entire body before returning 413. The shared reader now enforces the raw bound while consuming the stream and rejects before any route mutation.

Behavior and bounds

  • An honest over-limit Content-Length is rejected and the unlocked body is canceled before reading.
  • Missing, malformed, or dishonest declarations are bounded by a single-reader, single-geometric-buffer collector. It checks each chunk before growth or copy, cancels at the first over-limit chunk, and never waits for a rejecting or non-settling cancellation.
  • A body exactly at the cap is accepted only after EOF; another byte fails closed.
  • Request abort identity is rechecked after every read settlement so cancel-resolved EOF cannot become an empty-body fallback.
  • Raw compressed bytes and decompressed bytes must each fit the caller's limit before parse.
  • Empty or whitespace-only bodies still mean the existing default apply request.
  • Malformed JSON and unsupported encodings retain the management-plane 400 behavior; raw/decompressed size overflow uses the existing 413 response.
  • Runtime source chunks, geometric buffer growth, and Request.clone() tee queues can overlap by a finite constant factor; the security contract is a bounded logical-byte limit, not an exact resident-memory figure.
  • No authentication, credential, or successful apply response contract changes.

Verification

  • Bun 1.3.14: tests/request-decompress.test.ts 31/31 passed.
  • Bun 1.3.14: tests/native-claude-desktop-toggle.test.ts 9/9 passed.
  • Bun 1.3.14: tests/claude-management-api.test.ts 25/25 passed.
  • Bun 1.3.14: tests/management-integration-routes.test.ts 22/22 passed.
  • Bun 1.3.14: tests/claude-desktop-cli.test.ts 6/6 passed.
  • Bun 1.4.0-canary.1 (b22e0e6d0): request decompression + native Claude Desktop 40/40 passed.
  • Bun 1.3.14 randomized targeted run (seed 1272): 40/40 passed.
  • bun x tsc --noEmit: passed.
  • bun scripts/privacy-scan.ts: passed.
  • git diff --check: passed.
  • Independent review shards: no actionable P0–P3 findings.
  • CodeRabbit: one valid trim-order performance comment fixed in b9866e0b; thread resolved.
  • Codex Security diff scan: complete, 3/3 changed files covered, 0 reportable findings.
  • Windows full suite: attempted earlier, not passed and not counted as verification. The Bun 1.3.14 --isolate run hit an EBUSY storage-fixture cleanup, an unrelated management-auth 401 cascade, and then Bun's Internal assertion failure. This matches the repository's documented dispatch-only Windows/storage-runtime class in Windows test suite remains dispatch-only until full suite is green #1059; no storage, auth-admission, or Worker-lifecycle file is changed here.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes are not required because no user-facing configuration or successful response contract changes.
  • Focused security review covered wire/decompressed bounds, cancellation/abort behavior, empty-body compatibility, error mapping, mutation ordering, secrets, and unsafe defaults.
  • Upstream CI and explicit maintainer security review remain pending.

Draft pending upstream CI and the repository-required maintainer security review for management-boundary changes.

Review readiness checklist

This PR stays in draft until every box below is ticked. Tick all four boxes once the requirements are met:

  • All CI tests are green on my local testing.

  • I pushed my PR to the latest dev commit.

  • I resolved all correct Codex and CodeRabbit findings.

  • My PR is ready for review.

Summary by CodeRabbit

  • New Features

    • Claude Desktop integration can now be applied with selectable static, hybrid, or discovery modes.
    • Management requests support optional JSON bodies.
  • Bug Fixes

    • Improved handling of malformed, empty, oversized, and compressed request bodies.
    • Oversized requests are rejected with HTTP 413 without changing configuration.
    • Improved request cancellation and cleanup during body-size violations.
  • Tests

    • Expanded coverage for validation, streaming limits, compressed payloads, cancellation, and configuration safety.

@coderabbitai

coderabbitai Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The request-body reader now enforces streaming size limits and cancellation. Management routes accept optional JSON bodies, validate Claude Desktop apply modes, and defer state changes until validation succeeds. Tests cover malformed, oversized, compressed, empty, and streamed bodies.

Changes

Management request-body handling

Layer / File(s) Summary
Bounded streaming request reader
src/server/request-decompress.ts, tests/request-decompress.test.ts
Request bodies are read incrementally with wire-size and decompressed-size limits. The reader supports cancellation, abort reasons, cleanup, fragmented streams, and empty-body fallbacks.
Optional management JSON integration
src/server/management/body.ts, src/server/management/agent-settings-routes.ts, tests/claude-management-api.test.ts
Claude Desktop apply accepts an optional mode, validates supported values, and changes configuration only after body and profile validation succeeds. Tests cover malformed JSON, invalid profiles, and compressed oversized bodies.
Native apply stream rejection coverage
tests/native-claude-desktop-toggle.test.ts
Stream tests verify 413 responses, cancellation before sentinel chunks, zero configuration writes, and unchanged state for missing or misleading Content-Length headers.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ClaudeDesktopApplyRoute
  participant BoundedBodyReader
  participant Configuration
  Client->>ClaudeDesktopApplyRoute: Submit optional JSON body
  ClaudeDesktopApplyRoute->>BoundedBodyReader: Read bounded request stream
  BoundedBodyReader-->>ClaudeDesktopApplyRoute: Return body or size error
  ClaudeDesktopApplyRoute->>Configuration: Validate and apply profile
  Configuration-->>Client: Return success or error response
Loading

Possibly related PRs

  • lidge-jun/opencodex#1264: Both changes modify management Claude integration request-body validation and related tests.

Suggested reviewers: lidge-jun, wibias

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: bounding request bodies for the Claude Desktop apply endpoint.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

Deterministic PR hygiene checks passed.

@github-actions github-actions Bot added the bug Something isn't working label Aug 8, 2026
@github-actions

github-actions Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

⏳ DRAFT

  • review readiness checklist open (0/4 boxes ticked).

What to do

  • Tick all four boxes in the PR description once you're done (currently 0/4).

Review readiness checklist

  • ⬜ All CI tests are green on my local testing.
  • ⬜ I pushed my PR to the latest dev commit.
  • ⬜ I resolved all correct Codex and CodeRabbit findings.
  • ⬜ My PR is ready for review.

0/4 boxes ticked.

This PR stays in draft until every box above is ticked.

Port the Claude Desktop apply validation change onto current dev and stop raw request streams at the byte cap before full buffering. Missing or dishonest Content-Length values now cancel at the first overflow without waiting on hostile or teed streams, while preserving abort identity and existing 413 mappings.

Tests cover malformed and oversized compressed bodies, invalid profile no-mutation, absent and low Content-Length streams, exact-cap fragmentation, non-settling cancellation, and Claude Desktop config/file no-mutation.

luvs01 commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/server/request-decompress.ts`:
- Around line 217-219: Reorder the condition in the empty-body fallback check so
the `options && "emptyBodyFallback" in options` guard is evaluated before
`text.trim() === ""`. Preserve the existing fallback behavior for opted-in
callers while ensuring callers without options skip the full-body trim.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 34724dbd-3c40-4b65-9d14-2c43c6f6acc0

📥 Commits

Reviewing files that changed from the base of the PR and between e8ec8d1 and 20c2f8c.

📒 Files selected for processing (6)
  • src/server/management/agent-settings-routes.ts
  • src/server/management/body.ts
  • src/server/request-decompress.ts
  • tests/claude-management-api.test.ts
  • tests/native-claude-desktop-toggle.test.ts
  • tests/request-decompress.test.ts

Comment thread src/server/request-decompress.ts Outdated
Check optional fallback enrollment before scanning the decoded body for whitespace.
lidge-jun added a commit that referenced this pull request Aug 9, 2026
… closed (#1322)

Two of the four contributor-held PRs resolved. @Wibias met every condition on
#1244 -- rebase, Russian locale parity, two completed non-cancelled CI runs at
the same SHA -- including resolving the conflict I created by merging #1305.
Verified independently: two CI successes at d5e70a2 and a local full suite
of 10120 pass / 0 fail on that head. Landed as c75e68e, 58 files. #241
closed with its chain named, since #1244 references #1056 rather than #241.

#1301 rebased again after drifting 33 behind, then merged with --admin over a
red test 1/4. The failure is a 5000ms timeout in tests/crash-guard.test.ts,
which my one-file diff to tests/ci-workflows.test.ts cannot reach, and which
passes 14/14 locally three times. Logged as MERGE-DESPITE-CI with the reason
rather than as a clean green -- and recorded that this is the same shape of
reasoning I criticised as 'rerun until green' earlier.

#1272 hit a tenth #1302 occurrence and was rerun but NOT merged: it is still a
draft and those boxes are the contributor's attestation. A broken CI is not a
reason to tick them -- it is a reason not to, since they assert what CI can no
longer confirm.

Method note: rerun-failed-jobs overwrites the job log, so I destroyed the
#1302 evidence by fetching it after the rerun. Capture first, then rerun.
lidge-jun pushed a commit that referenced this pull request Aug 9, 2026
Stop raw request streams at the byte cap before full buffering and move
Desktop mutation after mode/profile validation. Missing or dishonest
Content-Length values now cancel at the first overflow instead of waiting
on hostile or teed streams, preserving abort identity and 413 mapping.

Squashed from PR #1272 (contributor branch carried dev merge commits).
@lidge-jun

Copy link
Copy Markdown
Owner

Landed on dev as 8e6d661. Your branch carried dev merge commits, so the net source diff was applied as a single commit with you as author rather than replaying the merges.

Independent security review passed. Confirmed the cap applies before allocation: readRequestBodyBytesCapped checks each chunk against maxBytes before growing its retained buffer, so a dishonest low Content-Length cannot force allocation against the claimed size, and compressed input is bounded twice (wire bytes before inflation, maxOutputLength during). Also confirmed the Desktop route now validates mode and profile before touching config or files.

The red aggregate CI on your head was an unrelated shard-4 hang in tests/cli-help.test.ts, not your change — it passes locally, and the full suite is green on the rebased head (10189 pass, 0 fail).

Thanks — cancelling at first overflow rather than draining the stream is the part that actually makes this a bound.

@lidge-jun lidge-jun closed this Aug 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants