package messenger import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "image" _ "image/jpeg" _ "image/png" "io" "mime" "net/http" "net/url" "os" "strconv" "strings" "time" "unicode" "unicode/utf8" "github.com/jackc/pgx/v5" ) const MaxUploadBytes int64 = 10 * 1024 * 1024 const MaxImagePixels int64 = 40000000 type Attachment struct { ID string `json:"id"` ChatID string `json:"chat_id"` OwnerID string `json:"owner_id"` Filename string `json:"filename"` ContentType string `json:"content_type"` SizeBytes int64 `json:"size_bytes"` SHA256 string `json:"sha256"` Status string `json:"status"` Variants []any `json:"variants"` ErrorCode *string `json:"error_code"` CreatedAt string `json:"created_at"` UpdatedAt string `json:"updated_at"` } func tooLarge() *apiError { return &apiError{status: 413, code: "payload_too_large", message: "Превышен лимит изображения"} } func invalidImage() *apiError { return &apiError{status: 415, code: "unsupported_media_type", message: "Требуется корректный PNG или JPEG"} } func rollbackUpload(tx pgx.Tx) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() _ = tx.Rollback(ctx) } func validFilename(s string) bool { if !utf8.ValidString(s) || strings.TrimSpace(s) == "" || utf8.RuneCountInString(s) > 255 { return false } for _, c := range s { if c == '/' || c == '\\' || unicode.IsControl(c) { return false } } return true } func (a *API) isMember(r *http.Request, uid, chatID string) *apiError { ctx, cancel := a.dbContext(r.Context()) defer cancel() var member bool if err := a.db.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2)`, chatID, uid).Scan(&member); err != nil { return unavailable() } if !member { return missing() } return nil } func (a *API) uploadAttachment(r *http.Request, uid, chatID string) (response, *apiError) { if e := a.isMember(r, uid, chatID); e != nil { return response{}, e } query, err := url.ParseQuery(r.URL.RawQuery) if err != nil || len(query) != 1 || len(query["filename"]) != 1 || !validFilename(query.Get("filename")) { return response{}, bad("Неверное имя файла") } kind, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil || (kind != "image/png" && kind != "image/jpeg") { return response{}, invalidImage() } if r.ContentLength > MaxUploadBytes { return response{}, tooLarge() } ctx, cancel := context.WithTimeout(r.Context(), 45*time.Second) defer cancel() // One decoder/temporary original per replica bounds RAM and tmpfs usage. select { case a.uploadSlots <- struct{}{}: defer func() { <-a.uploadSlots }() case <-ctx.Done(): return response{}, unavailable() } file, err := os.CreateTemp("", "upload-*") if err != nil { return response{}, unavailable() } defer os.Remove(file.Name()) defer file.Close() hash := sha256.New() size, err := io.CopyBuffer(io.MultiWriter(file, hash), io.LimitReader(r.Body, MaxUploadBytes+1), make([]byte, 32*1024)) if size > MaxUploadBytes { return response{}, tooLarge() } if err != nil { return response{}, bad("Загрузка прервана") } if size == 0 { return response{}, invalidImage() } file.Seek(0, io.SeekStart) config, format, err := image.DecodeConfig(file) if err != nil || (format != "png" && format != "jpeg") || "image/"+format != kind { return response{}, invalidImage() } if config.Width < 1 || config.Height < 1 || int64(config.Width) > MaxImagePixels/int64(config.Height) { return response{}, tooLarge() } file.Seek(0, io.SeekStart) // Decode after the dimension guard to reject corrupt payloads, not just // apparently valid headers. The decoded bitmap is never persisted. if e := validateImage(file); e != nil { return response{}, e } file.Seek(0, io.SeekStart) id := newID() key := "staging/" + id dbctx, dbcancel := a.dbContext(ctx) _, err = a.db.Exec(dbctx, `INSERT INTO attachment_uploads(id,object_key) VALUES($1,$2)`, id, key) dbcancel() if err != nil { return response{}, unavailable() } tx, err := a.db.Begin(ctx) if err != nil { return response{}, unavailable() } defer rollbackUpload(tx) // Cleanup and upload use the same lock. Cleanup cannot delete an object // while its upload/metadata transaction is in progress. if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,4))`, key); err != nil { return response{}, unavailable() } var pending bool if err = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachment_uploads WHERE id=$1)`, id).Scan(&pending); err != nil || !pending { return response{}, unavailable() } putctx, putcancel := context.WithTimeout(ctx, 20*time.Second) err = a.objects.Put(putctx, key, file, size, kind) putcancel() if err != nil { return response{}, unavailable() } att := Attachment{ID: id, ChatID: chatID, OwnerID: uid, Filename: query.Get("filename"), ContentType: kind, SizeBytes: size, SHA256: hex.EncodeToString(hash.Sum(nil)), Status: "queued", Variants: []any{}} var created, updated time.Time if err = tx.QueryRow(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,status) VALUES($1,$2,$3,$4,$5,$6,$7,$8,'queued') RETURNING created_at,updated_at`, id, chatID, uid, att.Filename, key, kind, size, att.SHA256).Scan(&created, &updated); err != nil { return response{}, unavailable() } if _, err = tx.Exec(ctx, `DELETE FROM attachment_uploads WHERE id=$1`, id); err != nil { return response{}, unavailable() } maxAttempts := 5 if raw := os.Getenv("JOB_MAX_ATTEMPTS"); raw != "" { n, parseErr := strconv.Atoi(raw) if parseErr != nil || n < 1 || n > 20 { return response{}, unavailable() } maxAttempts = n } if _, err = tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,staging_key,max_attempts) VALUES($1,$2,$3,$4)`, id, id, key, maxAttempts); err != nil { return response{}, unavailable() } if _, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id) VALUES($1)`, id); err != nil { return response{}, unavailable() } if err = tx.Commit(ctx); err != nil { return response{}, unavailable() } att.CreatedAt = formatTime(created) att.UpdatedAt = formatTime(updated) return response{status: 202, body: att}, nil } func validateImage(r io.Reader) *apiError { _, _, err := image.Decode(r) if err != nil { return invalidImage() } return nil } func (a *API) getAttachment(r *http.Request, uid, id string, content bool) (response, *apiError) { query, err := url.ParseQuery(r.URL.RawQuery) if err != nil { return response{}, bad("Неверные параметры вложения") } if (!content && len(query) > 0) || (content && (len(query) > 1 || (len(query) > 0 && len(query["variant"]) != 1))) { return response{}, bad("Неверные параметры вложения") } ctx, cancel := a.dbContext(r.Context()) defer cancel() att := Attachment{Variants: []any{}} var key string var variantsJSON []byte var created, updated time.Time err = a.db.QueryRow(ctx, `SELECT a.id::text,a.chat_id::text,a.owner_id::text,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,a.created_at,a.updated_at,a.variants,a.error_code FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id AND cm.user_id=$2 WHERE a.id=$1`, id, uid).Scan(&att.ID, &att.ChatID, &att.OwnerID, &att.Filename, &key, &att.ContentType, &att.SizeBytes, &att.SHA256, &att.Status, &created, &updated, &variantsJSON, &att.ErrorCode) if errors.Is(err, pgx.ErrNoRows) { return response{}, missing() } if err != nil { return response{}, unavailable() } _ = json.Unmarshal(variantsJSON, &att.Variants) att.CreatedAt = formatTime(created) att.UpdatedAt = formatTime(updated) if !content { return response{status: 200, body: att}, nil } if att.Status != "ready" { return response{}, &apiError{status: 409, code: "conflict", message: "Вложение не готово"} } if variant, ok := query["variant"]; ok && variant[0] != "original" { found := false for _, item := range att.Variants { v, ok := item.(map[string]any) if ok && v["name"] == variant[0] { key = "variants/" + id + "/v1/" + variant[0] att.ContentType = v["content_type"].(string) att.SizeBytes = int64(v["size_bytes"].(float64)) att.Filename = variant[0] + map[bool]string{true: ".webp", false: ".jpg"}[variant[0] == "optimized"] found = true break } } if !found { return response{}, missing() } } downloadCtx, downloadCancel := context.WithTimeout(r.Context(), 45*time.Second) object, err := a.objects.Get(downloadCtx, key) if err != nil { downloadCancel() return response{}, unavailable() } return response{status: 200, content: object, contentType: att.ContentType, length: att.SizeBytes, filename: att.Filename, cancel: downloadCancel}, nil }