lab4: S3-вложения, presigned upload и проверки
This commit is contained in:
@@ -0,0 +1,318 @@
|
||||
package attachment_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
"mtusi-messenger/internal/service/attachment"
|
||||
"mtusi-messenger/internal/service/attachment/mocks"
|
||||
)
|
||||
|
||||
type storedObject struct {
|
||||
data []byte
|
||||
contentType string
|
||||
metadata map[string]string
|
||||
lastModified time.Time
|
||||
}
|
||||
|
||||
type fakeStore struct {
|
||||
objects map[string]storedObject
|
||||
}
|
||||
|
||||
func newFakeStore() *fakeStore {
|
||||
return &fakeStore{objects: make(map[string]storedObject)}
|
||||
}
|
||||
|
||||
func (f *fakeStore) Put(
|
||||
_ context.Context,
|
||||
key string,
|
||||
body io.ReadSeeker,
|
||||
_ int64,
|
||||
contentType string,
|
||||
metadata map[string]string,
|
||||
) error {
|
||||
data, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
f.objects[key] = storedObject{
|
||||
data: data,
|
||||
contentType: contentType,
|
||||
metadata: metadata,
|
||||
lastModified: time.Now().UTC(),
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Open(_ context.Context, key string) (io.ReadCloser, objectstore.Object, error) {
|
||||
object, ok := f.objects[key]
|
||||
if !ok {
|
||||
return nil, objectstore.Object{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
return io.NopCloser(bytes.NewReader(object.data)), f.object(key, object), nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Head(_ context.Context, key string) (objectstore.Object, error) {
|
||||
object, ok := f.objects[key]
|
||||
if !ok {
|
||||
return objectstore.Object{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
return f.object(key, object), nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Copy(_ context.Context, src, dst, contentType string, metadata map[string]string) error {
|
||||
object, ok := f.objects[src]
|
||||
if !ok {
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
|
||||
f.objects[dst] = storedObject{
|
||||
data: append([]byte(nil), object.data...),
|
||||
contentType: contentType,
|
||||
metadata: metadata,
|
||||
lastModified: time.Now().UTC(),
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Delete(_ context.Context, key string) error {
|
||||
delete(f.objects, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) List(_ context.Context, prefix string) ([]objectstore.Object, error) {
|
||||
objects := make([]objectstore.Object, 0, len(f.objects))
|
||||
for key, object := range f.objects {
|
||||
if strings.HasPrefix(key, prefix) {
|
||||
objects = append(objects, f.object(key, object))
|
||||
}
|
||||
}
|
||||
|
||||
return objects, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) PresignPut(_ context.Context, key string, ttl time.Duration) (string, time.Time, error) {
|
||||
return "http://s3.example/" + key, time.Now().UTC().Add(ttl), nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) object(key string, object storedObject) objectstore.Object {
|
||||
return objectstore.Object{
|
||||
Key: key,
|
||||
Size: int64(len(object.data)),
|
||||
ContentType: object.contentType,
|
||||
LastModified: object.lastModified,
|
||||
Metadata: object.metadata,
|
||||
}
|
||||
}
|
||||
|
||||
func pngBytes(t *testing.T, width, height int) []byte {
|
||||
t.Helper()
|
||||
|
||||
source := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
for x := range width {
|
||||
for y := range height {
|
||||
source.Set(x, y, color.RGBA{R: uint8(x), G: uint8(y), B: 200, A: 255})
|
||||
}
|
||||
}
|
||||
|
||||
var buffer bytes.Buffer
|
||||
require.NoError(t, png.Encode(&buffer, source))
|
||||
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
func serviceConfig() attachment.Config {
|
||||
return attachment.Config{
|
||||
MaxUploadBytes: 1 << 20,
|
||||
MaxImagePixels: 1_000_000,
|
||||
PresignTTL: 5 * time.Minute,
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateFilename(t *testing.T) {
|
||||
valid := []string{"photo.png", "фото.png", "a b.jpeg", strings.Repeat("я", 255)}
|
||||
for _, name := range valid {
|
||||
require.NoError(t, attachment.ValidateFilename(name), name)
|
||||
}
|
||||
|
||||
invalid := []string{"", strings.Repeat("x", 256), "a/b.png", `a\b.png`, "a\x00b.png", "a\nb.png"}
|
||||
for _, name := range invalid {
|
||||
require.ErrorIs(t, attachment.ValidateFilename(name), domain.ErrValidation, name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadStoresOriginal(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
store := newFakeStore()
|
||||
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
||||
|
||||
chatID := uuid.New()
|
||||
ownerID := uuid.New()
|
||||
content := pngBytes(t, 16, 16)
|
||||
sum := sha256.Sum256(content)
|
||||
|
||||
repo.EXPECT().IsChatMember(mock.Anything, chatID, ownerID).Return(true, nil).Once()
|
||||
repo.EXPECT().Create(mock.Anything, mock.MatchedBy(func(draft domain.AttachmentDraft) bool {
|
||||
return draft.ChatID == chatID && draft.OwnerID == ownerID &&
|
||||
draft.ContentType == "image/png" && draft.SizeBytes == int64(len(content)) &&
|
||||
draft.SHA256 == hex.EncodeToString(sum[:]) && strings.HasPrefix(draft.ObjectKey, "attachments/")
|
||||
})).Return(domain.Attachment{Status: domain.AttachmentPending}, nil).Once()
|
||||
repo.EXPECT().MarkReady(mock.Anything, mock.Anything, mock.Anything).
|
||||
Return(domain.Attachment{Status: domain.AttachmentReady, ContentType: "image/png", SizeBytes: int64(len(content))}, nil).
|
||||
Once()
|
||||
|
||||
result, err := service.Upload(t.Context(), attachment.UploadInput{
|
||||
ChatID: chatID,
|
||||
OwnerID: ownerID,
|
||||
Filename: "photo.png",
|
||||
DeclaredContentType: "image/png",
|
||||
Body: bytes.NewReader(content),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, domain.AttachmentReady, result.Status)
|
||||
require.Len(t, store.objects, 1)
|
||||
}
|
||||
|
||||
func TestUploadRejectsTooLargeBody(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
service := attachment.NewService(repo, newFakeStore(), attachment.Config{
|
||||
MaxUploadBytes: 8,
|
||||
MaxImagePixels: 1_000_000,
|
||||
PresignTTL: time.Minute,
|
||||
}, slog.Default())
|
||||
|
||||
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
|
||||
|
||||
_, err := service.Upload(t.Context(), attachment.UploadInput{
|
||||
ChatID: uuid.New(),
|
||||
OwnerID: uuid.New(),
|
||||
Filename: "photo.png",
|
||||
DeclaredContentType: "image/png",
|
||||
Body: bytes.NewReader(bytes.Repeat([]byte("x"), 9)),
|
||||
})
|
||||
|
||||
require.ErrorIs(t, err, domain.ErrTooLarge)
|
||||
}
|
||||
|
||||
func TestUploadRejectsMIMEMismatch(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
||||
|
||||
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
|
||||
|
||||
_, err := service.Upload(t.Context(), attachment.UploadInput{
|
||||
ChatID: uuid.New(),
|
||||
OwnerID: uuid.New(),
|
||||
Filename: "photo.jpg",
|
||||
DeclaredContentType: "image/jpeg",
|
||||
Body: bytes.NewReader(pngBytes(t, 8, 8)),
|
||||
})
|
||||
|
||||
require.ErrorIs(t, err, domain.ErrUnsupportedMedia)
|
||||
}
|
||||
|
||||
func TestGetRejectsNonReadyAttachment(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
||||
|
||||
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, mock.Anything).
|
||||
Return(domain.Attachment{Status: domain.AttachmentPending}, nil).Once()
|
||||
|
||||
_, err := service.Get(t.Context(), uuid.New(), uuid.New())
|
||||
require.ErrorIs(t, err, domain.ErrConflict)
|
||||
}
|
||||
|
||||
func TestCompletePublishesPresignedObject(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
store := newFakeStore()
|
||||
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
||||
|
||||
id := uuid.New()
|
||||
chatID := uuid.New()
|
||||
ownerID := uuid.New()
|
||||
content := pngBytes(t, 10, 10)
|
||||
sum := sha256.Sum256(content)
|
||||
digest := hex.EncodeToString(sum[:])
|
||||
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
|
||||
|
||||
store.objects[stagingKey] = storedObject{
|
||||
data: content,
|
||||
contentType: "image/png",
|
||||
metadata: map[string]string{"sha256": digest},
|
||||
lastModified: time.Now().UTC(),
|
||||
}
|
||||
|
||||
pending := domain.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
|
||||
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
|
||||
Status: domain.AttachmentPending,
|
||||
}
|
||||
|
||||
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
|
||||
repo.EXPECT().MarkReady(mock.Anything, id, mock.MatchedBy(func(key string) bool {
|
||||
return strings.HasPrefix(key, "attachments/")
|
||||
})).Return(domain.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: ownerID, ContentType: "image/png",
|
||||
SizeBytes: int64(len(content)), SHA256: digest, Status: domain.AttachmentReady,
|
||||
}, nil).Once()
|
||||
|
||||
completed, err := service.Complete(t.Context(), ownerID, id, digest)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, domain.AttachmentReady, completed.Status)
|
||||
require.NotContains(t, store.objects, stagingKey)
|
||||
require.Len(t, store.objects, 1)
|
||||
}
|
||||
|
||||
func TestCompleteRejectsChecksumMismatch(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
store := newFakeStore()
|
||||
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
||||
|
||||
id := uuid.New()
|
||||
chatID := uuid.New()
|
||||
ownerID := uuid.New()
|
||||
content := pngBytes(t, 10, 10)
|
||||
sum := sha256.Sum256(content)
|
||||
digest := hex.EncodeToString(sum[:])
|
||||
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
|
||||
|
||||
store.objects[stagingKey] = storedObject{
|
||||
data: content,
|
||||
contentType: "image/png",
|
||||
metadata: map[string]string{"sha256": digest},
|
||||
}
|
||||
|
||||
pending := domain.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
|
||||
ContentType: "image/png", SizeBytes: int64(len(content)) + 1, SHA256: digest,
|
||||
Status: domain.AttachmentPending,
|
||||
}
|
||||
|
||||
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
|
||||
repo.EXPECT().DeletePending(mock.Anything, id).Return(nil).Once()
|
||||
|
||||
_, err := service.Complete(t.Context(), ownerID, id, digest)
|
||||
require.ErrorIs(t, err, domain.ErrValidation)
|
||||
require.NotContains(t, store.objects, stagingKey)
|
||||
}
|
||||
Reference in New Issue
Block a user