package httpapi import ( "context" "crypto/sha256" "encoding/hex" "errors" "image" _ "image/jpeg" _ "image/png" "io" "log" "mime" "net/http" "os" "strconv" "strings" "time" "unicode" "unicode/utf8" "mtusi2026/internal/blobstore" "mtusi2026/internal/idgen" "mtusi2026/internal/model" "mtusi2026/internal/store" ) const ( maxAttachmentBytes = 10 << 20 maxPixels = 40_000_000 fullDecodePixels = 4_000_000 // полное декодирование только для небольших изображений ) func validFilename(s string) bool { n := utf8.RuneCountInString(s) if n < 1 || n > 255 || strings.TrimSpace(s) == "" { return false } for _, r := range s { if r == '/' || r == '\\' || r == 0 || unicode.IsControl(r) { return false } } return true } func (a *api) acquireUploadSlot(ctx context.Context) (func(), bool) { t := time.NewTimer(5 * time.Second) defer t.Stop() select { case a.uploadSem <- struct{}{}: return func() { <-a.uploadSem }, true case <-t.C: return nil, false case <-ctx.Done(): return nil, false } } func (a *api) handleUploadAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) { chatID, ok := uuidParam(w, r, requestID, "chat_id") if !ok { return } if a.blobs == nil { writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable") return } member, err := a.store.IsChatMember(r.Context(), chatID, u.ID) if err != nil { writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable") return } if !member { writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found") return } q := r.URL.Query() filename := q.Get("filename") if !q.Has("filename") || !validFilename(filename) { writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid filename") return } mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil || (mt != "image/png" && mt != "image/jpeg") { writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "only image/png and image/jpeg are accepted") return } if r.ContentLength > maxAttachmentBytes { writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "file is too large") return } tmp, err := os.CreateTemp("", "upload-*") if err != nil { writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error") return } defer func() { tmp.Close(); os.Remove(tmp.Name()) }() h := sha256.New() n, err := io.Copy(io.MultiWriter(tmp, h), http.MaxBytesReader(w, r.Body, maxAttachmentBytes)) if err != nil { var mbe *http.MaxBytesError if errors.As(err, &mbe) { writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "file is too large") } else { writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "upload interrupted") } return } if n == 0 { writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "empty or invalid image") return } release, ok := a.acquireUploadSlot(r.Context()) if !ok { writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "upload capacity reached, retry later") return } defer release() head := make([]byte, 512) hn, _ := tmp.ReadAt(head, 0) if http.DetectContentType(head[:hn]) != mt { writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "content does not match declared type") return } cfg, format, err := image.DecodeConfig(io.NewSectionReader(tmp, 0, n)) want := map[string]string{"image/png": "png", "image/jpeg": "jpeg"}[mt] if err != nil || format != want || cfg.Width <= 0 || cfg.Height <= 0 { writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "invalid image") return } pixels := int64(cfg.Width) * int64(cfg.Height) if pixels > maxPixels { writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "image has too many pixels") return } if pixels <= fullDecodePixels { if _, _, err := image.Decode(io.NewSectionReader(tmp, 0, n)); err != nil { writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "corrupted image") return } } id := idgen.GenerateUUIDv4() key := "attachments/" + chatID + "/" + id baseCtx := context.WithoutCancel(r.Context()) putCtx, cancel := context.WithTimeout(baseCtx, 30*time.Second) err = a.blobs.Put(putCtx, key, io.NewSectionReader(tmp, 0, n), n, mt) cancel() if err != nil { log.Printf("s3 put failed: %v", err) delCtx, delCancel := context.WithTimeout(baseCtx, 5*time.Second) _ = a.blobs.Delete(delCtx, key) delCancel() writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable") return } dbCtx, dbCancel := context.WithTimeout(baseCtx, 10*time.Second) defer dbCancel() att, err := a.store.CreateAttachment(dbCtx, model.Attachment{ ID: id, ChatID: chatID, OwnerID: u.ID, Filename: filename, ContentType: mt, SizeBytes: n, SHA256: hex.EncodeToString(h.Sum(nil)), ObjectKey: key, }) if err != nil { log.Printf("attachment metadata insert failed, compensating: %v", err) if derr := a.blobs.Delete(dbCtx, key); derr != nil { log.Printf("compensation delete failed (reconciler will clean up) key=%s: %v", key, derr) } writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error") return } writeJSON(w, http.StatusCreated, requestID, att) } func (a *api) loadAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) (model.Attachment, bool) { id, ok := uuidParam(w, r, requestID, "attachment_id") if !ok { return model.Attachment{}, false } att, err := a.store.GetAttachmentForUser(r.Context(), id, u.ID) if err != nil { if errors.Is(err, store.ErrAttachmentNotFound) { writeError(w, http.StatusNotFound, requestID, codeNotFound, "attachment not found") } else { writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable") } return model.Attachment{}, false } return att, true } func (a *api) handleGetAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) { att, ok := a.loadAttachment(w, r, u, requestID) if !ok { return } writeJSON(w, http.StatusOK, requestID, att) } func (a *api) handleDownloadAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) { if q := r.URL.Query(); q.Has("variant") && q.Get("variant") != "original" { writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "unknown variant") return } att, ok := a.loadAttachment(w, r, u, requestID) if !ok { return } if a.blobs == nil { writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable") return } ctx, cancel := context.WithCancel(r.Context()) defer cancel() t := time.AfterFunc(8*time.Second, cancel) body, err := a.blobs.Get(ctx, att.ObjectKey) t.Stop() if err != nil { if errors.Is(err, blobstore.ErrNotFound) { log.Printf("INCONSISTENCY: metadata without object id=%s key=%s", att.ID, att.ObjectKey) writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error") } else { log.Printf("s3 get failed: %v", err) writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable") } return } defer body.Close() w.Header().Set("Content-Type", att.ContentType) w.Header().Set("Content-Length", strconv.FormatInt(att.SizeBytes, 10)) w.Header().Set("X-Request-Id", requestID) w.Header().Set("X-Content-Type-Options", "nosniff") w.WriteHeader(http.StatusOK) _, _ = io.Copy(w, body) }