Files
mtusi2026lab5/src/internal/api/attachments.go
T

335 lines
9.7 KiB
Go

package api
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"mime"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
"mtusi-messenger/internal/apperr"
"mtusi-messenger/internal/model"
"mtusi-messenger/internal/objstore"
"mtusi-messenger/internal/store"
)
const (
mimePNG = "image/png"
mimeJPEG = "image/jpeg"
maxDrainBytes = 64 << 20
)
func (s *Server) objectError(w http.ResponseWriter, r *http.Request, err error) {
s.log.Warn("object storage unavailable", "request_id", requestID(r), "error", err.Error())
apperr.Write(w, requestID(r), apperr.Unavailable("attachment storage temporarily unavailable"))
}
func validFilename(name string) bool {
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || name == "." || name == ".." {
return false
}
if n := runeLen(name); n < 1 || n > 255 {
return false
}
for _, c := range name {
switch {
case c == '/', c == '\\', c == 0, unicode.IsControl(c):
return false
case c >= 0x202a && c <= 0x202e, c >= 0x2066 && c <= 0x2069:
return false
}
}
return true
}
func sniffImage(data []byte) string {
switch {
case bytes.HasPrefix(data, []byte("\x89PNG\r\n\x1a\n")):
return mimePNG
case bytes.HasPrefix(data, []byte{0xff, 0xd8, 0xff}):
return mimeJPEG
}
return ""
}
type imageInfo struct {
contentType string
width, height int
}
func (s *Server) inspectImage(data []byte, declared string) (imageInfo, *apperr.AppError) {
detected := sniffImage(data)
if detected == "" {
return imageInfo{}, apperr.UnsupportedMedia("content is not a PNG or JPEG image")
}
if detected != declared {
return imageInfo{}, apperr.UnsupportedMedia("Content-Type does not match the image content")
}
cfg, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || cfg.Width <= 0 || cfg.Height <= 0 || (format != "png" && format != "jpeg") {
return imageInfo{}, apperr.UnsupportedMedia("image header is invalid")
}
pixels := int64(cfg.Width) * int64(cfg.Height)
if pixels > s.maxPixels {
return imageInfo{}, apperr.PayloadTooLarge("image exceeds " + strconv.FormatInt(s.maxPixels, 10) + " pixels")
}
return imageInfo{contentType: detected, width: cfg.Width, height: cfg.Height}, nil
}
func readBody(w http.ResponseWriter, r *http.Request, limit int64) ([]byte, *apperr.AppError) {
var buf bytes.Buffer
if r.ContentLength > 0 {
buf.Grow(int(r.ContentLength))
}
_, err := buf.ReadFrom(http.MaxBytesReader(w, r.Body, limit))
var maxErr *http.MaxBytesError
switch {
case errors.As(err, &maxErr):
return nil, apperr.PayloadTooLarge("attachment exceeds " + strconv.FormatInt(limit, 10) + " bytes")
case err != nil:
return nil, apperr.InvalidRequest("request body could not be read")
case buf.Len() == 0:
return nil, apperr.InvalidRequest("request body is empty")
}
return buf.Bytes(), nil
}
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
methodNotAllowed(w, r)
return
}
body := r.Body
defer func() { _, _ = io.CopyN(io.Discard, body, maxDrainBytes) }()
id := requestID(r)
chatID, ok := s.chatAccess(w, r)
if !ok {
return
}
query, err := url.ParseQuery(r.URL.RawQuery)
if err != nil || len(query["filename"]) != 1 {
apperr.Write(w, id, apperr.InvalidRequest("exactly one filename query parameter is required"))
return
}
filename := query.Get("filename")
if !validFilename(filename) {
apperr.Write(w, id, apperr.InvalidRequest("filename must be 1..255 code points without path separators or control characters"))
return
}
media, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
if media != mimePNG && media != mimeJPEG {
apperr.Write(w, id, apperr.UnsupportedMedia("Content-Type must be image/png or image/jpeg"))
return
}
if r.ContentLength > s.maxUpload {
apperr.Write(w, id, apperr.PayloadTooLarge("attachment exceeds "+strconv.FormatInt(s.maxUpload, 10)+" bytes"))
return
}
if s.maxActiveJobs > 0 {
n, err := s.store.ActiveJobs(r.Context())
if err != nil {
s.storeError(w, r, err)
return
}
if n >= s.maxActiveJobs {
w.Header().Set("Retry-After", "5")
apperr.Write(w, id, apperr.Unavailable("attachment processing queue is full, retry later"))
return
}
}
if err := s.uploadSem.Acquire(r.Context(), 1); err != nil {
apperr.Write(w, id, apperr.Unavailable("too many concurrent uploads, retry later"))
return
}
defer s.uploadSem.Release(1)
data, aerr := readBody(w, r, s.maxUpload)
if aerr != nil {
apperr.Write(w, id, aerr)
return
}
info, aerr := s.inspectImage(data, media)
if aerr != nil {
apperr.Write(w, id, aerr)
return
}
sum := sha256.Sum256(data)
attID := uuid.NewString()
att := &model.Attachment{
ID: attID, ChatID: chatID, OwnerID: currentUser(r).ID, Filename: filename,
ContentType: info.contentType, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(sum[:]),
Status: "queued", Variants: []model.Variant{},
ObjectKey: "attachments/" + chatID + "/" + attID,
}
stagingKey := "staging/" + attID
if err := s.store.InsertPendingAttachment(r.Context(), att, info.width, info.height, stagingKey); err != nil {
if errors.Is(err, store.ErrNotFound) {
apperr.Write(w, id, apperr.NotFound("chat not found or not accessible"))
return
}
s.storeError(w, r, err)
return
}
putCtx, cancel := context.WithTimeout(r.Context(), s.s3Timeout)
err = s.objects.Put(putCtx, stagingKey, data, att.ContentType)
cancel()
if err != nil {
go s.compensateUpload(att, stagingKey, id)
s.objectError(w, r, err)
return
}
_, updated, err := s.store.QueueAttachment(r.Context(), att.ID, s.pipelineVersion, s.maxAttempts, s.maxActiveJobs)
if err != nil {
go s.compensateUpload(att, stagingKey, id)
if errors.Is(err, store.ErrQueueFull) {
w.Header().Set("Retry-After", "5")
apperr.Write(w, id, apperr.Unavailable("attachment processing queue is full, retry later"))
return
}
if errors.Is(err, store.ErrNotFound) {
apperr.Write(w, id, apperr.Unavailable("upload expired, retry"))
return
}
s.storeError(w, r, err)
return
}
if s.faultInjection && strings.HasPrefix(filename, "fault-api-after-commit") {
s.log.Warn("FAULT: exit after COMMIT before publish/response", "attachment_id", att.ID)
os.Exit(42)
}
if s.relay != nil {
s.relay.Kick()
}
att.UpdatedAt = model.NewTime(updated)
writeJSON(w, r, http.StatusAccepted, att)
}
func (s *Server) compensateUpload(att *model.Attachment, stagingKey, reqID string) {
dctx, dcancel := context.WithTimeout(context.Background(), 3*time.Second)
defer dcancel()
deleted, err := s.store.DeletePendingAttachment(dctx, att.ID)
if err != nil || !deleted {
if err != nil {
s.log.Warn("upload compensation deferred to reconciler", "request_id", reqID,
"attachment_id", att.ID, "stage", "delete_row")
}
return
}
octx, ocancel := context.WithTimeout(context.Background(), 3*time.Second)
defer ocancel()
if err := s.objects.Remove(octx, stagingKey); err != nil {
s.log.Warn("upload compensation deferred to reconciler", "request_id", reqID,
"attachment_id", att.ID, "stage", "remove_object")
}
}
func (s *Server) attachmentForRequest(w http.ResponseWriter, r *http.Request) (*model.Attachment, bool) {
id := requestID(r)
attID, err := parseUUID(r.PathValue("attachment_id"))
if err != nil {
apperr.Write(w, id, apperr.InvalidRequest("attachment_id must be a UUID"))
return nil, false
}
att, err := s.store.AttachmentForUser(r.Context(), attID, currentUser(r).ID)
if errors.Is(err, store.ErrNotFound) {
apperr.Write(w, id, apperr.NotFound("attachment not found or not accessible"))
return nil, false
}
if err != nil {
s.storeError(w, r, err)
return nil, false
}
return att, true
}
func (s *Server) getAttachment(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
methodNotAllowed(w, r)
return
}
if att, ok := s.attachmentForRequest(w, r); ok {
writeJSON(w, r, http.StatusOK, att)
}
}
func (s *Server) downloadAttachment(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
methodNotAllowed(w, r)
return
}
id := requestID(r)
att, ok := s.attachmentForRequest(w, r)
if !ok {
return
}
variant := r.URL.Query().Get("variant")
switch variant {
case "", "original", "thumbnail", "crop", "optimized":
default:
apperr.Write(w, id, apperr.InvalidRequest("unknown variant"))
return
}
if att.Status != "ready" {
apperr.Write(w, id, apperr.Conflict("attachment is "+att.Status+", content is not available yet"))
return
}
key, contentType, etag := att.ObjectKey, att.ContentType, att.SHA256
if variant != "" && variant != "original" {
found := false
for _, v := range att.Variants {
if v.Name == variant {
key, contentType, etag, found = v.ObjectKey, v.ContentType, v.SHA256, true
}
}
if !found {
apperr.Write(w, id, apperr.NotFound("variant not found"))
return
}
}
ctx, cancel := context.WithTimeout(r.Context(), s.s3Timeout)
defer cancel()
obj, size, err := s.objects.Get(ctx, key)
if objstore.IsNotFound(err) {
s.log.Error("attachment object missing in S3", "request_id", id, "attachment_id", att.ID)
apperr.Write(w, id, apperr.NotFound("attachment content is not available"))
return
}
if err != nil {
s.objectError(w, r, err)
return
}
defer obj.Close()
h := w.Header()
h.Set("Content-Type", contentType)
h.Set("Content-Length", strconv.FormatInt(size, 10))
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Cache-Control", "private, no-store")
h.Set("Content-Disposition", "inline; filename*=UTF-8''"+url.PathEscape(att.Filename))
h.Set("ETag", `"`+etag+`"`)
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, obj); err != nil {
s.log.Warn("download interrupted", "request_id", id, "attachment_id", att.ID, "error", err.Error())
}
}