forked from mtusi2026/mtusi2026lab4
feat: add 4 grade things
This commit is contained in:
@@ -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