Files
mtusi2026lab4/internal/api/attachments.go
T
Mlvn 7cbb75c897 Реализовать lab4: вложения S3/MinIO, уровень 4 и трек 2 reconciler.
Метаданные в PostgreSQL, байты в приватном bucket; sync upload 201 ready;
компенсация orphan и cmd/reconcile с dry-run/apply и grace period.
2026-11-12 18:08:47 +03:00

449 lines
17 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package api
// Вложения lab4: загрузка, метаданные, скачивание.
//
// Загрузка (POST /chats/{id}/attachments?filename=...) идёт строго по шагам, и каждый шаг
// отсекает запрос как можно раньше и дешевле:
//
// 1. Bearer-аутентификация (requireUser), затем членство в чате: посторонний получает 404;
// 2. filename: 1–255 code points, без «/», «\», NUL и управляющих символов — иначе 400;
// 3. заявленный Content-Type — только image/png или image/jpeg, иначе 415;
// 4. тело копируется в спул (временный файл, при его отказе — память) с одновременным SHA-256
// и жёстким лимитом MaxUploadBytes+1: больше лимита — 413. Тело не буферизуется целиком
// в куче через ReadAll, поэтому пик RAM на загрузку — буфер копирования, а не размер файла;
// 5. тип по содержимому (http.DetectContentType) обязан совпасть с заявленным, иначе 415 (подмена MIME);
// 6. размеры берутся из заголовка PNG/JPEG БЕЗ декодирования пикселей; больше
// MaxImagePixels — 413. Это делается до любой «распаковки»: bomb 60000×60000 весит килобайты;
// 7. дешёвая структурная проверка (PNG: CRC всех чанков и IEND, JPEG: EOI) ловит обрезанные
// и повреждённые файлы — 415;
// 8. PUT в S3 по серверному ключу originals/<uuid>, затем INSERT метаданных. Только после
// обоих шагов — 201. Если INSERT не удался, объект удаляется сразу, а при отказе удаления
// его подберёт reconciler (cmd/reconcile) после grace period.
//
// До шага 8 в S3 ничего не пишется, поэтому оборванная загрузка клиента не оставляет объектов.
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"hash/crc32"
"image"
_ "image/jpeg" // регистрирует декодер JPEG для image.DecodeConfig
"io"
"log"
"mime"
"net/http"
"os"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/google/uuid"
"mtusi2026lab4/internal/blob"
"mtusi2026lab4/internal/store"
)
const (
maxMessageAttachments = 10
maxFilenameRunes = 255
// После превышения лимита дочитываем (и выбрасываем) не больше этого объёма:
// клиент успевает получить 413, а не «connection reset» посреди своей отправки.
drainOnOverflow = 64 << 20
)
var (
errBadImage = errors.New("not a valid png/jpeg image")
errTooManyPixels = errors.New("image has too many pixels")
errTooLarge = errors.New("upload exceeds size limit")
)
func (s *Server) handleUploadAttachment(w http.ResponseWriter, r *http.Request) {
chatID, err := uuid.Parse(r.PathValue("chat_id"))
if err != nil {
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid chat id")
return
}
uid := userFrom(r)
if err := s.Store.EnsureChatMember(r.Context(), chatID, uid); err != nil {
s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found")
return
}
filename := r.URL.Query().Get("filename")
if !validFilename(filename) {
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid filename")
return
}
declared, ok := declaredImageType(r.Header.Get("Content-Type"))
if !ok {
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "only image/png and image/jpeg are accepted")
return
}
// Клиент заранее заявил размер сильно больше лимита — не читаем ни байта.
if r.ContentLength > s.MaxUploadBytes+drainOnOverflow {
writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large")
return
}
sp, err := spoolBody(r.Body, s.MaxUploadBytes)
if err != nil {
switch {
case errors.Is(err, errTooLarge):
writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "file is too large")
default:
// Обрыв чтения тела или таймаут клиента. Ничего не записано ни в S3, ни в БД.
writeError(w, r, http.StatusBadRequest, "invalid_request", "could not read request body")
}
return
}
defer sp.Close()
if err := inspectImage(sp.reader(), sp.size, declared, s.MaxImagePixels); err != nil {
switch {
case errors.Is(err, errTooManyPixels):
writeError(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "image has too many pixels")
default:
writeError(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "invalid or unsupported image")
}
return
}
id := uuid.New()
att := &store.Attachment{
ID: id,
ChatID: chatID,
OwnerID: uid,
Filename: filename,
ContentType: declared,
SizeBytes: sp.size,
SHA256: sp.sum,
ObjectKey: blob.KeyPrefix + id.String(),
}
// 1) S3. Тело отдаём как ReadSeeker: minio-go шлёт один PUT без буферизации в памяти.
if err := s.Blob.Put(r.Context(), att.ObjectKey, sp.reader(), sp.size, declared); err != nil {
s.writeBlobErr(w, r, err)
return
}
// 2) PostgreSQL. Ошибка здесь оставила бы объект без строки — убираем его сразу.
if err := s.Store.CreateAttachment(r.Context(), att); err != nil {
s.compensateOrphan(r, att.ObjectKey)
s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found")
return
}
writeJSON(w, http.StatusCreated, attachmentDTO(att))
}
// compensateOrphan удаляет объект, для которого не удалось записать метаданные.
// Контекст отвязан от запроса: клиент мог отключиться, а чистить всё равно нужно.
// Если и удаление не удалось (S3 мигнул), объект останется до reconciler — это допустимо.
func (s *Server) compensateOrphan(r *http.Request, key string) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 5*time.Second)
defer cancel()
if err := s.Blob.Delete(ctx, key); err != nil {
log.Printf("request_id=%s orphan_cleanup_failed key=%s (reconciler will remove after grace)", requestID(r), key)
}
}
func (s *Server) handleGetAttachment(w http.ResponseWriter, r *http.Request) {
att, ok := s.loadAttachment(w, r)
if !ok {
return
}
writeJSON(w, http.StatusOK, attachmentDTO(att))
}
// handleDownloadAttachment отдаёт оригинал побайтно через API, без редиректа на S3:
// приватный bucket сам по себе не заменяет проверку членства в чате.
func (s *Server) handleDownloadAttachment(w http.ResponseWriter, r *http.Request) {
att, ok := s.loadAttachment(w, r)
if !ok {
return
}
// variant по умолчанию original. В lab4 вариантов нет (variants=[]), значит любой
// другой — «отсутствующий вариант ready-объекта», то есть 404.
if v := r.URL.Query().Get("variant"); v != "" && v != "original" {
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
return
}
switch att.Status {
case "ready":
default:
writeError(w, r, http.StatusConflict, "conflict", "attachment is not ready")
return
}
rc, err := s.Blob.Get(r.Context(), att.ObjectKey)
if err != nil {
if errors.Is(err, blob.ErrNotFound) {
// Строка есть, объекта нет — несогласованность, её чинит reconciler.
log.Printf("request_id=%s attachment_object_missing id=%s", requestID(r), att.ID)
writeError(w, r, http.StatusNotFound, "not_found", "object not found")
return
}
s.writeBlobErr(w, r, err)
return
}
defer rc.Close()
h := w.Header()
h.Set("Content-Type", att.ContentType)
h.Set("Content-Length", strconv.FormatInt(att.SizeBytes, 10))
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Cache-Control", "private, no-store")
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, rc); err != nil {
// Заголовки уже ушли; клиент увидит обрыв. В лог — без деталей S3.
log.Printf("request_id=%s attachment_stream_error id=%s", requestID(r), att.ID)
}
}
// loadAttachment разбирает {attachment_id} и проверяет членство в чате вложения.
func (s *Server) loadAttachment(w http.ResponseWriter, r *http.Request) (*store.Attachment, bool) {
id, err := uuid.Parse(r.PathValue("attachment_id"))
if err != nil {
writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid attachment id")
return nil, false
}
att, err := s.Store.GetAttachment(r.Context(), id, userFrom(r))
if err != nil {
s.writeStoreErr(w, r, err, http.StatusNotFound, "not_found", "object not found")
return nil, false
}
return att, true
}
// writeBlobErr: недоступный S3 — 503, остальное — 500. Текст ошибки клиенту не уходит.
func (s *Server) writeBlobErr(w http.ResponseWriter, r *http.Request, err error) {
if errors.Is(err, blob.ErrUnavailable) {
log.Printf("request_id=%s s3_unavailable", requestID(r))
writeError(w, r, http.StatusServiceUnavailable, "unavailable", "dependency unavailable")
return
}
log.Printf("request_id=%s blob_error_type=%T", requestID(r), err)
writeError(w, r, http.StatusInternalServerError, "internal_error", "internal error")
}
func attachmentDTO(a *store.Attachment) map[string]any {
var errCode any
if a.ErrorCode != nil {
errCode = *a.ErrorCode
}
return map[string]any{
"id": a.ID.String(),
"chat_id": a.ChatID.String(),
"owner_id": a.OwnerID.String(),
"filename": a.Filename,
"content_type": a.ContentType,
"size_bytes": a.SizeBytes,
"sha256": a.SHA256,
"status": a.Status,
"variants": []any{},
"error_code": errCode,
"created_at": formatTime(a.CreatedAt),
"updated_at": formatTime(a.UpdatedAt),
}
}
// validFilename: 1–255 code points, валидный UTF-8, не «пустой» после TrimSpace.
// «/», «\», NUL и управляющие символы запрещены: имя только отображается и никогда не
// становится путём или ключом S3. «.» и «..» отвергаются как заведомо опасные.
func validFilename(name string) bool {
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" {
return false
}
if n := utf8.RuneCountInString(name); n < 1 || n > maxFilenameRunes {
return false
}
if name == "." || name == ".." {
return false
}
for _, c := range name {
if c == '/' || c == '\\' || c == 0 || unicode.IsControl(c) {
return false
}
}
return true
}
// declaredImageType возвращает заявленный Content-Type без параметров, если он разрешён.
func declaredImageType(header string) (string, bool) {
mt, _, err := mime.ParseMediaType(header)
if err != nil {
return "", false
}
switch mt {
case "image/png", "image/jpeg":
return mt, true
}
return "", false
}
// spooled — принятое тело: размер, SHA-256 и произвольный доступ для проверок и PUT.
type spooled struct {
ra io.ReaderAt
size int64
sum string
cleanup func()
}
func (s *spooled) reader() *io.SectionReader { return io.NewSectionReader(s.ra, 0, s.size) }
func (s *spooled) Close() { s.cleanup() }
// spoolBody читает тело не больше max байт. Временный файл защищает кучу от 10 одновременных
// загрузок по 10 MiB; если /tmp недоступен, откатываемся на память (всё равно ограниченную max).
func spoolBody(body io.Reader, max int64) (*spooled, error) {
h := sha256.New()
f, ferr := os.CreateTemp("", "upload-*")
var (
dst io.Writer
buf *bytes.Buffer
cleanup = func() {}
)
if ferr == nil {
cleanup = func() { _ = f.Close(); _ = os.Remove(f.Name()) }
dst = io.MultiWriter(f, h)
} else {
buf = &bytes.Buffer{}
dst = io.MultiWriter(buf, h)
}
n, err := io.Copy(dst, io.LimitReader(body, max+1))
if err != nil {
cleanup()
return nil, err
}
if n > max {
cleanup()
_, _ = io.CopyN(io.Discard, body, drainOnOverflow)
return nil, errTooLarge
}
sp := &spooled{size: n, sum: hex.EncodeToString(h.Sum(nil)), cleanup: cleanup}
if f != nil && ferr == nil {
sp.ra = f
} else {
sp.ra = bytes.NewReader(buf.Bytes())
}
return sp, nil
}
// inspectImage проверяет содержимое. Порядок важен: тип → размеры из заголовка (лимит
// пикселей до любой распаковки) → структура файла.
func inspectImage(sr *io.SectionReader, size int64, declared string, maxPixels int64) error {
head := make([]byte, 512)
n, _ := sr.ReadAt(head, 0)
detected := ""
if n > 0 {
detected = http.DetectContentType(head[:n])
}
if size < 1 || (detected != "image/png" && detected != "image/jpeg") || detected != declared {
return errBadImage
}
var w, h int64
switch detected {
case "image/png":
// IHDR всегда первый чанк: 8 байт сигнатуры, 4 длина, 4 тип, затем width/height.
// Читаем сами: image/png.DecodeConfig отвергает файл с битым CRC раньше, чем
// мы успели бы честно ответить «слишком много пикселей».
if n < 24 || string(head[12:16]) != "IHDR" || binary.BigEndian.Uint32(head[8:12]) != 13 {
return errBadImage
}
w = int64(binary.BigEndian.Uint32(head[16:20]))
h = int64(binary.BigEndian.Uint32(head[20:24]))
case "image/jpeg":
cfg, _, err := image.DecodeConfig(io.NewSectionReader(sr, 0, size))
if err != nil {
return errBadImage
}
w, h = int64(cfg.Width), int64(cfg.Height)
}
if w < 1 || h < 1 {
return errBadImage
}
if w*h > maxPixels {
return errTooManyPixels
}
if detected == "image/png" {
return verifyPNG(io.NewSectionReader(sr, 0, size), size)
}
return verifyJPEGTail(sr, size)
}
// verifyPNG обходит чанки и проверяет их CRC без декомпрессии IDAT: обрезанный или
// испорченный PNG отвергается за один линейный проход по файлу.
func verifyPNG(r io.Reader, size int64) error {
br := bufio.NewReaderSize(r, 64<<10)
if _, err := br.Discard(8); err != nil { // сигнатура уже проверена DetectContentType
return errBadImage
}
consumed := int64(8)
var (
hdr [8]byte
crcBuf [4]byte
first = true
sawIDAT bool
sawIEND bool
crcHasher = crc32.NewIEEE()
)
for !sawIEND {
if _, err := io.ReadFull(br, hdr[:]); err != nil {
return errBadImage
}
length := int64(binary.BigEndian.Uint32(hdr[0:4]))
ctype := string(hdr[4:8])
if length > size-consumed-12 {
return errBadImage
}
if first && ctype != "IHDR" {
return errBadImage
}
first = false
crcHasher.Reset()
_, _ = crcHasher.Write(hdr[4:8])
if _, err := io.CopyN(crcHasher, br, length); err != nil {
return errBadImage
}
if _, err := io.ReadFull(br, crcBuf[:]); err != nil {
return errBadImage
}
if crcHasher.Sum32() != binary.BigEndian.Uint32(crcBuf[:]) {
return errBadImage
}
consumed += 12 + length
switch ctype {
case "IDAT":
sawIDAT = true
case "IEND":
sawIEND = true
}
}
// Данные после IEND — признак полиглота или склейки файлов, не принимаем.
if !sawIDAT || consumed != size {
return errBadImage
}
return nil
}
// verifyJPEGTail требует маркер конца изображения EOI (FF D9) в хвосте файла.
// Допускаются нулевые/мусорные байты выравнивания после него (до 1 KiB).
func verifyJPEGTail(sr *io.SectionReader, size int64) error {
tailLen := int64(1024)
if size < tailLen {
tailLen = size
}
tail := make([]byte, tailLen)
if _, err := sr.ReadAt(tail, size-tailLen); err != nil && !errors.Is(err, io.EOF) {
return errBadImage
}
if bytes.LastIndex(tail, []byte{0xFF, 0xD9}) < 0 {
return errBadImage
}
return nil
}