Cap JSON request bodies and bound how long a body may arrive.

decode stops at 32 MiB. ReadTimeout limits header and body arrival without cutting a handler that is already running.
This commit is contained in:
protonmatter
2026-11-17 13:04:50 -05:00
parent 6337341602
commit 69bdd94d13
3 changed files with 39 additions and 1 deletions
+5
View File
@@ -110,10 +110,15 @@ func run() int {
log.Printf("[config] trusted proxies: %v", trusted)
}
srv := server.New(ctx, mgr, skillDir, *dataDir, keyDir, server.WithSecretScrub(), server.WithTrustedProxies(trusted))
// ReadTimeout bounds how long the request headers and body may take to arrive.
// It does not limit how long a handler runs, so an event stream stays open.
// WriteTimeout is left unset: a write deadline would cut that stream.
httpSrv := &http.Server{
Addr: *addr,
Handler: srv.Handler(),
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Minute,
IdleTimeout: 2 * time.Minute,
}
go func() {
+25
View File
@@ -0,0 +1,25 @@
package server
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestDecodeAcceptsSmallBody(t *testing.T) {
r := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"x":"ok"}`))
var v map[string]string
if err := decode(r, &v); err != nil || v["x"] != "ok" {
t.Fatalf("decode: %v %+v", err, v)
}
}
func TestDecodeCapsBody(t *testing.T) {
body := strings.NewReader(`{"x":"` + strings.Repeat("a", decodeMaxBytes) + `"}`)
r := httptest.NewRequest(http.MethodPost, "/", body)
var v map[string]string
if err := decode(r, &v); err == nil {
t.Fatal("body over the limit was accepted")
}
}
+9 -1
View File
@@ -79,7 +79,15 @@ func pathInt(r *http.Request, name string) (int64, bool) {
return n, err == nil
}
func decode(r *http.Request, v any) error { return json.NewDecoder(r.Body).Decode(v) }
// decodeMaxBytes is the default JSON body cap. Handlers that already wrapped
// the body with a smaller MaxBytesReader keep that smaller cap. Multipart
// uploads do not use decode.
const decodeMaxBytes = 32 << 20
func decode(r *http.Request, v any) error {
r.Body = http.MaxBytesReader(nil, r.Body, decodeMaxBytes)
return json.NewDecoder(r.Body).Decode(v)
}
// ---------- tasks (delete) ----------