Files
tenant-registry/internal/keycloak/client_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

383 lines
12 KiB
Go

package keycloak
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
// stubKC builds a minimal KC look-alike: token endpoint + the Admin API
// paths the HTTPAdapter actually calls. Each path is a single handler that
// asserts the request shape and returns the bare-minimum valid response.
type stubKC struct {
srv *httptest.Server
tokenCalls atomic.Int32
orgCalls atomic.Int32
userCalls atomic.Int32
memberCalls atomic.Int32
orgAttrCalls atomic.Int32
emailCalls atomic.Int32
healthCalls atomic.Int32
syncCalls atomic.Int32
lastOrgBody string
tokenFails atomic.Bool // when true, /token returns 401 once
emailFails atomic.Bool // when true, execute-actions-email answers 400
}
func newStubKC(t *testing.T) *stubKC {
t.Helper()
s := &stubKC{}
mux := http.NewServeMux()
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", func(w http.ResponseWriter, r *http.Request) {
s.tokenCalls.Add(1)
if s.tokenFails.Swap(false) {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"access_token": "test-token", "expires_in": 60,
})
})
mux.HandleFunc("/admin/serverinfo", func(w http.ResponseWriter, r *http.Request) {
s.healthCalls.Add(1)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"systemInfo":{"version":"26.0.0"}}`))
})
mux.HandleFunc("/admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) {
s.orgCalls.Add(1)
if r.Method == http.MethodPost {
body, _ := io.ReadAll(r.Body)
s.lastOrgBody = string(body)
w.Header().Set("Location", s.srv.URL+"/admin/realms/test-realm/organizations/org-xyz")
w.WriteHeader(http.StatusCreated)
return
}
http.Error(w, "method", http.StatusMethodNotAllowed)
})
mux.HandleFunc("/admin/realms/test-realm/organizations/org-xyz/members", func(w http.ResponseWriter, r *http.Request) {
s.memberCalls.Add(1)
// Keycloak 26 wants the bare user id as a JSON string.
var id string
if err := json.NewDecoder(r.Body).Decode(&id); err != nil || id != "user-abc" {
http.Error(w, `{"errorMessage":"User does not exist"}`, http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusCreated)
})
mux.HandleFunc("/admin/realms/test-realm/organizations/org-xyz", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
_ = json.NewEncoder(w).Encode(map[string]any{"id": "org-xyz", "alias": "acme", "attributes": map[string]any{}})
case http.MethodPut:
var org map[string]any
_ = json.NewDecoder(r.Body).Decode(&org)
if attrs, _ := org["attributes"].(map[string]any); attrs["tenant_id"] == nil {
http.Error(w, "missing tenant_id", http.StatusBadRequest)
return
}
s.orgAttrCalls.Add(1)
w.WriteHeader(http.StatusNoContent)
}
})
mux.HandleFunc("/admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) {
s.userCalls.Add(1)
if r.Method == http.MethodPost {
w.Header().Set("Location", s.srv.URL+"/admin/realms/test-realm/users/user-abc")
w.WriteHeader(http.StatusCreated)
return
}
})
mux.HandleFunc("/admin/realms/test-realm/users/user-abc/execute-actions-email", func(w http.ResponseWriter, r *http.Request) {
s.emailCalls.Add(1)
if s.emailFails.Load() {
http.Error(w, `{"errorMessage":"Invalid redirect uri."}`, http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/admin/realms/test-realm/users/user-abc", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPut {
s.syncCalls.Add(1)
w.WriteHeader(http.StatusNoContent)
return
}
})
s.srv = httptest.NewServer(mux)
return s
}
func (s *stubKC) close() { s.srv.Close() }
func newTestAdapter(srv *httptest.Server) *HTTPAdapter {
return NewHTTPAdapter(HTTPConfig{
BaseURL: srv.URL,
Realm: "test-realm",
ClientID: "test-client",
ClientSecret: "test-secret",
Timeout: 5 * time.Second,
})
}
func TestHTTPAdapter_health(t *testing.T) {
s := newStubKC(t)
defer s.close()
a := newTestAdapter(s.srv)
if err := a.Health(context.Background()); err != nil {
t.Fatal(err)
}
if s.healthCalls.Load() != 1 {
t.Errorf("health calls = %d", s.healthCalls.Load())
}
}
func TestHTTPAdapter_createOrgAndInvite(t *testing.T) {
s := newStubKC(t)
defer s.close()
a := newTestAdapter(s.srv)
res, err := a.CreateOrgAndInvite(context.Background(), InviteInput{
TenantID: "t1", Slug: "acme", Name: "Acme Inc.",
AdminEmail: "owner@acme.test", AdminName: "Alice Owner",
})
if err != nil {
t.Fatal(err)
}
if res.OrganizationID != "org-xyz" || res.UserID != "user-abc" {
t.Errorf("unexpected ids: %+v", res)
}
if s.orgCalls.Load() != 1 || s.userCalls.Load() != 1 ||
s.memberCalls.Load() != 1 || s.emailCalls.Load() != 1 || s.orgAttrCalls.Load() != 1 {
t.Errorf("call counts: org=%d user=%d member=%d email=%d",
s.orgCalls.Load(), s.userCalls.Load(), s.memberCalls.Load(), s.emailCalls.Load())
}
// KC 26 rejects a domainless org; the adapter must send a synthetic
// per-slug domain so onboarding actually provisions.
if !strings.Contains(s.lastOrgBody, `"domains"`) ||
!strings.Contains(s.lastOrgBody, "acme.tenant.breakpilot.com") {
t.Errorf("org create body missing synthetic domain: %s", s.lastOrgBody)
}
}
func TestHTTPAdapter_emailMissingAdminEmailRejected(t *testing.T) {
s := newStubKC(t)
defer s.close()
a := newTestAdapter(s.srv)
_, err := a.CreateOrgAndInvite(context.Background(), InviteInput{
TenantID: "t1", Slug: "x", Name: "X",
})
if err == nil {
t.Fatal("expected error for empty admin email")
}
}
func TestHTTPAdapter_orgConflict(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", tokenOK)
mux.HandleFunc("/admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusConflict)
})
srv := httptest.NewServer(mux)
defer srv.Close()
a := newTestAdapter(srv)
_, err := a.CreateOrgAndInvite(context.Background(), InviteInput{
TenantID: "t1", Slug: "x", Name: "X", AdminEmail: "a@b.test",
})
if !errors.Is(err, ErrOrgConflict) {
t.Errorf("err = %v, want ErrOrgConflict", err)
}
}
func TestHTTPAdapter_tokenUnavailable(t *testing.T) {
// No KC server at all — adapter should surface ErrUnavailable.
a := NewHTTPAdapter(HTTPConfig{
BaseURL: "http://127.0.0.1:1", Realm: "test", ClientID: "x", ClientSecret: "y", Timeout: 1 * time.Second,
})
err := a.Health(context.Background())
if !errors.Is(err, ErrUnavailable) {
t.Errorf("err = %v, want ErrUnavailable", err)
}
}
func TestHTTPAdapter_tokenUnauthorized(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
})
srv := httptest.NewServer(mux)
defer srv.Close()
a := newTestAdapter(srv)
err := a.Health(context.Background())
if !errors.Is(err, ErrUnauthorized) {
t.Errorf("err = %v, want ErrUnauthorized", err)
}
}
func TestHTTPAdapter_syncClaims(t *testing.T) {
s := newStubKC(t)
defer s.close()
a := newTestAdapter(s.srv)
err := a.SyncClaims(context.Background(), "user-abc", Claims{
TenantID: "t1", TenantSlug: "acme", Plan: "professional",
Products: []string{"certifai"}, TenantStatus: "active",
})
if err != nil {
t.Fatal(err)
}
if s.syncCalls.Load() != 1 {
t.Errorf("sync calls = %d", s.syncCalls.Load())
}
}
func TestHTTPAdapter_tokenIsCached(t *testing.T) {
s := newStubKC(t)
defer s.close()
a := newTestAdapter(s.srv)
// Three Health calls should produce ONE token fetch (cached).
for i := 0; i < 3; i++ {
if err := a.Health(context.Background()); err != nil {
t.Fatal(err)
}
}
if s.tokenCalls.Load() != 1 {
t.Errorf("token fetches = %d, want 1 (cache miss)", s.tokenCalls.Load())
}
}
// tokenOK is a reusable handler that always returns a working token.
func tokenOK(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method", http.StatusMethodNotAllowed)
return
}
b := make([]byte, r.ContentLength)
_, _ = r.Body.Read(b)
if !strings.Contains(string(b), "client_credentials") {
http.Error(w, "grant_type", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"access_token":"t","expires_in":60}`))
}
func TestHTTPAdapter_userExists(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", tokenOK)
mux.HandleFunc("/admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Query().Get("email") {
case "a@b.test":
_ = json.NewEncoder(w).Encode([]map[string]string{{"id": "u1", "email": "A@b.test"}})
case "boom@b.test":
w.WriteHeader(http.StatusInternalServerError)
default:
_ = json.NewEncoder(w).Encode([]map[string]string{})
}
})
srv := httptest.NewServer(mux)
defer srv.Close()
a := newTestAdapter(srv)
ctx := context.Background()
if ok, err := a.UserExists(ctx, "a@b.test"); err != nil || !ok {
t.Errorf("existing: %v %v", ok, err)
}
if ok, err := a.UserExists(ctx, "new@b.test"); err != nil || ok {
t.Errorf("new: %v %v", ok, err)
}
if _, err := a.UserExists(ctx, "boom@b.test"); err == nil {
t.Error("lookup failure not reported")
}
}
func TestHTTPAdapter_inviteMailRefused(t *testing.T) {
s := newStubKC(t)
defer s.close()
s.emailFails.Store(true)
res, err := newTestAdapter(s.srv).CreateOrgAndInvite(context.Background(), InviteInput{
TenantID: "t1", Slug: "acme", Name: "Acme", AdminEmail: "it@acme.test",
})
if err != nil {
t.Fatalf("provisioning must still succeed: %v", err)
}
if res.UserID != "user-abc" || res.MailError == nil || !strings.Contains(res.MailError.Error(), "Invalid redirect uri") {
t.Fatalf("result = %+v", res)
}
}
func TestHTTPAdapter_purgeTenant(t *testing.T) {
var deleted []string
mux := http.NewServeMux()
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", tokenOK)
mux.HandleFunc("/admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode([]map[string]any{{"id": "org-1", "alias": "acme"}})
})
mux.HandleFunc("/admin/realms/test-realm/organizations/org-1/members", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode([]map[string]any{{"id": "u-mine"}, {"id": "u-other"}})
})
mux.HandleFunc("/admin/realms/test-realm/organizations/org-1", func(w http.ResponseWriter, r *http.Request) {
deleted = append(deleted, r.Method+" org-1")
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("/admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) {
// The first admin, no longer an org member.
_ = json.NewEncoder(w).Encode([]map[string]any{{"id": "u-admin", "email": "it@acme.test"}})
})
users := map[string]string{"u-mine": "t1", "u-other": "t2", "u-admin": "t1"}
for id, tenant := range users {
mux.HandleFunc("/admin/realms/test-realm/users/"+id, func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodDelete {
deleted = append(deleted, "DELETE "+id)
w.WriteHeader(http.StatusNoContent)
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"id": id, "attributes": map[string][]string{"tenant_id": {tenant}}})
})
}
srv := httptest.NewServer(mux)
defer srv.Close()
n, err := newTestAdapter(srv).PurgeTenant(context.Background(), "acme", "t1", []string{"it@acme.test", ""})
if err != nil || n != 2 {
t.Fatalf("removed %d, err %v", n, err)
}
if strings.Join(deleted, ",") != "DELETE u-mine,DELETE u-admin,DELETE org-1" {
t.Fatalf("deleted: %v", deleted)
}
}
func TestHTTPAdapter_purgeTenantWithoutOrg(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", tokenOK)
mux.HandleFunc("/admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode([]map[string]any{})
})
mux.HandleFunc("/admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode([]map[string]any{})
})
srv := httptest.NewServer(mux)
defer srv.Close()
if n, err := newTestAdapter(srv).PurgeTenant(context.Background(), "gone", "t1", []string{"x@y.test"}); err != nil || n != 0 {
t.Fatalf("removed %d, err %v", n, err)
}
}