Skip to content

fix(coordinator): cap plaintext inference request body - #338

Merged
Gajesh2007 merged 6 commits into
masterfrom
fix/coordinator-plaintext-body-cap
Jun 14, 2026
Merged

Gajesh2007 merged 6 commits into
masterfrom
fix/coordinator-plaintext-body-cap

Conversation

@anupsv

@anupsv anupsv commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

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

Path Body read Cap
Sealed (E2E ciphertext) io.ReadAll(http.MaxBytesReader(w, r.Body, 16<<20)) — sender_encryption.go:132 16 MiB ✅
Plaintext (/v1/chat/completions, /v1/completions) io.ReadAll(r.Body) — inference_preprocess.go (parseInferencePrelude) none ❌

Both plaintext handlers funnel through parseInferencePrelude, and io.ReadAll buffers the whole body up front (then NormalizeToolSchemas + parseJSONBody make 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

parseInferencePrelude now wraps r.Body in http.MaxBytesReader before reading and maps an over-cap read to HTTP 413:

r.Body = http.MaxBytesReader(w, r.Body, maxInferenceBodyBytes) // 16 MiB
rawBody, err := io.ReadAll(r.Body)
if err != nil {
    var maxBytesErr *http.MaxBytesError
    if errors.As(err, &maxBytesErr) { /* 413 */ }
    /* 400 */
}

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 (see console-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 in coordinator/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 MaxBytesReader makes 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.Body with no cap — POST /v1/invite/redeem (invite_handlers.go, API-key authed), and the unauthenticated enroll.go / device_auth.go sinks (json.NewDecoder still 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-body MaxBytesReader middleware (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.

@vercel

vercel Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 14, 2026 7:56pm
d-inference-console-ui-dev Ready Ready Preview Jun 14, 2026 7:56pm
d-inference-landing Ready Ready Preview Jun 14, 2026 7:56pm

Request Review

@github-actions

github-actions Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

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 affected_files lists.


Trust boundaries touched

  • TB-001 (Consumer → Coordinator): coordinator/api/consumer.go, coordinator/api/server.go, coordinator/api/inference_preprocess.go all sit on the hot path for authenticated inference requests.

Threat model file-pattern gaps

None of the changed files are listed in any affected_files entry, but several changes are security-relevant:

File Relevant threat(s) Notes
coordinator/api/inference_preprocess.go T-002 / SEC-006 If this introduces body parsing (e.g. json.Unmarshal, io.ReadAll) before a size cap is applied, it touches the open unbounded-body finding directly.
coordinator/api/inference_body_cap_test.go T-002 / SEC-006 Name strongly implies a body-size cap is being added — this would be a ✅ fix for SEC-006. Confirm MaxBytesReader (or equivalent) is applied before io.ReadAll in consumer.go.
coordinator/api/inference_body_remarshal_integration_test.go T-002 Re-marshalling a parsed body can silently re-inflate it past the cap if the cap is applied to the raw wire bytes but the re-marshalled form is passed downstream unchecked. Verify the cap survives the remarshal step.
coordinator/api/consumer.go T-002, T-005 Core inference handler; any change here should be audited for body-read order vs cap, and for usage-row write ordering (bill before return).
coordinator/api/server.go T-004, T-038 Middleware chain ordering and HTTP server config live here. Confirm ReadHeaderTimeout / MaxHeaderBytes are not regressed, and that admin vs consumer middleware scope is unchanged.
console-ui/src/lib/chat-messages.ts + chat-messages.test.ts T-018 If this touches the Zustand store serialization or what gets persisted to localStorage, it intersects the open SEC-024 finding (chat history not cleared on logout).

Potential new attack surface not covered by an existing threat

Re-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 r.Body read would not bound the downstream buffer. This is a new variant of T-002 not explicitly described in the threat model and should be added as a sub-finding under SEC-006.


Recommended threat model updates

The following affected_files entries should be extended:

  • T-002 / SEC-006: add coordinator/api/inference_preprocess.go, coordinator/api/consumer.go
  • T-004: add coordinator/api/server.go
  • T-018 / SEC-024: add console-ui/src/lib/chat-messages.ts
  • T-038 / SEC-027: add coordinator/api/server.go

SEC-* resolution signal

If inference_body_cap_test.go confirms a MaxBytesReader is now applied to all plaintext inference endpoints, this PR likely resolves SEC-006. Please confirm the cap is wired in consumer.go at coordinator/api/consumer.go:526 and ~:2359 (the two open call sites noted in TB-001) and update the finding status accordingly.


🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

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).
@anupsv
anupsv force-pushed the fix/coordinator-plaintext-body-cap branch from d5fd9eb to 39e8692 Compare June 14, 2026 04:25
@anupsv anupsv changed the title fix(coordinator): cap plaintext inference request body (OOM-M1) fix(coordinator): cap plaintext inference request body Jun 14, 2026
ethenotethan

This comment was marked as outdated.

ethenotethan

This comment was marked as outdated.

@Gajesh2007

Copy link
Copy Markdown
Member

@codex review this

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 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".

Comment thread coordinator/api/inference_preprocess.go Resolved

@ethenotethan ethenotethan 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.

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

Comment thread coordinator/api/inference_preprocess.go Resolved
Comment thread console-ui/src/lib/chat-messages.ts Resolved
Comment thread console-ui/src/lib/chat-messages.ts Resolved
@blacksmith-sh

blacksmith-sh Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Found 1 test failure on Blacksmith runners:

Failure

Test View Logs
github.com/eigeninference/d-inference/e2e/TestProfile_SingleProviderNonStreaming View Logs

Fix with Codesmith
Need help on this PR? Tag /codesmith with what you need.

… (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 ethenotethan 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.

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

Comment thread coordinator/api/inference_preprocess.go Resolved
Comment thread console-ui/src/lib/chat-messages.ts Resolved
Comment thread coordinator/api/inference_preprocess.go Resolved
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.
ethenotethan

This comment was marked as outdated.

…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 ethenotethan 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.

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

Comment thread coordinator/api/inference_preprocess.go Resolved
Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/api/inference_preprocess.go Resolved
Comment thread console-ui/src/lib/chat-messages.ts Resolved
Comment thread coordinator/api/inference_preprocess.go Resolved
Comment thread coordinator/api/inference_preprocess.go Resolved
Comment thread console-ui/src/lib/chat-messages.ts Resolved
Comment thread coordinator/api/consumer.go Resolved
@anupsv

anupsv commented Jun 14, 2026

Copy link
Copy Markdown
Contributor Author

@codex review this

Focus on the body-cap completeness fix at HEAD (0b3e3d02 + 9a042c05):

  • The plaintext inference body is capped at read (maxInferenceBodyBytes = 16 MiB), but the handlers re-marshal parsed before sealing it and sending it to a provider as one WebSocket frame. Go's json.Marshal HTML-escapes </>/& (~6×), which can re-inflate a capped body past the provider's 32 MiB frame limit and tear down its session.
  • Fix: every forward-marshal site now uses marshalForwardBody (SetEscapeHTML(false)), and there's a single authoritative cap on the final body at the point rawBody is frozen into dispatchState (chat) / before seal (generic).

Please verify completeness: enumerate every assignment to rawBody/inferenceBody and every body handed to e2e.Encrypt (consumer.go dispatchOneProvider, generic inline, dispatch.go speculative/retry), and confirm nothing re-marshals or seals an un-capped / HTML-escaped body on any path (self-route, allowlist, Responses, alias-capacity fallback, queue/retry).

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 0b3e3d02ea

ℹ️ 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".

@Gajesh2007
Gajesh2007 merged commit 431b199 into master Jun 14, 2026
51 of 55 checks passed
jonathan308 added a commit that referenced this pull request Oct 22, 2026
…4a297e2 (#338)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Oct 22, 2026
…7bed8216 (#338)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch had an error being deployed

1 failed and 3 active deployments
benchmarks — 0b3e3d02 Deployed Jun 14, 2026 by anupsv via E2E Benchmarks #875
Preview – d-inference-console-ui-dev — 0b3e3d02 Deployed Jun 14, 2026 by vercel[bot]
Preview – d-inference — 0b3e3d02 Deployed Jun 14, 2026 by vercel[bot]
Preview – d-inference-landing — 0b3e3d02 Deployed Jun 14, 2026 by vercel[bot]
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