From 69bdd94d139c01e200c4c342d8c2935df08173e4 Mon Sep 17 00:00:00 2001 From: protonmatter Date: Tue, 17 Nov 2026 13:04:50 -0500 Subject: [PATCH] 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. --- cmd/artex/main.go | 5 +++++ server/decode_limit_test.go | 25 +++++++++++++++++++++++++ server/server_mgmt.go | 10 +++++++++- 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 server/decode_limit_test.go diff --git a/cmd/artex/main.go b/cmd/artex/main.go index 99e1180..f83012f 100644 --- a/cmd/artex/main.go +++ b/cmd/artex/main.go @@ -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() { diff --git a/server/decode_limit_test.go b/server/decode_limit_test.go new file mode 100644 index 0000000..eb8eda0 --- /dev/null +++ b/server/decode_limit_test.go @@ -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") + } +} diff --git a/server/server_mgmt.go b/server/server_mgmt.go index c51e9fb..903f1a2 100644 --- a/server/server_mgmt.go +++ b/server/server_mgmt.go @@ -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) ----------