forked from mtusi2026/mtusi2026lab4
feat: add 4 grade things
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"log"
|
||||
"messenger/src/backend/repositories"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func runUploadCleanup(args []string) error {
|
||||
flags := flag.NewFlagSet("attachments-cleanup", flag.ContinueOnError)
|
||||
loop := flags.Bool("loop", false, "run every 60 seconds")
|
||||
dryRun := flags.Bool("dry-run", false, "report without deleting anything")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
init, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
db, err := repositories.OpenDatabase(init)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer db.Close()
|
||||
objects, err := repositories.NewObjectStoreFromEnvironment()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
store := repositories.NewAttachmentStore(db)
|
||||
for {
|
||||
pass, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
result, err := store.CleanupUploads(pass, *dryRun, objects.Delete)
|
||||
cancel()
|
||||
if encodeErr := json.NewEncoder(os.Stdout).Encode(result); encodeErr != nil {
|
||||
return encodeErr
|
||||
}
|
||||
if !*loop {
|
||||
return err
|
||||
}
|
||||
if err != nil {
|
||||
log.Print("upload cleanup pass failed; journal retained for retry")
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-time.After(60 * time.Second):
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-6
@@ -36,18 +36,20 @@ func main() {
|
||||
log.SetPrefix("[" + environment + "] ")
|
||||
}
|
||||
if len(os.Args) == 2 && os.Args[1] == "s3-bootstrap" {
|
||||
objects, err := repositories.NewObjectStoreFromEnvironment()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if err = objects.Bootstrap(ctx); err != nil {
|
||||
log.Fatal("S3 bootstrap failed")
|
||||
if err := repositories.BootstrapS3(ctx); err != nil {
|
||||
log.Fatal("S3 bootstrap failed: ", err)
|
||||
}
|
||||
log.Print("private S3 bucket ready")
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 && os.Args[1] == "attachments-cleanup" {
|
||||
if err := runUploadCleanup(os.Args[2:]); err != nil {
|
||||
log.Fatal("upload cleanup failed: ", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 {
|
||||
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
|
||||
client := http.Client{Timeout: 2 * time.Second}
|
||||
@@ -78,6 +80,9 @@ func main() {
|
||||
log.Printf("migration %s complete", os.Args[2])
|
||||
return
|
||||
}
|
||||
if _, err := repositories.UploadCleanupGrace(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
db, err := repositories.OpenDatabase(ctx)
|
||||
cancel()
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func UploadCleanupGrace() (time.Duration, error) {
|
||||
value := os.Getenv("UPLOAD_CLEANUP_GRACE_SECONDS")
|
||||
if value == "" {
|
||||
value = "600"
|
||||
}
|
||||
seconds, err := strconv.Atoi(value)
|
||||
if err != nil || seconds < 120 || seconds > 86400 {
|
||||
return 0, errors.New("UPLOAD_CLEANUP_GRACE_SECONDS must be between 120 and 86400")
|
||||
}
|
||||
return time.Duration(seconds) * time.Second, nil
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE upload_attempts;
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE upload_attempts (
|
||||
id uuid PRIMARY KEY,
|
||||
object_key text NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
cleanup_after timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX upload_attempts_cleanup_idx ON upload_attempts(cleanup_after,id);
|
||||
@@ -0,0 +1,83 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
madmin "github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
func readS3Secret(name string) (string, error) {
|
||||
data, err := os.ReadFile(os.Getenv(name))
|
||||
if err != nil {
|
||||
return "", errors.New("cannot read " + name)
|
||||
}
|
||||
value := strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", errors.New("empty " + name)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// BootstrapS3 is the only application command that needs administrative credentials.
|
||||
func BootstrapS3(ctx context.Context) error {
|
||||
endpoint, err := url.Parse(os.Getenv("S3_ENDPOINT"))
|
||||
if err != nil || endpoint.Host == "" {
|
||||
return errors.New("invalid S3_ENDPOINT")
|
||||
}
|
||||
rootAccess, err := readS3Secret("S3_ROOT_ACCESS_KEY_ID_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rootSecret, err := readS3Secret("S3_ROOT_SECRET_ACCESS_KEY_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
access, err := readS3Secret("S3_ACCESS_KEY_ID_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
secret, err := readS3Secret("S3_SECRET_ACCESS_KEY_FILE")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if access == rootAccess {
|
||||
return errors.New("API and root credentials must differ")
|
||||
}
|
||||
client, err := minio.New(endpoint.Host, &minio.Options{Creds: credentials.NewStaticV4(rootAccess, rootSecret, ""), Secure: endpoint.Scheme == "https", Region: os.Getenv("S3_REGION")})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
store := &ObjectStore{client: client, bucket: os.Getenv("S3_BUCKET")}
|
||||
if err = store.Bootstrap(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
admin, err := madmin.New(endpoint.Host, rootAccess, rootSecret, endpoint.Scheme == "https")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
policy := map[string]any{"Version": "2012-10-17", "Statement": []any{
|
||||
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetBucketLocation", "s3:ListBucket"}, "Resource": []string{"arn:aws:s3:::" + store.bucket}},
|
||||
map[string]any{"Effect": "Allow", "Action": []string{"s3:GetObject", "s3:PutObject", "s3:DeleteObject"}, "Resource": []string{"arn:aws:s3:::" + store.bucket + "/originals/*"}},
|
||||
}}
|
||||
data, err := json.Marshal(policy)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
const name = "messenger-attachments-api"
|
||||
if err = admin.AddCannedPolicy(ctx, name, data); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = admin.SetUserReq(ctx, access, madmin.AddOrUpdateUserReq{SecretKey: secret, Status: madmin.AccountEnabled}); err != nil {
|
||||
return err
|
||||
}
|
||||
// Explicitly assign the managed policy; creating a user alone grants no S3 rights.
|
||||
// This idempotent API is supported by our pinned MinIO server release.
|
||||
return admin.SetPolicy(ctx, name, access, false)
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// ReserveUpload is committed before any S3 PUT, so an interrupted request is tracked.
|
||||
func (s *AttachmentStore) ReserveUpload(ctx context.Context, a Attachment, grace time.Duration) error {
|
||||
ctx, cancel := boundedQuery(ctx)
|
||||
defer cancel()
|
||||
_, err := s.db.Exec(ctx, `INSERT INTO upload_attempts(id,object_key,cleanup_after) VALUES($1,$2,clock_timestamp()+$3*interval '1 second')`, a.ID, a.ObjectKey, grace.Seconds())
|
||||
return err
|
||||
}
|
||||
|
||||
// PublishUpload holds the journal row lock across PUT and metadata COMMIT.
|
||||
// Cleanup skips that row; a crash rolls back metadata but preserves the reservation.
|
||||
func (s *AttachmentStore) PublishUpload(ctx context.Context, a Attachment, put func(context.Context) error) error {
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var key string
|
||||
err = tx.QueryRow(ctx, `SELECT object_key FROM upload_attempts WHERE id=$1 AND cleanup_after>clock_timestamp() FOR UPDATE`, a.ID).Scan(&key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if key != a.ObjectKey {
|
||||
return errors.New("upload reservation mismatch")
|
||||
}
|
||||
if err = put(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, a.ID, a.ChatID, a.OwnerID, a.Filename, a.ObjectKey, a.ContentType, a.SizeBytes, a.SHA256, a.CreatedAt, a.UpdatedAt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "DELETE FROM upload_attempts WHERE id=$1", a.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
type CleanupResult struct {
|
||||
Candidates int `json:"candidates"`
|
||||
Deleted int `json:"deleted"`
|
||||
Eligible int `json:"eligible"`
|
||||
Protected int `json:"protected"`
|
||||
Skipped int `json:"skipped"`
|
||||
Failed int `json:"failed"`
|
||||
DryRun bool `json:"dry_run"`
|
||||
}
|
||||
|
||||
// CleanupUploads only visits journal entries; it never scans or deletes legacy data.
|
||||
func (s *AttachmentStore) CleanupUploads(ctx context.Context, dryRun bool, remove func(context.Context, string) error) (CleanupResult, error) {
|
||||
result := CleanupResult{DryRun: dryRun}
|
||||
rows, err := s.db.Query(ctx, `SELECT id::text FROM upload_attempts WHERE cleanup_after<=clock_timestamp() ORDER BY cleanup_after,id LIMIT 100`)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
ids := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err = rows.Scan(&id); err != nil {
|
||||
rows.Close()
|
||||
return result, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Candidates = len(ids)
|
||||
for _, id := range ids {
|
||||
outcome, err := s.cleanupUpload(ctx, id, dryRun, remove)
|
||||
if err != nil {
|
||||
result.Failed++
|
||||
continue
|
||||
}
|
||||
switch outcome {
|
||||
case "eligible":
|
||||
result.Eligible++
|
||||
case "deleted":
|
||||
result.Deleted++
|
||||
case "protected":
|
||||
result.Protected++
|
||||
default:
|
||||
result.Skipped++
|
||||
}
|
||||
}
|
||||
if result.Failed > 0 {
|
||||
return result, fmt.Errorf("%d upload cleanup operations failed", result.Failed)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *AttachmentStore) cleanupUpload(ctx context.Context, id string, dryRun bool, remove func(context.Context, string) error) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
var key string
|
||||
err = tx.QueryRow(ctx, `SELECT object_key FROM upload_attempts WHERE id=$1 AND cleanup_after<=clock_timestamp() FOR UPDATE SKIP LOCKED`, id).Scan(&key)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "skipped", nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Restrict destructive actions to server-generated keys even if a journal row is malformed.
|
||||
parsed, err := uuid.Parse(id)
|
||||
if err != nil || key != "originals/"+parsed.String() {
|
||||
return "", errors.New("invalid upload journal key")
|
||||
}
|
||||
var ready bool
|
||||
if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM attachments WHERE object_key=$1)", key).Scan(&ready); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if dryRun {
|
||||
if ready {
|
||||
return "protected", nil
|
||||
}
|
||||
return "eligible", nil
|
||||
}
|
||||
if !ready {
|
||||
// On DELETE failure retain the journal entry for the next pass.
|
||||
if err = remove(ctx, key); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "DELETE FROM upload_attempts WHERE id=$1", id); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if ready {
|
||||
return "protected", nil
|
||||
}
|
||||
return "deleted", nil
|
||||
}
|
||||
@@ -6,20 +6,20 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log"
|
||||
"messenger/src/backend/repositories"
|
||||
"mime"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const MaxUploadBytes int64 = 10485760
|
||||
@@ -31,11 +31,16 @@ var ErrAttachmentNotFound = errors.New("attachment not found")
|
||||
|
||||
type AttachmentService struct {
|
||||
metadata *repositories.AttachmentStore
|
||||
objects *repositories.ObjectStore
|
||||
objects AttachmentObjects
|
||||
uploadSlot chan struct{}
|
||||
}
|
||||
|
||||
func NewAttachmentService(metadata *repositories.AttachmentStore, objects *repositories.ObjectStore) *AttachmentService {
|
||||
type AttachmentObjects interface {
|
||||
Put(context.Context, string, io.Reader, int64, string) error
|
||||
Get(context.Context, string) (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
func NewAttachmentService(metadata *repositories.AttachmentStore, objects AttachmentObjects) *AttachmentService {
|
||||
return &AttachmentService{metadata: metadata, objects: objects, uploadSlot: make(chan struct{}, 1)}
|
||||
}
|
||||
func ValidateFilename(name string) error {
|
||||
@@ -50,11 +55,15 @@ func ValidateFilename(name string) error {
|
||||
return nil
|
||||
}
|
||||
func ValidateImage(data []byte, declared string) (string, error) {
|
||||
return ValidateImageReader(bytes.NewReader(data), declared)
|
||||
}
|
||||
|
||||
func ValidateImageReader(reader io.ReadSeeker, declared string) (string, error) {
|
||||
contentType, _, err := mime.ParseMediaType(declared)
|
||||
if err != nil || (contentType != "image/png" && contentType != "image/jpeg") {
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
config, format, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
config, format, err := image.DecodeConfig(reader)
|
||||
if err != nil {
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
@@ -66,7 +75,10 @@ func ValidateImage(data []byte, declared string) (string, error) {
|
||||
return "", ErrPayloadTooLarge
|
||||
}
|
||||
// DecodeConfig alone accepts truncated headers; decode only after bounding pixels.
|
||||
decoded, _, err := image.Decode(bytes.NewReader(data))
|
||||
if _, err = reader.Seek(0, io.SeekStart); err != nil {
|
||||
return "", err
|
||||
}
|
||||
decoded, _, err := image.Decode(reader)
|
||||
if err != nil {
|
||||
return "", ErrUnsupportedMedia
|
||||
}
|
||||
@@ -80,37 +92,55 @@ func (s *AttachmentService) Upload(ctx context.Context, userID, chatID, filename
|
||||
case <-ctx.Done():
|
||||
return repositories.Attachment{}, ctx.Err()
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(body, MaxUploadBytes+1))
|
||||
grace, err := repositories.UploadCleanupGrace()
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
if int64(len(data)) > MaxUploadBytes {
|
||||
directory := os.Getenv("UPLOAD_TMP_DIR")
|
||||
file, err := os.CreateTemp(directory, "upload-*")
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
defer file.Close()
|
||||
// Linux keeps the open descriptor usable; no abandoned pathname survives a crash.
|
||||
if err = os.Remove(file.Name()); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
hash := sha256.New()
|
||||
size, err := io.CopyBuffer(io.MultiWriter(file, hash), io.LimitReader(body, MaxUploadBytes+1), make([]byte, 32*1024))
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
if size > MaxUploadBytes {
|
||||
return repositories.Attachment{}, ErrPayloadTooLarge
|
||||
}
|
||||
actual, err := ValidateImage(data, contentType)
|
||||
if err = ctx.Err(); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
if _, err = file.Seek(0, io.SeekStart); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
actual, err := ValidateImageReader(file, contentType)
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
a := repositories.Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: filename, ContentType: actual, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(sum[:]), Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
|
||||
a.ObjectKey = "originals/" + a.ID
|
||||
if err = s.objects.Put(ctx, a.ObjectKey, bytes.NewReader(data), a.SizeBytes, a.ContentType); err != nil {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
if err = s.metadata.Create(ctx, a); err != nil {
|
||||
// A connection error can hide a successful autocommit. Delete only after
|
||||
// a definite SQL rejection; otherwise preserve bytes for later reconciliation.
|
||||
var rejected *pgconn.PgError
|
||||
if errors.As(err, &rejected) {
|
||||
cleanup, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
if cleanupErr := s.objects.Delete(cleanup, a.ObjectKey); cleanupErr != nil {
|
||||
log.Printf("attachment compensation failed for %s", a.ID)
|
||||
}
|
||||
} else {
|
||||
log.Printf("attachment metadata outcome uncertain for %s; preserving S3 object", a.ID)
|
||||
}
|
||||
if _, err = file.Seek(0, io.SeekStart); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
a := repositories.Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: filename, ContentType: actual, SizeBytes: size, SHA256: hex.EncodeToString(hash.Sum(nil)), Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now}
|
||||
a.ObjectKey = "originals/" + a.ID
|
||||
if err = s.metadata.ReserveUpload(ctx, a, grace); err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
err = s.metadata.PublishUpload(ctx, a, func(ctx context.Context) error {
|
||||
return s.objects.Put(ctx, a.ObjectKey, file, a.SizeBytes, a.ContentType)
|
||||
})
|
||||
// On any uncertainty leave the durable reservation to the cleanup worker.
|
||||
if err != nil {
|
||||
return repositories.Attachment{}, err
|
||||
}
|
||||
return a, nil
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestAttachmentCleanupGraceLocksProtectionAndRetry(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
ctx := context.Background()
|
||||
data := uploadPNG(t)
|
||||
makeAttempt := func(age bool, ready bool) repositories.Attachment {
|
||||
id := uuid.NewString()
|
||||
now := time.Now().UTC()
|
||||
a := repositories.Attachment{ID: id, ObjectKey: "originals/" + id, ChatID: chat, OwnerID: user, Filename: "cleanup.png", ContentType: "image/png", SizeBytes: int64(len(data)), SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", CreatedAt: now, UpdatedAt: now}
|
||||
if err := objects.Put(ctx, a.ObjectKey, bytes.NewReader(data), a.SizeBytes, a.ContentType); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { objects.Delete(context.Background(), a.ObjectKey) })
|
||||
if err := store.ReserveUpload(ctx, a, 600*time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if age {
|
||||
if _, err := f.db.Exec(ctx, "UPDATE upload_attempts SET cleanup_after=clock_timestamp()-interval '1 second' WHERE id=$1", id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if ready {
|
||||
if err := store.Create(ctx, a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return a
|
||||
}
|
||||
fresh := makeAttempt(false, false)
|
||||
expired := makeAttempt(true, false)
|
||||
ready := makeAttempt(true, true)
|
||||
locked := makeAttempt(true, false)
|
||||
tx, err := f.db.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err = tx.Exec(ctx, "SELECT id FROM upload_attempts WHERE id=$1 FOR UPDATE", locked.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dry, err := store.CleanupUploads(ctx, true, objects.Delete)
|
||||
if err != nil || dry.Deleted != 0 || dry.Candidates != 3 || dry.Protected != 1 {
|
||||
t.Fatalf("dry run: %+v %v", dry, err)
|
||||
}
|
||||
result, err := store.CleanupUploads(ctx, false, objects.Delete)
|
||||
if err != nil || result.Deleted != 1 || result.Protected != 1 || result.Skipped != 1 {
|
||||
t.Fatalf("cleanup: %+v %v", result, err)
|
||||
}
|
||||
if content, err := objects.Get(ctx, expired.ObjectKey); err == nil {
|
||||
content.Close()
|
||||
t.Fatal("expired object not removed")
|
||||
}
|
||||
for _, a := range []repositories.Attachment{fresh, ready, locked} {
|
||||
content, err := objects.Get(ctx, a.ObjectKey)
|
||||
if err != nil {
|
||||
t.Fatalf("protected object removed: %v", err)
|
||||
}
|
||||
content.Close()
|
||||
}
|
||||
tx.Rollback(ctx)
|
||||
failure, err := store.CleanupUploads(ctx, false, func(context.Context, string) error { return errors.New("injected S3 DELETE failure") })
|
||||
if err == nil || failure.Failed != 1 {
|
||||
t.Fatalf("DELETE failure: %+v %v", failure, err)
|
||||
}
|
||||
var count int
|
||||
f.db.QueryRow(ctx, "SELECT count(*) FROM upload_attempts WHERE id=$1", locked.ID).Scan(&count)
|
||||
if count != 1 {
|
||||
t.Fatal("DELETE failure lost journal")
|
||||
}
|
||||
result, err = store.CleanupUploads(ctx, false, objects.Delete)
|
||||
if err != nil || result.Deleted != 1 {
|
||||
t.Fatalf("retry: %+v %v", result, err)
|
||||
}
|
||||
result, err = store.CleanupUploads(ctx, false, objects.Delete)
|
||||
if err != nil || result.Candidates != 0 {
|
||||
t.Fatalf("repeat not idempotent: %+v %v", result, err)
|
||||
}
|
||||
cancelled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if _, err = store.CleanupUploads(cancelled, false, objects.Delete); err == nil {
|
||||
t.Fatal("cancelled DB operation succeeded")
|
||||
}
|
||||
f.db.QueryRow(ctx, "SELECT count(*) FROM upload_attempts WHERE id=$1", fresh.ID).Scan(&count)
|
||||
if count != 1 {
|
||||
t.Fatal("DB failure lost fresh reservation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentCleanupInvalidKeyIsNeverDeleted(t *testing.T) {
|
||||
f, store, _, _, _ := uploadFixture(t)
|
||||
ctx := context.Background()
|
||||
if _, err := f.db.Exec(ctx, "INSERT INTO upload_attempts(id,object_key,cleanup_after) VALUES($1,$2,clock_timestamp()-interval '1 second')", uuid.NewString(), "do-not-delete/anything"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
called := false
|
||||
result, err := store.CleanupUploads(ctx, false, func(context.Context, string) error { called = true; return nil })
|
||||
if err == nil || called || result.Failed != 1 {
|
||||
t.Fatalf("unsafe key: %+v %v delete=%v", result, err, called)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/handlers"
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func attachmentRouter(f *testFixture, objects *repositories.ObjectStore) http.Handler {
|
||||
users := services.NewUserService(f.users)
|
||||
return handlers.NewRouter(services.NewHealthService(repositories.NewHealthStore(f.db), f.sessionStore), users, f.sessions, services.NewChatService(f.chats), services.NewMessageService(f.messages), services.NewAttachmentService(repositories.NewAttachmentStore(f.db), objects))
|
||||
}
|
||||
func attachmentCall(t *testing.T, f *testFixture, router http.Handler, method, path, user, mime string, body []byte, status int) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(method, path, bytes.NewReader(body))
|
||||
if mime != "" {
|
||||
r.Header.Set("Content-Type", mime)
|
||||
}
|
||||
if method == "POST" && strings.HasSuffix(path, "/messages") {
|
||||
r.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
}
|
||||
if user != "" {
|
||||
authorizeTestRequest(t, f, r, user)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, r)
|
||||
if w.Code != status {
|
||||
t.Fatalf("%s %s: expected %d, got %d: %s", method, path, status, w.Code, w.Body.String())
|
||||
}
|
||||
if status >= 400 {
|
||||
var error struct {
|
||||
Error struct {
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &error); err != nil || error.Error.RequestID != w.Header().Get("X-Request-Id") {
|
||||
t.Fatal("invalid error envelope")
|
||||
}
|
||||
}
|
||||
return w
|
||||
}
|
||||
func TestAttachmentValidationHTTP(t *testing.T) {
|
||||
f, _, objects, user, chat := uploadFixture(t)
|
||||
router := attachmentRouter(f, objects)
|
||||
path := "/api/v1/chats/" + chat + "/attachments?filename=photo.png"
|
||||
png := uploadPNG(t)
|
||||
for _, sample := range []struct {
|
||||
body []byte
|
||||
mime string
|
||||
status int
|
||||
}{{bytes.Repeat([]byte("x"), 10485761), "image/png", 413}, {png[:40], "image/png", 415}, {png, "image/jpeg", 415}, {png, "text/plain", 415}} {
|
||||
attachmentCall(t, f, router, "POST", path, user, sample.mime, sample.body, sample.status)
|
||||
}
|
||||
huge := append([]byte(nil), png...)
|
||||
binary.BigEndian.PutUint32(huge[16:20], 10001)
|
||||
binary.BigEndian.PutUint32(huge[20:24], 4000)
|
||||
binary.BigEndian.PutUint32(huge[29:33], crc32.ChecksumIEEE(huge[12:29]))
|
||||
attachmentCall(t, f, router, "POST", path, user, "image/png", huge, 413)
|
||||
for _, name := range []string{"", " ", "../file.png", `a\b.png`, "a\x00.png", "a\n.png", strings.Repeat("x", 256)} {
|
||||
attachmentCall(t, f, router, "POST", "/api/v1/chats/"+chat+"/attachments?"+url.Values{"filename": {name}}.Encode(), user, "image/png", png, 400)
|
||||
}
|
||||
// Exercise the real HTTP chunked path without Content-Length.
|
||||
server := httptest.NewServer(router)
|
||||
defer server.Close()
|
||||
token, _, err := f.sessions.CreateForUser(context.Background(), user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader, writer := io.Pipe()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
defer writer.Close()
|
||||
io.Copy(writer, bytes.NewReader(bytes.Repeat([]byte("x"), 10485761)))
|
||||
}()
|
||||
request, err := http.NewRequest("POST", server.URL+path, reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
request.Header.Set("Content-Type", "image/png")
|
||||
response, err := server.Client().Do(request)
|
||||
if err != nil {
|
||||
reader.Close()
|
||||
<-done
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
reader.Close()
|
||||
<-done
|
||||
if response.StatusCode != 413 {
|
||||
t.Fatalf("chunked limit: %d", response.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentAccessHTTP(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
router := attachmentRouter(f, objects)
|
||||
eve, _ := createTestUser(t, f.users, "eve", "Eve")
|
||||
other := createTestChat(t, f.chats, "Other", []string{user})
|
||||
a, err := services.NewAttachmentService(store, objects).Upload(context.Background(), user, chat, "photo.png", "image/png", bytes.NewReader(uploadPNG(t)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { objects.Delete(context.Background(), a.ObjectKey) })
|
||||
for _, suffix := range []string{"", "/content"} {
|
||||
path := "/api/v1/attachments/" + a.ID + suffix
|
||||
attachmentCall(t, f, router, "GET", path, eve.ID, "", nil, 404)
|
||||
attachmentCall(t, f, router, "GET", path, "", "", nil, 401)
|
||||
}
|
||||
attachmentCall(t, f, router, "POST", "/api/v1/chats/"+chat+"/attachments?filename=photo.png", eve.ID, "image/png", uploadPNG(t), 404)
|
||||
for _, target := range []string{uuid.NewString(), a.ID} {
|
||||
attachmentCall(t, f, router, "POST", "/api/v1/chats/"+other.ID+"/messages", user, "application/json", []byte(`{"text":"","attachment_ids":["`+target+`"]}`), 404)
|
||||
}
|
||||
attachmentCall(t, f, router, "POST", "/api/v1/chats/"+chat+"/messages", user, "application/json", []byte(`{"text":"","attachment_ids":["`+a.ID+`","`+a.ID+`"]}`), 400)
|
||||
}
|
||||
|
||||
func TestUploadRecoveryHTTPDisconnect(t *testing.T) {
|
||||
f, _, objects, user, chat := uploadFixture(t)
|
||||
directory := t.TempDir()
|
||||
t.Setenv("UPLOAD_TMP_DIR", directory)
|
||||
completed := make(chan struct{})
|
||||
router := attachmentRouter(f, objects)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer close(completed); router.ServeHTTP(w, r) }))
|
||||
defer server.Close()
|
||||
token, _, err := f.sessions.CreateForUser(context.Background(), user)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
address := strings.TrimPrefix(server.URL, "http://")
|
||||
connection, err := net.Dial("tcp", address)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw := "POST /api/v1/chats/" + chat + "/attachments?filename=aborted.png HTTP/1.1\r\nHost: " + address + "\r\nAuthorization: Bearer " + token + "\r\nContent-Type: image/png\r\nContent-Length: 10485760\r\n\r\npartial"
|
||||
if _, err = io.WriteString(connection, raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
connection.Close()
|
||||
select {
|
||||
case <-completed:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("disconnected upload did not stop")
|
||||
}
|
||||
var count int
|
||||
f.db.QueryRow(context.Background(), "SELECT count(*) FROM upload_attempts").Scan(&count)
|
||||
if count != 0 {
|
||||
t.Fatal("incomplete HTTP body reserved an object")
|
||||
}
|
||||
files, err := os.ReadDir(directory)
|
||||
if err != nil || len(files) > 0 {
|
||||
t.Fatalf("temporary paths remain: %v %v", files, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
|
||||
"github.com/google/uuid"
|
||||
madmin "github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
func s3Client(t *testing.T, root bool, anonymous bool) *minio.Client {
|
||||
t.Helper()
|
||||
if os.Getenv("S3_ENDPOINT") == "" {
|
||||
t.Skip("S3 integration: run make test-backend")
|
||||
}
|
||||
endpoint, err := url.Parse(os.Getenv("S3_ENDPOINT"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
read := func(name string) string {
|
||||
data, err := os.ReadFile(os.Getenv(name))
|
||||
if err != nil {
|
||||
t.Fatal("S3 credential file not mounted")
|
||||
}
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
access, secret := "", ""
|
||||
if !anonymous {
|
||||
if root {
|
||||
access = read("S3_ROOT_ACCESS_KEY_ID_FILE")
|
||||
secret = read("S3_ROOT_SECRET_ACCESS_KEY_FILE")
|
||||
} else {
|
||||
access = read("S3_ACCESS_KEY_ID_FILE")
|
||||
secret = read("S3_SECRET_ACCESS_KEY_FILE")
|
||||
}
|
||||
}
|
||||
client, err := minio.New(endpoint.Host, &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Secure: endpoint.Scheme == "https", Region: os.Getenv("S3_REGION")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return client
|
||||
}
|
||||
func denied(t *testing.T, err error) {
|
||||
t.Helper()
|
||||
if err == nil || minio.ToErrorResponse(err).StatusCode != 403 {
|
||||
t.Fatalf("expected S3 HTTP 403, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestS3PermissionsAndBootstrap(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
app := s3Client(t, false, false)
|
||||
root := s3Client(t, true, false)
|
||||
anon := s3Client(t, false, true)
|
||||
bucket := os.Getenv("S3_BUCKET")
|
||||
key := "originals/" + uuid.NewString()
|
||||
data := []byte("permission fixture")
|
||||
t.Cleanup(func() { root.RemoveObject(context.Background(), bucket, key, minio.RemoveObjectOptions{}) })
|
||||
if _, err := app.PutObject(ctx, bucket, key, bytes.NewReader(data), int64(len(data)), minio.PutObjectOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := repositories.BootstrapS3(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
content, err := app.GetObject(ctx, bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actual, err := io.ReadAll(content)
|
||||
content.Close()
|
||||
if err != nil || !bytes.Equal(actual, data) {
|
||||
t.Fatalf("bootstrap changed existing object: %v", err)
|
||||
}
|
||||
object, err := anon.GetObject(ctx, bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = object.Stat()
|
||||
object.Close()
|
||||
denied(t, err)
|
||||
listing, ok := <-anon.ListObjects(ctx, bucket, minio.ListObjectsOptions{})
|
||||
if !ok {
|
||||
t.Fatal("anonymous list did not return AccessDenied")
|
||||
}
|
||||
denied(t, listing.Err)
|
||||
forbidden := "forbidden/" + uuid.NewString()
|
||||
t.Cleanup(func() { root.RemoveObject(context.Background(), bucket, forbidden, minio.RemoveObjectOptions{}) })
|
||||
_, err = app.PutObject(ctx, bucket, forbidden, bytes.NewReader(data), int64(len(data)), minio.PutObjectOptions{})
|
||||
denied(t, err)
|
||||
if _, err = root.PutObject(ctx, bucket, forbidden, bytes.NewReader(data), int64(len(data)), minio.PutObjectOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outside, err := app.GetObject(ctx, bucket, forbidden, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = outside.Stat()
|
||||
outside.Close()
|
||||
denied(t, err)
|
||||
denied(t, app.RemoveObject(ctx, bucket, forbidden, minio.RemoveObjectOptions{}))
|
||||
other := "upload-permissions-" + uuid.NewString()
|
||||
if err = root.MakeBucket(ctx, other, minio.MakeBucketOptions{Region: os.Getenv("S3_REGION")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
root.RemoveObject(context.Background(), other, key, minio.RemoveObjectOptions{})
|
||||
root.RemoveBucket(context.Background(), other)
|
||||
})
|
||||
_, err = app.PutObject(ctx, other, key, bytes.NewReader(data), int64(len(data)), minio.PutObjectOptions{})
|
||||
denied(t, err)
|
||||
denied(t, app.MakeBucket(ctx, "forbidden-"+uuid.NewString(), minio.MakeBucketOptions{}))
|
||||
denied(t, app.SetBucketPolicy(ctx, bucket, ""))
|
||||
if err = app.RemoveObject(ctx, bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Admin APIs have a separate JSON error type; reject exactly AccessDenied.
|
||||
endpoint, _ := url.Parse(os.Getenv("S3_ENDPOINT"))
|
||||
access, _ := os.ReadFile(os.Getenv("S3_ACCESS_KEY_ID_FILE"))
|
||||
secret, _ := os.ReadFile(os.Getenv("S3_SECRET_ACCESS_KEY_FILE"))
|
||||
admin, err := madmin.New(endpoint.Host, strings.TrimSpace(string(access)), strings.TrimSpace(string(secret)), endpoint.Scheme == "https")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = admin.ListUsers(ctx)
|
||||
if err == nil || madmin.ToErrorResponse(err).Code != "AccessDenied" {
|
||||
t.Fatalf("API credentials permit admin access or wrong error: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -58,6 +58,7 @@ func newTestFixture(t *testing.T) *testFixture {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["search_path"] = schema
|
||||
cfg.ConnConfig.RuntimeParams["application_name"] = schema
|
||||
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -92,6 +93,13 @@ func newTestFixture(t *testing.T) *testFixture {
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ddl, err = os.ReadFile("../repositories/migrations/000005_upload_attempts.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(ctx, string(ddl)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = redisClient.Close() })
|
||||
if err := redisClient.Ping(ctx).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/src/backend/repositories"
|
||||
"messenger/src/backend/services"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type uploadFault struct {
|
||||
*repositories.ObjectStore
|
||||
afterPut func() error
|
||||
}
|
||||
|
||||
func (s uploadFault) Put(ctx context.Context, key string, reader io.Reader, size int64, mime string) error {
|
||||
if err := s.ObjectStore.Put(ctx, key, reader, size, mime); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.afterPut()
|
||||
}
|
||||
|
||||
func uploadObjects(t *testing.T) *repositories.ObjectStore {
|
||||
t.Helper()
|
||||
if os.Getenv("S3_ENDPOINT") == "" {
|
||||
t.Skip("S3 integration: run make test-backend")
|
||||
}
|
||||
store, err := repositories.NewObjectStoreFromEnvironment()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return store
|
||||
}
|
||||
func uploadPNG(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
var buffer bytes.Buffer
|
||||
if err := png.Encode(&buffer, image.NewRGBA(image.Rect(0, 0, 8, 8))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buffer.Bytes()
|
||||
}
|
||||
func uploadFixture(t *testing.T) (*testFixture, *repositories.AttachmentStore, *repositories.ObjectStore, string, string) {
|
||||
f := newTestFixture(t)
|
||||
user, _ := createTestUser(t, f.users, "alice", "Alice")
|
||||
chat := createTestChat(t, f.chats, "Upload recovery", []string{user.ID})
|
||||
return f, repositories.NewAttachmentStore(f.db), uploadObjects(t), user.ID, chat.ID
|
||||
}
|
||||
func ageAndClean(t *testing.T, f *testFixture, store *repositories.AttachmentStore, objects *repositories.ObjectStore) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
var key string
|
||||
if err := f.db.QueryRow(ctx, "SELECT object_key FROM upload_attempts").Scan(&key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { objects.Delete(context.Background(), key) })
|
||||
if _, err := f.db.Exec(ctx, "UPDATE upload_attempts SET cleanup_after=clock_timestamp()-interval '1 second'"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := store.CleanupUploads(ctx, false, objects.Delete)
|
||||
if err != nil || result.Deleted != 1 {
|
||||
t.Fatalf("cleanup: %+v %v", result, err)
|
||||
}
|
||||
if content, err := objects.Get(ctx, key); err == nil {
|
||||
content.Close()
|
||||
t.Fatal("orphan still exists")
|
||||
}
|
||||
var count int
|
||||
if err := f.db.QueryRow(ctx, "SELECT count(*) FROM upload_attempts").Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("journal: %d %v", count, err)
|
||||
}
|
||||
if err := f.db.QueryRow(ctx, "SELECT count(*) FROM attachments").Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("unexpected metadata: %d %v", count, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadRecoveryAfterPutFailure(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
service := services.NewAttachmentService(store, uploadFault{objects, func() error { return errors.New("injected PUT result loss") }})
|
||||
if _, err := service.Upload(context.Background(), user, chat, "photo.png", "image/png", bytes.NewReader(uploadPNG(t))); err == nil {
|
||||
t.Fatal("expected failure")
|
||||
}
|
||||
ageAndClean(t, f, store, objects)
|
||||
}
|
||||
func TestUploadRecoveryMetadataRejection(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
if _, err := f.db.Exec(context.Background(), `ALTER TABLE attachments ADD CONSTRAINT reject_fixture CHECK(filename <> 'reject.png')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := services.NewAttachmentService(store, objects)
|
||||
if _, err := service.Upload(context.Background(), user, chat, "reject.png", "image/png", bytes.NewReader(uploadPNG(t))); err == nil {
|
||||
t.Fatal("expected metadata rejection")
|
||||
}
|
||||
ageAndClean(t, f, store, objects)
|
||||
}
|
||||
func TestUploadRecoveryDatabaseConnectionLoss(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
// Kill only this fixture's idle upload transaction, after its S3 PUT.
|
||||
fault := func() error {
|
||||
_, err := f.db.Exec(context.Background(), `SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name=$1 AND state='idle in transaction' AND pid<>pg_backend_pid()`, f.db.Config().ConnConfig.RuntimeParams["application_name"])
|
||||
return err
|
||||
}
|
||||
service := services.NewAttachmentService(store, uploadFault{objects, fault})
|
||||
if _, err := service.Upload(context.Background(), user, chat, "photo.png", "image/png", bytes.NewReader(uploadPNG(t))); err == nil {
|
||||
t.Fatal("expected connection loss")
|
||||
}
|
||||
ageAndClean(t, f, store, objects)
|
||||
}
|
||||
|
||||
func TestUploadRecoveryProcessExit(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
directory := t.TempDir()
|
||||
t.Setenv("UPLOAD_TMP_DIR", directory)
|
||||
child := exec.Command(os.Args[0], "-test.run=^TestUploadCrashHelper$")
|
||||
child.Env = append(os.Environ(), "UPLOAD_CRASH_HELPER=1", "UPLOAD_TEST_DATABASE="+f.db.Config().ConnString(), "UPLOAD_TEST_SCHEMA="+f.db.Config().ConnConfig.RuntimeParams["search_path"], "UPLOAD_TEST_USER="+user, "UPLOAD_TEST_CHAT="+chat)
|
||||
output, err := child.CombinedOutput()
|
||||
var exit *exec.ExitError
|
||||
if !errors.As(err, &exit) || exit.ExitCode() != 23 {
|
||||
t.Fatalf("helper did not exit after PUT: %v %s", err, output)
|
||||
}
|
||||
ageAndClean(t, f, store, objects)
|
||||
files, err := os.ReadDir(directory)
|
||||
if err != nil || len(files) != 0 {
|
||||
t.Fatalf("temporary files left after exit: %v %v", files, err)
|
||||
}
|
||||
}
|
||||
func TestUploadCrashHelper(t *testing.T) {
|
||||
if os.Getenv("UPLOAD_CRASH_HELPER") != "1" {
|
||||
return
|
||||
}
|
||||
cfg, err := pgxpool.ParseConfig(os.Getenv("UPLOAD_TEST_DATABASE"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["search_path"] = os.Getenv("UPLOAD_TEST_SCHEMA")
|
||||
cfg.ConnConfig.RuntimeParams["application_name"] = os.Getenv("UPLOAD_TEST_SCHEMA")
|
||||
db, err := pgxpool.NewWithConfig(context.Background(), cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
objects := uploadObjects(t)
|
||||
service := services.NewAttachmentService(repositories.NewAttachmentStore(db), uploadFault{objects, func() error { os.Exit(23); return nil }})
|
||||
_, err = service.Upload(context.Background(), os.Getenv("UPLOAD_TEST_USER"), os.Getenv("UPLOAD_TEST_CHAT"), "crash.png", "image/png", bytes.NewReader(uploadPNG(t)))
|
||||
t.Fatalf("helper failed before exit: %v", err)
|
||||
}
|
||||
|
||||
type interruptedReader struct{ first bool }
|
||||
|
||||
func (r *interruptedReader) Read(p []byte) (int, error) {
|
||||
if !r.first {
|
||||
r.first = true
|
||||
return copy(p, []byte("partial PNG")), nil
|
||||
}
|
||||
return 0, io.ErrUnexpectedEOF
|
||||
}
|
||||
func TestUploadRecoveryInterruptedBody(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
directory := t.TempDir()
|
||||
t.Setenv("UPLOAD_TMP_DIR", directory)
|
||||
service := services.NewAttachmentService(store, objects)
|
||||
if _, err := service.Upload(context.Background(), user, chat, "photo.png", "image/png", &interruptedReader{}); !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
t.Fatalf("body interruption: %v", err)
|
||||
}
|
||||
var count int
|
||||
f.db.QueryRow(context.Background(), "SELECT count(*) FROM upload_attempts").Scan(&count)
|
||||
if count != 0 {
|
||||
t.Fatal("reservation before complete body")
|
||||
}
|
||||
files, err := os.ReadDir(directory)
|
||||
if err != nil || len(files) != 0 {
|
||||
t.Fatalf("temporary paths left: %v %v", files, err)
|
||||
}
|
||||
}
|
||||
func TestUploadRecoveryWaitingCancellation(t *testing.T) {
|
||||
f, store, objects, user, chat := uploadFixture(t)
|
||||
entered := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
service := services.NewAttachmentService(store, uploadFault{objects, func() error { close(entered); <-release; return errors.New("test stop") }})
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
service.Upload(context.Background(), user, chat, "first.png", "image/png", bytes.NewReader(uploadPNG(t)))
|
||||
}()
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("first upload did not reach PUT")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err := service.Upload(ctx, user, chat, "second.png", "image/png", strings.NewReader("unused"))
|
||||
close(release)
|
||||
<-done
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("waiting upload ignored cancellation: %v", err)
|
||||
}
|
||||
ageAndClean(t, f, store, objects)
|
||||
}
|
||||
Reference in New Issue
Block a user