forked from mtusi2026/mtusi2026lab6
341 lines
13 KiB
Go
341 lines
13 KiB
Go
package auth_tests
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
repo "highload/internal/repository"
|
|
"highload/internal/repository/postgres"
|
|
"highload/internal/service"
|
|
"highload/internal/storage"
|
|
"highload/internal/storage/s3"
|
|
"highload/internal/transport/http/handler"
|
|
"highload/internal/transport/http/middleware"
|
|
|
|
"github.com/aws/aws-sdk-go-v2/aws"
|
|
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
func newAttachmentTxFixture(t *testing.T) (*fixture, repo.CreateAttachmentParams) {
|
|
t.Helper()
|
|
f := newDatabaseFixture(t, "LAB4_TEST_DATABASE_URL", 4)
|
|
owner := uuid.NewString()
|
|
if _, err := f.pool.Exec(f.ctx, "INSERT INTO users(id,username,display_name,password_hash) VALUES($1,'tx_fixture','TX fixture','unused')", owner); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
chat, err := postgres.NewChatRepository(f.queries, f.pool).CreateChat(f.ctx, "Attachment transaction", []string{owner})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return f, repo.CreateAttachmentParams{
|
|
ChatID: chat.ID, OwnerID: owner, ObjectKey: "attachments/" + uuid.NewString(),
|
|
Filename: "fixture.png", ContentType: "image/png", SizeBytes: 1, Sha256: strings.Repeat("a", 64),
|
|
}
|
|
}
|
|
|
|
func assertAttachmentCount(t *testing.T, f *fixture, want int) {
|
|
t.Helper()
|
|
var attachments, jobs, outbox int
|
|
err := f.pool.QueryRow(f.ctx, `SELECT (SELECT count(*) FROM attachments),
|
|
(SELECT count(*) FROM attachment_jobs), (SELECT count(*) FROM outbox)`).Scan(&attachments, &jobs, &outbox)
|
|
if err != nil || attachments != want || jobs != want || outbox != want {
|
|
t.Fatalf("expected %d rows each, got attachments=%d jobs=%d outbox=%d (%v)", want, attachments, jobs, outbox, err)
|
|
}
|
|
}
|
|
|
|
func TestAttachmentTxLockAndRollback(t *testing.T) {
|
|
f, params := newAttachmentTxFixture(t)
|
|
// Run the isolation check on the very connection doing the callback INSERT.
|
|
// A query through the pool would only establish the observer's isolation.
|
|
if _, err := f.pool.Exec(f.ctx, `
|
|
CREATE FUNCTION assert_attachment_isolation() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
BEGIN
|
|
IF current_setting('transaction_isolation') <> 'read committed' THEN
|
|
RAISE EXCEPTION 'expected read committed during attachment INSERT';
|
|
END IF;
|
|
RETURN NEW;
|
|
END $$;
|
|
CREATE TRIGGER assert_attachment_isolation BEFORE INSERT ON attachments
|
|
FOR EACH ROW EXECUTE FUNCTION assert_attachment_isolation();
|
|
`, pgx.QueryExecModeSimpleProtocol); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
attachments := postgres.NewAttachmentRepository(f.queries, f.pool)
|
|
id := uuid.NewString()
|
|
key := "staging/" + id + "/original"
|
|
entered := make(chan struct{})
|
|
release := make(chan struct{})
|
|
type outcome struct {
|
|
locked bool
|
|
err error
|
|
}
|
|
done := make(chan outcome, 1)
|
|
holdCtx, cancelHold := context.WithCancel(f.ctx)
|
|
defer cancelHold()
|
|
go func() {
|
|
locked, err := attachments.WithObjectKeyLock(holdCtx, key, func(ctx context.Context, _ repo.AttachmentTx) error {
|
|
close(entered)
|
|
select {
|
|
case <-release:
|
|
return nil
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
})
|
|
done <- outcome{locked, err}
|
|
}()
|
|
select {
|
|
case <-entered:
|
|
case result := <-done:
|
|
t.Fatalf("holder never entered callback: %+v", result)
|
|
case <-time.After(3 * time.Second):
|
|
t.Fatal("holder did not acquire the lock")
|
|
}
|
|
unexpected := func(context.Context, repo.AttachmentTx) error {
|
|
return errors.New("contending callback ran")
|
|
}
|
|
if locked, err := attachments.WithObjectKeyLock(f.ctx, key, unexpected); locked || err != nil {
|
|
t.Fatalf("same key must return false, nil without callback: %t, %v", locked, err)
|
|
}
|
|
noop := func(context.Context, repo.AttachmentTx) error { return nil }
|
|
if locked, err := attachments.WithObjectKeyLock(f.ctx, key+"-other", noop); !locked || err != nil {
|
|
t.Fatalf("another key was blocked: %t, %v", locked, err)
|
|
}
|
|
close(release)
|
|
select {
|
|
case result := <-done:
|
|
if !result.locked || result.err != nil {
|
|
t.Fatalf("holder did not complete: %+v", result)
|
|
}
|
|
case <-time.After(3 * time.Second):
|
|
t.Fatal("holder did not close its transaction")
|
|
}
|
|
if locked, err := attachments.WithObjectKeyLock(f.ctx, key, noop); !locked || err != nil {
|
|
t.Fatalf("committed lock was not released: %t, %v", locked, err)
|
|
}
|
|
|
|
for _, name := range []string{"callback_error", "context_canceled"} {
|
|
t.Run(name, func(t *testing.T) {
|
|
sentinel := errors.New("synthetic callback failure")
|
|
ctx, cancel := context.WithCancel(f.ctx)
|
|
defer cancel()
|
|
want := error(sentinel)
|
|
if name == "context_canceled" {
|
|
want = context.Canceled
|
|
}
|
|
locked, err := attachments.WithObjectKeyLock(ctx, key, func(txCtx context.Context, tx repo.AttachmentTx) error {
|
|
if _, err := tx.CreateQueued(txCtx, id, params.ChatID, params.OwnerID, params.ContentType,
|
|
params.Sha256, key, params.Filename, params.SizeBytes); err != nil {
|
|
return err
|
|
}
|
|
exists, err := tx.ExistsByObjectKey(txCtx, key)
|
|
if err != nil || !exists {
|
|
return fmt.Errorf("transaction did not see its INSERT: %w", err)
|
|
}
|
|
assertAttachmentCount(t, f, 0)
|
|
if name == "context_canceled" {
|
|
cancel()
|
|
return txCtx.Err()
|
|
}
|
|
return sentinel
|
|
})
|
|
if !locked || err != want {
|
|
t.Fatalf("callback error must pass through unchanged with true: %t, %v", locked, err)
|
|
}
|
|
assertAttachmentCount(t, f, 0)
|
|
if locked, err = attachments.WithObjectKeyLock(f.ctx, key, noop); !locked || err != nil {
|
|
t.Fatalf("rollback failed to free lock/pool: %t, %v", locked, err)
|
|
}
|
|
t.Log("INSERT ran at read committed, rollback left zero rows and released the lock")
|
|
})
|
|
}
|
|
}
|
|
|
|
// txS3Transport observes the real SDK requests and retains synthetic bytes for GET.
|
|
// Before accepting a PUT it challenges the lock from a separate PostgreSQL session.
|
|
type txS3Transport struct {
|
|
fixture *fixture
|
|
key string
|
|
data []byte
|
|
put, get, delete int
|
|
failPut bool
|
|
}
|
|
|
|
func (s *txS3Transport) Do(request *http.Request) (*http.Response, error) {
|
|
resp := &http.Response{StatusCode: 200, Header: make(http.Header), Body: http.NoBody}
|
|
key := strings.TrimPrefix(request.URL.Path, "/tx-test/")
|
|
parts := strings.Split(key, "/")
|
|
if len(parts) != 3 || parts[0] != "staging" || parts[2] != "original" {
|
|
return nil, errors.New("unexpected synthetic S3 staging key")
|
|
}
|
|
if _, err := uuid.Parse(parts[1]); err != nil {
|
|
return nil, errors.New("staging key lacks an attachment UUID")
|
|
}
|
|
switch request.Method {
|
|
case http.MethodPut:
|
|
s.put++
|
|
s.key = key
|
|
var acquired bool
|
|
err := s.fixture.pool.QueryRow(request.Context(),
|
|
"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))", key).Scan(&acquired)
|
|
if err != nil || acquired {
|
|
return nil, fmt.Errorf("PUT ran without held object lock: acquired=%t, error=%v", acquired, err)
|
|
}
|
|
if s.failPut {
|
|
resp.StatusCode = 503
|
|
resp.Header.Set("Content-Type", "application/xml")
|
|
resp.Body = io.NopCloser(strings.NewReader("<Error><Code>SlowDown</Code><Message>Synthetic outage</Message></Error>"))
|
|
return resp, nil
|
|
}
|
|
defer request.Body.Close()
|
|
s.data, err = io.ReadAll(request.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
case http.MethodGet:
|
|
s.get++
|
|
if key != s.key || s.data == nil {
|
|
return nil, errors.New("object unavailable in fixture")
|
|
}
|
|
resp.Body = io.NopCloser(bytes.NewReader(s.data))
|
|
resp.ContentLength = int64(len(s.data))
|
|
case http.MethodDelete:
|
|
s.delete++
|
|
s.data = nil
|
|
default:
|
|
return nil, fmt.Errorf("unexpected S3 method %s", request.Method)
|
|
}
|
|
return resp, nil
|
|
}
|
|
|
|
func TestAttachmentTxHTTP(t *testing.T) {
|
|
_, source, _, _ := runtime.Caller(0)
|
|
png, err := os.ReadFile(filepath.Join(filepath.Dir(source), "../../tests/fixtures/sample.png"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
hash := fmt.Sprintf("%x", sha256.Sum256(png))
|
|
for _, scenario := range []struct {
|
|
name string
|
|
faultSQL string
|
|
http int
|
|
errorCode string
|
|
}{
|
|
{name: "s3_unavailable", http: 503, errorCode: "unavailable"},
|
|
{name: "insert_after_put", faultSQL: "ALTER TABLE attachments ADD CHECK (filename <> 'fixture.png')", http: 500, errorCode: "internal_error"},
|
|
{name: "commit_after_insert", faultSQL: `
|
|
CREATE FUNCTION reject_attachment_commit() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
BEGIN RAISE EXCEPTION 'synthetic deferred failure'; END $$;
|
|
CREATE CONSTRAINT TRIGGER reject_attachment_commit AFTER INSERT ON attachments
|
|
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION reject_attachment_commit();
|
|
`, http: 500, errorCode: "internal_error"},
|
|
{name: "committed_upload_is_queued", http: http.StatusAccepted},
|
|
} {
|
|
t.Run(scenario.name, func(t *testing.T) {
|
|
f, params := newAttachmentTxFixture(t)
|
|
if scenario.faultSQL != "" {
|
|
if _, err := f.pool.Exec(f.ctx, scenario.faultSQL, pgx.QueryExecModeSimpleProtocol); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
transport := &txS3Transport{fixture: f, failPut: scenario.http == 503}
|
|
objects := &s3.Storage{Bucket: "tx-test", Client: awss3.New(awss3.Options{
|
|
Region: "us-east-1", UsePathStyle: true, BaseEndpoint: aws.String("http://tx-s3.invalid"),
|
|
Credentials: aws.AnonymousCredentials{}, Retryer: aws.NopRetryer{}, HTTPClient: transport,
|
|
})}
|
|
chats := service.NewChatService(postgres.NewChatRepository(f.queries, f.pool), nil, nil)
|
|
attachments := postgres.NewAttachmentRepository(f.queries, f.pool)
|
|
svc := service.NewAttachmentService(attachments, chats, objects)
|
|
h := handler.NewAttachmentHandler(svc)
|
|
call := func(method, path, param, value string, data []byte, next http.HandlerFunc) *httptest.ResponseRecorder {
|
|
r := httptest.NewRequest(method, path, bytes.NewReader(data))
|
|
r = r.WithContext(middleware.WithUserID(f.ctx, params.OwnerID))
|
|
r.SetPathValue(param, value)
|
|
r.Header.Set("Content-Type", "image/png")
|
|
w := httptest.NewRecorder()
|
|
mid := middleware.NewMiddleware(nil, "attachment-tx")
|
|
mid.InstanceID(mid.RequestID(next)).ServeHTTP(w, r)
|
|
return w
|
|
}
|
|
w := call(http.MethodPost, "/attachments?filename=fixture.png", "chat_id", params.ChatID, png, h.CreateAttachment)
|
|
if transport.put != 1 || transport.delete != 0 {
|
|
t.Fatalf("expected one PUT and zero DELETE, got %d/%d", transport.put, transport.delete)
|
|
}
|
|
if scenario.http != http.StatusAccepted {
|
|
assertContractError(t, w, scenario.http, scenario.errorCode)
|
|
assertAttachmentCount(t, f, 0)
|
|
if scenario.http == 503 {
|
|
if transport.data != nil {
|
|
t.Fatal("failed S3 PUT stored an object")
|
|
}
|
|
_, err := svc.CreateAttachment(f.ctx, params.ChatID, params.OwnerID, "fixture.png", "image/png", bytes.NewReader(png), int64(len(png)))
|
|
if !errors.Is(err, service.ErrServiceUnavailable) || errors.Is(err, storage.ErrStorage) {
|
|
t.Fatalf("storage category did not reach service as unavailable: %v", err)
|
|
}
|
|
} else if !bytes.Equal(transport.data, png) {
|
|
t.Fatal("failed database write did not leave the already stored original")
|
|
}
|
|
if locked, err := attachments.WithObjectKeyLock(f.ctx, transport.key, func(context.Context, repo.AttachmentTx) error { return nil }); !locked || err != nil {
|
|
t.Fatalf("failed upload left key locked: %t, %v", locked, err)
|
|
}
|
|
t.Logf("direct handler HTTP %d; committed rows=0; DELETE=0", w.Code)
|
|
return
|
|
}
|
|
if w.Code != http.StatusAccepted {
|
|
t.Fatalf("expected 202 after commit, got %d", w.Code)
|
|
}
|
|
assertAttachmentCount(t, f, 1)
|
|
var response struct {
|
|
ID string `json:"id"`
|
|
SHA string `json:"sha256"`
|
|
Status string `json:"status"`
|
|
Variants []json.RawMessage `json:"variants"`
|
|
ErrorCode *string `json:"error_code"`
|
|
}
|
|
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil || response.SHA != hash ||
|
|
response.Status != "queued" || response.Variants == nil || len(response.Variants) != 0 || response.ErrorCode != nil {
|
|
t.Fatal("invalid queued upload response or SHA-256")
|
|
}
|
|
row, err := attachments.GetAttachmentForUser(f.ctx, params.OwnerID, response.ID)
|
|
if err != nil || row.SHA256 != hash || row.ObjectKey != "" || row.StagingKey != transport.key ||
|
|
transport.key != "staging/"+response.ID+"/original" || row.SizeBytes != int64(len(png)) ||
|
|
!bytes.Equal(transport.data, png) {
|
|
t.Fatal("committed metadata/staging does not match uploaded file")
|
|
}
|
|
var linked bool
|
|
err = f.pool.QueryRow(f.ctx, `SELECT EXISTS(SELECT 1 FROM attachment_jobs j
|
|
JOIN outbox o ON o.job_id=j.id WHERE j.attachment_id=$1
|
|
AND o.payload->>'attachment_id' = $1::uuid::text AND o.payload->>'job_id'=j.id::text
|
|
AND o.sent_at IS NULL)`, response.ID).Scan(&linked)
|
|
if err != nil || !linked {
|
|
t.Fatal("202 lacks a pending outbox record for the same durable job")
|
|
}
|
|
get := call(http.MethodGet, "/attachments/"+response.ID, "attachment_id", response.ID, nil, h.GetAttachment)
|
|
if get.Code != 200 || !bytes.Equal(bytes.TrimSpace(get.Body.Bytes()), bytes.TrimSpace(w.Body.Bytes())) {
|
|
t.Fatal("metadata GET changed")
|
|
}
|
|
body := call(http.MethodGet, "/attachments/"+response.ID+"/content", "attachment_id", response.ID, nil, h.GetAttachmentContent)
|
|
assertContractError(t, body, http.StatusConflict, "conflict")
|
|
if transport.get != 0 {
|
|
t.Fatal("content GET attempted to read S3 for a queued attachment")
|
|
}
|
|
t.Logf("HTTP 202, attachment/job/outbox committed, metadata=200, queued content=409, SHA-256=%s", hash)
|
|
})
|
|
}
|
|
}
|