Files
tenant-registry/internal/keycloak/status_test.go
T
Sharang ParnerkarandClaude Opus 5.5 72be56d72a
ci / shared (pull_request) Successful in 12s
ci / test (pull_request) Successful in 23m35s
ci / image (pull_request) Skipped
fix(keycloak): keep email and names when writing user attributes
Keycloak 26 validates a user PUT against the declarative user profile and
clears email, firstName and lastName when the body leaves them out. The
registry wrote attributes with a body of only {attributes}, so every status
sync wiped the members' email addresses. Reprovision syncs the status right
after the invitation goes out; the action link then failed with "invalid
email address".

Attribute writes now read the full user, change the attributes in it and
write the whole representation back (SyncTenantStatus, ensureUserAttributes,
SyncClaims).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-09-28 09:20:33 +02:00

215 lines
8.2 KiB
Go

package keycloak
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// stubStatusKC models the org → members → user attribute round-trip that
// SyncTenantStatus performs. `puts` collects the attribute payloads.
func stubStatusKC(t *testing.T, orgs map[string]string, members map[string][]string, users map[string]userRepresentation, puts map[string]map[string][]string, failUser string) *httptest.Server {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": "test-token", "expires_in": 60})
})
mux.HandleFunc("GET /admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) {
alias := r.URL.Query().Get("search")
out := []map[string]string{}
if id, ok := orgs[alias]; ok {
out = append(out, map[string]string{"id": id, "alias": alias})
}
_ = json.NewEncoder(w).Encode(out)
})
mux.HandleFunc("GET /admin/realms/test-realm/organizations/{id}/members", func(w http.ResponseWriter, r *http.Request) {
out := []map[string]string{}
for _, m := range members[r.PathValue("id")] {
out = append(out, map[string]string{"id": m})
}
_ = json.NewEncoder(w).Encode(out)
})
mux.HandleFunc("GET /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, r *http.Request) {
u, ok := users[r.PathValue("id")]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
_ = json.NewEncoder(w).Encode(u)
})
mux.HandleFunc("PUT /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, r *http.Request) {
if r.PathValue("id") == failUser {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte("boom"))
return
}
var body struct {
Attributes map[string][]string `json:"attributes"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
puts[r.PathValue("id")] = body.Attributes
w.WriteHeader(http.StatusNoContent)
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv
}
func TestHTTPAdapter_SyncTenantStatus(t *testing.T) {
puts := map[string]map[string][]string{}
srv := stubStatusKC(t,
map[string]string{"acme": "org-1"},
map[string][]string{"org-1": {"u-1", "u-2", "u-missing"}},
map[string]userRepresentation{
"u-1": {ID: "u-1", Attributes: map[string][]string{"org_roles": {"IT_ADMIN"}, "tenant_status": {"trial"}}},
"u-2": {ID: "u-2"},
},
puts, "")
a := usersAdapter(srv)
err := a.SyncTenantStatus(context.Background(), "acme", "restricted")
if err == nil || !strings.Contains(err.Error(), "u-missing") {
t.Fatalf("expected the missing member to surface as first error, got %v", err)
}
if got := puts["u-1"]["tenant_status"]; len(got) != 1 || got[0] != "restricted" {
t.Fatalf("u-1 tenant_status = %v", got)
}
if got := puts["u-1"]["org_roles"]; len(got) != 1 || got[0] != "IT_ADMIN" {
t.Fatalf("org_roles must be preserved, got %v", puts["u-1"])
}
if got := puts["u-2"]["tenant_status"]; len(got) != 1 || got[0] != "restricted" {
t.Fatalf("u-2 (no attributes) tenant_status = %v", got)
}
}
func TestHTTPAdapter_SyncTenantStatus_errors(t *testing.T) {
puts := map[string]map[string][]string{}
srv := stubStatusKC(t,
map[string]string{"acme": "org-1"},
map[string][]string{"org-1": {"u-1"}},
map[string]userRepresentation{"u-1": {ID: "u-1"}},
puts, "u-1")
a := usersAdapter(srv)
if err := a.SyncTenantStatus(context.Background(), "nope", "active"); !errors.Is(err, ErrOrgNotFound) {
t.Fatalf("unknown org: %v", err)
}
if err := a.SyncTenantStatus(context.Background(), "acme", "active"); err == nil || !strings.Contains(err.Error(), "update user u-1: 500") {
t.Fatalf("update failure must be reported: %v", err)
}
}
func TestHTTPAdapter_findUserByEmail(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", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("email") == "Ada@Example.com" {
_ = json.NewEncoder(w).Encode([]map[string]string{{"id": "u-ada", "email": "ada@example.com"}})
return
}
_ = json.NewEncoder(w).Encode([]map[string]string{})
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
a := usersAdapter(srv)
id, err := a.findUserByEmail(context.Background(), "Ada@Example.com")
if err != nil || id != "u-ada" {
t.Fatalf("got %q, %v", id, err)
}
if _, err := a.findUserByEmail(context.Background(), "nobody@example.com"); err == nil {
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)
}
}