forked from mtusi2026/mtusi2026lab4
306 lines
11 KiB
Go
306 lines
11 KiB
Go
package integration
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"image"
|
|
"image/png"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"backend/internal/adapter/password"
|
|
"backend/internal/adapter/repository/postgres"
|
|
"backend/internal/adapter/storage"
|
|
"backend/internal/application/usecase"
|
|
"backend/internal/config"
|
|
"backend/internal/domain/model"
|
|
"backend/internal/domain/port"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/minio/minio-go/v7"
|
|
"github.com/minio/minio-go/v7/pkg/credentials"
|
|
)
|
|
|
|
type countedTransport struct {
|
|
base http.RoundTripper
|
|
requests, bytes atomic.Int64
|
|
}
|
|
|
|
func (c *countedTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
|
c.requests.Add(1)
|
|
response, err := c.base.RoundTrip(r)
|
|
if err == nil {
|
|
response.Body = &countedBody{response.Body, &c.bytes}
|
|
}
|
|
return response, err
|
|
}
|
|
|
|
type countedBody struct {
|
|
io.ReadCloser
|
|
count *atomic.Int64
|
|
}
|
|
|
|
func (c *countedBody) Read(p []byte) (int, error) {
|
|
n, e := c.ReadCloser.Read(p)
|
|
c.count.Add(int64(n))
|
|
return n, e
|
|
}
|
|
|
|
type lostPutResponse struct{ port.Objects }
|
|
|
|
func (o lostPutResponse) Put(ctx context.Context, key string, r io.Reader, size int64, mime string) error {
|
|
if e := o.Objects.Put(ctx, key, r, size, mime); e != nil {
|
|
return e
|
|
}
|
|
return model.ErrUnavailable
|
|
}
|
|
|
|
func TestReconciliationAgainstPostgresAndPrivateS3(t *testing.T) {
|
|
if os.Getenv("RUN_ISOLATED_RECONCILIATION") != "1" {
|
|
t.Skip("explicit isolated Compose integration stand required")
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)
|
|
defer cancel()
|
|
dsn, e := config.ReadSecret("/run/secrets/database_url")
|
|
if e != nil {
|
|
t.Fatal("database configuration unavailable")
|
|
}
|
|
pool, e := pgxpool.New(ctx, dsn)
|
|
if e != nil {
|
|
t.Fatal("database connection failed")
|
|
}
|
|
defer pool.Close()
|
|
c, e := storage.ReadConfig("/run/secrets/s3_credentials")
|
|
if e != nil {
|
|
t.Fatal("S3 configuration unavailable")
|
|
}
|
|
counter := &countedTransport{base: &http.Transport{ResponseHeaderTimeout: 3 * time.Second}}
|
|
native, e := minio.New(c.Endpoint, &minio.Options{Creds: credentials.NewStaticV4(c.Access, c.Secret, ""), Secure: false, Region: "us-east-1", Transport: counter})
|
|
if e != nil {
|
|
t.Fatal("S3 client initialization failed")
|
|
}
|
|
objects := &storage.S3{Client: native, Bucket: c.Bucket}
|
|
var existing int
|
|
if e = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM users)+(SELECT count(*) FROM chats)+(SELECT count(*) FROM attachments)`).Scan(&existing); e != nil || existing != 0 {
|
|
t.Fatal("destructive integration requires an empty disposable database")
|
|
}
|
|
inventory, _, e := objects.List(ctx, "")
|
|
if e != nil || len(inventory) != 0 {
|
|
t.Fatal("destructive integration requires an empty disposable bucket")
|
|
}
|
|
// RustFS can list authorized bucket names without global bucket-list privileges.
|
|
// Verify the concrete forbidden write using a fresh test-owned name.
|
|
deniedBucket := "forbidden-" + uuid.NewString()
|
|
if e = native.MakeBucket(ctx, deniedBucket, minio.MakeBucketOptions{Region: "us-east-1"}); minio.ToErrorResponse(e).Code != "AccessDenied" {
|
|
if e == nil {
|
|
_ = native.RemoveBucket(ctx, deniedBucket)
|
|
}
|
|
t.Fatal("application identity did not reject creating an unrelated bucket")
|
|
}
|
|
repo := postgres.New(pool, nil)
|
|
app := usecase.NewMessenger(repo)
|
|
prefix := "st_" + uuid.NewString()[:8] + uuid.NewString()[:8]
|
|
draft, e := model.NewUserDraft(prefix, "Synthetic reconciliation")
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
draft.PasswordHash, e = password.New().Hash("synthetic-only-password")
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
user, e := repo.CreateUser(ctx, draft)
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
chatDraft, e := model.NewChatDraft(user.ID, "Synthetic reconciliation", []uuid.UUID{user.ID})
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
chat, e := repo.CreateChat(ctx, chatDraft)
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
var imageBytes bytes.Buffer
|
|
if e = png.Encode(&imageBytes, image.NewNRGBA(image.Rect(0, 0, 3, 2))); e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
raw := imageBytes.Bytes()
|
|
sum := sha256.Sum256(raw)
|
|
sha := hex.EncodeToString(sum[:])
|
|
ownObjects := []uuid.UUID{}
|
|
defer func() {
|
|
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cleanupCancel()
|
|
for _, id := range ownObjects {
|
|
if err := objects.Remove(cleanupCtx, usecase.ObjectKey(id)); err != nil {
|
|
t.Errorf("S3 fixture cleanup failed")
|
|
}
|
|
}
|
|
statements := []string{
|
|
`DELETE FROM message_attachments WHERE message_id IN (SELECT id FROM messages WHERE sender_id=$1)`,
|
|
`DELETE FROM idempotency WHERE user_id=$1`,
|
|
`DELETE FROM messages WHERE sender_id=$1`,
|
|
`DELETE FROM sessions WHERE user_id=$1`,
|
|
`DELETE FROM attachments WHERE owner_id=$1`,
|
|
`DELETE FROM chat_members WHERE user_id=$1`,
|
|
}
|
|
for _, statement := range statements {
|
|
if _, err := pool.Exec(cleanupCtx, statement, user.ID); err != nil {
|
|
t.Errorf("PostgreSQL fixture cleanup failed")
|
|
}
|
|
}
|
|
if _, err := pool.Exec(cleanupCtx, `DELETE FROM chats WHERE id=$1`, chat.ID); err != nil {
|
|
t.Errorf("chat cleanup failed")
|
|
}
|
|
if _, err := pool.Exec(cleanupCtx, `DELETE FROM users WHERE id=$1`, user.ID); err != nil {
|
|
t.Errorf("user cleanup failed")
|
|
}
|
|
}()
|
|
reserve := func(name string) model.Attachment {
|
|
t.Helper()
|
|
id := uuid.New()
|
|
ownObjects = append(ownObjects, id)
|
|
a, err := repo.ReserveAttachment(ctx, model.Attachment{ID: id, ChatID: chat.ID, OwnerID: user.ID, Filename: name, ContentType: "image/png", SizeBytes: int64(len(raw)), SHA256: sha})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return a
|
|
}
|
|
put := func(id uuid.UUID) {
|
|
t.Helper()
|
|
if err := objects.Put(ctx, usecase.ObjectKey(id), bytes.NewReader(raw), int64(len(raw)), "image/png"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
ready := func(a model.Attachment) {
|
|
t.Helper()
|
|
if _, err := repo.SetAttachmentStatus(ctx, a.ID, "uploading", "ready"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
orphan := uuid.New()
|
|
ownObjects = append(ownObjects, orphan)
|
|
put(orphan)
|
|
used := reserve("used.png")
|
|
put(used.ID)
|
|
ready(used)
|
|
if _, e = app.SendMessage(ctx, user.ID, chat.ID, "", uuid.NewString(), []uuid.UUID{used.ID}); e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
missing := reserve("missing.png")
|
|
put(missing.ID)
|
|
ready(missing)
|
|
if _, e = app.SendMessage(ctx, user.ID, chat.ID, "", uuid.NewString(), []uuid.UUID{missing.ID}); e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
if e = objects.Remove(ctx, usecase.ObjectKey(missing.ID)); e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
// A real DB trigger injects a failed finalization after the original is stored.
|
|
triggerName := "fixture_" + uuid.NewString()[:8]
|
|
_, e = pool.Exec(ctx, `CREATE FUNCTION `+triggerName+`() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.owner_id='`+user.ID.String()+`'::uuid AND NEW.filename='db-failure.png' THEN RAISE EXCEPTION 'synthetic finalization failure'; END IF;RETURN NEW;END;$$;CREATE TRIGGER `+triggerName+` BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION `+triggerName+`();`)
|
|
if e != nil {
|
|
t.Fatal("failure injection setup failed")
|
|
}
|
|
removeTrigger := func() {
|
|
if _, err := pool.Exec(context.Background(), `DROP TRIGGER IF EXISTS `+triggerName+` ON attachments;DROP FUNCTION IF EXISTS `+triggerName+`();`); err != nil {
|
|
t.Error("failure trigger cleanup failed")
|
|
}
|
|
}
|
|
defer removeTrigger()
|
|
uploader := usecase.NewAttachments(repo, app, objects)
|
|
if _, e = uploader.Upload(ctx, user.ID, chat.ID, "db-failure.png", "image/png", sha, int64(len(raw)), bytes.NewReader(raw)); !errors.Is(e, model.ErrUnavailable) {
|
|
t.Fatal("failed DB finalization was not reported")
|
|
}
|
|
removeTrigger()
|
|
var pending uuid.UUID
|
|
if e = pool.QueryRow(ctx, `SELECT id FROM attachments WHERE owner_id=$1 AND filename='db-failure.png'`, user.ID).Scan(&pending); e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
ownObjects = append(ownObjects, pending)
|
|
pendingMissing := reserve("interrupted.png")
|
|
// Lost response after an actual S3 PUT is injected at the explicit port boundary.
|
|
lost := usecase.NewAttachments(repo, app, lostPutResponse{objects})
|
|
if _, e = lost.Upload(ctx, user.ID, chat.ID, "lost-response.png", "image/png", sha, int64(len(raw)), bytes.NewReader(raw)); !errors.Is(e, model.ErrUnavailable) {
|
|
t.Fatal("lost PUT response did not report an error")
|
|
}
|
|
var lostID uuid.UUID
|
|
if e = pool.QueryRow(ctx, `SELECT id FROM attachments WHERE owner_id=$1 AND filename='lost-response.png'`, user.ID).Scan(&lostID); e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
ownObjects = append(ownObjects, lostID)
|
|
if _, e = pool.Exec(ctx, `UPDATE attachments SET created_at=clock_timestamp()-interval '10 minutes',updated_at=clock_timestamp()-interval '10 minutes' WHERE owner_id=$1`, user.ID); e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
t.Log("Waiting 61 seconds for the real S3 orphan to exceed the safe minimum grace period")
|
|
select {
|
|
case <-time.After(61 * time.Second):
|
|
case <-ctx.Done():
|
|
t.Fatal("integration deadline")
|
|
}
|
|
fresh := uuid.New()
|
|
ownObjects = append(ownObjects, fresh)
|
|
put(fresh)
|
|
reconciler := usecase.NewReconciler(repo, objects, time.Now)
|
|
counter.requests.Store(0)
|
|
counter.bytes.Store(0)
|
|
dry, e := reconciler.Run(ctx, uuid.Nil, "", time.Minute, false)
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
if dry.Orphans < 1 || dry.Missing < 1 || dry.Recovered < 2 || dry.Deleted != 0 || dry.Changed != 0 {
|
|
t.Fatalf("unexpected dry run counts: %+v", dry)
|
|
}
|
|
if _, e = objects.Stat(ctx, usecase.ObjectKey(orphan)); e != nil {
|
|
t.Fatal("dry run deleted orphan")
|
|
}
|
|
counter.requests.Store(0)
|
|
counter.bytes.Store(0)
|
|
repaired, e := reconciler.Run(ctx, uuid.Nil, "", time.Minute, true)
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
requestCount, readBytes := counter.requests.Load(), counter.bytes.Load()
|
|
if _, e = objects.Stat(ctx, usecase.ObjectKey(orphan)); !errors.Is(e, model.ErrNotFound) {
|
|
t.Fatal("old orphan remains")
|
|
}
|
|
for _, id := range []uuid.UUID{used.ID, pending, lostID, fresh} {
|
|
if _, err := objects.Stat(ctx, usecase.ObjectKey(id)); err != nil {
|
|
t.Fatal("fresh, used or recoverable original was removed")
|
|
}
|
|
}
|
|
for id, want := range map[uuid.UUID]string{used.ID: "ready", missing.ID: "missing", pending: "ready", lostID: "ready", pendingMissing.ID: "abandoned"} {
|
|
a, err := repo.GetAttachment(ctx, id)
|
|
if err != nil || a.Status != want {
|
|
t.Fatalf("metadata repair differs for %s: %s", id, a.Status)
|
|
}
|
|
}
|
|
if _, e = uploader.Get(ctx, user.ID, missing.ID); !errors.Is(e, model.ErrUnavailable) {
|
|
t.Fatal("missing original remained publicly ready")
|
|
}
|
|
repeat, e := reconciler.Run(ctx, uuid.Nil, "", time.Minute, true)
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
if repeat.Deleted != 0 || repeat.Changed != 0 {
|
|
t.Fatal("repeat repair changed settled data")
|
|
}
|
|
put(missing.ID)
|
|
if _, e = reconciler.Run(ctx, uuid.Nil, "", time.Minute, true); e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
if _, e = uploader.Get(ctx, user.ID, missing.ID); e != nil {
|
|
t.Fatal("restored matching original did not recover")
|
|
}
|
|
encoded, _ := json.Marshal(map[string]any{"dry_run": dry, "apply": repaired, "repeat": repeat, "s3_http_requests": requestCount, "s3_response_bytes": readBytes, "private_application_identity": true})
|
|
t.Log(string(encoded))
|
|
}
|