Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions pkgs/mcpx/internal/daemon/body_limits_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package daemon

import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"

"github.com/developing-today/code/pkgs/mcpx/internal/settings"
)

// #2082: every daemon handler that reads a request body goes through
// http.MaxBytesReader at its route class's configured limit. These tests
// pin the over-limit refusal shape — 400 via the handler's existing error
// path, matching the routes that were already bounded — and a source
// guard so a new unbounded reader fails CI instead of shipping.

func bodyLimitSet(t *testing.T) *settings.Set {
t.Helper()
sch, err := settings.New(settings.Registry())
if err != nil {
t.Fatal(err)
}
return settings.NewSet(sch).WithOverrides(map[string]string{
"http.bodyLimit": "64B",
"http.callBodyLimit": "64B",
"http.controlBodyLimit": "64B",
}, "test")
}

func post(t *testing.T, s *Server, path, body string, h http.HandlerFunc) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
w := httptest.NewRecorder()
h(w, req)
return w
}

func TestBodyLimitsRefuseOverLimit(t *testing.T) {
s := &Server{set: bodyLimitSet(t)}
big := strings.Repeat("x", 256)
cases := []struct {
name string
path string
body string
handler http.HandlerFunc
}{
{"chat completions", "/v1/chat/completions", `{"model":"m","messages":[{"role":"user","content":"` + big + `"}]}`, s.handleChatCompletions},
{"exec", "/v1/exec", `{"source":"` + big + `"}`, s.handleExec},
{"intent", "/v1/intent", `{"prompt":"` + big + `"}`, s.handleIntent},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
w := post(t, s, tc.path, tc.body, tc.handler)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), "request body too large") {
t.Fatalf("expected MaxBytesReader refusal, got: %s", w.Body.String())
}
})
}
// handleUpgrade answers over-limit reads with its fixed 400 message.
w := post(t, s, "/v1/upgrade", `{"binary":"/bin/`+big+`"}`, s.handleUpgrade)
if w.Code != http.StatusBadRequest {
t.Fatalf("upgrade: expected 400, got %d: %s", w.Code, w.Body.String())
}
}

func TestBodyLimitsUnderLimitUnchanged(t *testing.T) {
s := &Server{set: bodyLimitSet(t)}
// Under the limit the decode succeeds and the handler reaches its
// normal validation: an intent with no prompt is refused for the
// prompt, not for its size.
w := post(t, s, "/v1/intent", `{}`, s.handleIntent)
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "prompt is required") {
t.Fatalf("expected prompt-required 400, got %d: %s", w.Code, w.Body.String())
}
}

// TestNoUnboundedBodyReaders is the #2082 guard: a non-test daemon source
// file may touch r.Body only through a ceiling (MaxBytesReader /
// LimitReader) or a bounded handoff (the artifact store enforces its own
// size and quota caps), or to close it.
func TestNoUnboundedBodyReaders(t *testing.T) {
entries, err := os.ReadDir(".")
if err != nil {
t.Fatal(err)
}
allowed := []string{"MaxBytesReader", "LimitReader", "store.Put(r.Body", ".Close()"}
for _, e := range entries {
name := e.Name()
if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
continue
}
data, err := os.ReadFile(filepath.Join(".", name))
if err != nil {
t.Fatal(err)
}
for i, line := range strings.Split(string(data), "\n") {
if !strings.Contains(line, "r.Body") {
continue
}
ok := false
for _, a := range allowed {
if strings.Contains(line, a) {
ok = true
break
}
}
if !ok {
t.Errorf("%s:%d: r.Body read without a size ceiling: %s", name, i+1, strings.TrimSpace(line))
}
}
}
}
9 changes: 5 additions & 4 deletions pkgs/mcpx/internal/daemon/routes_consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"strings"
"time"

"github.com/developing-today/code/pkgs/mcpx/internal/defaults"
"github.com/developing-today/code/pkgs/mcpx/internal/diagnose"
"github.com/developing-today/code/pkgs/mcpx/internal/logging"
"github.com/developing-today/code/pkgs/mcpx/internal/recipes"
Expand Down Expand Up @@ -42,7 +43,7 @@ func (s *Server) handleDiagnose(w http.ResponseWriter, r *http.Request) {
Session string `json:"session"`
Repair bool `json:"repair"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.bodyLimit", defaults.HTTPBodyLimit))).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, err)
return
}
Expand Down Expand Up @@ -200,7 +201,7 @@ func (s *Server) handleRecipeSave(w http.ResponseWriter, r *http.Request) {
Source string `json:"source"`
Overwrite bool `json:"overwrite"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.bodyLimit", defaults.HTTPBodyLimit))).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, err)
return
}
Expand Down Expand Up @@ -275,7 +276,7 @@ func (s *Server) handleRecipeRun(w http.ResponseWriter, r *http.Request) {
}
// Every field here is optional, so an empty body is a legal request for
// a recipe that takes no placeholders.
if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.callBodyLimit", defaults.HTTPCallBodyLimit))).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
writeErr(w, http.StatusBadRequest, err)
return
}
Expand Down Expand Up @@ -366,7 +367,7 @@ func (s *Server) handleIntent(w http.ResponseWriter, r *http.Request) {
Provider string `json:"provider"`
Model string `json:"model"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.callBodyLimit", defaults.HTTPCallBodyLimit))).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, err)
return
}
Expand Down
4 changes: 2 additions & 2 deletions pkgs/mcpx/internal/daemon/routes_embeddings.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ type embeddingResponse struct {
// handleEmbeddings implements OpenAI-compatible POST /v1/embeddings.
func (s *Server) handleEmbeddings(w http.ResponseWriter, r *http.Request) {
var req embeddingRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.callBodyLimit", defaults.HTTPCallBodyLimit))).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, fmt.Errorf("invalid json request: %w", err))
return
}
Expand Down Expand Up @@ -115,7 +115,7 @@ func (s *Server) handleEmbeddingsImport(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusNotFound, fmt.Errorf("vector index not initialized"))
return
}
count, err := vIdx.Import(r.Body)
count, err := vIdx.Import(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.callBodyLimit", defaults.HTTPCallBodyLimit)))
if err != nil {
writeErr(w, http.StatusBadRequest, fmt.Errorf("failed to import embeddings: %w", err))
return
Expand Down
2 changes: 1 addition & 1 deletion pkgs/mcpx/internal/daemon/routes_exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ type execReq struct {

func (s *Server) handleExec(w http.ResponseWriter, r *http.Request) {
var req execReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.callBodyLimit", defaults.HTTPCallBodyLimit))).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, err)
return
}
Expand Down
3 changes: 2 additions & 1 deletion pkgs/mcpx/internal/daemon/routes_feedback.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strconv"
"strings"

"github.com/developing-today/code/pkgs/mcpx/internal/defaults"
"github.com/developing-today/code/pkgs/mcpx/internal/logstore"
)

Expand All @@ -30,7 +31,7 @@ func (s *Server) handleFeedbackSubmit(w http.ResponseWriter, r *http.Request) {
}

var req feedbackSubmitReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.bodyLimit", defaults.HTTPBodyLimit))).Decode(&req); err != nil {
writeErr(w, http.StatusBadRequest, fmt.Errorf("invalid json request: %w", err))
return
}
Expand Down
3 changes: 2 additions & 1 deletion pkgs/mcpx/internal/daemon/routes_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"strings"
"time"

"github.com/developing-today/code/pkgs/mcpx/internal/defaults"
"github.com/developing-today/code/pkgs/mcpx/internal/logstore"
)

Expand Down Expand Up @@ -41,7 +42,7 @@ type chatCompletionReq struct {
}

func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
bodyBytes, err := io.ReadAll(r.Body)
bodyBytes, err := io.ReadAll(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.callBodyLimit", defaults.HTTPCallBodyLimit)))
if err != nil {
writeErr(w, http.StatusBadRequest, err)
return
Expand Down
22 changes: 17 additions & 5 deletions pkgs/mcpx/internal/daemon/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -810,7 +810,7 @@ func (s *Server) routes(mux *http.ServeMux) {
SessionID string `json:"sessionId"`
CallID string `json:"callId"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.bodyLimit", defaults.HTTPBodyLimit))).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]any{"error": err.Error()})
return
}
Expand Down Expand Up @@ -1084,7 +1084,7 @@ func callContext(r *http.Request, body config.CallContext, session string) confi

func (s *Server) handleCall(w http.ResponseWriter, r *http.Request) {
var req callReq
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, s.set.Bytes("http.callBodyLimit"))).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.callBodyLimit", defaults.HTTPCallBodyLimit))).Decode(&req); err != nil {
writeErr(w, 400, err)
return
}
Expand Down Expand Up @@ -1188,6 +1188,18 @@ type batchReq struct {
Session string `json:"session"`
}

// bodyBytes is the configured request-body limit for key, falling back
// to the built-in default when the server carries no settings set —
// the shape handleBatch already used for its limit, shared by every
// MaxBytesReader wrap so a bare &Server{} in a test cannot nil-panic
// in Set.Bytes (#2082).
func (s *Server) bodyBytes(key string, fallback int64) int64 {
if s.set == nil {
return fallback
}
return s.set.Bytes(key)
}

func (s *Server) handleBatch(w http.ResponseWriter, r *http.Request) {
var req batchReq
limit := defaults.HTTPCallBodyLimit
Expand Down Expand Up @@ -1318,7 +1330,7 @@ type resourceReq struct {

func (s *Server) handleResource(w http.ResponseWriter, r *http.Request) {
var req resourceReq
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, s.set.Bytes("http.bodyLimit"))).Decode(&req); err != nil {
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.bodyLimit", defaults.HTTPBodyLimit))).Decode(&req); err != nil {
writeErr(w, 400, err)
return
}
Expand All @@ -1335,7 +1347,7 @@ func (s *Server) handleRelease(w http.ResponseWriter, r *http.Request) {
var req struct {
Session string `json:"session"`
}
_ = json.NewDecoder(http.MaxBytesReader(w, r.Body, s.set.Bytes("http.controlBodyLimit"))).Decode(&req)
_ = json.NewDecoder(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.controlBodyLimit", defaults.HTTPControlBodyLimit))).Decode(&req)
if req.Session == "" {
req.Session = r.Header.Get("X-Mcpx-Session")
}
Expand Down Expand Up @@ -1387,7 +1399,7 @@ func (s *Server) handleRestart(w http.ResponseWriter, r *http.Request) {
Server string `json:"server"`
Lazy bool `json:"lazy"`
}
_ = json.NewDecoder(http.MaxBytesReader(w, r.Body, s.set.Bytes("http.controlBodyLimit"))).Decode(&req)
_ = json.NewDecoder(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.controlBodyLimit", defaults.HTTPControlBodyLimit))).Decode(&req)
res, err := s.reg.Restart(r.Context(), req.Server, req.Lazy)
if err != nil {
writeErr(w, 400, err)
Expand Down
4 changes: 3 additions & 1 deletion pkgs/mcpx/internal/daemon/upgrade.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"path/filepath"
"sync"
"time"

"github.com/developing-today/code/pkgs/mcpx/internal/defaults"
)

const upgradeRoute = "/v1/upgrade"
Expand Down Expand Up @@ -103,7 +105,7 @@ func (s *Server) handleUpgrade(w http.ResponseWriter, r *http.Request) {
// with. See startSuccessor.
Start []string `json:"start,omitempty"`
}
body, err := io.ReadAll(r.Body)
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, s.bodyBytes("http.controlBodyLimit", defaults.HTTPControlBodyLimit)))
if err != nil || json.Unmarshal(body, &req) != nil || req.Binary == "" {
http.Error(w, "an upgrade needs the path of the new binary", http.StatusBadRequest)
return
Expand Down
Loading