package auth_tests import ( "context" "errors" "io" "net/http" "slices" "strings" "testing" "testing/synctest" "time" "highload/internal/model" "highload/internal/repository" "highload/internal/service" "highload/internal/storage" "highload/internal/storage/s3" "github.com/aws/aws-sdk-go-v2/aws" awss3 "github.com/aws/aws-sdk-go-v2/service/s3" ) type cleanupRepo struct { repository.AttachmentRepository referenced map[string]bool busy string existsErr error checked []string locked string } type cleanupTx struct{ repo *cleanupRepo } func (tx cleanupTx) CreateAttachment(context.Context, repository.CreateAttachmentParams) (*model.Attachment, error) { return nil, errors.New("unexpected INSERT") } func (tx cleanupTx) GetAttachmentByID(context.Context, string) (*model.Attachment, error) { return nil, errors.New("unexpected attachment lookup") } func (tx cleanupTx) ExistsByObjectKey(ctx context.Context, key string) (bool, error) { r := tx.repo if r.locked != key { return false, errors.New("EXISTS outside locked transaction") } r.checked = append(r.checked, key) return r.referenced[key], r.existsErr } func (r *cleanupRepo) WithObjectKeyLock(ctx context.Context, key string, fn func(context.Context, repository.AttachmentTx) error) (bool, error) { if key == r.busy { return false, nil } r.locked = key defer func() { r.locked = "" }() return true, fn(ctx, cleanupTx{repo: r}) } type cleanupStore struct { pages map[string][]storage.ObjectInfo next map[string]string listed, deleted []string repo *cleanupRepo listErr, deleteErr error waitList bool } func (s *cleanupStore) ListPage(ctx context.Context, token *string, prefix string) ([]storage.ObjectInfo, *string, error) { if prefix != "attachments/" { return nil, nil, errors.New("unexpected prefix") } if _, ok := ctx.Deadline(); !ok { return nil, nil, errors.New("LIST did not receive deadline") } if s.waitList { <-ctx.Done() return nil, nil, ctx.Err() } key := aws.ToString(token) s.listed = append(s.listed, key) if s.listErr != nil { return nil, nil, s.listErr } if next, ok := s.next[key]; ok { return s.pages[key], &next, nil } return s.pages[key], nil, nil } func (s *cleanupStore) Delete(_ context.Context, key string) error { if s.repo.locked != key { return errors.New("DELETE outside locked transaction") } s.deleted = append(s.deleted, key) return s.deleteErr } func TestAttachmentCleanupPagesAndCutoff(t *testing.T) { synctest.Test(t, func(t *testing.T) { now := time.Now() old := now.Add(-time.Minute - time.Nanosecond) orphan := "attachments/orphan" opts := &service.AttachmentCleanupOptions{GracePeriod: time.Minute, ListTimeout: time.Second} repo := &cleanupRepo{referenced: map[string]bool{"attachments/referenced": true}, busy: "attachments/busy"} objects := &cleanupStore{repo: repo, pages: map[string][]storage.ObjectInfo{ "": {{Key: "attachments/equal", LastModified: now.Add(-time.Minute)}, {Key: "attachments/fresh", LastModified: now.Add(-time.Second)}, {Key: "attachments/future", LastModified: now.Add(time.Hour)}, {Key: "attachments/zero"}, {Key: "other/orphan", LastModified: old}, {Key: "attachments/busy", LastModified: old}}, "last": {{Key: "attachments/referenced", LastModified: old}, {Key: orphan, LastModified: old}}, }, next: map[string]string{"": "empty", "empty": "last"}} svc := service.NewAttachmentCleanupService(repo, objects, opts) opts.DryRun = true if err := svc.RunOnce(context.Background()); err != nil || len(objects.deleted) != 0 || !slices.Equal(repo.checked, []string{"attachments/referenced", orphan}) { t.Fatalf("dry-run must check old unlocked keys without deleting: err=%v checked=%v deletes=%v", err, repo.checked, objects.deleted) } opts.DryRun = false objects.listed = nil if err := svc.RunOnce(context.Background()); err != nil || !slices.Equal(objects.listed, []string{"", "empty", "last"}) || !slices.Equal(objects.deleted, []string{orphan}) { t.Fatalf("wrong cutoff or page walk: err=%v pages=%v deletes=%v", err, objects.listed, objects.deleted) } }) } func TestAttachmentCleanupFaults(t *testing.T) { for _, name := range []string{"list", "exists", "delete", "list_timeout", "pass_timeout", "canceled"} { t.Run(name, func(t *testing.T) { synctest.Test(t, func(t *testing.T) { repo := &cleanupRepo{} objects := &cleanupStore{repo: repo, pages: map[string][]storage.ObjectInfo{"": {{Key: "attachments/old", LastModified: time.Now().Add(-time.Hour)}}}} svc := service.NewAttachmentCleanupService(repo, objects, &service.AttachmentCleanupOptions{GracePeriod: time.Second, ListTimeout: time.Second}) sentinel := errors.New("synthetic " + name + " error") var want error = sentinel ctx, cancel := context.WithCancel(context.Background()) defer cancel() switch name { case "list": objects.listErr = sentinel case "exists": repo.existsErr = sentinel case "delete": objects.deleteErr = sentinel case "list_timeout": objects.waitList = true want = context.DeadlineExceeded case "pass_timeout": var stop context.CancelFunc ctx, stop = context.WithTimeout(ctx, 100*time.Millisecond) defer stop() objects.waitList = true want = context.DeadlineExceeded case "canceled": cancel() want = context.Canceled } start := time.Now() got := svc.RunOnce(ctx) if !errors.Is(got, want) { t.Fatalf("want %v, got %v", want, got) } if (name == "list_timeout" && time.Since(start) != time.Second) || (name == "pass_timeout" && time.Since(start) != 100*time.Millisecond) { t.Fatal("wrong cancellation budget") } if name != "delete" && len(objects.deleted) > 0 { t.Fatal("DELETE ran after unsafe precondition") } if name == "delete" && len(objects.deleted) != 1 { t.Fatal("DELETE fault not reached") } repo.existsErr, objects.listErr, objects.deleteErr = nil, nil, nil objects.waitList = false objects.deleted = nil if err := svc.RunOnce(context.Background()); err != nil || !slices.Equal(objects.deleted, []string{"attachments/old"}) { t.Fatalf("cleanup did not recover: %v %v", err, objects.deleted) } }) }) } } type cleanupListTransport func(*http.Request) (*http.Response, error) func (fn cleanupListTransport) Do(req *http.Request) (*http.Response, error) { return fn(req) } func TestAttachmentCleanupS3InvalidNextToken(t *testing.T) { for _, tc := range []struct { name string token *string xml string }{ {"missing", nil, ""}, {"empty", nil, ""}, {"repeat", aws.String("same"), "same"}, } { t.Run(tc.name, func(t *testing.T) { n := 0 obj := &s3.Storage{Bucket: "test", Client: awss3.New(awss3.Options{ Region: "us-east-1", UsePathStyle: true, BaseEndpoint: aws.String("http://cleanup.invalid"), Credentials: aws.AnonymousCredentials{}, Retryer: aws.NopRetryer{}, HTTPClient: cleanupListTransport(func(req *http.Request) (*http.Response, error) { n++ if req.URL.Query().Get("continuation-token") != aws.ToString(tc.token) { return nil, errors.New("wrong request token") } return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader( "true" + tc.xml + ""))}, nil }), })} _, _, err := obj.ListPage(context.Background(), tc.token, "attachments/") if !errors.Is(err, storage.ErrStorage) || n != 1 { t.Fatalf("invalid token was not rejected: %v, calls=%d", err, n) } }) } }