Files
mtusi2026lab4/internal/messenger/attachments.go
T

261 lines
8.1 KiB
Go

package messenger
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"golang.org/x/sync/semaphore"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/objectstore"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
)
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError {
started := time.Now()
result := "client_error"
defer func() {
s.metrics.attachmentUploads.WithLabelValues(result).Inc()
s.metrics.attachmentDuration.Observe(time.Since(started).Seconds())
}()
if r.Method != http.MethodPost {
return methodNotAllowed(w, http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
filename, valid := attachmentFilename(r.URL.Query())
if !valid {
return invalidRequest()
}
if _, err := s.messengerStore.ChatForUser(r.Context(), chatID, user.ID); errors.Is(err, postgres.ErrNotFound) {
return notFound()
} else if err != nil {
result = "dependency_error"
return unavailable()
}
data, contentType, readErr := readImage(w, r, s.maxUploadBytes, s.maxImagePixels, s.decodeMemory)
if readErr != nil {
return readErr
}
attachmentID, err := newID()
if err != nil {
result = "dependency_error"
return internalError()
}
objectID, err := newID()
if err != nil {
result = "dependency_error"
return internalError()
}
objectKey := "attachments/" + objectID + "/original"
if err := s.objects.Put(r.Context(), objectKey, contentType, data); err != nil {
result = "dependency_error"
return unavailable()
}
digest := sha256.Sum256(data)
attachment, err := s.messengerStore.CreateAttachment(r.Context(), model.Attachment{
ID: attachmentID, ChatID: chatID, OwnerID: user.ID, Filename: filename,
ContentType: contentType, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(digest[:]), ObjectKey: objectKey,
})
if err != nil {
result = "dependency_error"
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), s.requestTTL)
defer cancel()
stored, lookupErr := s.messengerStore.AttachmentByStorage(cleanupCtx, attachmentID, objectKey)
if lookupErr == nil {
result = "success"
s.metrics.attachmentBytes.Add(float64(len(data)))
writeJSON(w, http.StatusCreated, stored)
return nil
}
if !errors.Is(lookupErr, postgres.ErrNotFound) {
s.logger.Error("attachment outcome is unknown", "attachment_id", attachmentID, "error", lookupErr)
return unavailable()
}
if cleanupErr := s.objects.Delete(cleanupCtx, objectKey); cleanupErr != nil {
s.logger.Error("attachment compensation failed", "object_key", objectKey, "error", cleanupErr)
}
if errors.Is(err, postgres.ErrNotFound) {
return notFound()
}
return unavailable()
}
result = "success"
s.metrics.attachmentBytes.Add(float64(len(data)))
writeJSON(w, http.StatusCreated, attachment)
return nil
}
func attachmentFilename(query url.Values) (string, bool) {
if len(query) != 1 || len(query["filename"]) != 1 {
return "", false
}
filename := query["filename"][0]
length := utf8.RuneCountInString(filename)
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || length < 1 || length > 255 {
return "", false
}
for _, char := range filename {
if char == '/' || char == '\\' || char == 0 || unicode.IsControl(char) {
return "", false
}
}
return filename, true
}
func readImage(
w http.ResponseWriter,
r *http.Request,
maxBytes int64,
maxPixels int64,
decodeMemory *semaphore.Weighted,
) ([]byte, string, *apiError) {
mediaType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || len(parameters) != 0 || mediaType != "image/png" && mediaType != "image/jpeg" {
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "unsupported image type"}
}
if r.ContentLength > maxBytes {
return nil, "", &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image is too large"}
}
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
data, err := io.ReadAll(r.Body)
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return nil, "", &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image is too large"}
}
return nil, "", invalidRequest()
}
if len(data) == 0 {
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "invalid image"}
}
detected := http.DetectContentType(data)
if detected != mediaType {
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "content type does not match image"}
}
imageConfig, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || imageContentType(format) != mediaType {
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "invalid image"}
}
pixels := int64(imageConfig.Width) * int64(imageConfig.Height)
if imageConfig.Width < 1 || imageConfig.Height < 1 || pixels > maxPixels {
return nil, "", &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image dimensions are too large"}
}
decodeBytes := pixels*8 + int64(len(data))
if !decodeMemory.TryAcquire(decodeBytes) {
w.Header().Set("Retry-After", "1")
return nil, "", &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "image capacity is temporarily exhausted"}
}
defer decodeMemory.Release(decodeBytes)
if _, format, err := image.Decode(bytes.NewReader(data)); err != nil || imageContentType(format) != mediaType {
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "invalid image"}
}
return data, mediaType, nil
}
func imageContentType(format string) string {
switch format {
case "png":
return "image/png"
case "jpeg":
return "image/jpeg"
default:
return ""
}
}
func (s *Server) attachmentMetadata(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
attachment, apiErr := s.attachmentForUser(r, user.ID)
if apiErr != nil {
return apiErr
}
writeJSON(w, http.StatusOK, attachment)
return nil
}
func (s *Server) attachmentContent(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
if !originalVariant(r.URL.Query()) {
return invalidRequest()
}
attachment, apiErr := s.attachmentForUser(r, user.ID)
if apiErr != nil {
return apiErr
}
content, err := s.objects.Get(r.Context(), attachment.ObjectKey)
if errors.Is(err, objectstore.ErrNotFound) {
return unavailable()
}
if err != nil {
return unavailable()
}
defer func() { _ = content.Close() }()
w.Header().Set("Content-Type", attachment.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(attachment.SizeBytes, 10))
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": attachment.Filename}))
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, content); err != nil {
s.logger.Warn("attachment download interrupted", "attachment_id", attachment.ID, "error", err)
}
return nil
}
func originalVariant(query url.Values) bool {
if len(query) == 0 {
return true
}
return len(query) == 1 && len(query["variant"]) == 1 && query["variant"][0] == "original"
}
func (s *Server) attachmentForUser(r *http.Request, userID string) (Attachment, *apiError) {
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
attachmentID, valid := canonicalID(parts[3])
if !valid {
return Attachment{}, invalidRequest()
}
attachment, err := s.messengerStore.AttachmentForUser(r.Context(), attachmentID, userID)
if errors.Is(err, postgres.ErrNotFound) {
return Attachment{}, notFound()
}
if err != nil {
return Attachment{}, unavailable()
}
return attachment, nil
}