From a9557fa221ac1db69e1a4f6b5338b7b03475c488 Mon Sep 17 00:00:00 2001 From: TAskMAster339 Date: Thu, 15 Oct 2026 22:15:58 +0300 Subject: [PATCH] fix: json decoder and uuid dubles --- src/backend/handlers/user_http.go | 29 ++++- src/backend/services/chat.go | 13 ++- src/backend/tests/json_body_test.go | 61 +++++++++++ .../tests/validation_regression_test.go | 103 ++++++++++++++++++ 4 files changed, 199 insertions(+), 7 deletions(-) create mode 100644 src/backend/tests/json_body_test.go create mode 100644 src/backend/tests/validation_regression_test.go diff --git a/src/backend/handlers/user_http.go b/src/backend/handlers/user_http.go index e298f48f..aaa018a1 100644 --- a/src/backend/handlers/user_http.go +++ b/src/backend/handlers/user_http.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "net/http" + "reflect" "strings" "messenger/src/backend/services" @@ -18,8 +19,8 @@ type createUserRequest struct { func decodeJSONBody(r *http.Request, destination any) error { decoder := json.NewDecoder(r.Body) - decoder.DisallowUnknownFields() - if err := decoder.Decode(destination); err != nil { + var body json.RawMessage + if err := decoder.Decode(&body); err != nil { return err } var extra any @@ -29,7 +30,29 @@ func decodeJSONBody(r *http.Request, destination any) error { } return fmt.Errorf("more than one JSON value") } - return nil + var fields map[string]json.RawMessage + if err := json.Unmarshal(body, &fields); err != nil { + return err + } + if fields == nil { + return fmt.Errorf("JSON body must be an object") + } + // encoding/json matches struct fields case-insensitively, even with + // DisallowUnknownFields. Check exact contract names before decoding values. + typeOfRequest := reflect.TypeOf(destination).Elem() + allowed := make(map[string]bool, typeOfRequest.NumField()) + for i := 0; i < typeOfRequest.NumField(); i++ { + name := strings.Split(typeOfRequest.Field(i).Tag.Get("json"), ",")[0] + if name != "" && name != "-" { + allowed[name] = true + } + } + for name := range fields { + if !allowed[name] { + return fmt.Errorf("unknown JSON field %q", name) + } + } + return json.Unmarshal(body, destination) } func createUserHandler(users *services.UserService) http.HandlerFunc { diff --git a/src/backend/services/chat.go b/src/backend/services/chat.go index 48ad9914..f266fdba 100644 --- a/src/backend/services/chat.go +++ b/src/backend/services/chat.go @@ -9,8 +9,9 @@ import ( "strings" "unicode/utf8" - "github.com/google/uuid" "messenger/src/backend/repositories" + + "github.com/google/uuid" ) type ChatPage struct { @@ -46,19 +47,23 @@ func (s *ChatService) Create(ctx context.Context, currentUserID, title string, m return repositories.Chat{}, InvalidInput{"member_ids must contain from 1 to 100 users"} } seen := make(map[string]struct{}, len(memberIDs)) - for _, memberID := range memberIDs { - if _, err := uuid.Parse(memberID); err != nil { + normalizedMembers := make([]string, len(memberIDs)) + for i, memberID := range memberIDs { + parsed, err := uuid.Parse(memberID) + if err != nil { return repositories.Chat{}, InvalidInput{"member_ids must contain valid UUIDs"} } + memberID = parsed.String() if _, exists := seen[memberID]; exists { return repositories.Chat{}, InvalidInput{"member_ids must not contain duplicates"} } seen[memberID] = struct{}{} + normalizedMembers[i] = memberID } if _, exists := seen[currentUserID]; !exists { return repositories.Chat{}, InvalidInput{"current user must be a chat member"} } - chat, err := s.chats.Create(ctx, title, memberIDs) + chat, err := s.chats.Create(ctx, title, normalizedMembers) if errors.Is(err, repositories.ErrUnknownMember) { return repositories.Chat{}, InvalidInput{"all members must be existing users"} } diff --git a/src/backend/tests/json_body_test.go b/src/backend/tests/json_body_test.go new file mode 100644 index 00000000..dd7a72e8 --- /dev/null +++ b/src/backend/tests/json_body_test.go @@ -0,0 +1,61 @@ +package tests + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/google/uuid" +) + +func TestDecodeJSONBodyRequiresExactFieldNames(t *testing.T) { + fixture := newTestFixture(t) + user, _ := createTestUser(t, fixture.users, "json_tester", "JSON tester") + chat := createTestChat(t, fixture.chats, "JSON body tests", []string{user.ID}) + path := "/api/v1/chats/" + chat.ID + "/messages" + for _, test := range []struct { + name string + body string + valid bool + }{ + {"canonical", `{"text":"first","attachment_ids":[]}`, true}, + {"escaped canonical name", `{"te\u0078t":"first"}`, true}, + {"uppercase extra", `{"text":"first","TEXT":"second"}`, false}, + {"uppercase extra first", `{"TEXT":"second","text":"first"}`, false}, + {"mixed case", `{"Text":"second"}`, false}, + {"uppercase attachments", `{"text":"first","ATTACHMENT_IDS":[]}`, false}, + {"escaped uppercase", `{"text":"first","\u0054EXT":"second"}`, false}, + {"unknown field", `{"text":"first","sender_id":"other"}`, false}, + {"wrong type", `{"text":123}`, false}, + {"null", `null`, false}, + {"array", `[]`, false}, + {"trailing object", `{"text":"first"}{}`, false}, + } { + t.Run(test.name, func(t *testing.T) { + request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(test.body)) + request.Header.Set("Content-Type", "application/json") + request.Header.Set("Idempotency-Key", uuid.NewString()) + authorizeTestRequest(t, fixture, request, user.ID) + response := httptest.NewRecorder() + fixture.router.ServeHTTP(response, request) + want := http.StatusBadRequest + if test.valid { + want = http.StatusCreated + } + if response.Code != want { + t.Fatalf("want %d, got %d: %s", want, response.Code, response.Body.String()) + } + if test.valid { + var value map[string]any + if err := json.Unmarshal(response.Body.Bytes(), &value); err != nil { + t.Fatal(err) + } + if value["text"] != "first" { + t.Fatal("text changed") + } + } + }) + } +} diff --git a/src/backend/tests/validation_regression_test.go b/src/backend/tests/validation_regression_test.go new file mode 100644 index 00000000..ac57818c --- /dev/null +++ b/src/backend/tests/validation_regression_test.go @@ -0,0 +1,103 @@ +package tests + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/google/uuid" + "messenger/src/backend/services" +) + +func TestCaseVariantExtraFieldsReturn400WithoutSaving(t *testing.T) { + f := newTestFixture(t) + user, _ := createTestUser(t, f.users, "alice", "Alice") + chat := createTestChat(t, f.chats, "Chat", []string{user.ID}) + path := "/api/v1/chats/" + chat.ID + "/messages" + key := uuid.NewString() + send := func(path, body, key string) *httptest.ResponseRecorder { + t.Helper() + r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Idempotency-Key", key) + authorizeTestRequest(t, f, r, user.ID) + w := httptest.NewRecorder() + f.router.ServeHTTP(w, r) + return w + } + for _, test := range []struct{ path, body string }{ + {path, `{"text":"first","TEXT":"second"}`}, + {path, `{"TEXT":"second","text":"first"}`}, + {path, `{"Text":"second"}`}, + {path, `{"text":"first","Attachment_IDs":[]}`}, + {"/api/v1/chats", fmt.Sprintf(`{"title":"Chat","TITLE":"other","member_ids":[%q]}`, user.ID)}, + {"/api/v1/chats", fmt.Sprintf(`{"title":"Chat","MEMBER_IDS":[%q]}`, user.ID)}, + {"/api/v1/users", `{"username":"new","USERNAME":"other","display_name":"New","password":"test-password"}`}, + {"/api/v1/users", `{"username":"new","display_name":"New","Password":"test-password"}`}, + } { + w := send(test.path, test.body, key) + if w.Code != 400 || !strings.Contains(w.Body.String(), `"code":"invalid_request"`) { + t.Fatalf("%s: want invalid_request 400, got %d %s", test.path, w.Code, w.Body.String()) + } + } + if len(listTestMessages(t, f.messages, chat.ID)) != 0 { + t.Fatal("rejected request saved a message") + } + w := send(path, `{"text":"first"}`, key) + if w.Code != 201 { + t.Fatalf("corrected request with same key: %d %s", w.Code, w.Body.String()) + } + if w = send(path, `{"text":"first","attachment_ids":[]}`, key); w.Code != 201 { + t.Fatalf("valid replay: %d %s", w.Code, w.Body.String()) + } + messages := listTestMessages(t, f.messages, chat.ID) + if len(messages) != 1 || messages[0].Text != "first" { + t.Fatal("wrong message or duplicate saved") + } +} + +func TestChatRejectsCaseVariantDuplicateMembersBeforeSQL(t *testing.T) { + const id = "abcdef01-abcd-4abc-8abc-abcdef012345" + for _, members := range [][]string{{id, strings.ToUpper(id)}, {strings.ToUpper(id), id}} { + _, err := services.NewChatService(nil).Create(context.Background(), id, "Chat", members) + var invalid services.InvalidInput + if !errors.As(err, &invalid) { + t.Fatalf("want InvalidInput before SQL, got %v", err) + } + } +} + +func TestChatNormalizesMemberUUIDsHTTP(t *testing.T) { + f := newTestFixture(t) + user, _ := createTestUser(t, f.users, "alice", "Alice") + for _, duplicate := range []bool{true, false} { + members := fmt.Sprintf(`[%q]`, strings.ToUpper(user.ID)) + want := 201 + if duplicate { + members = fmt.Sprintf(`[%q,%q]`, user.ID, strings.ToUpper(user.ID)) + want = 400 + } + r := httptest.NewRequest(http.MethodPost, "/api/v1/chats", strings.NewReader(`{"title":"Chat","member_ids":`+members+`}`)) + r.Header.Set("Content-Type", "application/json") + authorizeTestRequest(t, f, r, user.ID) + w := httptest.NewRecorder() + f.router.ServeHTTP(w, r) + if w.Code != want { + t.Fatalf("duplicate=%v: want %d, got %d %s", duplicate, want, w.Code, w.Body.String()) + } + } + var chats, members int + if err := f.db.QueryRow(context.Background(), "SELECT count(*) FROM chats").Scan(&chats); err != nil { + t.Fatal(err) + } + if err := f.db.QueryRow(context.Background(), "SELECT count(*) FROM chat_members").Scan(&members); err != nil { + t.Fatal(err) + } + if chats != 1 || members != 1 { + t.Fatalf("unexpected persisted chats=%d members=%d", chats, members) + } +}