package handler import ( "bytes" "crypto/sha256" "encoding/hex" "errors" "github.com/google/uuid" "image" _ "image/jpeg" _ "image/png" "io" "mtusi2026lab2/internal/middleware" "mtusi2026lab2/internal/model" "mtusi2026lab2/internal/storage" "net/http" "strconv" "strings" "time" "unicode" "unicode/utf8" ) const maxUpload = 10 * 1024 * 1024 const maxPixels = 40000000 type AttachmentHandler struct { Chats *storage.ChatStore Attachments *storage.AttachmentStore S3 *storage.S3Client } func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) { user, _ := middleware.GetCurrentUser(r.Context()) chatID, err := uuid.Parse(r.PathValue("chat_id")) if err != nil { writeError(w, r, 400, "invalid_request", "invalid chat id") return } _, err = h.Chats.GetChatForUser(r.Context(), chatID, user.ID) if errors.Is(err, storage.ErrChatNotFound) { writeError(w, r, 404, "not_found", "chat not found") return } if err != nil { writeError(w, r, 503, "unavailable", "database unavailable") return } filename := r.URL.Query().Get("filename") if filename == "" || utf8.RuneCountInString(filename) > 255 || strings.ContainsAny(filename, "/\\") || strings.IndexFunc(filename, unicode.IsControl) >= 0 { writeError(w, r, 400, "invalid_request", "invalid filename") return } ct := r.Header.Get("Content-Type") if ct != "image/png" && ct != "image/jpeg" { writeError(w, r, 415, "unsupported_media_type", "unsupported content type") return } if r.ContentLength > maxUpload { writeError(w, r, 413, "payload_too_large", "file too large") return } data, err := io.ReadAll(io.LimitReader(r.Body, maxUpload+1)) if err != nil { writeError(w, r, 400, "invalid_request", "invalid body") return } if len(data) > maxUpload { writeError(w, r, 413, "payload_too_large", "file too large") return } if len(data) == 0 { writeError(w, r, 415, "unsupported_media_type", "empty file") return } actual := http.DetectContentType(data) if actual != ct { writeError(w, r, 415, "unsupported_media_type", "image content type mismatch") return } cfg, format, err := image.DecodeConfig(bytes.NewReader(data)) if err != nil || (format != "png" && format != "jpeg") { writeError(w, r, 415, "unsupported_media_type", "invalid image") return } if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > maxPixels { writeError(w, r, 413, "payload_too_large", "too many pixels") return } // Decode fully to reject truncated/corrupt compressed image data. Dimensions already checked. if _, _, err = image.Decode(bytes.NewReader(data)); err != nil { writeError(w, r, 415, "unsupported_media_type", "corrupt image") return } now := time.Now().UTC().Truncate(time.Microsecond) id := uuid.New() key := "original/" + id.String() digest := sha256.Sum256(data) a := model.Attachment{ID: id, ChatID: chatID, OwnerID: user.ID, Filename: filename, ContentType: ct, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(digest[:]), Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now, ObjectKey: key} if err = h.S3.Put(r.Context(), key, ct, data); err != nil { writeError(w, r, 503, "unavailable", "object storage unavailable") return } if err = h.Attachments.Create(r.Context(), a); err != nil { // Best-effort rollback for S3 write that could not be committed to DB. cleanupCtx := r.Context() _ = h.S3.Delete(cleanupCtx, key) writeError(w, r, 503, "unavailable", "metadata unavailable") return } writeJSON(w, 201, a) } func (h *AttachmentHandler) read(w http.ResponseWriter, r *http.Request, content bool) { user, _ := middleware.GetCurrentUser(r.Context()) id, err := uuid.Parse(r.PathValue("id")) if err != nil { writeError(w, r, 400, "invalid_request", "invalid attachment id") return } a, err := h.Attachments.GetForUser(r.Context(), id, user.ID) if errors.Is(err, storage.ErrAttachmentNotFound) { writeError(w, r, 404, "not_found", "attachment not found") return } if err != nil { writeError(w, r, 503, "unavailable", "metadata unavailable") return } if !content { writeJSON(w, 200, a) return } variant := r.URL.Query().Get("variant") if variant != "" && variant != "original" { writeError(w, r, 404, "not_found", "variant not found") return } data, err := h.S3.Get(r.Context(), a.ObjectKey) if err != nil { writeError(w, r, 503, "unavailable", "object storage unavailable") return } if int64(len(data)) != a.SizeBytes { writeError(w, r, 503, "unavailable", "object size mismatch") return } sum := sha256.Sum256(data) if hex.EncodeToString(sum[:]) != a.SHA256 { writeError(w, r, 503, "unavailable", "object checksum mismatch") return } w.Header().Set("Content-Type", a.ContentType) w.Header().Set("Content-Length", strconv.FormatInt(a.SizeBytes, 10)) w.WriteHeader(200) _, _ = w.Write(data) } func (h *AttachmentHandler) Metadata(w http.ResponseWriter, r *http.Request) { h.read(w, r, false) } func (h *AttachmentHandler) Content(w http.ResponseWriter, r *http.Request) { h.read(w, r, true) }