package auth_tests import ( "bytes" "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "os" "reflect" "slices" "strings" "sync" "testing" "time" "highload/internal/model" domainrepo "highload/internal/repository" postgresrepo "highload/internal/repository/postgres" "highload/internal/service" "highload/internal/transport/http/handler" "highload/internal/transport/http/middleware" "github.com/google/uuid" ) // Uses the real handler/service/PostgreSQL repository and metadata-only fixtures. // Authentication is already covered by the existing auth tests: only the current // user context is injected here. No S3 server, upload endpoint or Redis is needed. type messageAttachmentFixture struct { *fixture http http.Handler alice, bob string chat, other *model.Chat ids, foreign []string } type attachmentMessage struct { ID string `json:"id"` ChatID string `json:"chat_id"` SenderID string `json:"sender_id"` Text string `json:"text"` CreatedAt string `json:"created_at"` AttachmentIDs []string `json:"attachment_ids"` } // Small dependencies for the real service's one-attachment regression. They // compare UUID identity without prescribing where normalization takes place. // They do not implement persistence/idempotency: PostgreSQL cases prove that. type singleAttachmentChatRepo struct { domainrepo.ChatRepository chat *model.Chat } func (r *singleAttachmentChatRepo) GetChatByID(_ context.Context, id string) (*model.Chat, error) { if id != r.chat.ID { return nil, domainrepo.ErrNotFound } return r.chat, nil } type singleAttachmentMessageRepo struct { domainrepo.MessageRepository message *model.Message key string calls [][]string } func (r *singleAttachmentMessageRepo) CreateMessage(_ context.Context, chatID, userID, text, key string, ids []string) (*model.Message, error) { r.calls = append(r.calls, append([]string{}, ids...)) if chatID != r.message.ChatID || userID != r.message.SenderID || text != r.message.Text || key != r.key { return nil, domainrepo.ErrServerError } if len(ids) != len(r.message.AttachmentIDs) { return nil, domainrepo.ErrInvalidInput } for index, raw := range ids { id, err := uuid.Parse(raw) if err != nil || id.String() != r.message.AttachmentIDs[index] { return nil, domainrepo.ErrInvalidInput } } return r.message, nil } func TestMessageAttachmentsSingleIDServiceRegression(t *testing.T) { const attachmentID = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee" for _, scenario := range []struct { name, inputID string requests int }{ {name: "single_attachment_without_panic", inputID: attachmentID, requests: 1}, {name: "identical_uppercase_body_replay", inputID: strings.ToUpper(attachmentID), requests: 2}, } { t.Run(scenario.name, func(t *testing.T) { defer func() { if recovered := recover(); recovered != nil { t.Errorf("CreateMessage with one valid attachment panicked: %v", recovered) } }() userID, chatID, key := uuid.NewString(), uuid.NewString(), uuid.NewString() original := &model.Message{ID: uuid.NewString(), ChatID: chatID, SenderID: userID, Text: "", AttachmentIDs: []string{attachmentID}, CreatedAt: time.Unix(1700000000, 0).UTC()} repo := &singleAttachmentMessageRepo{message: original, key: key} chatRepo := &singleAttachmentChatRepo{chat: &model.Chat{ID: chatID, MemberIDs: []string{userID}}} chats := service.NewChatService(chatRepo, nil, nil) messages := service.NewMessageService(repo, chats, nil) for range scenario.requests { // The uppercase case starts uppercase and repeats EXACTLY the same // values. It never assumes different string bodies must be equivalent. input := []string{scenario.inputID} message, err := messages.CreateMessage(context.Background(), "", chatID, userID, key, input) if err != nil || !reflect.DeepEqual(message, original) { t.Fatalf("one attachment / identical uppercase replay: expected original Message without conflict, got %v", err) } } if len(repo.calls) == 0 { t.Fatal("service did not create the message through its repository") } for _, ids := range repo.calls { if len(ids) != 1 { t.Fatal("service lost the single attachment") } id, err := uuid.Parse(ids[0]) if err != nil || id.String() != attachmentID { t.Fatal("service changed the attachment UUID identity") } } }) } } func newMessageAttachmentFixture(t *testing.T) *messageAttachmentFixture { t.Helper() f := newDatabaseFixture(t, "LAB4_TEST_DATABASE_URL", 12) result := &messageAttachmentFixture{fixture: f, alice: uuid.NewString(), bob: uuid.NewString()} for _, id := range []string{result.alice, result.bob} { _, err := f.pool.Exec(f.ctx, `INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,'Synthetic attachment test','fixture-only-not-used-for-login')`, id, "attach_"+strings.ReplaceAll(id, "-", "")[:18]) if err != nil { t.Fatal("cannot prepare synthetic users") } } chatRepo := postgresrepo.NewChatRepository(f.queries, f.pool) var err error result.chat, err = chatRepo.CreateChat(f.ctx, "Message attachments", []string{result.alice, result.bob}) if err != nil { t.Fatal("cannot prepare primary chat") } result.other, err = chatRepo.CreateChat(f.ctx, "Other attachment scope", []string{result.alice}) if err != nil { t.Fatal("cannot prepare other chat") } attachments := postgresrepo.NewAttachmentRepository(f.queries, f.pool) for _, chat := range []*model.Chat{result.chat, result.other} { for i := 0; i < 11; i++ { att, err := attachments.CreateAttachment(f.ctx, domainrepo.CreateAttachmentParams{ ChatID: chat.ID, OwnerID: result.alice, Filename: fmt.Sprintf("synthetic-%d.png", i), ObjectKey: "metadata-only/" + uuid.NewString(), ContentType: "image/png", Sha256: strings.Repeat("a", 64), SizeBytes: 1, }) if err != nil { t.Fatal("cannot seed attachment metadata through its PostgreSQL repository") } if chat.ID == result.chat.ID { result.ids = append(result.ids, att.ID) } else { result.foreign = append(result.foreign, att.ID) } } } // Deliberately disagree with UUID ordering to catch accidental ORDER BY id. slices.Sort(result.ids) slices.Reverse(result.ids) users := service.NewUserService(postgresrepo.NewUserRepository(f.queries)) chats := service.NewChatService(chatRepo, postgresrepo.NewUserRepository(f.queries), users) messages := service.NewMessageService(postgresrepo.NewMessageRepository(f.queries, f.pool), chats, users) h := handler.NewMessageHandler(messages) mux := http.NewServeMux() mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", h.CreateMessage) mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", h.GetMessagesByChatID) mid := middleware.NewMiddleware(nil, "message-pg-test") result.http = mid.InstanceID(mid.RequestID(mux)) return result } func (f *messageAttachmentFixture) call(actor, method, chatID, key string, body any) *httptest.ResponseRecorder { var raw []byte if body != nil { raw, _ = json.Marshal(body) } request := httptest.NewRequest(method, "/api/v1/chats/"+chatID+"/messages?limit=100", bytes.NewReader(raw)) request = request.WithContext(middleware.WithUserID(f.ctx, actor)) request.Header.Set("Content-Type", "application/json") if key != "" { request.Header.Set("Idempotency-Key", key) } recorder := httptest.NewRecorder() f.http.ServeHTTP(recorder, request) return recorder } func attachmentBody(text string, ids []string) map[string]any { return map[string]any{"text": text, "attachment_ids": ids} } func decodeAttachmentMessage(t *testing.T, response *httptest.ResponseRecorder) attachmentMessage { t.Helper() if response.Code != http.StatusCreated { t.Fatalf("POST message: expected HTTP 201, got %d", response.Code) } var value map[string]json.RawMessage if err := json.Unmarshal(response.Body.Bytes(), &value); err != nil || len(value) != 6 { t.Fatal("Message must contain exactly the six lab4 contract fields, including attachment_ids") } var message attachmentMessage if err := json.Unmarshal(response.Body.Bytes(), &message); err != nil || message.AttachmentIDs == nil { t.Fatal("attachment_ids must be an array, including [] for a text-only message") } for _, id := range []string{message.ID, message.ChatID, message.SenderID} { if _, err := uuid.Parse(id); err != nil { t.Fatal("Message contains an invalid UUID") } } if _, err := time.Parse(time.RFC3339Nano, message.CreatedAt); err != nil || !strings.HasSuffix(message.CreatedAt, "Z") { t.Fatal("Message must preserve a server UTC timestamp") } if response.Header().Get("X-Request-Id") == "" || response.Header().Get("X-Instance-Id") != "message-pg-test" { t.Fatal("message response is missing request/instance identity") } return message } func (f *messageAttachmentFixture) history(t *testing.T) []attachmentMessage { t.Helper() r := f.call(f.bob, "GET", f.chat.ID, "", nil) var page struct { Items []attachmentMessage `json:"items"` NextCursor *string `json:"next_cursor"` } if r.Code != 200 || json.Unmarshal(r.Body.Bytes(), &page) != nil || page.NextCursor != nil { t.Fatal("cannot read the complete synthetic history") } for _, message := range page.Items { if message.AttachmentIDs == nil { t.Fatal("history must include attachment_ids arrays") } } return page.Items } func (f *messageAttachmentFixture) assertLinks(t *testing.T, message attachmentMessage, expected []string) { t.Helper() if !sameOrderedAttachmentUUIDs(message.AttachmentIDs, expected) { t.Fatal("Message attachment order or contents differ from request") } rows, err := f.pool.Query(f.ctx, `SELECT attachment_id::text, position, chat_id::text FROM messages_attachments WHERE message_id=$1 ORDER BY position`, message.ID) if err != nil { t.Fatal("cannot inspect attachment links") } defer rows.Close() var actual []string for rows.Next() { var id, chatID string var position int if rows.Scan(&id, &position, &chatID) != nil || position != len(actual) || chatID != f.chat.ID { t.Fatal("attachment link has incorrect position or chat scope") } actual = append(actual, id) } if rows.Err() != nil || !slices.Equal(actual, expected) { t.Fatal("database links do not match exactly the submitted attachment order") } } func sameOrderedAttachmentUUIDs(actual, expected []string) bool { if actual == nil || len(actual) != len(expected) { return false } for index, raw := range actual { id, err := uuid.Parse(raw) want, wantErr := uuid.Parse(expected[index]) if err != nil || wantErr != nil || id != want { return false } } return true } func sameHistoryMessage(actual, expected attachmentMessage) bool { if !sameOrderedAttachmentUUIDs(actual.AttachmentIDs, expected.AttachmentIDs) { return false } actual.AttachmentIDs = expected.AttachmentIDs return reflect.DeepEqual(actual, expected) } func (f *messageAttachmentFixture) snapshot(t *testing.T) map[string][]string { t.Helper() state := make(map[string][]string) for _, table := range []string{"messages", "messages_attachments", "message_idempotency", "attachments"} { // Table names are fixed test constants, never request input. rows, err := f.pool.Query(f.ctx, "SELECT to_jsonb(item)::text FROM "+table+" AS item ORDER BY to_jsonb(item)::text") if err != nil { t.Fatal("cannot inspect transaction state") } for rows.Next() { var row string if rows.Scan(&row) != nil { t.Fatal("cannot decode transaction state") } state[table] = append(state[table], row) } err = rows.Err() rows.Close() if err != nil { t.Fatal("cannot finish inspecting transaction state") } } return state } func (f *messageAttachmentFixture) assertUnchanged(t *testing.T, before map[string][]string) { t.Helper() if !reflect.DeepEqual(before, f.snapshot(t)) { t.Fatal("failed/conflicting request changed messages, links, idempotency or metadata") } } func TestMessageAttachmentsTextCompatibility(t *testing.T) { f := newMessageAttachmentFixture(t) key := uuid.NewString() first := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, map[string]any{"text": "Legacy text 👋"})) second := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody(first.Text, []string{}))) if first.ChatID != f.chat.ID || first.SenderID != f.alice || first.Text != "Legacy text 👋" || !reflect.DeepEqual(first, second) { t.Fatal("absent attachment_ids and [] must preserve the same text-only Message") } f.assertLinks(t, first, []string{}) if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) { t.Fatal("text-only replay changed or duplicated history") } } func TestMessageAttachmentsOnlyAndOrderZeroToTen(t *testing.T) { if os.Getenv("LAB4_TEST_DATABASE_URL") == "" { t.Skip("PENDING_INFRA: set LAB4_TEST_DATABASE_URL for dedicated PostgreSQL") } for count := 0; count <= 10; count++ { t.Run(fmt.Sprintf("count_%d", count), func(t *testing.T) { f := newMessageAttachmentFixture(t) ids := append([]string{}, f.ids[:count]...) text := "" if count == 0 { text = "Text without attachments" } key := uuid.NewString() body := attachmentBody(text, ids) if count == 1 { body = attachmentBody(text, []string{strings.ToUpper(ids[0])}) } first := decodeAttachmentMessage(t, f.call(f.bob, "POST", f.chat.ID, key, body)) if count == 1 { before := f.snapshot(t) if replay := decodeAttachmentMessage(t, f.call(f.bob, "POST", f.chat.ID, key, body)); !reflect.DeepEqual(replay, first) { t.Fatal("identical JSON with uppercase attachment UUID must replay the same 201/Message") } f.assertUnchanged(t, before) } if first.Text != text || first.SenderID != f.bob || first.ChatID != f.chat.ID { t.Fatal("message-only/attachment-only content or sender changed") } f.assertLinks(t, first, ids) if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) { t.Fatal("history lost the message or attachment order") } }) } } func TestMessageAttachmentsInvalidReferencesAreAtomic(t *testing.T) { if os.Getenv("LAB4_TEST_DATABASE_URL") == "" { t.Skip("PENDING_INFRA: set LAB4_TEST_DATABASE_URL for dedicated PostgreSQL") } for _, kind := range []string{"unknown_id", "attachment_from_other_chat", "foreign_chat"} { t.Run(kind, func(t *testing.T) { f := newMessageAttachmentFixture(t) ids, actor, chatID := []string{f.ids[0], uuid.NewString()}, f.alice, f.chat.ID if kind == "attachment_from_other_chat" { ids[1] = f.foreign[0] } else if kind == "foreign_chat" { actor, chatID, ids = f.bob, f.other.ID, []string{f.foreign[0]} } before, key := f.snapshot(t), uuid.NewString() response := f.call(actor, "POST", chatID, key, attachmentBody("Must not be written", ids)) assertContractError(t, response, 404, "not_found") f.assertUnchanged(t, before) // A rejected attempt must not reserve this user's key as a final result. valid := decodeAttachmentMessage(t, f.call(actor, "POST", f.chat.ID, key, attachmentBody("Valid after 404", f.ids[:1]))) f.assertLinks(t, valid, f.ids[:1]) }) } } func TestMessageAttachmentsInvalidListLeavesNoRows(t *testing.T) { if os.Getenv("LAB4_TEST_DATABASE_URL") == "" { t.Skip("PENDING_INFRA: set LAB4_TEST_DATABASE_URL for dedicated PostgreSQL") } for _, kind := range []string{"duplicate", "eleven"} { t.Run(kind, func(t *testing.T) { f := newMessageAttachmentFixture(t) ids := f.ids if kind == "duplicate" { ids = []string{f.ids[0], f.ids[0]} } before := f.snapshot(t) assertContractError(t, f.call(f.alice, "POST", f.chat.ID, uuid.NewString(), attachmentBody("invalid list", ids)), 400, "invalid_request") f.assertUnchanged(t, before) }) } } func TestMessageAttachmentsIdempotencyIncludesListAndOrder(t *testing.T) { f := newMessageAttachmentFixture(t) key, ids := uuid.NewString(), f.ids[:2] upperIDs := []string{strings.ToUpper(ids[0]), strings.ToUpper(ids[1])} if slices.Equal(upperIDs, ids) { t.Fatal("normalization fixture must contain a UUID with hexadecimal letters") } body := attachmentBody("Same text", upperIDs) first := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, body)) before := f.snapshot(t) for range 3 { if replay := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, body)); !reflect.DeepEqual(replay, first) { t.Fatal("same key/body did not return the same Message") } f.assertUnchanged(t, before) } for _, changed := range [][]string{{ids[1], ids[0]}, {ids[0], f.ids[2]}, {ids[0]}, {}} { assertContractError(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Same text", changed)), 409, "conflict") f.assertUnchanged(t, before) } assertContractError(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Changed text", ids)), 409, "conflict") f.assertUnchanged(t, before) f.assertLinks(t, first, ids) if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) { t.Fatal("idempotency conflict changed history") } } func TestMessageAttachmentsConcurrentReplayDoesNotMultiplyLinks(t *testing.T) { f := newMessageAttachmentFixture(t) const workers = 8 key, ids := uuid.NewString(), f.ids[:3] gate := make(chan struct{}) results := make(chan *httptest.ResponseRecorder, workers) var group sync.WaitGroup for range workers { group.Add(1) go func() { defer group.Done() <-gate results <- f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Concurrent attachment replay", ids)) }() } close(gate) group.Wait() close(results) var first attachmentMessage for response := range results { message := decodeAttachmentMessage(t, response) if first.ID == "" { first = message } else if !reflect.DeepEqual(message, first) { t.Fatal("concurrent replay returned a different Message") } } f.assertLinks(t, first, ids) state := f.snapshot(t) if len(state["messages"]) != 1 || len(state["messages_attachments"]) != len(ids) || len(state["message_idempotency"]) != 1 { t.Fatal("concurrent replay multiplied message, link or idempotency rows") } if got := f.history(t); len(got) != 1 || !sameHistoryMessage(got[0], first) { t.Fatal("concurrent replay changed history") } } func TestMessageAttachmentsLinkFailureRollsBackEverything(t *testing.T) { f := newMessageAttachmentFixture(t) ids, key := f.ids[:2], uuid.NewString() // The sequence survives rollback. It proves that the fault was reached only // after the first link was visible inside the actual application transaction. _, err := f.pool.Exec(f.ctx, `CREATE SEQUENCE test_link_fault_reached; CREATE FUNCTION fail_second_test_link() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF (SELECT count(*) FROM messages_attachments WHERE message_id=NEW.message_id) >= 1 THEN PERFORM nextval('test_link_fault_reached'); RAISE EXCEPTION 'synthetic link failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER test_link_fault BEFORE INSERT ON messages_attachments FOR EACH ROW EXECUTE FUNCTION fail_second_test_link();`) if err != nil { t.Fatal("cannot prepare isolated link fault") } before := f.snapshot(t) response := f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Rollback all writes", ids)) assertContractError(t, response, 500, "internal_error") var faultReached bool if f.pool.QueryRow(f.ctx, "SELECT is_called FROM test_link_fault_reached").Scan(&faultReached) != nil || !faultReached { t.Fatal("test did not reach an injected link failure after one real link insert") } f.assertUnchanged(t, before) if strings.Contains(response.Body.String(), "synthetic link failure") { t.Fatal("response exposed internal SQL fault details") } if _, err := f.pool.Exec(f.ctx, "DROP TRIGGER test_link_fault ON messages_attachments"); err != nil { t.Fatal("cannot clear isolated link fault") } message := decodeAttachmentMessage(t, f.call(f.alice, "POST", f.chat.ID, key, attachmentBody("Rollback all writes", ids))) f.assertLinks(t, message, ids) state := f.snapshot(t) if len(state["messages"]) != 1 || len(state["messages_attachments"]) != 2 || len(state["message_idempotency"]) != 1 { t.Fatal("retry after transient link failure did not commit exactly one complete message") } }