lab4: исправления по ревью
This commit is contained in:
@@ -54,7 +54,7 @@ type S3 struct {
|
||||
|
||||
MaxUploadBytes int64 `mapstructure:"max_upload_bytes" validate:"required,gt=0,lte=10485760"`
|
||||
MaxImagePixels int64 `mapstructure:"max_image_pixels" validate:"required,gt=0,lte=40000000"`
|
||||
PresignTTL time.Duration `mapstructure:"presign_ttl" validate:"required,gt=0"`
|
||||
PresignTTL time.Duration `mapstructure:"presign_ttl" validate:"required,gt=0,lte=168h"`
|
||||
SweepInterval time.Duration `mapstructure:"sweep_interval" validate:"required,gt=0"`
|
||||
SweepGrace time.Duration `mapstructure:"sweep_grace" validate:"required,gt=0"`
|
||||
}
|
||||
@@ -229,6 +229,10 @@ func (c Config) validateDependencies() error {
|
||||
return errors.New("validate config: cache.enabled requires redis.enabled")
|
||||
}
|
||||
|
||||
if c.S3.SweepGrace <= c.S3.PresignTTL {
|
||||
return errors.New("validate config: s3.sweep_grace must exceed s3.presign_ttl")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -28,5 +28,5 @@ type Store interface {
|
||||
Copy(ctx context.Context, src, dst, contentType string, metadata map[string]string) error
|
||||
Delete(ctx context.Context, key string) error
|
||||
List(ctx context.Context, prefix string) ([]Object, error)
|
||||
PresignPut(ctx context.Context, key string, ttl time.Duration) (string, time.Time, error)
|
||||
PresignPut(ctx context.Context, key string, size int64, ttl time.Duration) (string, time.Time, error)
|
||||
}
|
||||
|
||||
@@ -229,13 +229,15 @@ func (s *S3) List(ctx context.Context, prefix string) ([]Object, error) {
|
||||
return objects, nil
|
||||
}
|
||||
|
||||
// PresignPut signs only the bucket, key and host. Deliberately no Content-Type
|
||||
// or checksum: adding them to the signed headers forces every client to send
|
||||
// exactly those headers, and SeaweedFS does not validate checksums anyway.
|
||||
// Completion verifies the actual bytes instead.
|
||||
// PresignPut signs the bucket, key, host and exact Content-Length. The size is
|
||||
// therefore enforced by S3 at write time: a client that uploads a different
|
||||
// number of bytes gets 403 SignatureDoesNotMatch. Content-Type and checksums
|
||||
// are not signed (SeaweedFS does not validate checksums); completion verifies
|
||||
// the actual bytes and their structure.
|
||||
func (s *S3) PresignPut(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
size int64,
|
||||
ttl time.Duration,
|
||||
) (string, time.Time, error) {
|
||||
expiresAt := time.Now().UTC().Add(ttl)
|
||||
@@ -243,8 +245,9 @@ func (s *S3) PresignPut(
|
||||
presigned, err := s3.NewPresignClient(s.public).PresignPutObject(
|
||||
ctx,
|
||||
&s3.PutObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
ContentLength: aws.Int64(size),
|
||||
},
|
||||
func(options *s3.PresignOptions) {
|
||||
options.Expires = ttl
|
||||
@@ -270,7 +273,9 @@ func mapObjectError(operation, subject string, err error) error {
|
||||
|
||||
if errors.As(err, &apiErr) {
|
||||
switch apiErr.ErrorCode() {
|
||||
case "NotFound", "NoSuchKey", "NoSuchBucket":
|
||||
case "NoSuchBucket":
|
||||
return fmt.Errorf("%w: %s %q: %w", domain.ErrUnavailable, operation, subject, err)
|
||||
case "NotFound", "NoSuchKey":
|
||||
return fmt.Errorf("%s %q: %w", operation, subject, domain.ErrNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/aws/smithy-go"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
func TestMapObjectErrorBucketIsUnavailable(t *testing.T) {
|
||||
err := mapObjectError("put object", "key", &smithy.GenericAPIError{
|
||||
Code: "NoSuchBucket",
|
||||
Message: "bucket is missing",
|
||||
})
|
||||
require.ErrorIs(t, err, domain.ErrUnavailable)
|
||||
}
|
||||
|
||||
func TestMapObjectErrorMissingKeyIsNotFound(t *testing.T) {
|
||||
err := mapObjectError("open object", "key", &smithy.GenericAPIError{
|
||||
Code: "NoSuchKey",
|
||||
Message: "object is missing",
|
||||
})
|
||||
require.ErrorIs(t, err, domain.ErrNotFound)
|
||||
}
|
||||
@@ -207,7 +207,11 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d
|
||||
return domain.PresignResult{}, fmt.Errorf("%w: content type %q", domain.ErrUnsupportedMedia, request.ContentType)
|
||||
}
|
||||
|
||||
if request.SizeBytes < 1 || request.SizeBytes > s.config.MaxUploadBytes {
|
||||
if request.SizeBytes < 1 {
|
||||
return domain.PresignResult{}, fmt.Errorf("%w: size %d", domain.ErrValidation, request.SizeBytes)
|
||||
}
|
||||
|
||||
if request.SizeBytes > s.config.MaxUploadBytes {
|
||||
return domain.PresignResult{}, fmt.Errorf("%w: size %d", domain.ErrTooLarge, request.SizeBytes)
|
||||
}
|
||||
|
||||
@@ -244,7 +248,7 @@ func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (d
|
||||
return domain.PresignResult{}, err
|
||||
}
|
||||
|
||||
url, expiresAt, err := s.store.PresignPut(ctx, stagingKey, s.config.PresignTTL)
|
||||
url, expiresAt, err := s.store.PresignPut(ctx, stagingKey, request.SizeBytes, s.config.PresignTTL)
|
||||
if err != nil {
|
||||
s.cleanupPending(ctx, id, "")
|
||||
|
||||
@@ -346,8 +350,8 @@ func (s *Service) Complete(
|
||||
}
|
||||
|
||||
if requestSHA != attachment.SHA256 {
|
||||
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
||||
|
||||
// The object is valid; only the completion request is inconsistent.
|
||||
// Keep the pending row and staging object so a retry can succeed.
|
||||
return domain.Attachment{}, fmt.Errorf("%w: completion checksum mismatch", domain.ErrConflict)
|
||||
}
|
||||
|
||||
@@ -454,6 +458,10 @@ func ValidateFilename(name string) error {
|
||||
return fmt.Errorf("%w: filename length is %d, want 1-255 code points", domain.ErrValidation, length)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(name) == "" {
|
||||
return fmt.Errorf("%w: filename consists of whitespace only", domain.ErrValidation)
|
||||
}
|
||||
|
||||
if strings.ContainsAny(name, "/\\\x00") {
|
||||
return fmt.Errorf("%w: filename contains a path separator or NUL", domain.ErrValidation)
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ func (f *fakeStore) List(_ context.Context, prefix string) ([]objectstore.Object
|
||||
return objects, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) PresignPut(_ context.Context, key string, ttl time.Duration) (string, time.Time, error) {
|
||||
func (f *fakeStore) PresignPut(_ context.Context, key string, _ int64, ttl time.Duration) (string, time.Time, error) {
|
||||
return "http://s3.example/" + key, time.Now().UTC().Add(ttl), nil
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ func TestValidateFilename(t *testing.T) {
|
||||
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"}
|
||||
invalid := []string{"", " ", "\t\n", 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)
|
||||
}
|
||||
@@ -316,3 +316,46 @@ func TestCompleteRejectsChecksumMismatch(t *testing.T) {
|
||||
require.ErrorIs(t, err, domain.ErrValidation)
|
||||
require.NotContains(t, store.objects, stagingKey)
|
||||
}
|
||||
|
||||
func TestCompleteKeepsObjectOnWrongRequestChecksum(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)), SHA256: digest,
|
||||
Status: domain.AttachmentPending,
|
||||
}
|
||||
|
||||
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
|
||||
|
||||
_, err := service.Complete(t.Context(), ownerID, id, strings.Repeat("0", 64))
|
||||
require.ErrorIs(t, err, domain.ErrConflict)
|
||||
require.Contains(t, store.objects, stagingKey)
|
||||
}
|
||||
|
||||
func TestPresignRejectsNonPositiveSize(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
||||
|
||||
_, err := service.Presign(t.Context(), domain.PresignRequest{
|
||||
ChatID: uuid.New(), OwnerID: uuid.New(),
|
||||
Filename: "photo.png", ContentType: "image/png",
|
||||
SizeBytes: 0, SHA256: strings.Repeat("a", 64),
|
||||
})
|
||||
require.ErrorIs(t, err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
@@ -151,10 +151,18 @@ func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) {
|
||||
}
|
||||
|
||||
if head.Size == row.SizeBytes && head.Metadata["sha256"] == row.SHA256 {
|
||||
if _, err := s.repo.MarkReady(ctx, row.ID, row.ObjectKey); err == nil {
|
||||
stats.Recovered++
|
||||
if _, err := s.repo.MarkReady(ctx, row.ID, row.ObjectKey); err != nil {
|
||||
// A transient database failure must not destroy a valid object.
|
||||
// Leave both the row and the object for the next sweep.
|
||||
s.log.WarnContext(ctx, "sweep recovery failed",
|
||||
slog.String("attachment_id", row.ID.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
stats.Recovered++
|
||||
continue
|
||||
}
|
||||
|
||||
if s.deleteObject(ctx, row.ObjectKey) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package attachment_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -88,3 +89,38 @@ func TestSweepSkipsWhenAnotherReplicaHoldsTheLock(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, stats)
|
||||
}
|
||||
|
||||
func TestSweepKeepsObjectWhenMarkReadyFails(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
locker := mocks.NewMockLockStore(t)
|
||||
store := newFakeStore()
|
||||
|
||||
stale := time.Now().UTC().Add(-time.Hour)
|
||||
row := domain.Attachment{
|
||||
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
|
||||
SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
Status: domain.AttachmentPending, CreatedAt: stale,
|
||||
}
|
||||
|
||||
store.objects[row.ObjectKey] = storedObject{
|
||||
data: []byte("abc"),
|
||||
lastModified: stale,
|
||||
metadata: map[string]string{"sha256": row.SHA256},
|
||||
}
|
||||
|
||||
repo.EXPECT().ListStalePending(mock.Anything, mock.Anything, int32(100)).
|
||||
Return([]domain.Attachment{row}, nil).Once()
|
||||
repo.EXPECT().MarkReady(mock.Anything, row.ID, row.ObjectKey).
|
||||
Return(domain.Attachment{}, context.DeadlineExceeded).Once()
|
||||
repo.EXPECT().ListKeys(mock.Anything, int32(1000), int32(0)).
|
||||
Return([]domain.AttachmentKey{{ID: row.ID, ObjectKey: row.ObjectKey, Status: domain.AttachmentPending}}, nil).Once()
|
||||
locker.EXPECT().AcquireSweepLock(mock.Anything).Return(func() {}, true, nil).Once()
|
||||
|
||||
sweeper := attachment.NewSweeper(repo, store, locker, time.Minute, time.Hour, slog.Default())
|
||||
|
||||
stats, err := sweeper.SweepOnce(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, stats.Recovered)
|
||||
require.Zero(t, stats.RowsDeleted)
|
||||
require.Contains(t, store.objects, row.ObjectKey)
|
||||
}
|
||||
|
||||
@@ -105,7 +105,9 @@ func (e *Extensions) authenticate(r *http.Request) (uuid.UUID, error) {
|
||||
|
||||
user, err := e.sessions.Resolve(r.Context(), token)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%w: %w", domain.ErrUnauthenticated, err)
|
||||
// session.Resolve already distinguishes an invalid session (401) from a
|
||||
// database outage (503); do not collapse both into 401 here.
|
||||
return uuid.Nil, err
|
||||
}
|
||||
|
||||
return user.ID, nil
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type resolverFunc func(ctx context.Context, token string) (domain.User, error)
|
||||
|
||||
func (f resolverFunc) Resolve(ctx context.Context, token string) (domain.User, error) {
|
||||
return f(ctx, token)
|
||||
}
|
||||
|
||||
func TestExtensionPreservesDependencyErrors(t *testing.T) {
|
||||
extensions := NewExtensions(nil, resolverFunc(func(context.Context, string) (domain.User, error) {
|
||||
return domain.User{}, domain.ErrUnavailable
|
||||
}), nil)
|
||||
|
||||
request := httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments/presign", nil,
|
||||
)
|
||||
request.Header.Set("Authorization", "Bearer token")
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
extensions.Presign().ServeHTTP(recorder, request)
|
||||
|
||||
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
|
||||
}
|
||||
|
||||
func TestExtensionInvalidSessionIsUnauthorized(t *testing.T) {
|
||||
extensions := NewExtensions(nil, resolverFunc(func(context.Context, string) (domain.User, error) {
|
||||
return domain.User{}, domain.ErrUnauthenticated
|
||||
}), nil)
|
||||
|
||||
request := httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodPost, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments/presign", nil,
|
||||
)
|
||||
request.Header.Set("Authorization", "Bearer token")
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
extensions.Presign().ServeHTTP(recorder, request)
|
||||
|
||||
require.Equal(t, http.StatusUnauthorized, recorder.Code)
|
||||
}
|
||||
|
||||
func TestExtensionWrongMethodIsNotAllowed(t *testing.T) {
|
||||
extensions := NewExtensions(nil, nil, nil)
|
||||
|
||||
request := httptest.NewRequestWithContext(
|
||||
t.Context(), http.MethodGet, "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments/presign", nil,
|
||||
)
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
extensions.Presign().ServeHTTP(recorder, request)
|
||||
|
||||
require.Equal(t, http.StatusMethodNotAllowed, recorder.Code)
|
||||
require.Equal(t, http.MethodPost, recorder.Header().Get("Allow"))
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -271,15 +270,15 @@ func (h *Handler) CreateMessage(
|
||||
}, nil
|
||||
}
|
||||
|
||||
// messageFingerprint canonicalises the create-message payload so that the key
|
||||
// order of the client JSON cannot change the fingerprint, while a different
|
||||
// payload with the same Idempotency-Key can (contract 1.3.0).
|
||||
// messageFingerprint canonicalises the create-message payload so that JSON key
|
||||
// order cannot change the fingerprint, while a different payload (including a
|
||||
// different attachment order) with the same Idempotency-Key can. Absent
|
||||
// attachment_ids and [] are equivalent, as required by the contract.
|
||||
func messageFingerprint(req *oas.CreateMessage) ([sha256.Size]byte, error) {
|
||||
ids := make([]uuid.UUID, 0, len(req.AttachmentIds))
|
||||
ids = append(ids, req.AttachmentIds...)
|
||||
slices.SortFunc(ids, func(left, right uuid.UUID) int {
|
||||
return bytes.Compare(left[:], right[:])
|
||||
})
|
||||
ids := req.AttachmentIds
|
||||
if ids == nil {
|
||||
ids = []uuid.UUID{}
|
||||
}
|
||||
|
||||
payload, err := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
func TestMessageFingerprintPreservesAttachmentOrder(t *testing.T) {
|
||||
first, second := uuid.New(), uuid.New()
|
||||
|
||||
forward, err := messageFingerprint(&oas.CreateMessage{
|
||||
Text: "x",
|
||||
AttachmentIds: []uuid.UUID{first, second},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
reverse, err := messageFingerprint(&oas.CreateMessage{
|
||||
Text: "x",
|
||||
AttachmentIds: []uuid.UUID{second, first},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NotEqual(t, forward, reverse,
|
||||
"reordered attachment_ids are a different payload and must not replay")
|
||||
}
|
||||
|
||||
func TestMessageFingerprintTreatsAbsentAndEmptyAsEqual(t *testing.T) {
|
||||
absent, err := messageFingerprint(&oas.CreateMessage{Text: "x"})
|
||||
require.NoError(t, err)
|
||||
|
||||
empty, err := messageFingerprint(&oas.CreateMessage{Text: "x", AttachmentIds: []uuid.UUID{}})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, absent, empty)
|
||||
}
|
||||
Reference in New Issue
Block a user