Repository navigation
fix(coordinator): cap request body size globally + tighten unauth endpoints - #339
Conversation
…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.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
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 — 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 bareanyparameter for dst- Suggestion: Consider using a generic type parameter like
func decodeCappedJSON[T any](w http.ResponseWriter, r *http.Request, maxBytes int64, dst *T) boolto provide compile-time type safety
- Suggestion: Consider using a generic type parameter like
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
| h := s.bodyLimitMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| _, readErr = io.Copy(io.Discard, r.Body) |
There was a problem hiding this comment.
🟡 [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
| h := s.bodyLimitMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| _, readErr = io.Copy(io.Discard, r.Body) |
There was a problem hiding this comment.
🟡 [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
| // 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 { |
There was a problem hiding this comment.
🔵 [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
| // 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 |
There was a problem hiding this comment.
🔵 [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
| 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 | ||
| } | ||
|
|
There was a problem hiding this comment.
🔵 [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
|
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
Threat Assessment
New Attack SurfaceNone introduced. The diff removes a code path and delegates to an already-audited shared helper. Open Findings Resolved
Minor Notes
🔐 Threat model: |
|
@codex review this |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
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 — 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 bareanyparameter for dst- Suggestion: Consider using a generic type parameter like
func decodeCappedJSON[T any](w http.ResponseWriter, r *http.Request, maxBytes int64, dst *T) boolto provide compile-time type safety
- Suggestion: Consider using a generic type parameter like
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) { |
There was a problem hiding this comment.
🟡 [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) { |
There was a problem hiding this comment.
🟡 [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
| // 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 { |
There was a problem hiding this comment.
🔵 [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
| // 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 |
There was a problem hiding this comment.
🔵 [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
| 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) | ||
| } |
There was a problem hiding this comment.
🔵 [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
| if r.Body != nil && r.URL.Path != "/ws/provider" { | ||
| r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodyBytes) | ||
| } | ||
| next.ServeHTTP(w, r) | ||
| }) |
There was a problem hiding this comment.
🔵 [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
…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).
…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.
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.Bodywith no limit — worst on the unauthenticated control-plane endpoints, which need no credential at all.The problem
json.Decoder.Decode/io.ReadAllbuffer 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:POST /v1/enrollPOST /v1/device/tokenPOST /v1/admin/auth/initPOST /v1/admin/auth/verify…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 toHandler():cors(recover(logging(bodyLimit(mux))))) wraps every request body inhttp.MaxBytesReaderat 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/provideris exempt — it hijacks the connection and reads framed messages (bounded separately bySetReadLimit), notr.Body.decodeCappedJSONapplies a tight 64 KiB cap on the four unauthenticated control-plane endpoints (they carry small fixed structs): over-cap → 413, malformed → 400.MaxBytesReaders, so they still fire first.Test plan
go test ./coordinator/api/— full package green (no regression from the handler changes). New tests incoordinator/api/body_cap_test.go:TestBodyLimitMiddlewareCapsOversizedBody— an over-ceiling body on a normal route is capped (*http.MaxBytesError).TestBodyLimitMiddlewareExemptsProviderWS—/ws/provideris not capped.TestDecodeCappedJSON— over-cap → 413, malformed → 400, valid → decoded.Verified the load-bearing test fails without the fix: removing the middleware's
MaxBytesReadermakes the caps test read the full stream (nilinstead 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).Need help on this PR? Tag
/codesmithwith what you need. Autofix is disabled.