lab4: S3-вложения, presigned upload и проверки

This commit is contained in:
Vladislav Kunetskiy
2026-10-21 22:42:48 +03:00
parent d342b2a227
commit 49c2fe3071
79 changed files with 12266 additions and 910 deletions
+31 -9
View File
@@ -3,22 +3,36 @@ 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. 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 {
// 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)
@@ -33,3 +47,11 @@ func bodyLimitMiddleware(limit int64, log *slog.Logger, next http.Handler) http.
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
}