package keycloak import ( "context" "encoding/json" "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"); err == nil || !strings.Contains(err.Error(), "org not found") { 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") } }