feat: add minio

This commit is contained in:
TAskMAster339
2026-10-18 18:06:27 +03:00
parent 9bbd342756
commit e3cd2516ba
30 changed files with 1213 additions and 177 deletions
+145
View File
@@ -0,0 +1,145 @@
package handlers
import (
"context"
"errors"
"github.com/google/uuid"
"io"
"log"
"messenger/src/backend/services"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
func uploadAttachmentHandler(chats *services.ChatService, attachments *services.AttachmentService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
requestID := newRequestID()
w.Header().Set("X-Request-Id", requestID)
if r.Method != http.MethodPost {
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
return
}
userID, ok := requestUserID(w, r, requestID)
if !ok {
return
}
raw := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/api/v1/chats/"), "/attachments")
chatID, err := uuid.Parse(raw)
if err != nil {
writeError(w, 400, "invalid_request", "invalid chat id", requestID)
return
}
if _, err = chats.Get(r.Context(), userID, chatID.String()); err != nil {
writeServiceError(w, err, requestID)
return
}
query, err := urlQuery(r)
if err != nil {
writeServiceError(w, err, requestID)
return
}
filenames := query["filename"]
if len(filenames) != 1 {
writeError(w, 400, "invalid_request", "exactly one filename is required", requestID)
return
}
if err = services.ValidateFilename(filenames[0]); err != nil {
writeServiceError(w, err, requestID)
return
}
if r.ContentLength > services.MaxUploadBytes {
writeServiceError(w, services.ErrPayloadTooLarge, requestID)
return
}
r.Body = http.MaxBytesReader(w, r.Body, services.MaxUploadBytes)
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
defer cancel()
attachment, err := attachments.Upload(ctx, userID, chatID.String(), filenames[0], r.Header.Get("Content-Type"), r.Body)
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
err = services.ErrPayloadTooLarge
}
if err != nil {
writeServiceError(w, err, requestID)
return
}
writeJSON(w, 201, attachment)
}
}
func attachmentHandler(attachments *services.AttachmentService) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
requestID := newRequestID()
w.Header().Set("X-Request-Id", requestID)
if r.Method != http.MethodGet {
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
return
}
userID, ok := requestUserID(w, r, requestID)
if !ok {
return
}
path := strings.TrimPrefix(r.URL.Path, "/api/v1/attachments/")
parts := strings.Split(path, "/")
if len(parts) > 2 || (len(parts) == 2 && parts[1] != "content") {
writeServiceError(w, services.ErrAttachmentNotFound, requestID)
return
}
id, err := uuid.Parse(parts[0])
if err != nil {
writeError(w, 400, "invalid_request", "invalid attachment id", requestID)
return
}
a, err := attachments.Get(r.Context(), id.String(), userID)
if err != nil {
writeServiceError(w, err, requestID)
return
}
if len(parts) == 1 {
writeJSON(w, 200, a)
return
}
query, err := urlQuery(r)
if err != nil {
writeServiceError(w, err, requestID)
return
}
if variants, exists := query["variant"]; exists {
if len(variants) != 1 {
writeError(w, 400, "invalid_request", "invalid variant", requestID)
return
}
if variants[0] != "original" {
writeServiceError(w, services.ErrAttachmentNotFound, requestID)
return
}
}
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
defer cancel()
content, err := attachments.Content(ctx, a)
if err != nil {
writeServiceError(w, err, requestID)
return
}
defer content.Close()
w.Header().Set("Content-Type", a.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(a.SizeBytes, 10))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "private, no-store")
w.WriteHeader(200)
if _, err = io.Copy(w, content); err != nil {
log.Printf("attachment download interrupted, request %s", requestID)
}
}
}
func urlQuery(r *http.Request) (url.Values, error) {
q, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
return nil, services.InvalidInput{Message: "invalid query"}
}
return q, nil
}
+5 -1
View File
@@ -110,11 +110,15 @@ func chatCollectionHandler(chats *services.ChatService) http.HandlerFunc {
}
}
func chatSubresourceHandler(chats *services.ChatService, messages *services.MessageService) http.HandlerFunc {
func chatSubresourceHandler(chats *services.ChatService, messages *services.MessageService, attachments *services.AttachmentService) http.HandlerFunc {
get := getChatHandler(chats)
createMessage := createMessageHandler(chats, messages)
listMessages := listMessagesHandler(chats, messages)
return func(w http.ResponseWriter, r *http.Request) {
if attachments != nil && strings.HasSuffix(r.URL.Path, "/attachments") {
uploadAttachmentHandler(chats, attachments)(w, r)
return
}
if strings.HasSuffix(r.URL.Path, "/messages") {
if r.Method == http.MethodGet {
listMessages(w, r)
+15 -2
View File
@@ -48,6 +48,12 @@ func writeServiceError(w http.ResponseWriter, err error, requestID string) {
switch {
case errors.As(err, &invalid):
writeError(w, 400, "invalid_request", invalid.Message, requestID)
case errors.Is(err, services.ErrPayloadTooLarge):
writeError(w, 413, "payload_too_large", "image exceeds upload limits", requestID)
case errors.Is(err, services.ErrUnsupportedMedia):
writeError(w, 415, "unsupported_media_type", "a valid PNG or JPEG matching Content-Type is required", requestID)
case errors.Is(err, services.ErrAttachmentNotFound):
writeError(w, 404, "not_found", "attachment not found", requestID)
case errors.Is(err, services.ErrConflict):
writeError(w, 409, "conflict", "request conflicts with an existing resource", requestID)
case errors.Is(err, services.ErrUnknownUser):
@@ -130,7 +136,11 @@ func readyHandler(health *services.HealthService) http.HandlerFunc {
}
}
func NewRouter(health *services.HealthService, users *services.UserService, sessions *services.SessionService, chats *services.ChatService, messages *services.MessageService) http.Handler {
func NewRouter(health *services.HealthService, users *services.UserService, sessions *services.SessionService, chats *services.ChatService, messages *services.MessageService, attachmentServices ...*services.AttachmentService) http.Handler {
var attachments *services.AttachmentService
if len(attachmentServices) > 0 {
attachments = attachmentServices[0]
}
mux := http.NewServeMux()
mux.HandleFunc("/health/live", healthHandler)
mux.HandleFunc("/health/ready", readyHandler(health))
@@ -139,6 +149,9 @@ func NewRouter(health *services.HealthService, users *services.UserService, sess
mux.Handle("/api/v1/auth/sessions/current", authRequired(sessions, logoutHandler(sessions)))
mux.Handle("/api/v1/users/me", authRequired(sessions, currentUserHandler(users)))
mux.Handle("/api/v1/chats", authRequired(sessions, chatCollectionHandler(chats)))
mux.Handle("/api/v1/chats/", authRequired(sessions, chatSubresourceHandler(chats, messages)))
mux.Handle("/api/v1/chats/", authRequired(sessions, chatSubresourceHandler(chats, messages, attachments)))
if attachments != nil {
mux.Handle("/api/v1/attachments/", authRequired(sessions, attachmentHandler(attachments)))
}
return withInstance(mux)
}
+9 -5
View File
@@ -10,7 +10,7 @@ import (
)
type createMessageRequest struct {
Text string `json:"text"`
Text *string `json:"text"`
AttachmentIDs json.RawMessage `json:"attachment_ids"`
}
@@ -62,10 +62,14 @@ func createMessageHandler(chats *services.ChatService, messages *services.Messag
writeError(w, 400, "invalid_request", "invalid JSON body", requestID)
return
}
ids := []string{}
if request.Text == nil {
writeError(w, 400, "invalid_request", "text must be a string", requestID)
return
}
if len(request.AttachmentIDs) > 0 {
var ids []string
if err := json.Unmarshal(request.AttachmentIDs, &ids); err != nil || ids == nil || len(ids) != 0 {
writeError(w, 400, "invalid_request", "attachments are not supported in lab3; use an empty array or omit attachment_ids", requestID)
if err := json.Unmarshal(request.AttachmentIDs, &ids); err != nil || ids == nil {
writeError(w, 400, "invalid_request", "attachment_ids must be an array of UUIDs", requestID)
return
}
}
@@ -74,7 +78,7 @@ func createMessageHandler(chats *services.ChatService, messages *services.Messag
writeError(w, 400, "invalid_request", "exactly one Idempotency-Key is required", requestID)
return
}
message, err := messages.CreateIdempotent(r.Context(), userID, chat, request.Text, keys[0])
message, err := messages.CreateIdempotent(r.Context(), userID, chat, *request.Text, keys[0], ids)
if err != nil {
writeServiceError(w, err, requestID)
return
+21 -3
View File
@@ -35,6 +35,19 @@ func main() {
if environment := os.Getenv("APP_ENV"); environment != "" {
log.SetPrefix("[" + environment + "] ")
}
if len(os.Args) == 2 && os.Args[1] == "s3-bootstrap" {
objects, err := repositories.NewObjectStoreFromEnvironment()
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err = objects.Bootstrap(ctx); err != nil {
log.Fatal("S3 bootstrap failed")
}
log.Print("private S3 bucket ready")
return
}
if len(os.Args) > 1 {
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
client := http.Client{Timeout: 2 * time.Second}
@@ -109,14 +122,19 @@ func main() {
sessionService := services.NewSessionService(userService, sessionStore, ttl)
chatService := services.NewChatService(chatStore)
messageService := services.NewMessageService(messageStore)
mux := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db), sessionStore), userService, sessionService, chatService, messageService)
objects, err := repositories.NewObjectStoreFromEnvironment()
if err != nil {
log.Fatal(err)
}
attachmentService := services.NewAttachmentService(repositories.NewAttachmentStore(db), objects)
mux := handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(db), sessionStore, objects), userService, sessionService, chatService, messageService, attachmentService)
server := &http.Server{
Addr: serverAddress(),
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
+42
View File
@@ -0,0 +1,42 @@
package repositories
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
"time"
)
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 time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ObjectKey string `json:"-"`
}
type AttachmentStore struct{ db *pgxpool.Pool }
func NewAttachmentStore(db *pgxpool.Pool) *AttachmentStore { return &AttachmentStore{db: db} }
func (s *AttachmentStore) Create(ctx context.Context, a Attachment) error {
ctx, cancel := boundedQuery(ctx)
defer cancel()
_, err := s.db.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ObjectKey, a.ContentType, a.SizeBytes, a.SHA256, a.CreatedAt, a.UpdatedAt)
return err
}
func (s *AttachmentStore) GetForMember(ctx context.Context, id, userID string) (Attachment, error) {
ctx, cancel := boundedQuery(ctx)
defer cancel()
a := Attachment{Status: "ready", Variants: []any{}}
err := s.db.QueryRow(ctx, `SELECT a.id,a.chat_id,a.owner_id,a.filename,a.object_key,a.content_type,a.size_bytes,a.sha256,a.created_at,a.updated_at FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id WHERE a.id=$1 AND cm.user_id=$2`, id, userID).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.CreatedAt, &a.UpdatedAt)
a.CreatedAt = a.CreatedAt.UTC()
a.UpdatedAt = a.UpdatedAt.UTC()
return a, err
}
+27 -5
View File
@@ -3,16 +3,23 @@ package repositories
import (
"context"
"errors"
"reflect"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
var ErrAttachmentNotFound = errors.New("attachment not found")
var ErrIdempotencyConflict = errors.New("idempotency key belongs to a different message")
// CreateIdempotent commits the message and its replay record together.
func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, text, key string) (Message, error) {
func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, text, key string, attachments ...[]string) (Message, error) {
ids := []string{}
if len(attachments) > 0 && attachments[0] != nil {
ids = attachments[0]
}
ctx, cancel := boundedQuery(ctx)
defer cancel()
tx, err := s.db.Begin(ctx)
@@ -27,16 +34,26 @@ func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, t
if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", scope); err != nil {
return Message{}, err
}
// Validate attachments in this same transaction, including replay.
for _, id := range ids {
var exists bool
if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachments WHERE id=$1 AND chat_id=$2)", id, chatID).Scan(&exists); err != nil {
return Message{}, err
}
if !exists {
return Message{}, ErrAttachmentNotFound
}
}
var message Message
err = tx.QueryRow(ctx, `
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, ARRAY(SELECT attachment_id::text FROM message_attachments ma WHERE ma.message_id=m.id ORDER BY position)
FROM message_idempotency i JOIN messages m ON m.id = i.message_id
WHERE i.sender_id=$1 AND i.chat_id=$2 AND i.key=$3
AND i.expires_at > clock_timestamp()`, senderID, chatID, key).
Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt)
Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt, &message.AttachmentIDs)
if err == nil {
message.CreatedAt = message.CreatedAt.UTC()
if message.Text != text {
if message.Text != text || !reflect.DeepEqual(message.AttachmentIDs, ids) {
return Message{}, ErrIdempotencyConflict
}
return message, tx.Commit(ctx)
@@ -50,12 +67,17 @@ func (s *MessageStore) CreateIdempotent(ctx context.Context, chatID, senderID, t
return Message{}, err
}
message = Message{
ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text,
AttachmentIDs: ids, ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text,
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
}
if _, err = tx.Exec(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", message.ID, chatID, senderID, text, message.CreatedAt); err != nil {
return Message{}, err
}
for position, id := range ids {
if _, err = tx.Exec(ctx, "INSERT INTO message_attachments(message_id,attachment_id,position) VALUES($1,$2,$3)", message.ID, id, position); err != nil {
return Message{}, err
}
}
if _, err = tx.Exec(ctx, `INSERT INTO message_idempotency(sender_id,chat_id,key,message_id,expires_at)
VALUES($1,$2,$3,$4,clock_timestamp() + $5 * interval '1 second')`, senderID, chatID, key, message.ID, s.idempotencyTTL.Seconds()); err != nil {
return Message{}, err
+14 -12
View File
@@ -9,11 +9,12 @@ import (
)
type Message struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt time.Time `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
type MessageStore struct {
@@ -38,11 +39,12 @@ func (s *MessageStore) Create(
ctx, cancel := boundedQuery(ctx)
defer cancel()
message := Message{
ID: uuid.New().String(),
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
AttachmentIDs: []string{},
ID: uuid.New().String(),
ChatID: chatID,
SenderID: senderID,
Text: text,
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
}
_, err := s.db.Exec(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt)
@@ -63,7 +65,7 @@ func (s *MessageStore) ListPageByChat(
afterTime = cursor.CreatedAt
afterID = cursor.MessageID
}
rows, err := s.db.Query(ctx, `SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=$1 AND (created_at,id)>($2,$3::uuid) ORDER BY created_at,id LIMIT $4`, chatID, afterTime, afterID, limit+1)
rows, err := s.db.Query(ctx, `SELECT id,chat_id,sender_id,text,created_at,ARRAY(SELECT attachment_id::text FROM message_attachments ma WHERE ma.message_id=messages.id ORDER BY position) FROM messages WHERE chat_id=$1 AND (created_at,id)>($2,$3::uuid) ORDER BY created_at,id LIMIT $4`, chatID, afterTime, afterID, limit+1)
if err != nil {
return nil, false, err
}
@@ -71,7 +73,7 @@ func (s *MessageStore) ListPageByChat(
items := []Message{}
for rows.Next() {
var m Message
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt, &m.AttachmentIDs); err != nil {
return nil, false, err
}
items = append(items, m)
@@ -0,0 +1,5 @@
-- An operator must first remove attachment-only messages before this rollback.
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
ALTER TABLE messages ADD CONSTRAINT messages_text_check CHECK (char_length(text) BETWEEN 1 AND 4000);
DROP TABLE message_attachments;
DROP TABLE attachments;
@@ -0,0 +1,22 @@
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id),
owner_id uuid NOT NULL REFERENCES users(id),
filename text NOT NULL,
object_key text NOT NULL UNIQUE,
content_type text NOT NULL CHECK (content_type IN ('image/png','image/jpeg')),
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL
);
CREATE INDEX attachments_chat_idx ON attachments(chat_id);
CREATE TABLE message_attachments (
message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
attachment_id uuid NOT NULL REFERENCES attachments(id),
position smallint NOT NULL CHECK (position BETWEEN 0 AND 9),
PRIMARY KEY (message_id, attachment_id),
UNIQUE(message_id, position)
);
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
ALTER TABLE messages ADD CONSTRAINT messages_text_check CHECK (char_length(text) <= 4000);
+99
View File
@@ -0,0 +1,99 @@
package repositories
import (
"context"
"errors"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
)
type ObjectStore struct {
client *minio.Client
bucket string
}
func NewObjectStoreFromEnvironment() (*ObjectStore, error) {
endpoint, err := url.Parse(os.Getenv("S3_ENDPOINT"))
if err != nil || endpoint.Host == "" || (endpoint.Scheme != "http" && endpoint.Scheme != "https") || endpoint.Path != "" {
return nil, errors.New("invalid S3_ENDPOINT")
}
read := func(name string) (string, error) {
b, e := os.ReadFile(os.Getenv(name))
if e != nil {
return "", errors.New("cannot read " + name)
}
v := strings.TrimSpace(string(b))
if v == "" {
return "", errors.New("empty " + name)
}
return v, nil
}
access, err := read("S3_ACCESS_KEY_ID_FILE")
if err != nil {
return nil, err
}
secret, err := read("S3_SECRET_ACCESS_KEY_FILE")
if err != nil {
return nil, err
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.ResponseHeaderTimeout = 5 * time.Second
transport.MaxIdleConnsPerHost = 8
client, err := minio.New(endpoint.Host, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: endpoint.Scheme == "https", Region: os.Getenv("S3_REGION"), Transport: transport})
if err != nil {
return nil, err
}
bucket := os.Getenv("S3_BUCKET")
if bucket == "" {
return nil, errors.New("S3_BUCKET is required")
}
return &ObjectStore{client: client, bucket: bucket}, nil
}
func (s *ObjectStore) Ping(ctx context.Context) error {
exists, err := s.client.BucketExists(ctx, s.bucket)
if err != nil {
return err
}
if !exists {
return errors.New("bucket missing")
}
return nil
}
func (s *ObjectStore) Bootstrap(ctx context.Context) error {
exists, err := s.client.BucketExists(ctx, s.bucket)
if err != nil {
return err
}
if !exists {
if err = s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{Region: os.Getenv("S3_REGION")}); err != nil {
return err
}
}
// No anonymous policy: every object operation requires signed credentials.
return s.client.SetBucketPolicy(ctx, s.bucket, "")
}
func (s *ObjectStore) Put(ctx context.Context, key string, body io.Reader, size int64, contentType string) error {
_, err := s.client.PutObject(ctx, s.bucket, key, body, size, minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true})
return err
}
func (s *ObjectStore) Delete(ctx context.Context, key string) error {
return s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{})
}
func (s *ObjectStore) Get(ctx context.Context, key string) (io.ReadCloser, error) {
object, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
if err != nil {
return nil, err
}
// GetObject is lazy: force the request before writing HTTP 200 headers.
if _, err = object.Stat(); err != nil {
object.Close()
return nil, err
}
return object, nil
}
+148
View File
@@ -0,0 +1,148 @@
package services
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"log"
"messenger/src/backend/repositories"
"mime"
"strings"
"time"
"unicode"
"unicode/utf8"
)
const MaxUploadBytes int64 = 10485760
const MaxImagePixels int64 = 40000000
var ErrPayloadTooLarge = errors.New("payload too large")
var ErrUnsupportedMedia = errors.New("unsupported image")
var ErrAttachmentNotFound = errors.New("attachment not found")
type AttachmentService struct {
metadata *repositories.AttachmentStore
objects *repositories.ObjectStore
uploadSlot chan struct{}
}
func NewAttachmentService(metadata *repositories.AttachmentStore, objects *repositories.ObjectStore) *AttachmentService {
return &AttachmentService{metadata: metadata, objects: objects, uploadSlot: make(chan struct{}, 1)}
}
func ValidateFilename(name string) error {
if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 {
return InvalidInput{"filename must contain 1-255 characters"}
}
for _, r := range name {
if r == '/' || r == '\\' || unicode.IsControl(r) {
return InvalidInput{"invalid filename"}
}
}
return nil
}
func ValidateImage(data []byte, declared string) (string, error) {
contentType, _, err := mime.ParseMediaType(declared)
if err != nil || (contentType != "image/png" && contentType != "image/jpeg") {
return "", ErrUnsupportedMedia
}
config, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil {
return "", ErrUnsupportedMedia
}
actual := "image/" + format
if actual != contentType {
return "", ErrUnsupportedMedia
}
if config.Width <= 0 || config.Height <= 0 || int64(config.Width) > MaxImagePixels/int64(config.Height) {
return "", ErrPayloadTooLarge
}
// DecodeConfig alone accepts truncated headers; decode only after bounding pixels.
decoded, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return "", ErrUnsupportedMedia
}
_ = decoded
return actual, nil
}
func (s *AttachmentService) Upload(ctx context.Context, userID, chatID, filename, contentType string, body io.Reader) (repositories.Attachment, error) {
select {
case s.uploadSlot <- struct{}{}:
defer func() { <-s.uploadSlot }()
case <-ctx.Done():
return repositories.Attachment{}, ctx.Err()
}
data, err := io.ReadAll(io.LimitReader(body, MaxUploadBytes+1))
if err != nil {
return repositories.Attachment{}, err
}
if int64(len(data)) > MaxUploadBytes {
return repositories.Attachment{}, ErrPayloadTooLarge
}
actual, err := ValidateImage(data, contentType)
if err != nil {
return repositories.Attachment{}, err
}
sum := sha256.Sum256(data)
now := time.Now().UTC().Truncate(time.Microsecond)
a := repositories.Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: filename, ContentType: actual, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(sum[:]), Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
a.ObjectKey = "originals/" + a.ID
if err = s.objects.Put(ctx, a.ObjectKey, bytes.NewReader(data), a.SizeBytes, a.ContentType); err != nil {
return repositories.Attachment{}, err
}
if err = s.metadata.Create(ctx, a); err != nil {
// A connection error can hide a successful autocommit. Delete only after
// a definite SQL rejection; otherwise preserve bytes for later reconciliation.
var rejected *pgconn.PgError
if errors.As(err, &rejected) {
cleanup, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if cleanupErr := s.objects.Delete(cleanup, a.ObjectKey); cleanupErr != nil {
log.Printf("attachment compensation failed for %s", a.ID)
}
} else {
log.Printf("attachment metadata outcome uncertain for %s; preserving S3 object", a.ID)
}
return repositories.Attachment{}, err
}
return a, nil
}
func (s *AttachmentService) Get(ctx context.Context, id, userID string) (repositories.Attachment, error) {
a, err := s.metadata.GetForMember(ctx, id, userID)
if errors.Is(err, pgx.ErrNoRows) {
return a, ErrAttachmentNotFound
}
return a, err
}
func (s *AttachmentService) Content(ctx context.Context, a repositories.Attachment) (io.ReadCloser, error) {
return s.objects.Get(ctx, a.ObjectKey)
}
func NormalizeAttachmentIDs(ids []string) ([]string, error) {
if len(ids) > 10 {
return nil, InvalidInput{"at most 10 attachments are allowed"}
}
result := make([]string, 0, len(ids))
seen := map[string]bool{}
for _, id := range ids {
parsed, err := uuid.Parse(id)
if err != nil {
return nil, InvalidInput{"invalid attachment id"}
}
id = strings.ToLower(parsed.String())
if seen[id] {
return nil, InvalidInput{"duplicate attachment id"}
}
seen[id] = true
result = append(result, id)
}
return result, nil
}
+14 -3
View File
@@ -9,15 +9,26 @@ import (
type HealthService struct {
health *repositories.HealthStore
sessions *repositories.SessionStore
objects interface{ Ping(context.Context) error }
}
func NewHealthService(health *repositories.HealthStore, sessions *repositories.SessionStore) *HealthService {
return &HealthService{health: health, sessions: sessions}
func NewHealthService(health *repositories.HealthStore, sessions *repositories.SessionStore, objects ...interface{ Ping(context.Context) error }) *HealthService {
service := &HealthService{health: health, sessions: sessions}
if len(objects) > 0 {
service.objects = objects[0]
}
return service
}
func (s *HealthService) Ready(ctx context.Context) error {
if err := s.health.Ping(ctx); err != nil {
return err
}
return s.sessions.Ping(ctx)
if err := s.sessions.Ping(ctx); err != nil {
return err
}
if s.objects != nil {
return s.objects.Ping(ctx)
}
return nil
}
+15 -4
View File
@@ -12,17 +12,28 @@ import (
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (s *MessageService) CreateIdempotent(ctx context.Context, userID string, chat repositories.Chat, text, key string) (repositories.Message, error) {
func (s *MessageService) CreateIdempotent(ctx context.Context, userID string, chat repositories.Chat, text, key string, attachments ...[]string) (repositories.Message, error) {
if !ChatHasMember(chat, userID) {
return repositories.Message{}, ErrChatNotFound
}
if !idempotencyKeyPattern.MatchString(key) {
return repositories.Message{}, InvalidInput{"Idempotency-Key must contain 1-128 ASCII letters, digits or ._:-"}
}
if strings.TrimSpace(text) == "" || utf8.RuneCountInString(text) > 4000 {
return repositories.Message{}, InvalidInput{"text must contain 1-4000 characters and must not be blank"}
var ids []string
if len(attachments) > 0 {
ids = attachments[0]
}
ids, err := NormalizeAttachmentIDs(ids)
if err != nil {
return repositories.Message{}, err
}
if (strings.TrimSpace(text) == "" && len(ids) == 0) || utf8.RuneCountInString(text) > 4000 {
return repositories.Message{}, InvalidInput{"text must be at most 4000 characters; nonblank text or attachments required"}
}
message, err := s.messages.CreateIdempotent(ctx, chat.ID, userID, text, key, ids)
if errors.Is(err, repositories.ErrAttachmentNotFound) {
return repositories.Message{}, ErrAttachmentNotFound
}
message, err := s.messages.CreateIdempotent(ctx, chat.ID, userID, text, key)
if errors.Is(err, repositories.ErrIdempotencyConflict) {
return repositories.Message{}, ErrConflict
}
@@ -0,0 +1,94 @@
package tests
import (
"bytes"
"context"
"encoding/binary"
"errors"
"github.com/google/uuid"
"hash/crc32"
"image"
"image/jpeg"
"image/png"
"messenger/src/backend/repositories"
"messenger/src/backend/services"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestAttachmentImageValidation(t *testing.T) {
img := image.NewRGBA(image.Rect(0, 0, 3, 2))
var pngData, jpegData bytes.Buffer
if err := png.Encode(&pngData, img); err != nil {
t.Fatal(err)
}
if err := jpeg.Encode(&jpegData, img, nil); err != nil {
t.Fatal(err)
}
for _, sample := range []struct {
data []byte
mime string
}{{pngData.Bytes(), "image/png"}, {jpegData.Bytes(), "image/jpeg"}} {
if actual, err := services.ValidateImage(sample.data, sample.mime); err != nil || actual != sample.mime {
t.Fatalf("valid image: %s %v", actual, err)
}
}
huge := append([]byte(nil), pngData.Bytes()...)
binary.BigEndian.PutUint32(huge[16:20], 10001)
binary.BigEndian.PutUint32(huge[20:24], 4000)
binary.BigEndian.PutUint32(huge[29:33], crc32.ChecksumIEEE(huge[12:29]))
if _, err := services.ValidateImage(huge, "image/png"); !errors.Is(err, services.ErrPayloadTooLarge) {
t.Fatalf("pixel limit: %v", err)
}
for _, sample := range []struct {
data []byte
mime string
}{{pngData.Bytes(), "image/jpeg"}, {jpegData.Bytes(), "image/png"}, {pngData.Bytes()[:40], "image/png"}, {[]byte("not an image"), "image/png"}, {pngData.Bytes(), "text/plain"}} {
if _, err := services.ValidateImage(sample.data, sample.mime); !errors.Is(err, services.ErrUnsupportedMedia) {
t.Fatalf("invalid image accepted: %v", err)
}
}
}
func TestAttachmentFilenameValidation(t *testing.T) {
for _, name := range []string{"", " ", "../photo.png", `a\b.png`, "photo\x00.png", "photo\n.png"} {
if services.ValidateFilename(name) == nil {
t.Fatalf("accepted %q", name)
}
}
if err := services.ValidateFilename("Фотография 1.png"); err != nil {
t.Fatal(err)
}
}
func TestAttachmentMessageRequiresStringText(t *testing.T) {
f := newTestFixture(t)
user, _ := createTestUser(t, f.users, "alice", "Alice")
chat := createTestChat(t, f.chats, "Images", []string{user.ID})
id := uuid.NewString()
// Repository-level fixture: message validation does not fetch S3 bytes.
err := repositories.NewAttachmentStore(f.db).Create(context.Background(), repositories.Attachment{
ID: id, ChatID: chat.ID, OwnerID: user.ID, Filename: "photo.png", ObjectKey: "test/" + id,
ContentType: "image/png", SizeBytes: 1, SHA256: strings.Repeat("a", 64), CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC(),
})
if err != nil {
t.Fatal(err)
}
for _, body := range []string{`{"attachment_ids":["` + id + `"]}`, `{"text":null,"attachment_ids":["` + id + `"]}`} {
r := httptest.NewRequest(http.MethodPost, "/api/v1/chats/"+chat.ID+"/messages", strings.NewReader(body))
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Idempotency-Key", uuid.NewString())
authorizeTestRequest(t, f, r, user.ID)
w := httptest.NewRecorder()
f.router.ServeHTTP(w, r)
if w.Code != 400 {
t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
}
}
if len(listTestMessages(t, f.messages, chat.ID)) != 0 {
t.Fatal("invalid request saved a message")
}
}
+2 -1
View File
@@ -3,6 +3,7 @@ package tests
import (
"context"
"errors"
"reflect"
"sync"
"testing"
@@ -44,7 +45,7 @@ func TestIdempotencyConcurrentStoresAndScopes(t *testing.T) {
for message := range results {
if original.ID == "" {
original = message
} else if message != original {
} else if !reflect.DeepEqual(message, original) {
t.Fatalf("replay changed the message: %v != %v", message, original)
}
}
+7
View File
@@ -85,6 +85,13 @@ func newTestFixture(t *testing.T) *testFixture {
if _, err = db.Exec(ctx, string(ddl)); err != nil {
t.Fatal(err)
}
ddl, err = os.ReadFile("../repositories/migrations/000004_attachments.up.sql")
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, string(ddl)); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = redisClient.Close() })
if err := redisClient.Ping(ctx).Err(); err != nil {
t.Fatal(err)