forked from mtusi2026/mtusi2026lab4
459 lines
15 KiB
Go
459 lines
15 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"image"
|
|
_ "image/jpeg" // register the JPEG decoder used by image.DecodeConfig/Decode
|
|
_ "image/png" // register the PNG decoder used by image.DecodeConfig/Decode
|
|
"io"
|
|
"mime"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
|
|
"mtusi.ru/messenger-lab4/internal/model"
|
|
"mtusi.ru/messenger-lab4/internal/objectstore"
|
|
"mtusi.ru/messenger-lab4/internal/store"
|
|
"mtusi.ru/messenger-lab4/internal/uuid"
|
|
)
|
|
|
|
const (
|
|
objectPrefix = "attachments/"
|
|
decodeWaitTimeout = 30 * time.Second
|
|
putWaitTimeout = 10 * time.Second
|
|
maxFilenameCodePoints = 255
|
|
imagePNG = "image/png"
|
|
imageJPEG = "image/jpeg"
|
|
attachmentStateReady = "ready"
|
|
attachmentStatePending = "pending"
|
|
maxImageDimensionProduct = int64(40_000_000)
|
|
)
|
|
|
|
// attachmentRoutes handles /api/v1/attachments/{id} and .../content. The
|
|
// caller has already been authenticated by withAuth.
|
|
func (a *App) attachmentRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
|
|
parts := splitPath(rest)
|
|
if len(parts) == 1 {
|
|
if r.Method != http.MethodGet {
|
|
a.notFound(w, r)
|
|
return
|
|
}
|
|
a.getAttachment(w, r, parts[0], actor)
|
|
return
|
|
}
|
|
if len(parts) == 2 && parts[1] == "content" {
|
|
if r.Method != http.MethodGet {
|
|
a.notFound(w, r)
|
|
return
|
|
}
|
|
a.downloadAttachment(w, r, parts[0], actor)
|
|
return
|
|
}
|
|
a.notFound(w, r)
|
|
}
|
|
|
|
// createAttachment performs a synchronous binary upload. The body is streamed
|
|
// to a bounded temporary file while its SHA-256 is computed; the image is
|
|
// validated before any S3 or database write. Only a validated image can create
|
|
// a pending row, so an invalid request never leaves an accounted object behind.
|
|
func (a *App) createAttachment(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
|
|
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
|
|
if problem != nil {
|
|
a.writeError(w, r, problem)
|
|
return
|
|
}
|
|
filename, problem := uploadFilename(r)
|
|
if problem != nil {
|
|
a.writeError(w, r, problem)
|
|
return
|
|
}
|
|
declared, problem := uploadMediaType(r)
|
|
if problem != nil {
|
|
a.writeError(w, r, problem)
|
|
return
|
|
}
|
|
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
|
|
if err != nil {
|
|
a.log.Error("attachment membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
if errors.Is(err, store.ErrUnavailable) {
|
|
a.writeError(w, r, statusUnavailable)
|
|
return
|
|
}
|
|
a.writeError(w, r, statusInternal)
|
|
return
|
|
}
|
|
if !member {
|
|
a.writeError(w, r, statusNotFound)
|
|
return
|
|
}
|
|
if r.ContentLength > a.maxUpload {
|
|
a.writeError(w, r, statusPayloadTooLarge)
|
|
return
|
|
}
|
|
|
|
temp, err := os.CreateTemp(a.tempDir, "lab4-upload-*")
|
|
if err != nil {
|
|
a.log.Error("could not create upload temp file", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
a.writeError(w, r, statusUnavailable)
|
|
return
|
|
}
|
|
tempName := temp.Name()
|
|
defer func() {
|
|
_ = temp.Close()
|
|
_ = os.Remove(tempName)
|
|
}()
|
|
|
|
hasher := sha256.New()
|
|
body := http.MaxBytesReader(w, r.Body, a.maxUpload)
|
|
written, err := io.Copy(io.MultiWriter(temp, hasher), body)
|
|
if err != nil {
|
|
var tooLarge *http.MaxBytesError
|
|
switch {
|
|
case errors.As(err, &tooLarge):
|
|
a.writeError(w, r, statusPayloadTooLarge)
|
|
case errors.Is(err, syscall.ENOSPC):
|
|
a.log.Error("upload temp file is full", "request_id", requestIDFromContext(r.Context()))
|
|
a.writeError(w, r, statusUnavailable)
|
|
default:
|
|
a.writeError(w, r, invalidRequest("could not read the upload body"))
|
|
}
|
|
return
|
|
}
|
|
if written > a.maxUpload {
|
|
a.writeError(w, r, statusPayloadTooLarge)
|
|
return
|
|
}
|
|
if written == 0 {
|
|
a.writeError(w, r, unsupportedMediaType("the upload body is empty"))
|
|
return
|
|
}
|
|
|
|
detected, width, height, problem := a.validateImage(r.Context(), temp, declared)
|
|
if problem != nil {
|
|
a.writeError(w, r, problem)
|
|
return
|
|
}
|
|
|
|
sum := hex.EncodeToString(hasher.Sum(nil))
|
|
attachmentID := uuid.New()
|
|
objectKey := objectPrefix + attachmentID
|
|
createdAt := time.Now().UTC()
|
|
record := store.AttachmentRecord{
|
|
Attachment: model.Attachment{
|
|
ID: attachmentID,
|
|
ChatID: chatID,
|
|
OwnerID: actor.user.ID,
|
|
Filename: filename,
|
|
ContentType: detected,
|
|
SizeBytes: written,
|
|
SHA256: sum,
|
|
Status: attachmentStatePending,
|
|
Variants: []model.Variant{},
|
|
ErrorCode: nil,
|
|
CreatedAt: model.Time{Time: createdAt},
|
|
UpdatedAt: model.Time{Time: createdAt},
|
|
},
|
|
ObjectKey: objectKey,
|
|
}
|
|
|
|
if err := a.store.CreatePendingAttachment(r.Context(), record, createdAt); err != nil {
|
|
a.log.Error("could not record attachment intent", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
if errors.Is(err, store.ErrUnavailable) {
|
|
a.writeError(w, r, statusUnavailable)
|
|
return
|
|
}
|
|
a.writeError(w, r, statusInternal)
|
|
return
|
|
}
|
|
|
|
if _, err := temp.Seek(0, io.SeekStart); err != nil {
|
|
_ = a.store.DeleteAttachmentRow(context.Background(), attachmentID)
|
|
a.writeError(w, r, statusInternal)
|
|
return
|
|
}
|
|
// Bound the number of simultaneous object writes per API replica. A queued
|
|
// upload has already been streamed to a bounded temporary file and is not
|
|
// holding a decoded image, so waiting here does not add unbounded RAM.
|
|
select {
|
|
case a.putSem <- struct{}{}:
|
|
err = a.objects.Put(r.Context(), objectKey, temp, written, detected)
|
|
<-a.putSem
|
|
case <-time.After(putWaitTimeout):
|
|
a.compensatePending(attachmentID)
|
|
a.log.Warn("S3 upload queue timed out", "request_id", requestIDFromContext(r.Context()),
|
|
"attachment_id", attachmentID)
|
|
a.writeError(w, r, statusUnavailable)
|
|
return
|
|
case <-r.Context().Done():
|
|
a.compensatePending(attachmentID)
|
|
a.writeError(w, r, statusUnavailable)
|
|
return
|
|
}
|
|
if err != nil {
|
|
// Compensation for a failed PUT: the pending row is removed. If this
|
|
// best-effort delete also fails, the reconciler removes the stale row
|
|
// and any object after the grace period.
|
|
a.compensatePending(attachmentID)
|
|
a.log.Error("S3 upload failed", "request_id", requestIDFromContext(r.Context()), "attachment_id", attachmentID, "error", err)
|
|
if errors.Is(err, objectstore.ErrUnavailable) || errors.Is(err, objectstore.ErrNotFound) {
|
|
a.writeError(w, r, statusUnavailable)
|
|
return
|
|
}
|
|
a.writeError(w, r, statusInternal)
|
|
return
|
|
}
|
|
|
|
updatedAt, err := a.store.MarkAttachmentReady(r.Context(), attachmentID, time.Now().UTC())
|
|
if err != nil {
|
|
// The object and the pending row are both durable. Never delete the
|
|
// object here: an ambiguous COMMIT could have promoted the row already,
|
|
// and deleting a ready original is worse than a reconciler pass.
|
|
a.log.Error("could not promote attachment after S3 upload", "request_id", requestIDFromContext(r.Context()), "attachment_id", attachmentID, "error", err)
|
|
if errors.Is(err, store.ErrUnavailable) {
|
|
a.writeError(w, r, statusUnavailable)
|
|
return
|
|
}
|
|
a.writeError(w, r, statusInternal)
|
|
return
|
|
}
|
|
record.Status = attachmentStateReady
|
|
record.UpdatedAt = model.Time{Time: updatedAt}
|
|
a.log.Info("attachment ready",
|
|
"request_id", requestIDFromContext(r.Context()),
|
|
"attachment_id", attachmentID,
|
|
"chat_id", chatID,
|
|
"size_bytes", written,
|
|
"content_type", detected,
|
|
"image_width", width,
|
|
"image_height", height,
|
|
)
|
|
a.writeJSON(w, r, http.StatusCreated, record.Attachment)
|
|
}
|
|
|
|
// compensatePending removes the upload intent after a failed or abandoned S3
|
|
// write. A failed best-effort delete is intentionally left to the reconciler:
|
|
// deleting a possibly committed row here would be worse than a stale pending row.
|
|
func (a *App) compensatePending(attachmentID string) {
|
|
cleanupCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
_ = a.store.DeleteAttachmentRow(cleanupCtx, attachmentID)
|
|
cancel()
|
|
}
|
|
|
|
// validateImage applies every content rule before S3 or PostgreSQL is touched.
|
|
// The declared media type must match the bytes; the decoded pixel count is
|
|
// checked from the header before a potentially large full decode.
|
|
func (a *App) validateImage(ctx context.Context, temp *os.File, declared string) (detected string, width, height int, problem *apiError) {
|
|
if _, err := temp.Seek(0, io.SeekStart); err != nil {
|
|
return "", 0, 0, statusInternal
|
|
}
|
|
header := make([]byte, 512)
|
|
n, err := io.ReadFull(temp, header)
|
|
if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) {
|
|
return "", 0, 0, unsupportedMediaType("the upload body is not a valid image")
|
|
}
|
|
detected = http.DetectContentType(header[:n])
|
|
if detected != imagePNG && detected != imageJPEG {
|
|
return "", 0, 0, unsupportedMediaType("only PNG and JPEG images are accepted")
|
|
}
|
|
if declared != detected {
|
|
return "", 0, 0, unsupportedMediaType("Content-Type does not match the image bytes")
|
|
}
|
|
|
|
if _, err := temp.Seek(0, io.SeekStart); err != nil {
|
|
return "", 0, 0, statusInternal
|
|
}
|
|
config, format, err := image.DecodeConfig(temp)
|
|
if err != nil || (format != "png" && format != "jpeg") {
|
|
return "", 0, 0, unsupportedMediaType("the image header is corrupt or unsupported")
|
|
}
|
|
if config.Width < 1 || config.Height < 1 {
|
|
return "", 0, 0, unsupportedMediaType("the image has invalid dimensions")
|
|
}
|
|
pixels := int64(config.Width) * int64(config.Height)
|
|
if pixels > a.maxPixels || pixels > maxImageDimensionProduct {
|
|
return "", 0, 0, statusPayloadTooLarge
|
|
}
|
|
|
|
select {
|
|
case a.decodeSem <- struct{}{}:
|
|
defer func() { <-a.decodeSem }()
|
|
case <-time.After(decodeWaitTimeout):
|
|
return "", 0, 0, statusUnavailable
|
|
case <-ctx.Done():
|
|
return "", 0, 0, statusUnavailable
|
|
}
|
|
|
|
if _, err := temp.Seek(0, io.SeekStart); err != nil {
|
|
return "", 0, 0, statusInternal
|
|
}
|
|
decoded, _, err := image.Decode(temp)
|
|
if err != nil {
|
|
return "", 0, 0, unsupportedMediaType("the image is corrupt or truncated")
|
|
}
|
|
bounds := decoded.Bounds()
|
|
if bounds.Dx() < 1 || bounds.Dy() < 1 {
|
|
return "", 0, 0, unsupportedMediaType("the image has invalid dimensions")
|
|
}
|
|
return detected, bounds.Dx(), bounds.Dy(), nil
|
|
}
|
|
|
|
// uploadMediaType parses the declared Content-Type strictly. Parameters are
|
|
// accepted; any other media type is rejected before the body is read.
|
|
func uploadMediaType(r *http.Request) (string, *apiError) {
|
|
raw := strings.TrimSpace(r.Header.Get("Content-Type"))
|
|
if raw == "" {
|
|
return "", unsupportedMediaType("Content-Type must be image/png or image/jpeg")
|
|
}
|
|
mediaType, _, err := mime.ParseMediaType(raw)
|
|
if err != nil || (mediaType != imagePNG && mediaType != imageJPEG) {
|
|
return "", unsupportedMediaType("Content-Type must be image/png or image/jpeg")
|
|
}
|
|
return mediaType, nil
|
|
}
|
|
|
|
// uploadFilename validates the display-only filename query parameter. The
|
|
// value is never used as a path or an object key.
|
|
func uploadFilename(r *http.Request) (string, *apiError) {
|
|
query, err := url.ParseQuery(r.URL.RawQuery)
|
|
if err != nil {
|
|
return "", invalidRequest("query string is not valid")
|
|
}
|
|
values, present := query["filename"]
|
|
if !present || len(values) != 1 || values[0] == "" {
|
|
return "", invalidRequest("filename query parameter is required exactly once")
|
|
}
|
|
name := values[0]
|
|
if !utf8.ValidString(name) {
|
|
return "", invalidRequest("filename must be valid UTF-8")
|
|
}
|
|
if count := utf8.RuneCountInString(name); count < 1 || count > maxFilenameCodePoints {
|
|
return "", invalidRequest("filename must contain 1 to 255 Unicode code points")
|
|
}
|
|
if name == "." || name == ".." {
|
|
return "", invalidRequest("filename must not be a path component")
|
|
}
|
|
for _, char := range name {
|
|
if char == '/' || char == '\\' || char == 0 || unicode.IsControl(char) {
|
|
return "", invalidRequest("filename must not contain path separators, NUL or control characters")
|
|
}
|
|
}
|
|
return name, nil
|
|
}
|
|
|
|
func (a *App) getAttachment(w http.ResponseWriter, r *http.Request, rawID string, actor identity) {
|
|
attachmentID, problem := normalizePathUUID(rawID, "attachment_id")
|
|
if problem != nil {
|
|
a.writeError(w, r, problem)
|
|
return
|
|
}
|
|
record, err := a.store.ReadyAttachmentForUser(r.Context(), attachmentID, actor.user.ID)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, store.ErrNotFound):
|
|
a.writeError(w, r, statusNotFound)
|
|
case errors.Is(err, store.ErrUnavailable):
|
|
a.log.Error("attachment metadata lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
a.writeError(w, r, statusUnavailable)
|
|
default:
|
|
a.log.Error("attachment metadata lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
a.writeError(w, r, statusInternal)
|
|
}
|
|
return
|
|
}
|
|
// The object is the source of truth for existence. A row whose bytes are
|
|
// gone must not be presented as a ready attachment.
|
|
if _, err := a.objects.Stat(r.Context(), record.ObjectKey); err != nil {
|
|
switch {
|
|
case errors.Is(err, objectstore.ErrNotFound):
|
|
a.writeError(w, r, statusNotFound)
|
|
case errors.Is(err, objectstore.ErrUnavailable):
|
|
a.log.Error("attachment object stat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
a.writeError(w, r, statusUnavailable)
|
|
default:
|
|
a.log.Error("attachment object stat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
a.writeError(w, r, statusInternal)
|
|
}
|
|
return
|
|
}
|
|
a.writeJSON(w, r, http.StatusOK, record.Attachment)
|
|
}
|
|
|
|
func (a *App) downloadAttachment(w http.ResponseWriter, r *http.Request, rawID string, actor identity) {
|
|
attachmentID, problem := normalizePathUUID(rawID, "attachment_id")
|
|
if problem != nil {
|
|
a.writeError(w, r, problem)
|
|
return
|
|
}
|
|
if problem := requireOriginalVariant(r); problem != nil {
|
|
a.writeError(w, r, problem)
|
|
return
|
|
}
|
|
record, err := a.store.ReadyAttachmentForUser(r.Context(), attachmentID, actor.user.ID)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, store.ErrNotFound):
|
|
a.writeError(w, r, statusNotFound)
|
|
case errors.Is(err, store.ErrUnavailable):
|
|
a.log.Error("attachment download lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
a.writeError(w, r, statusUnavailable)
|
|
default:
|
|
a.log.Error("attachment download lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
a.writeError(w, r, statusInternal)
|
|
}
|
|
return
|
|
}
|
|
body, info, err := a.objects.Get(r.Context(), record.ObjectKey)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Is(err, objectstore.ErrNotFound):
|
|
a.writeError(w, r, statusNotFound)
|
|
case errors.Is(err, objectstore.ErrUnavailable):
|
|
a.log.Error("attachment object read failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
a.writeError(w, r, statusUnavailable)
|
|
default:
|
|
a.log.Error("attachment object read failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
|
a.writeError(w, r, statusInternal)
|
|
}
|
|
return
|
|
}
|
|
defer body.Close()
|
|
|
|
w.Header().Set("Content-Type", record.ContentType)
|
|
w.Header().Set("Content-Length", strconv.FormatInt(info.Size, 10))
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
w.Header().Set("Cache-Control", "private, no-store")
|
|
w.WriteHeader(http.StatusOK)
|
|
if _, err := io.Copy(w, body); err != nil {
|
|
a.log.Warn("attachment stream interrupted", "request_id", requestIDFromContext(r.Context()), "attachment_id", attachmentID, "error", err)
|
|
}
|
|
}
|
|
|
|
// requireOriginalVariant accepts the optional variant parameter but lab4 has
|
|
// only the original. An unknown variant of a ready object is 404.
|
|
func requireOriginalVariant(r *http.Request) *apiError {
|
|
query, err := url.ParseQuery(r.URL.RawQuery)
|
|
if err != nil {
|
|
return invalidRequest("query string is not valid")
|
|
}
|
|
values, present := query["variant"]
|
|
if !present {
|
|
return nil
|
|
}
|
|
if len(values) != 1 || values[0] == "" {
|
|
return invalidRequest("variant must be a non-empty string")
|
|
}
|
|
if values[0] == "original" {
|
|
return nil
|
|
}
|
|
return statusNotFound
|
|
}
|