package httpapi import ( "context" "data-terminal-cloud/internal/identity" "net/http" "net/http/httptest" "strings" "testing" ) type profileStub struct { called bool name string principal identity.Principal } func (s *profileStub) UpdateDisplayName(_ context.Context, p identity.Principal, name string) error { s.called = true s.name = name s.principal = p return nil } func TestProfileHandlerAuthenticatesAndValidates(t *testing.T) { for _, tc := range []struct { name, body string auth bool want int }{{"anonymous", `{"display_name":"家人"}`, false, 401}, {"empty", `{"display_name":" "}`, true, 400}, {"target injection", `{"display_name":"家人","user_id":"other"}`, true, 400}, {"valid", `{"display_name":" 家人 "}`, true, 200}} { t.Run(tc.name, func(t *testing.T) { repo := &profileStub{} r := httptest.NewRequest(http.MethodPatch, "/api/v1/me/profile", strings.NewReader(tc.body)) r.Header.Set("Content-Type", "application/json") if tc.auth { r = r.WithContext(identity.WithPrincipal(r.Context(), identity.Principal{Issuer: "test", Subject: "self"})) } w := httptest.NewRecorder() UpdateCustomerProfileHandler(repo).ServeHTTP(w, r) if w.Code != tc.want { t.Fatalf("status=%d body=%s", w.Code, w.Body) } if repo.called != (tc.want == 200) { t.Fatal("invalid request mutated account") } if repo.called && (repo.name != "家人" || repo.principal.Subject != "self") { t.Fatal("wrong account or nickname") } }) } }