mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-20 07:00:58 +08:00
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:
@@ -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() {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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) ----------
|
||||
|
||||
|
||||
Reference in New Issue
Block a user