Skip to content

fix(coordinator): cap request body size globally + tighten unauth endpoints - #339

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

Gajesh2007 merged 2 commits into
masterfrom
fix/coordinator-global-body-cap

Conversation

@anupsv

@anupsv anupsv commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Caps the size of every consumer request body so an unbounded POST can't OOM the coordinator (the trusted TEE component). Several endpoints decoded r.Body with no limit — worst on the unauthenticated control-plane endpoints, which need no credential at all.

The problem

json.Decoder.Decode / io.ReadAll buffer the request body with no cap on many routes. A multi-GB POST is allocated in full before the handler can validate or reject it. The most exposed are unauthenticated:

Endpoint Auth
POST /v1/enroll none
POST /v1/device/token none
POST /v1/admin/auth/init none (sends OTP)
POST /v1/admin/auth/verify none (returns token)

…and the same uncapped pattern exists on API-key (invite/redeem) and authed (billing, model, release) decoders.

The fix — one ceiling + tight caps where it counts

  • bodyLimitMiddleware (added to Handler(): cors(recover(logging(bodyLimit(mux))))) wraps every request body in http.MaxBytesReader at a 64 MiB global ceiling, so every route is bounded in one place. The ceiling clears the largest legitimate body (the 64 MiB plaintext-inference image path). /ws/provider is exempt — it hijacks the connection and reads framed messages (bounded separately by SetReadLimit), not r.Body.
  • decodeCappedJSON applies a tight 64 KiB cap on the four unauthenticated control-plane endpoints (they carry small fixed structs): over-cap → 413, malformed → 400.
  • Nothing loosens: existing tighter per-handler caps (sealed 16 MiB, telemetry/release 64 KiB, MDM 1 MiB) are inner MaxBytesReaders, so they still fire first.

Test plan

go test ./coordinator/api/ — full package green (no regression from the handler changes). New tests in coordinator/api/body_cap_test.go:

  • TestBodyLimitMiddlewareCapsOversizedBody — an over-ceiling body on a normal route is capped (*http.MaxBytesError).
  • TestBodyLimitMiddlewareExemptsProviderWS — /ws/provider is not capped.
  • TestDecodeCappedJSON — over-cap → 413, malformed → 400, valid → decoded.

Verified the load-bearing test fails without the fix: removing the middleware's MaxBytesReader makes the caps test read the full stream (nil instead of *http.MaxBytesError).

Context

Pre-existing on master; fixed here so all branches inherit it. Completes the consumer-side body bounding (the inference-body cap is in #338; this global middleware also covers that path) and is the ingress sibling of the provider-side chunk-accumulation issue (#337).


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

…points

Several consumer endpoints decoded the request body with no size limit, so a
caller could POST a multi-GB body and OOM the coordinator (the trusted TEE
component). Worst on the unauthenticated control-plane endpoints (enroll, device
token, admin auth init/verify), which need no credential at all; also reachable
via the API-key invite/redeem and the authed billing/model/release decoders.

- bodyLimitMiddleware: a global 64 MiB ceiling on every request body (clears the
  largest legitimate body, the plaintext-inference image path). The provider
  WebSocket upgrade is exempt — it hijacks the connection and reads framed
  messages, not r.Body. Per-handler tighter caps still win (nested readers), so
  nothing loosens (sealed 16 MiB, telemetry/release 64 KiB, MDM 1 MiB).
- decodeCappedJSON: a tight 64 KiB cap on the unauthenticated control-plane
  endpoints (enroll, device/token, admin/auth/init+verify), which carry small
  fixed structs. Over-cap -> 413, malformed -> 400.

Tests: middleware caps an oversized body + exempts /ws/provider; decodeCappedJSON
413/400/ok. Full api package green.
@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 6:46pm
d-inference-console-ui-dev Ready Ready Preview Jun 14, 2026 6:46pm
d-inference-landing Ready Ready Preview Jun 14, 2026 6:46pm

Request Review

@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 — 2 finding(s) (2 blocking)

  • 🟡 [MEDIUM] coordinator/api/body_cap_test.go:29-30 — io.Copy with unbounded reader could allocate large buffer
    • Suggestion: Use io.CopyN or io.LimitReader to bound the copy operation in tests
  • 🟡 [MEDIUM] coordinator/api/body_cap_test.go:47-48 — io.Copy with unbounded reader could allocate large buffer
    • Suggestion: Use io.CopyN or io.LimitReader to bound the copy operation in tests

Type_diligence — 1 finding(s)

  • 🔵 [INFO] coordinator/api/server.go:1707 — decodeCappedJSON uses bare any parameter for dst
    • Suggestion: Consider using a generic type parameter like func decodeCappedJSON[T any](w http.ResponseWriter, r *http.Request, maxBytes int64, dst *T) bool to provide compile-time type safety

Additive_complexity — 2 finding(s)

  • 🔵 [INFO] coordinator/api/body_cap_test.go:13-20 — Custom infiniteReader reimplements strings.Repeat functionality
    • Suggestion: Use strings.NewReader(strings.Repeat("a", size)) instead of custom infiniteReader type
  • 🔵 [INFO] coordinator/api/server.go:1707-1722 — decodeCappedJSON helper adds abstraction layer for simple JSON decode pattern
    • Suggestion: Consider inlining the MaxBytesReader + Decode pattern in handlers since it's only used in 4 places and the abstraction doesn't significantly reduce complexity

5 finding(s) total, 2 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment on lines +29 to +30
h := s.bodyLimitMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, readErr = io.Copy(io.Discard, r.Body)

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.

🟡 [MEDIUM] ⚡ io.Copy with unbounded reader could allocate large buffer

💡 Suggestion: Use io.CopyN or io.LimitReader to bound the copy operation in tests

📊 Score: 2×4 = 8 · Category: Unbounded allocations

Comment on lines +47 to +48
h := s.bodyLimitMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, readErr = io.Copy(io.Discard, r.Body)

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.

🟡 [MEDIUM] ⚡ io.Copy with unbounded reader could allocate large buffer

💡 Suggestion: Use io.CopyN or io.LimitReader to bound the copy operation in tests

📊 Score: 2×4 = 8 · Category: Unbounded allocations

Comment thread coordinator/api/server.go
// decodeCappedJSON JSON-decodes the request body under a hard size cap, writing
// a 413 (too large) or 400 (bad JSON) and returning false on failure. For small
// unauthenticated control-plane endpoints that must not buffer an unbounded body.
func decodeCappedJSON(w http.ResponseWriter, r *http.Request, maxBytes int64, dst any) bool {

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.

🔵 [INFO] 🏷️ decodeCappedJSON uses bare any parameter for dst

💡 Suggestion: Consider using a generic type parameter like func decodeCappedJSON[T any](w http.ResponseWriter, r *http.Request, maxBytes int64, dst *T) bool to provide compile-time type safety

📊 Score: 2×1 = 2 · Category: bare_any_parameter

Comment on lines +13 to +20
// over-cap body without allocating it, so the cap surfaces as a read error.
type infiniteReader struct{}

func (infiniteReader) Read(p []byte) (int, error) {
for i := range p {
p[i] = 'a'
}
return len(p), nil

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.

🔵 [INFO] 🧩 Custom infiniteReader reimplements strings.Repeat functionality

💡 Suggestion: Use strings.NewReader(strings.Repeat("a", size)) instead of custom infiniteReader type

📊 Score: 2×3 = 6 · Category: reinventing stdlib

Comment thread coordinator/api/server.go
Comment on lines +1707 to 1722
func decodeCappedJSON(w http.ResponseWriter, r *http.Request, maxBytes int64, dst any) bool {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
if err := json.NewDecoder(r.Body).Decode(dst); err != nil {
var maxErr *http.MaxBytesError
if errors.As(err, &maxErr) {
writeJSON(w, http.StatusRequestEntityTooLarge,
errorResponse("invalid_request_error", "request body too large"))
return false
}
writeJSON(w, http.StatusBadRequest,
errorResponse("invalid_request_error", "invalid JSON"))
return false
}
return true
}

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.

🔵 [INFO] 🧩 decodeCappedJSON helper adds abstraction layer for simple JSON decode pattern

💡 Suggestion: Consider inlining the MaxBytesReader + Decode pattern in handlers since it's only used in 4 places and the abstraction doesn't significantly reduce complexity

📊 Score: 2×2 = 4 · Category: over-abstraction

@github-actions

github-actions Bot commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor

This is a positive, targeted hardening change that adds a missing request-body size cap to the enrollment endpoint, reducing DoS exposure on the control plane.


Trust Boundaries Touched

  • TB-001 — Consumer → Coordinator API (enrollment is an unauthenticated or pre-auth HTTP endpoint reachable by external parties)
  • TB-005 — Coordinator → Apple MDM/MDA (enroll.go is the entry point for the MDM enrollment flow)

Threat Assessment

Threat Status Notes
T-041 (Configuration-profile signing identity exfiltration / misuse) ✅ Strengthens The enrollment handler is the signing surface for the .mobileconfig. Before this change, json.NewDecoder(r.Body).Decode() imposed no size cap, meaning an unauthenticated caller could stream an arbitrarily large body into the enrollment handler — one of the few places that triggers the profile-signing code path. The replacement decodeCappedJSON(w, r, maxControlPlaneBodyBytes, &req) enforces the shared control-plane body limit, closing an incidental DoS vector against the signing path.
T-002 (Unbounded request body causes coordinator OOM) ✅ Strengthens SEC-006 tracks uncapped io.ReadAll/json.Decode calls. handleEnroll was one such site; this PR fixes it consistently with how other control-plane handlers are already hardened.
T-021 (Unauthenticated MDM webhook injection) ℹ️ Neutral This change tightens the enrollment request body, not the MDM webhook body. TB-005's main open finding (unauthenticated POST /v1/mdm/webhook with no MaxBytesReader) is untouched; SEC-004 remains open.

New Attack Surface

None introduced. The diff removes a code path and delegates to an already-audited shared helper.


Open Findings Resolved

  • Partial progress toward SEC-006 — handleEnroll is now capped. The bulk of SEC-006 (inference endpoints in consumer.go:526, 2359) remains open and is out of scope for this PR.

Minor Notes

  • maxControlPlaneBodyBytes is referenced but not shown in the diff. Reviewers should confirm the constant is defined at a sane value (e.g. ≤ 64 KB for an enrollment request containing only a serial number and public key) and that decodeCappedJSON returns a non-2xx status and stops reading on limit breach — both to ensure the body is not partially consumed before the cap triggers.
  • The removed "encoding/json" import confirms no other JSON decode site in this file was missed.

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

@Gajesh2007

Copy link
Copy Markdown
Member

@codex review this

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: e398a964c3

ℹ️ 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 689a367 into master Jun 14, 2026
13 of 15 checks passed

@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 — 2 finding(s) (2 blocking)

  • 🟡 [MEDIUM] coordinator/api/body_cap_test.go:29 — io.Copy with unbounded source could allocate large buffers
    • Suggestion: Use io.CopyN or io.LimitReader to bound the copy operation in tests
  • 🟡 [MEDIUM] coordinator/api/body_cap_test.go:47 — io.Copy with unbounded source could allocate large buffers
    • Suggestion: Use io.CopyN or io.LimitReader to bound the copy operation in tests

Type_diligence — 1 finding(s)

  • 🔵 [INFO] coordinator/api/server.go:1736 — decodeCappedJSON uses bare any parameter for dst
    • Suggestion: Consider using a generic type parameter like func decodeCappedJSON[T any](w http.ResponseWriter, r *http.Request, maxBytes int64, dst *T) bool to provide compile-time type safety

Additive_complexity — 3 finding(s)

  • 🔵 [INFO] coordinator/api/body_cap_test.go:13-20 — Custom infiniteReader when strings.Repeat or io.LimitReader(strings.NewReader()) would be simpler
    • Suggestion: Use strings.Repeat to create a large string or io.LimitReader(strings.NewReader(largeString), limit) instead of custom infiniteReader type
  • 🔵 [INFO] coordinator/api/body_cap_test.go:26-39 — Test creates complex setup when httptest could simulate oversized body more directly
    • Suggestion: Consider using strings.NewReader with a pre-allocated large string instead of infiniteReader + io.LimitReader pattern
  • 🔵 [INFO] coordinator/api/server.go:1726-1730 — Body size limiting logic mixed with path-based exemption creates coupling
    • Suggestion: Consider extracting path exemption logic to a separate function or using a more explicit routing approach for WebSocket endpoints

6 finding(s) total, 2 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

func TestBodyLimitMiddlewareCapsOversizedBody(t *testing.T) {
s := &Server{}
var readErr error
h := s.bodyLimitMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

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.

🟡 [MEDIUM] ⚡ io.Copy with unbounded source could allocate large buffers

💡 Suggestion: Use io.CopyN or io.LimitReader to bound the copy operation in tests

📊 Score: 2×4 = 8 · Category: Unbounded allocations

func TestBodyLimitMiddlewareExemptsProviderWS(t *testing.T) {
s := &Server{}
var readErr error
h := s.bodyLimitMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

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.

🟡 [MEDIUM] ⚡ io.Copy with unbounded source could allocate large buffers

💡 Suggestion: Use io.CopyN or io.LimitReader to bound the copy operation in tests

📊 Score: 2×4 = 8 · Category: Unbounded allocations

Comment thread coordinator/api/server.go
// decodeCappedJSON JSON-decodes the request body under a hard size cap, writing
// a 413 (too large) or 400 (bad JSON) and returning false on failure. For small
// unauthenticated control-plane endpoints that must not buffer an unbounded body.
func decodeCappedJSON(w http.ResponseWriter, r *http.Request, maxBytes int64, dst any) bool {

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.

🔵 [INFO] 🏷️ decodeCappedJSON uses bare any parameter for dst

💡 Suggestion: Consider using a generic type parameter like func decodeCappedJSON[T any](w http.ResponseWriter, r *http.Request, maxBytes int64, dst *T) bool to provide compile-time type safety

📊 Score: 2×1 = 2 · Category: bare_any_parameter

Comment on lines +13 to +20
// over-cap body without allocating it, so the cap surfaces as a read error.
type infiniteReader struct{}

func (infiniteReader) Read(p []byte) (int, error) {
for i := range p {
p[i] = 'a'
}
return len(p), nil

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.

🔵 [INFO] 🧩 Custom infiniteReader when strings.Repeat or io.LimitReader(strings.NewReader()) would be simpler

💡 Suggestion: Use strings.Repeat to create a large string or io.LimitReader(strings.NewReader(largeString), limit) instead of custom infiniteReader type

📊 Score: 2×3 = 6 · Category: reinventing stdlib

Comment on lines +26 to +39
func TestBodyLimitMiddlewareCapsOversizedBody(t *testing.T) {
s := &Server{}
var readErr error
h := s.bodyLimitMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, readErr = io.Copy(io.Discard, r.Body)
}))
req := httptest.NewRequest(http.MethodPost, "/v1/enroll",
io.LimitReader(infiniteReader{}, int64(maxRequestBodyBytes)+1))
h.ServeHTTP(httptest.NewRecorder(), req)

var maxErr *http.MaxBytesError
if !errors.As(readErr, &maxErr) {
t.Fatalf("expected the body to be capped (*http.MaxBytesError), got %v", readErr)
}

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.

🔵 [INFO] 🧩 Test creates complex setup when httptest could simulate oversized body more directly

💡 Suggestion: Consider using strings.NewReader with a pre-allocated large string instead of infiniteReader + io.LimitReader pattern

📊 Score: 1×2 = 2 · Category: over-abstraction

Comment thread coordinator/api/server.go
Comment on lines +1726 to +1730
if r.Body != nil && r.URL.Path != "/ws/provider" {
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes)
}
next.ServeHTTP(w, r)
})

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.

🔵 [INFO] 🧩 Body size limiting logic mixed with path-based exemption creates coupling

💡 Suggestion: Consider extracting path exemption logic to a separate function or using a more explicit routing approach for WebSocket endpoints

📊 Score: 2×3 = 6 · Category: misplaced responsibility

jonathan308 added a commit that referenced this pull request Oct 24, 2026
…SDK main)

Pins libs/mlx-swift-lm to Layr-Labs/mlx-swift-lm#356's head efd38585:
#342 + #354 + #353 + #355 merged with SDK main 755bdf67, which carries
#339 (upstream sync 2026-10-22), #349 and #348. The SDK pins mlx-swift
6c31f9f1 (#349: compiled traces keyed by the task's default stream), so
libs/mlx-swift moves 67dc7528 -> 6c31f9f1 (nested mlx 83dbdb04, mlx-c
cb19abf6) and libs/mlx moves ad4745a2 -> 83dbdb04 in lockstep; the
provider links the local mlx-swift, and scripts/fetch-metallib.sh builds
the metallib from its nested mlx (ca34a2e8..., was 156f2624...).
provider-swift/Package.resolved is unchanged.

API adaptations, each the minimal change to the upstream API:
- MLXLLM.Gemma4AssistantDraftModel: upstream added an MLXVLM type of the
  same name; the provider keeps the fork's MLXLLM drafter it always used
  (EngineV2MTPAssistant, ProviderBenchmark BackendParityHarness and
  MTPProductionSession).
- LanguageModel.prepare(_:cache:state:prefill:) replaces
  prepare(_:cache:windowSize:): GLM5NextProtectedModel forwards the new
  arguments to its root (no provider caller; serving runs through the
  native steppable), and 25 test stubs take the new signature.
- newCache(parameters:) throws: GLM5NextProtectedModel forwards with try;
  ThroughputSweep's default caches use try? (nil parameters cannot fail
  validation, as the SDK's own probes do).
- UserInput.Image and UserInput.Video are structs with a source enum:
  MediaIngest's realized-extent check and the MiMo encoded-media ingress
  match on .source; 9 test patterns likewise.
- Qwen35Model.sanitize(weights:) throws: EngineV2VLMTextExtraction.
  reKeyedQwenTargetWeights propagates it (its caller already throws).
- Generation gained .rejectedToolCall: ModelBenchmark ignores it, as it
  ignores .toolCall.
- GatedDeltaPrefill moved from MLXLLM to MLXLMCommon: the LaunchAgent
  passthrough test imports MLXLMCommon @testable; LaunchAgent's comment
  names the new module; four docs cite
  Libraries/MLXLMCommon/GatedDelta.swift (docs-check follows the pin).
jonathan308 added a commit that referenced this pull request Oct 24, 2026
…n trait

The synced SDK (mlx-swift-lm #356, with #339) enables its
FoundationModelsIntegration trait by default. Through MLXLMServer ->
MLXHuggingFace -> MLXFoundationModels -> MLXGuidedGeneration ->
MLXCXGrammar, that trait linked three things into the provider:

- an adapter for Apple's FoundationModels framework (gated at macOS 27);
- a weak FoundationModels.framework load;
- the vendored xgrammar C++, whose three static initializers run at
  every launch.

The provider calls none of them.

`traits: []` on the SDK dependency is the SDK's documented opt-out: it
compiles MLXFoundationModels empty, and nothing else depends on
MLXGuidedGeneration or MLXCXGrammar. The dev release binary now:

- links the same 52 libraries as 0.10.1, with no FoundationModels;
- has 5 static initializers, as 0.10.1 has;
- has no xgrammar, MLXGuidedGeneration or MLXFoundationModels symbols;
- is 129,709,496 bytes instead of 131,509,816.

Package.resolved is unchanged.

This branch had an error being deployed

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