forked from mtusi2026/mtusi2026lab4
feat: attachments over S3 (grade 3)
This commit is contained in:
@@ -0,0 +1,186 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
originalVariant = "original"
|
||||
maxFilenameRunes = 255
|
||||
sniffBytes = 512
|
||||
)
|
||||
|
||||
type AttachmentService struct {
|
||||
chats *ChatService
|
||||
repo AttachmentRepository
|
||||
store ObjectStore
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
}
|
||||
|
||||
func NewAttachmentService(chats *ChatService, repo AttachmentRepository, store ObjectStore, maxBytes, maxPixels int64) *AttachmentService {
|
||||
return &AttachmentService{chats: chats, repo: repo, store: store, maxBytes: maxBytes, maxPixels: maxPixels}
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Upload(ctx context.Context, actor domain.User, chatID uuid.UUID, filename, contentType string, body io.Reader) (domain.Attachment, error) {
|
||||
if _, err := s.chats.Get(ctx, actor, chatID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := checkFilename(filename); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if contentType != domain.ContentPNG && contentType != domain.ContentJPEG {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: content type must be image/png or image/jpeg", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
raw, err := readLimited(body, s.maxBytes)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if detected := detectImageType(raw); detected != contentType {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: body does not match the declared image type", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
if err := checkPixels(raw, s.maxPixels); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := checkIntegrity(raw); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
id := uuid.New()
|
||||
sum := sha256.Sum256(raw)
|
||||
createdAt := now()
|
||||
attachment := domain.Attachment{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
OwnerID: actor.ID,
|
||||
Filename: filename,
|
||||
ContentType: contentType,
|
||||
SizeBytes: int64(len(raw)),
|
||||
SHA256: hex.EncodeToString(sum[:]),
|
||||
ObjectKey: "chats/" + chatID.String() + "/" + id.String(),
|
||||
Status: domain.AttachmentReady,
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: createdAt,
|
||||
}
|
||||
if err := s.store.Put(ctx, attachment.ObjectKey, bytes.NewReader(raw), attachment.SizeBytes, contentType); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if err := s.repo.CreateAttachment(ctx, attachment); err != nil {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = s.store.Delete(cleanupCtx, attachment.ObjectKey)
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Get(ctx context.Context, actor domain.User, id uuid.UUID) (domain.Attachment, error) {
|
||||
attachment, err := s.repo.GetAttachment(ctx, id)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
if _, err := s.chats.Get(ctx, actor, attachment.ChatID); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentService) Open(ctx context.Context, actor domain.User, id uuid.UUID, variant string) (domain.Attachment, io.ReadCloser, error) {
|
||||
if variant == "" {
|
||||
variant = originalVariant
|
||||
}
|
||||
if variant != originalVariant {
|
||||
return domain.Attachment{}, nil, fmt.Errorf("%w: only the original variant is available", domain.ErrInvalidInput)
|
||||
}
|
||||
attachment, err := s.repo.GetAttachment(ctx, id)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
if _, err := s.chats.Get(ctx, actor, attachment.ChatID); err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
if attachment.Status != domain.AttachmentReady {
|
||||
return domain.Attachment{}, nil, fmt.Errorf("%w: attachment is not ready", domain.ErrConflict)
|
||||
}
|
||||
content, err := s.store.Get(ctx, attachment.ObjectKey)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
return attachment, content, nil
|
||||
}
|
||||
|
||||
func checkFilename(filename string) error {
|
||||
if n := utf8.RuneCountInString(filename); n < 1 || n > maxFilenameRunes {
|
||||
return fmt.Errorf("%w: filename must be 1 to 255 characters", domain.ErrInvalidInput)
|
||||
}
|
||||
for _, r := range filename {
|
||||
if unicode.IsControl(r) || r == '/' || r == '\\' {
|
||||
return fmt.Errorf("%w: filename contains forbidden characters", domain.ErrInvalidInput)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readLimited(body io.Reader, max int64) ([]byte, error) {
|
||||
raw, err := io.ReadAll(io.LimitReader(body, max+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: cannot read the upload body", domain.ErrInvalidInput)
|
||||
}
|
||||
if int64(len(raw)) > max {
|
||||
return nil, fmt.Errorf("%w: upload exceeds %d bytes", domain.ErrTooLarge, max)
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
return nil, fmt.Errorf("%w: upload body is empty", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
func detectImageType(raw []byte) string {
|
||||
sniff := raw
|
||||
if len(sniff) > sniffBytes {
|
||||
sniff = sniff[:sniffBytes]
|
||||
}
|
||||
switch http.DetectContentType(sniff) {
|
||||
case domain.ContentPNG:
|
||||
return domain.ContentPNG
|
||||
case domain.ContentJPEG:
|
||||
return domain.ContentJPEG
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func checkPixels(raw []byte, max int64) error {
|
||||
config, _, err := image.DecodeConfig(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: image header cannot be decoded", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
if config.Width <= 0 || config.Height <= 0 {
|
||||
return fmt.Errorf("%w: image has invalid dimensions", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
if int64(config.Width) > max/int64(config.Height) {
|
||||
return fmt.Errorf("%w: image exceeds %d pixels", domain.ErrTooLarge, max)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkIntegrity(raw []byte) error {
|
||||
if _, _, err := image.Decode(bytes.NewReader(raw)); err != nil {
|
||||
return fmt.Errorf("%w: image is corrupted", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/png"
|
||||
"strings"
|
||||
"testing"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
func TestCheckFilename(t *testing.T) {
|
||||
valid := []string{"photo.png", "фото 1.jpg", strings.Repeat("a", 255)}
|
||||
for _, name := range valid {
|
||||
if err := checkFilename(name); err != nil {
|
||||
t.Errorf("%q: unexpected error %v", name, err)
|
||||
}
|
||||
}
|
||||
invalid := []string{"", strings.Repeat("a", 256), "dir/photo.png", `dir\photo.png`, "photo\x00.png", "photo\n.png", "photo\x7f.png"}
|
||||
for _, name := range invalid {
|
||||
if err := checkFilename(name); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("%q: got %v, want ErrInvalidInput", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectImageType(t *testing.T) {
|
||||
if got := detectImageType(encodePNG(t, 4, 4)); got != domain.ContentPNG {
|
||||
t.Errorf("png: got %q", got)
|
||||
}
|
||||
if got := detectImageType([]byte("not an image at all")); got != "" {
|
||||
t.Errorf("garbage: got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckPixels(t *testing.T) {
|
||||
if err := checkPixels(encodePNG(t, 320, 200), 40000000); err != nil {
|
||||
t.Errorf("small image: unexpected error %v", err)
|
||||
}
|
||||
if err := checkPixels(pngHeader(8000, 5000), 40000000); err != nil {
|
||||
t.Errorf("exact pixel limit: unexpected error %v", err)
|
||||
}
|
||||
if err := checkPixels(pngHeader(20000, 2001), 40000000); !errors.Is(err, domain.ErrTooLarge) {
|
||||
t.Errorf("above pixel limit: got %v, want ErrTooLarge", err)
|
||||
}
|
||||
if err := checkPixels(pngHeader(65536, 65536), 40000000); !errors.Is(err, domain.ErrTooLarge) {
|
||||
t.Errorf("huge dimensions: got %v, want ErrTooLarge", err)
|
||||
}
|
||||
if err := checkPixels([]byte("garbage"), 40000000); !errors.Is(err, domain.ErrUnsupportedMedia) {
|
||||
t.Errorf("garbage: got %v, want ErrUnsupportedMedia", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckIntegrity(t *testing.T) {
|
||||
if err := checkIntegrity(encodePNG(t, 8, 8)); err != nil {
|
||||
t.Errorf("valid png: unexpected error %v", err)
|
||||
}
|
||||
corrupted := encodePNG(t, 8, 8)
|
||||
corrupted = corrupted[:len(corrupted)-20]
|
||||
if err := checkIntegrity(corrupted); !errors.Is(err, domain.ErrUnsupportedMedia) {
|
||||
t.Errorf("truncated png: got %v, want ErrUnsupportedMedia", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckMessageText(t *testing.T) {
|
||||
if err := checkMessageText("", false); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("empty text without attachments: got %v", err)
|
||||
}
|
||||
if err := checkMessageText(" ", false); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("blank text without attachments: got %v", err)
|
||||
}
|
||||
if err := checkMessageText("", true); err != nil {
|
||||
t.Errorf("empty text with attachments: unexpected error %v", err)
|
||||
}
|
||||
if err := checkMessageText(strings.Repeat("я", 4000), true); err != nil {
|
||||
t.Errorf("4000 characters: unexpected error %v", err)
|
||||
}
|
||||
if err := checkMessageText(strings.Repeat("я", 4001), true); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("4001 characters: got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckAttachmentIDs(t *testing.T) {
|
||||
ids := make([]uuid.UUID, 10)
|
||||
for i := range ids {
|
||||
ids[i] = uuid.New()
|
||||
}
|
||||
if err := checkAttachmentIDs(ids); err != nil {
|
||||
t.Errorf("ten unique ids: unexpected error %v", err)
|
||||
}
|
||||
if err := checkAttachmentIDs(append(ids, uuid.New())); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("eleven ids: got %v", err)
|
||||
}
|
||||
if err := checkAttachmentIDs([]uuid.UUID{ids[0], ids[0]}); !errors.Is(err, domain.ErrInvalidInput) {
|
||||
t.Errorf("duplicate ids: got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageHash(t *testing.T) {
|
||||
first, second := uuid.New(), uuid.New()
|
||||
if messageHash("", nil) != messageHash("", []uuid.UUID{}) {
|
||||
t.Error("absent attachment_ids must hash like an empty list")
|
||||
}
|
||||
if messageHash("hi", []uuid.UUID{first, second}) != messageHash("hi", []uuid.UUID{second, first}) {
|
||||
t.Error("attachment order must not change the hash")
|
||||
}
|
||||
if messageHash("hi", nil) == messageHash("hi!", nil) {
|
||||
t.Error("different text must change the hash")
|
||||
}
|
||||
if messageHash("hi", []uuid.UUID{first}) == messageHash("hi", []uuid.UUID{second}) {
|
||||
t.Error("different attachments must change the hash")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadLimited(t *testing.T) {
|
||||
raw, err := readLimited(strings.NewReader("abcd"), 4)
|
||||
if err != nil || string(raw) != "abcd" {
|
||||
t.Fatalf("exact limit: got %q, %v", raw, err)
|
||||
}
|
||||
if _, err := readLimited(strings.NewReader("abcde"), 4); !errors.Is(err, domain.ErrTooLarge) {
|
||||
t.Errorf("over limit: got %v, want ErrTooLarge", err)
|
||||
}
|
||||
if _, err := readLimited(strings.NewReader(""), 4); !errors.Is(err, domain.ErrUnsupportedMedia) {
|
||||
t.Errorf("empty body: got %v, want ErrUnsupportedMedia", err)
|
||||
}
|
||||
}
|
||||
|
||||
func encodePNG(t *testing.T, width, height int) []byte {
|
||||
t.Helper()
|
||||
var buffer bytes.Buffer
|
||||
if err := png.Encode(&buffer, image.NewRGBA(image.Rect(0, 0, width, height))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
func pngHeader(width, height uint32) []byte {
|
||||
var buffer bytes.Buffer
|
||||
buffer.WriteString("\x89PNG\r\n\x1a\n")
|
||||
header := make([]byte, 13)
|
||||
binary.BigEndian.PutUint32(header[0:4], width)
|
||||
binary.BigEndian.PutUint32(header[4:8], height)
|
||||
header[8], header[9] = 8, 2
|
||||
buffer.Write(binary.BigEndian.AppendUint32(nil, uint32(len(header))))
|
||||
buffer.WriteString("IHDR")
|
||||
buffer.Write(header)
|
||||
checksum := crc32.NewIEEE()
|
||||
checksum.Write([]byte("IHDR"))
|
||||
checksum.Write(header)
|
||||
buffer.Write(binary.BigEndian.AppendUint32(nil, checksum.Sum32()))
|
||||
return buffer.Bytes()
|
||||
}
|
||||
@@ -6,11 +6,16 @@ import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
"uuid"
|
||||
|
||||
"messenger/internal/domain"
|
||||
)
|
||||
|
||||
const maxMessageAttachments = 10
|
||||
|
||||
type MessageService struct {
|
||||
chats *ChatService
|
||||
messages MessageRepository
|
||||
@@ -20,22 +25,25 @@ func NewMessageService(chats *ChatService, messages MessageRepository) *MessageS
|
||||
return &MessageService{chats: chats, messages: messages}
|
||||
}
|
||||
|
||||
func (s *MessageService) Send(ctx context.Context, actor domain.User, chatID uuid.UUID, key, text string) (domain.Message, error) {
|
||||
func (s *MessageService) Send(ctx context.Context, actor domain.User, chatID uuid.UUID, key, text string, attachmentIDs []uuid.UUID) (domain.Message, error) {
|
||||
if _, err := s.chats.Get(ctx, actor, chatID); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := checkText("text", text, 4000); err != nil {
|
||||
if err := checkMessageText(text, len(attachmentIDs) > 0); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
if err := checkAttachmentIDs(attachmentIDs); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
m := domain.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: actor.ID,
|
||||
Text: text,
|
||||
CreatedAt: now(),
|
||||
ID: uuid.New(),
|
||||
ChatID: chatID,
|
||||
SenderID: actor.ID,
|
||||
Text: text,
|
||||
AttachmentIDs: attachmentIDs,
|
||||
CreatedAt: now(),
|
||||
}
|
||||
sum := sha256.Sum256([]byte(text))
|
||||
stored, err := s.messages.CreateMessageIdempotent(ctx, m, key, hex.EncodeToString(sum[:]))
|
||||
stored, err := s.messages.CreateMessageIdempotent(ctx, m, key, messageHash(text, attachmentIDs))
|
||||
if errors.Is(err, domain.ErrConflict) {
|
||||
return domain.Message{}, fmt.Errorf("%w: Idempotency-Key was already used with a different body", domain.ErrConflict)
|
||||
}
|
||||
@@ -63,3 +71,37 @@ func (s *MessageService) History(ctx context.Context, actor domain.User, chatID
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func checkMessageText(text string, hasAttachments bool) error {
|
||||
if utf8.RuneCountInString(text) > 4000 {
|
||||
return fmt.Errorf("%w: text must be at most 4000 characters", domain.ErrInvalidInput)
|
||||
}
|
||||
if !hasAttachments && strings.TrimSpace(text) == "" {
|
||||
return fmt.Errorf("%w: text must not be empty without attachments", domain.ErrInvalidInput)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkAttachmentIDs(ids []uuid.UUID) error {
|
||||
if len(ids) > maxMessageAttachments {
|
||||
return fmt.Errorf("%w: attachment_ids must contain at most %d items", domain.ErrInvalidInput, maxMessageAttachments)
|
||||
}
|
||||
seen := make(map[uuid.UUID]struct{}, len(ids))
|
||||
for _, id := range ids {
|
||||
if _, duplicate := seen[id]; duplicate {
|
||||
return fmt.Errorf("%w: attachment_ids must not contain duplicates", domain.ErrInvalidInput)
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func messageHash(text string, ids []uuid.UUID) string {
|
||||
sorted := make([]string, len(ids))
|
||||
for i, id := range ids {
|
||||
sorted[i] = id.String()
|
||||
}
|
||||
sort.Strings(sorted)
|
||||
sum := sha256.Sum256([]byte(text + "\n" + strings.Join(sorted, ",")))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
"uuid"
|
||||
|
||||
@@ -25,6 +26,18 @@ type MessageRepository interface {
|
||||
ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error)
|
||||
}
|
||||
|
||||
type AttachmentRepository interface {
|
||||
CreateAttachment(ctx context.Context, a domain.Attachment) error
|
||||
GetAttachment(ctx context.Context, id uuid.UUID) (domain.Attachment, error)
|
||||
}
|
||||
|
||||
type ObjectStore interface {
|
||||
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
type SessionStore interface {
|
||||
Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error
|
||||
Get(ctx context.Context, tokenHash string) (uuid.UUID, error)
|
||||
|
||||
Reference in New Issue
Block a user