diff --git a/internal/keycloak/client_test.go b/internal/keycloak/client_test.go index 69c590e..8612f05 100644 --- a/internal/keycloak/client_test.go +++ b/internal/keycloak/client_test.go @@ -112,8 +112,8 @@ func newStubKC(t *testing.T) *stubKC { }) mux.HandleFunc("/admin/realms/test-realm/users/user-abc", func(w http.ResponseWriter, r *http.Request) { - s.syncCalls.Add(1) if r.Method == http.MethodPut { + s.syncCalls.Add(1) w.WriteHeader(http.StatusNoContent) return } diff --git a/internal/keycloak/members.go b/internal/keycloak/members.go index d944160..b8919f6 100644 --- a/internal/keycloak/members.go +++ b/internal/keycloak/members.go @@ -7,7 +7,6 @@ import ( "io" "log/slog" "net/http" - "net/url" "strings" "time" ) @@ -183,39 +182,16 @@ func (a *HTTPAdapter) createUser(ctx context.Context, u userCreate) (string, err // ensureUserAttributes merges attrs into the user's attributes, adding only // keys that are absent (same contract as ensureOrgAttributes). func (a *HTTPAdapter) ensureUserAttributes(ctx context.Context, userID string, attrs map[string][]string) error { - var u userRepresentation - resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+url.PathEscape(userID), nil, &u) - if err != nil { - return err - } - if resp.StatusCode/100 != 2 { - _ = resp.Body.Close() - return fmt.Errorf("get user: %d", resp.StatusCode) - } - existing := u.Attributes - if existing == nil { - existing = map[string][]string{} - } - changed := false - for k, v := range attrs { - if len(attrValues(existing, k)) == 0 { - existing[k] = v - changed = true + return a.updateUserAttributes(ctx, userID, func(existing map[string][]string) bool { + changed := false + for k, v := range attrs { + if len(attrValues(existing, k)) == 0 { + existing[k] = v + changed = true + } } - } - if !changed { - return nil - } - resp, err = a.adminCall(ctx, http.MethodPut, "/users/"+url.PathEscape(userID), map[string]any{"attributes": existing}, nil) - if err != nil { - return err - } - defer func() { _ = resp.Body.Close() }() - if resp.StatusCode/100 != 2 { - body, _ := io.ReadAll(resp.Body) - return fmt.Errorf("put user: %d %s", resp.StatusCode, body) - } - return nil + return changed + }) } func (a *HTTPAdapter) ResendInvite(ctx context.Context, slug, email string) error { diff --git a/internal/keycloak/orgs.go b/internal/keycloak/orgs.go index 421b0c1..7df0441 100644 --- a/internal/keycloak/orgs.go +++ b/internal/keycloak/orgs.go @@ -182,17 +182,12 @@ func (a *HTTPAdapter) SyncClaims(ctx context.Context, userID string, c Claims) e "plan": {c.Plan}, "tenant_status": {c.TenantStatus}, } - resp, err := a.adminCall(ctx, http.MethodPut, "/users/"+userID, - map[string]any{"attributes": attrs}, nil) - if err != nil { - return err - } - defer func() { _ = resp.Body.Close() }() - if resp.StatusCode/100 != 2 { - body, _ := io.ReadAll(resp.Body) - return fmt.Errorf("sync claims: %d %s", resp.StatusCode, body) - } - return nil + return a.updateUserAttributes(ctx, userID, func(existing map[string][]string) bool { + for k, v := range attrs { + existing[k] = v + } + return true + }) } // ─── helpers ───────────────────────────────────────────────────────────── @@ -355,37 +350,13 @@ func (a *HTTPAdapter) SyncTenantStatus(ctx context.Context, slug, status string) } var firstErr error for _, m := range members { - var u userRepresentation - resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+m.ID, nil, &u) - if err != nil || resp.StatusCode/100 != 2 { - if err == nil { - _ = resp.Body.Close() - err = fmt.Errorf("get user %s: %d", m.ID, resp.StatusCode) - } - if firstErr == nil { - firstErr = err - } - continue + err := a.updateUserAttributes(ctx, m.ID, func(attrs map[string][]string) bool { + attrs["tenant_status"] = []string{status} + return true + }) + if err != nil && firstErr == nil { + firstErr = err } - attrs := u.Attributes - if attrs == nil { - attrs = map[string][]string{} - } - attrs["tenant_status"] = []string{status} - resp, err = a.adminCall(ctx, http.MethodPut, "/users/"+m.ID, map[string]any{"attributes": attrs}, nil) - if err != nil { - if firstErr == nil { - firstErr = err - } - continue - } - if resp.StatusCode/100 != 2 { - body, _ := io.ReadAll(resp.Body) - if firstErr == nil { - firstErr = fmt.Errorf("update user %s: %d %s", m.ID, resp.StatusCode, body) - } - } - _ = resp.Body.Close() } return firstErr } diff --git a/internal/keycloak/status_test.go b/internal/keycloak/status_test.go index 8fd2ef2..872a48f 100644 --- a/internal/keycloak/status_test.go +++ b/internal/keycloak/status_test.go @@ -127,3 +127,88 @@ func TestHTTPAdapter_findUserByEmail(t *testing.T) { t.Fatal("expected not found") } } + +// Keycloak 26 clears email, firstName and lastName when a user PUT leaves +// them out. Every attribute write must send the account back whole. +func TestHTTPAdapter_attributeWritesKeepTheProfile(t *testing.T) { + user := map[string]any{ + "id": "u-1", "username": "ada@example.com", "email": "ada@example.com", + "firstName": "Ada", "lastName": "Lovelace", "emailVerified": false, "enabled": true, + "requiredActions": []string{}, + "attributes": map[string][]string{"tenant_slug": {"acme"}, "org_roles": {"IT_ADMIN"}}, + } + var puts []map[string]any + mux := http.NewServeMux() + mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"access_token": "t", "expires_in": 60}) + }) + mux.HandleFunc("GET /admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode([]map[string]string{{"id": "org-1", "alias": "acme"}}) + }) + mux.HandleFunc("GET /admin/realms/test-realm/organizations/{id}/members", func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode([]map[string]string{{"id": "u-1"}}) + }) + mux.HandleFunc("GET /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(user) + }) + mux.HandleFunc("PUT /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + puts = append(puts, body) + w.WriteHeader(http.StatusNoContent) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + a := usersAdapter(srv) + ctx := context.Background() + + if err := a.SyncTenantStatus(ctx, "acme", "active"); err != nil { + t.Fatal(err) + } + if err := a.ensureUserAttributes(ctx, "u-1", map[string][]string{"tenant_id": {"t-1"}}); err != nil { + t.Fatal(err) + } + if err := a.SyncClaims(ctx, "u-1", Claims{TenantID: "t-1", TenantSlug: "acme", TenantStatus: "active"}); err != nil { + t.Fatal(err) + } + // Nothing missing → no write. + if err := a.ensureUserAttributes(ctx, "u-1", map[string][]string{"tenant_slug": {"other"}}); err != nil { + t.Fatal(err) + } + if len(puts) != 3 { + t.Fatalf("puts = %d, want 3", len(puts)) + } + for i, p := range puts { + for _, k := range []string{"username", "email", "firstName", "lastName", "enabled", "requiredActions"} { + if _, ok := p[k]; !ok { + t.Errorf("put %d dropped %q: %v", i, k, p) + } + } + if p["email"] != "ada@example.com" || p["firstName"] != "Ada" { + t.Errorf("put %d changed the profile: %v", i, p) + } + attrs, _ := p["attributes"].(map[string]any) + if _, ok := attrs["org_roles"]; !ok { + t.Errorf("put %d dropped org_roles: %v", i, attrs) + } + } + if st := puts[0]["attributes"].(map[string]any)["tenant_status"]; st.([]any)[0] != "active" { + t.Errorf("tenant_status = %v", st) + } +} + +func TestHTTPAdapter_updateUserAttributes_getFails(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"access_token": "t", "expires_in": 60}) + }) + mux.HandleFunc("GET /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNotFound) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + err := usersAdapter(srv).ensureUserAttributes(context.Background(), "u-x", map[string][]string{"a": {"b"}}) + if err == nil || !strings.Contains(err.Error(), "get user u-x: 404") { + t.Fatalf("err = %v", err) + } +} diff --git a/internal/keycloak/users.go b/internal/keycloak/users.go index de0cf5c..faa197a 100644 --- a/internal/keycloak/users.go +++ b/internal/keycloak/users.go @@ -3,7 +3,9 @@ package keycloak import ( "context" "fmt" + "io" "net/http" + "net/url" "strings" ) @@ -107,3 +109,51 @@ func attrValues(attrs map[string][]string, key string) []string { } return out } + +// updateUserAttributes changes a user's attributes without touching the rest +// of the account. Keycloak 26 validates a user PUT against the declarative +// user profile and treats a missing email, firstName or lastName as "clear +// it", so a body with only `attributes` wiped the address the invitation had +// just been sent to (the action link then failed with "invalid email +// address"). The full representation is read, the attributes changed in it, +// and the whole thing written back. mutate reports whether anything changed; +// nothing is written otherwise. +func (a *HTTPAdapter) updateUserAttributes(ctx context.Context, userID string, mutate func(attrs map[string][]string) bool) error { + var raw map[string]any + resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+url.PathEscape(userID), nil, &raw) + if err != nil { + return err + } + _ = resp.Body.Close() + if resp.StatusCode/100 != 2 { + return fmt.Errorf("get user %s: %d", userID, resp.StatusCode) + } + if raw == nil { + raw = map[string]any{} + } + attrs := map[string][]string{} + if m, ok := raw["attributes"].(map[string]any); ok { + for k, v := range m { + vals, _ := v.([]any) + for _, s := range vals { + if str, ok := s.(string); ok { + attrs[k] = append(attrs[k], str) + } + } + } + } + if !mutate(attrs) { + return nil + } + raw["attributes"] = attrs + resp, err = a.adminCall(ctx, http.MethodPut, "/users/"+url.PathEscape(userID), raw, nil) + if err != nil { + return err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode/100 != 2 { + body, _ := io.ReadAll(resp.Body) + return fmt.Errorf("update user %s: %d %s", userID, resp.StatusCode, body) + } + return nil +}