package rest import ( "log/slog" "net/http" "regexp" ) // attachmentUploadPath matches POST /api/v1/chats/{chat_id}/attachments. The // UUID syntax is not validated here; this middleware only selects a body limit, // and the generated transport rejects malformed identifiers later. var attachmentUploadPath = regexp.MustCompile(`^/api/v1/chats/[^/]+/attachments$`) // bodyLimitMiddleware bounds the request body before it reaches the generated // transport. JSON endpoints keep the small default limit; the attachment upload // gets its own larger limit. Without this split the 10 MiB upload would be // rejected before the handler, and raising the global limit would let any // public JSON endpoint read a 10 MiB body. func bodyLimitMiddleware( defaultLimit, uploadLimit int64, log *slog.Logger, next http.Handler, ) http.Handler { if defaultLimit <= 0 && uploadLimit <= 0 { return next } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { limit := limitForRequest(r, defaultLimit, uploadLimit) if limit <= 0 { next.ServeHTTP(w, r) return } 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) }) } func limitForRequest(r *http.Request, defaultLimit, uploadLimit int64) int64 { if r.Method == http.MethodPost && attachmentUploadPath.MatchString(r.URL.Path) { return uploadLimit } return defaultLimit }