36 lines
1.1 KiB
Go
36 lines
1.1 KiB
Go
package rest
|
|
|
|
import (
|
|
"log/slog"
|
|
"net/http"
|
|
)
|
|
|
|
// bodyLimitMiddleware bounds the request body before it reaches the generated
|
|
// transport. Without it the JSON decoders read the whole body into memory before
|
|
// any schema check or authentication happens, so an oversized request to a public
|
|
// endpoint (for example POST /api/v1/users) could exhaust the replica's memory.
|
|
//
|
|
// The declared length is rejected early with 413; a client that lies about
|
|
// Content-Length is cut off by http.MaxBytesReader, which also makes the server
|
|
// close the connection instead of reading the rest.
|
|
func bodyLimitMiddleware(limit int64, log *slog.Logger, next http.Handler) http.Handler {
|
|
if limit <= 0 {
|
|
return next
|
|
}
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.ContentLength > limit {
|
|
logRejected(r.Context(), log, r, http.StatusRequestEntityTooLarge, nil)
|
|
writeError(r.Context(), log, w, r, http.StatusRequestEntityTooLarge)
|
|
|
|
return
|
|
}
|
|
|
|
if r.Body != nil {
|
|
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|