Repository navigation
fix(coordinator): cap plaintext inference request body - #338
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This PR modifies coordinator inference preprocessing and the console-UI chat message library — the coordinator files directly touch TB-001 mitigations and should be added to the threat model's Trust boundaries touched
Threat model file-pattern gapsNone of the changed files are listed in any
Potential new attack surface not covered by an existing threatRe-marshal amplification (inference_preprocess.go + consumer.go): If the preprocessing step deserializes the request body into a Go struct and then re-serializes it for downstream routing, the re-serialized form could be larger than the original (e.g. escaped unicode, added whitespace, or additional fields injected by default struct values). A body cap applied only to the inbound Recommended threat model updatesThe following
SEC-* resolution signalIf 🔐 Threat model: |
The plaintext inference path (handleChatCompletions / handleGenericInference -> parseInferencePrelude) read the request body with an unbounded io.ReadAll(r.Body), so any API-key holder could POST a multi-GB JSON body and OOM the coordinator — the trusted TEE component. The sealed (E2E) path already caps at 16 MiB via http.MaxBytesReader (sender_encryption.go); the common plaintext path had no limit. Model-independent (the read is in the shared prelude, before routing). parseInferencePrelude now wraps r.Body in http.MaxBytesReader and maps an over-cap read to HTTP 413. The cap is 64 MiB — sized to the first-party UI's per-message image limit (MAX_IMAGES_PER_MESSAGE=4 x MAX_IMAGE_BYTES=10 MB = 40 MB raw ~= 53 MiB after base64, plus JSON/text overhead) so legitimate multimodal requests aren't rejected (a 16 MiB cap would 413 two max-size images). Regression: an oversized body (streamed, not allocated) -> 413; a small invalid-JSON body -> 400 (not 413). Verified the oversized test fails without the cap (falls through to 400).
d5fd9eb to
39e8692
Compare
|
@codex review this |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a618f78681
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 1 finding(s) (1 blocking)
- 🔴 [CRITICAL]
coordinator/api/inference_preprocess.go:55-56— io.ReadAll with unbounded body could cause OOM attacks- Suggestion: The fix correctly adds http.MaxBytesReader to cap the body size before io.ReadAll - this prevents attackers from sending multi-GB bodies to OOM the coordinator
Type_diligence — ✅ No issues found
Additive_complexity — 2 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/lib/chat-messages.ts:22-35— Complex image filtering logic could be simplified with a single pass- Suggestion: Replace the two-pass approach (findNewestImageIndex + flatMap) with a single reverse iteration that builds the result array directly, eliminating the helper function and reducing cognitive load
- 🔵 [INFO]
console-ui/src/lib/chat-messages.ts:38-49— Unnecessary helper function for simple reverse iteration- Suggestion: Inline this logic into the main function since it's only used once and the reverse iteration pattern is straightforward
3 finding(s) total, 2 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
|
Found 1 test failure on Blacksmith runners: Failure
|
… (16 MiB) Review (P1) caught that the 64 MiB cap exceeds what providers can receive: the coordinator sends the encrypted request as ONE WebSocket frame (base64 NaCl-box), and the Swift provider rejects frames >32 MiB by tearing down the session and cancelling every unrelated in-flight request. base64 adds x4/3, so a body over ~24 MiB produced an oversized frame — passing the prelude only to disconnect the provider instead of returning a clean 413. Lower to 16 MiB to match the provider's documented frame budget (16 MiB body -> ~21.3 MiB frame, comfortably under 32 MiB) and the sealed path. The console's image-history trim is complementary, but a single 4x10MB turn still exceeds this and is undeliverable — aligning the per-turn UI image budget with the frame cap is tracked separately. Also dedupes the infiniteReader test helper (now shared from body_cap_test.go after the global body-cap change merged) and drops a stale finding-id comment.
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — ✅ No issues found
Performance — 1 finding(s) (1 blocking)
- 🔴 [CRITICAL]
coordinator/api/inference_preprocess.go:40— maxInferenceBodyBytes set to 16 MiB but PR description claims 64 MiB cap- Suggestion: Update constant to match PR description: const maxInferenceBodyBytes = 64 << 20 // 64 MiB
Type_diligence — ✅ No issues found
Additive_complexity — 2 finding(s) (1 blocking)
- 🟡 [MEDIUM]
console-ui/src/lib/chat-messages.ts:21-36— Complex message filtering logic could be simplified with a single pass- Suggestion: Replace the two-pass approach (findNewestImageMessageIndex + flatMap) with a single reverse iteration that builds the result array directly, eliminating the helper function and reducing cognitive load
- 🔵 [INFO]
coordinator/api/inference_preprocess.go:15-41— Long comment explains provider WebSocket constraints but introduces coupling- Suggestion: Move the provider-specific frame size reasoning to a separate constant or config section, keeping the security comment focused on the OOM protection aspect
3 finding(s) total, 2 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
The 16 MiB read cap bounds the request as received, but the chat/generic handlers re-marshal the parsed body before sealing it (max_tokens injection, Responses->chat lowering, tool normalization). encoding/json's default Marshal HTML-escapes '<' '>' '&' into 6-byte \uXXXX forms, so a benign request that fit the read cap — e.g. a prompt with a long run of '<' — could re-marshal ~6x larger and seal into a WebSocket frame the provider rejects by tearing down its session and cancelling every unrelated in-flight request. Two-part fix: - marshalForwardBody: re-marshal with HTML escaping disabled (the body is sealed and parsed as JSON by the provider, never embedded in HTML), so the forwarded body tracks the size-capped input instead of inflating. - Re-check maxInferenceBodyBytes on the FINAL sealed body in both handlers, before the balance reservation (chat) or with a refund (generic), returning a clean 413 instead of disconnecting a provider mid-flight. Adds TestMarshalForwardBodyDoesNotHTMLEscape and refreshes the now-stale maxRequestBodyBytes comment.
…le freeze-point cap Follow-up review found the prior commit was incomplete: the chat handler re-marshals the parsed body in five more places besides the two it fixed — alias resolution, allowlist/routing-field stripping, reasoning_parser injection, and (the live escape) the alias-capacity fallback that switches a saturated desired build to its previous build. All used the HTML-escaping json.Marshal, and the fallback's result is what gets frozen into dispatchState and sealed — so a '<'-heavy request taking the fallback could still inflate ~6x and seal an oversized frame, tearing down the provider session. - Switch every forward-marshal site in the chat path to marshalForwardBody. - Replace the mid-handler cap recheck with a single authoritative cap at the point rawBody is frozen into dispatchState — after ALL re-marshals including the fallback — so one check covers every upstream mutation. Refunds the held reservation before the 413. - Add TestAliasCapacityFallbackForwardsUnescapedBody: drives a real request through the alias-capacity fallback over the WS protocol and asserts the body the provider decrypts is unescaped. Verified it fails (\u003c detected) when any fallback marshal site regresses to json.Marshal.
ethenotethan
left a comment
There was a problem hiding this comment.
Automated Code Review — Layr-Labs/d-inference#
Verdict: REQUEST_CHANGES
Security — 1 finding(s)
- 🔵 [INFO]
coordinator/api/inference_preprocess.go:48— Hardcoded body size limit may be insufficient for legitimate use cases- Suggestion: Consider making maxInferenceBodyBytes configurable or document the 16 MiB limit clearly for users
Performance — 4 finding(s) (2 blocking)
- 🟡 [MEDIUM]
coordinator/api/consumer.go:1583-1602— Body size check after multiple re-marshaling operations creates redundant work- Suggestion: Move the size check earlier in the pipeline or track body size during mutations to avoid repeated marshaling overhead
- 🟡 [MEDIUM]
coordinator/api/consumer.go:4220-4236— Duplicate body size validation in handleGenericInference after re-marshaling- Suggestion: Consolidate size validation logic to avoid checking the same constraint twice in similar code paths
- 🔵 [INFO]
coordinator/api/inference_preprocess.go:49-57— marshalForwardBody creates intermediate buffer for every request- Suggestion: Consider pooling bytes.Buffer instances or using json.Marshal with SetEscapeHTML(false) on a reused encoder to reduce allocations
- 🔵 [INFO]
console-ui/src/lib/chat-messages.ts:26-36— findNewestImageMessageIndex reverses array and iterates backwards inefficiently- Suggestion: Iterate the original array backwards with a simple for loop: for (let i = messages.length - 1; i >= 0; i--) to avoid array copying
Type_diligence — 1 finding(s)
- 🔵 [INFO]
coordinator/api/inference_preprocess.go:49— marshalForwardBody accepts bare any parameter- Suggestion: Consider constraining the parameter type to map[string]any or a specific struct type if the function only handles JSON-serializable request bodies
Additive_complexity — 3 finding(s) (1 blocking)
- 🔵 [INFO]
coordinator/api/inference_preprocess.go:48-57— custom JSON marshaler duplicates encoding/json functionality- Suggestion: use json.Marshal with SetEscapeHTML(false) called once on a shared encoder, or document why this custom approach is necessary
- 🟡 [MEDIUM]
console-ui/src/lib/chat-messages.ts:38-49— complex image filtering logic could be simplified- Suggestion: consider a simpler approach like keeping only the last N messages with images, or extracting this to a dedicated function with clearer naming
- 🔵 [INFO]
coordinator/api/consumer.go:1598-1603— duplicate body size check in two handlers- Suggestion: extract the body size validation into a shared helper function used by both handleChatCompletions and handleGenericInference
9 finding(s) total, 3 blocking. Verdict: REQUEST_CHANGES.
🤖 Automated review by Centaur · DAR-186
|
@codex review this Focus on the body-cap completeness fix at HEAD (
Please verify completeness: enumerate every assignment to |
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…4a297e2 (#338) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…7bed8216 (#338) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Summary
Caps the plaintext inference request body. The common (non-sealed) path read the body with an unbounded
io.ReadAll(r.Body), so any API-key holder could POST a multi-GB JSON body and OOM the coordinator — the trusted TEE component.The asymmetry
io.ReadAll(http.MaxBytesReader(w, r.Body, 16<<20))—sender_encryption.go:132/v1/chat/completions,/v1/completions)io.ReadAll(r.Body)—inference_preprocess.go(parseInferencePrelude)Both plaintext handlers funnel through
parseInferencePrelude, andio.ReadAllbuffers the whole body up front (thenNormalizeToolSchemas+parseJSONBodymake further copies). Authenticated, but an API key is cheap and the victim is the trusted coordinator — model-independent (the read is in the shared prelude, before routing).Fix
parseInferencePreludenow wrapsr.Bodyinhttp.MaxBytesReaderbefore reading and maps an over-cap read to HTTP 413:The cap is 64 MiB, sized to the first-party UI's per-message image limit so legitimate multimodal requests aren't rejected:
MAX_IMAGES_PER_MESSAGE(4) ×MAX_IMAGE_BYTES(10 MB) = 40 MB raw ≈ 53 MiB after base64, plus JSON/text overhead (seeconsole-ui/src/lib/image-upload.ts). A 16 MiB cap (the sealed-path value) would 413 two max-size images; this is the plaintext image path, so it's sized for that. The sealed E2E path keeps its own 16 MiB cap (sender_encryption.go).Test plan
go test ./coordinator/api/— pass (full package, no regression). New tests incoordinator/api/inference_body_cap_test.go:TestParseInferencePreludeRejectsOversizedBody— a body one byte over the cap → 413.TestParseInferencePreludeUnderCapNotSizeRejected— a small invalid-JSON body → 400 (not 413), proving the cap fires only on size and never false-triggers.Verified the tests fail without the fix: removing the
MaxBytesReadermakes the oversized test get 400 instead of 413.Known related, NOT in this PR
Review flagged that the same OOM class is reachable via other consumer endpoints that decode
r.Bodywith no cap —POST /v1/invite/redeem(invite_handlers.go, API-key authed), and the unauthenticatedenroll.go/device_auth.gosinks (json.NewDecoderstill buffers a giant body to find a parse error). This PR is scoped to the reported plaintext inference-path body OOM. The sibling endpoints want their own fix — most cleanly a small global request-bodyMaxBytesReadermiddleware (none exists today; caps are per-handler). Tracking separately.Context
Pre-existing on
master; fixed here so all branches inherit it. Sibling of #337 (provider-side unbounded chunk accumulation) — both let a caller OOM the trusted TEE coordinator via unbounded buffering: this one on consumer ingress, #337 on provider egress.