487 lines
18 KiB
Go
487 lines
18 KiB
Go
package keycloak
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// membersKC is a KC 26 look-alike for the organization-membership surface:
|
|
// org lookup by alias, member list, user search/create/get/put, member add
|
|
// (bare-id body, 409 when already a member) and execute-actions e-mail.
|
|
type membersKC struct {
|
|
mu sync.Mutex
|
|
orgs map[string]string // alias → org id
|
|
members map[string][]string // org id → user ids
|
|
users map[string]memberRepresentation // user id → user
|
|
brief bool // member list omits attributes
|
|
mails []string // user ids that got the execute-actions mail
|
|
redirects []string // redirect_uri of each execute-actions mail
|
|
created []userCreate
|
|
puts map[string]map[string][]string // user id → attributes PUT
|
|
createErr int // non-zero: POST /users answers this status
|
|
nextID int
|
|
creds map[string][]string // user id → credential types
|
|
idp map[string]bool // user id → linked to an identity provider
|
|
logouts []string // user ids logged out
|
|
deleted []string // user ids deleted
|
|
failWrite int // non-zero: member DELETE / logout answer this status
|
|
orgsCreated []string // aliases of organizations created
|
|
ldapOnly bool // member list carries only LDAP attributes
|
|
}
|
|
|
|
// orgName is the display name the registry gives an organization: the company
|
|
// name, never the slug — which is the whole reason an alias lookup cannot use
|
|
// KC's `exact` flag.
|
|
func (k *membersKC) orgName(alias string) string {
|
|
return strings.ToUpper(alias[:1]) + alias[1:] + " GmbH"
|
|
}
|
|
|
|
func newMembersKC(t *testing.T) (*membersKC, *HTTPAdapter) {
|
|
t.Helper()
|
|
k := &membersKC{
|
|
orgs: map[string]string{"acme": "org-acme"},
|
|
members: map[string][]string{"org-acme": {"u-admin"}},
|
|
users: map[string]memberRepresentation{
|
|
"u-admin": {ID: "u-admin", Username: "admin@acme.test", Email: "admin@acme.test", FirstName: "Ada", LastName: "Admin",
|
|
Enabled: true, CreatedTimestamp: 1_700_000_000_000,
|
|
Attributes: map[string][]string{"org_roles": {"IT_ADMIN##OWNER"}, "tenant_slug": {"acme"}}},
|
|
"u-loose": {ID: "u-loose", Username: "loose@acme.test", Email: "loose@acme.test", Enabled: true,
|
|
Attributes: map[string][]string{"tenant_id": {"other"}}},
|
|
},
|
|
puts: map[string]map[string][]string{},
|
|
creds: map[string][]string{"u-admin": {"otp", "password"}},
|
|
idp: map[string]bool{},
|
|
}
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", tokenOK)
|
|
// Mirrors KC 26: `q=alias:x` matches the alias exactly, `search=x` is a
|
|
// substring match over name AND alias (so "demo" also finds "stage-demo"),
|
|
// and `exact=true` compares the display NAME — which is why searching by
|
|
// alias with exact=true finds nothing.
|
|
mux.HandleFunc("GET /admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
q := r.URL.Query()
|
|
out := []map[string]string{}
|
|
add := func(alias, id string) {
|
|
out = append(out, map[string]string{"id": id, "alias": alias, "name": k.orgName(alias)})
|
|
}
|
|
if v := strings.TrimPrefix(q.Get("q"), "alias:"); q.Get("q") != "" {
|
|
if id, ok := k.orgs[v]; ok {
|
|
add(v, id)
|
|
}
|
|
_ = json.NewEncoder(w).Encode(out)
|
|
return
|
|
}
|
|
term := q.Get("search")
|
|
for alias, id := range k.orgs {
|
|
switch {
|
|
case q.Get("exact") == "true":
|
|
if k.orgName(alias) == term {
|
|
add(alias, id)
|
|
}
|
|
case term == "" || strings.Contains(alias, term) || strings.Contains(k.orgName(alias), term):
|
|
add(alias, id)
|
|
}
|
|
}
|
|
_ = json.NewEncoder(w).Encode(out)
|
|
})
|
|
mux.HandleFunc("GET /admin/realms/test-realm/organizations/{id}/members", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
out := []memberRepresentation{}
|
|
for _, id := range k.members[r.PathValue("id")] {
|
|
u := k.users[id]
|
|
if k.brief {
|
|
u.Attributes = nil
|
|
}
|
|
if k.ldapOnly {
|
|
// KC 26 for a federated user: only the LDAP attributes in the list.
|
|
u.Attributes = map[string][]string{"LDAP_ID": {"x"}}
|
|
}
|
|
out = append(out, u)
|
|
}
|
|
_ = json.NewEncoder(w).Encode(out)
|
|
})
|
|
mux.HandleFunc("POST /admin/realms/test-realm/organizations/{id}/members", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
var id string
|
|
if err := json.NewDecoder(r.Body).Decode(&id); err != nil {
|
|
http.Error(w, `{"errorMessage":"User does not exist"}`, http.StatusBadRequest)
|
|
return
|
|
}
|
|
if _, ok := k.users[id]; !ok {
|
|
http.Error(w, `{"errorMessage":"User does not exist"}`, http.StatusBadRequest)
|
|
return
|
|
}
|
|
for _, m := range k.members[r.PathValue("id")] {
|
|
if m == id {
|
|
http.Error(w, `{"errorMessage":"User is already a member"}`, http.StatusConflict)
|
|
return
|
|
}
|
|
}
|
|
k.members[r.PathValue("id")] = append(k.members[r.PathValue("id")], id)
|
|
w.WriteHeader(http.StatusCreated)
|
|
})
|
|
mux.HandleFunc("GET /admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
out := []memberRepresentation{}
|
|
for _, u := range k.users {
|
|
if strings.EqualFold(u.Email, r.URL.Query().Get("email")) {
|
|
out = append(out, u)
|
|
}
|
|
}
|
|
_ = json.NewEncoder(w).Encode(out)
|
|
})
|
|
mux.HandleFunc("POST /admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
var u userCreate
|
|
_ = json.NewDecoder(r.Body).Decode(&u)
|
|
k.created = append(k.created, u)
|
|
if k.createErr != 0 {
|
|
if k.createErr == http.StatusConflict {
|
|
// A racing creator won: the user exists by the time we look again.
|
|
k.users["u-race"] = memberRepresentation{ID: "u-race", Username: u.Username, Email: u.Email, Enabled: true}
|
|
}
|
|
w.WriteHeader(k.createErr)
|
|
return
|
|
}
|
|
k.nextID++
|
|
id := "u-new-" + string(rune('0'+k.nextID))
|
|
k.users[id] = memberRepresentation{ID: id, Username: u.Username, Email: u.Email, FirstName: u.FirstName, LastName: u.LastName, Enabled: u.Enabled, Attributes: u.Attributes}
|
|
w.Header().Set("Location", "http://kc/admin/realms/test-realm/users/"+id)
|
|
w.WriteHeader(http.StatusCreated)
|
|
})
|
|
mux.HandleFunc("GET /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
u, ok := k.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) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
var body struct {
|
|
Attributes map[string][]string `json:"attributes"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
k.puts[r.PathValue("id")] = body.Attributes
|
|
u := k.users[r.PathValue("id")]
|
|
u.Attributes = body.Attributes
|
|
k.users[r.PathValue("id")] = u
|
|
w.WriteHeader(http.StatusNoContent)
|
|
})
|
|
mux.HandleFunc("PUT /admin/realms/test-realm/users/{id}/execute-actions-email", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
if r.URL.Query().Get("client_id") != "portal-test" {
|
|
http.Error(w, "bad invite client", http.StatusBadRequest)
|
|
return
|
|
}
|
|
k.mails = append(k.mails, r.PathValue("id"))
|
|
k.redirects = append(k.redirects, r.URL.Query().Get("redirect_uri"))
|
|
w.WriteHeader(http.StatusNoContent)
|
|
})
|
|
mux.HandleFunc("GET /admin/realms/test-realm/users/{id}/credentials", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
if _, ok := k.users[r.PathValue("id")]; !ok {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
out := []map[string]string{}
|
|
for _, typ := range k.creds[r.PathValue("id")] {
|
|
out = append(out, map[string]string{"type": typ})
|
|
}
|
|
_ = json.NewEncoder(w).Encode(out)
|
|
})
|
|
mux.HandleFunc("GET /admin/realms/test-realm/users/{id}/federated-identity", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
out := []map[string]string{}
|
|
if k.idp[r.PathValue("id")] {
|
|
out = append(out, map[string]string{"identityProvider": "company-sso"})
|
|
}
|
|
_ = json.NewEncoder(w).Encode(out)
|
|
})
|
|
mux.HandleFunc("DELETE /admin/realms/test-realm/organizations/{id}/members/{uid}", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
if k.failWrite != 0 {
|
|
w.WriteHeader(k.failWrite)
|
|
return
|
|
}
|
|
org := r.PathValue("id")
|
|
for i, m := range k.members[org] {
|
|
if m == r.PathValue("uid") {
|
|
k.members[org] = append(k.members[org][:i], k.members[org][i+1:]...)
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
}
|
|
w.WriteHeader(http.StatusNotFound)
|
|
})
|
|
mux.HandleFunc("GET /admin/realms/test-realm/organizations/members/{uid}/organizations", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
out := []memberOrgRepresentation{}
|
|
for alias, org := range k.orgs {
|
|
for _, m := range k.members[org] {
|
|
if m == r.PathValue("uid") {
|
|
out = append(out, memberOrgRepresentation{ID: org, Alias: alias, Enabled: true})
|
|
}
|
|
}
|
|
}
|
|
_ = json.NewEncoder(w).Encode(out)
|
|
})
|
|
mux.HandleFunc("DELETE /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
delete(k.users, r.PathValue("id"))
|
|
k.deleted = append(k.deleted, r.PathValue("id"))
|
|
w.WriteHeader(http.StatusNoContent)
|
|
})
|
|
mux.HandleFunc("POST /admin/realms/test-realm/users/{id}/logout", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
if k.failWrite != 0 {
|
|
w.WriteHeader(k.failWrite)
|
|
return
|
|
}
|
|
k.logouts = append(k.logouts, r.PathValue("id"))
|
|
w.WriteHeader(http.StatusNoContent)
|
|
})
|
|
// Organization create (directory-mode admin path).
|
|
mux.HandleFunc("POST /admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) {
|
|
k.mu.Lock()
|
|
defer k.mu.Unlock()
|
|
var body struct {
|
|
Alias string `json:"alias"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&body)
|
|
if _, taken := k.orgs[body.Alias]; taken {
|
|
w.WriteHeader(http.StatusConflict)
|
|
return
|
|
}
|
|
id := "org-" + body.Alias
|
|
k.orgs[body.Alias] = id
|
|
k.members[id] = []string{}
|
|
k.orgsCreated = append(k.orgsCreated, body.Alias)
|
|
w.Header().Set("Location", "http://kc/admin/realms/test-realm/organizations/"+id)
|
|
w.WriteHeader(http.StatusCreated)
|
|
})
|
|
srv := httptest.NewServer(mux)
|
|
t.Cleanup(srv.Close)
|
|
a := NewHTTPAdapter(HTTPConfig{
|
|
BaseURL: srv.URL, Realm: "test-realm", ClientID: "c", ClientSecret: "s", Timeout: 5 * time.Second,
|
|
InviteClientID: "portal-test", InviteRedirectURI: "https://portal.test/{slug}/dashboard",
|
|
})
|
|
return k, a
|
|
}
|
|
|
|
func TestHTTPAdapter_ListOrgMembers(t *testing.T) {
|
|
k, a := newMembersKC(t)
|
|
members, err := a.ListOrgMembers(context.Background(), "acme")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(members) != 1 {
|
|
t.Fatalf("want 1 member, got %+v", members)
|
|
}
|
|
m := members[0]
|
|
if m.UserID != "u-admin" || m.Email != "admin@acme.test" || m.FirstName != "Ada" || m.LastName != "Admin" || !m.Enabled {
|
|
t.Errorf("identity fields: %+v", m)
|
|
}
|
|
if strings.Join(m.OrgRoles, ",") != "IT_ADMIN,OWNER" {
|
|
t.Errorf("org_roles must split ## joined values: %v", m.OrgRoles)
|
|
}
|
|
if m.CreatedAt == nil || m.CreatedAt.UnixMilli() != 1_700_000_000_000 {
|
|
t.Errorf("created_at from createdTimestamp: %v", m.CreatedAt)
|
|
}
|
|
|
|
// Brief member representation → attributes fetched per user.
|
|
k.brief = true
|
|
members, err = a.ListOrgMembers(context.Background(), "acme")
|
|
if err != nil || len(members) != 1 || len(members[0].OrgRoles) != 2 {
|
|
t.Fatalf("brief fallback: err=%v members=%+v", err, members)
|
|
}
|
|
|
|
if _, err := a.ListOrgMembers(context.Background(), "ghost"); !errors.Is(err, ErrOrgNotFound) {
|
|
t.Fatalf("missing org must be ErrOrgNotFound, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestHTTPAdapter_InviteMember_newUser(t *testing.T) {
|
|
k, a := newMembersKC(t)
|
|
res, err := a.InviteMember(context.Background(), MemberInviteInput{
|
|
TenantID: "t-1", Slug: "acme", TenantStatus: "trial",
|
|
Email: "new@acme.test", FirstName: "New", LastName: "Person", Role: "USER",
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if res.Status != InviteStatusInvited || !res.Created || res.UserID == "" || res.MailError != nil {
|
|
t.Fatalf("result: %+v", res)
|
|
}
|
|
if len(k.created) != 1 {
|
|
t.Fatalf("want one user created, got %d", len(k.created))
|
|
}
|
|
u := k.created[0]
|
|
if u.Username != "new@acme.test" || !u.Enabled || u.EmailVerified {
|
|
t.Errorf("user payload: %+v", u)
|
|
}
|
|
want := map[string]string{"tenant_id": "t-1", "tenant_slug": "acme", "org_roles": "USER", "tenant_status": "trial"}
|
|
for key, val := range want {
|
|
if got := u.Attributes[key]; len(got) != 1 || got[0] != val {
|
|
t.Errorf("attribute %s = %v, want %s", key, got, val)
|
|
}
|
|
}
|
|
if len(k.mails) != 1 || k.mails[0] != res.UserID {
|
|
t.Errorf("execute-actions mail: %v", k.mails)
|
|
}
|
|
// "Back to application" in the invite must land in the workspace, not on /start.
|
|
if len(k.redirects) != 1 || k.redirects[0] != "https://portal.test/acme/dashboard" {
|
|
t.Errorf("invite redirect: %v", k.redirects)
|
|
}
|
|
if got := k.members["org-acme"]; len(got) != 2 || got[1] != res.UserID {
|
|
t.Errorf("membership: %v", got)
|
|
}
|
|
}
|
|
|
|
func TestHTTPAdapter_InviteMember_existingMemberIsIdempotent(t *testing.T) {
|
|
k, a := newMembersKC(t)
|
|
res, err := a.InviteMember(context.Background(), MemberInviteInput{Slug: "acme", Email: "Admin@acme.test", Role: "USER"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if res.Status != InviteStatusMember || res.UserID != "u-admin" || res.Created {
|
|
t.Fatalf("result: %+v", res)
|
|
}
|
|
if len(k.mails) != 0 || len(k.created) != 0 {
|
|
t.Errorf("existing member must get no mail and no user: mails=%v created=%d", k.mails, len(k.created))
|
|
}
|
|
// Existing attributes are never overwritten.
|
|
if roles := k.users["u-admin"].Attributes["org_roles"]; len(roles) != 1 || roles[0] != "IT_ADMIN##OWNER" {
|
|
t.Errorf("org_roles must stay untouched: %v", roles)
|
|
}
|
|
}
|
|
|
|
func TestHTTPAdapter_InviteMember_existingUserNotMember(t *testing.T) {
|
|
k, a := newMembersKC(t)
|
|
res, err := a.InviteMember(context.Background(), MemberInviteInput{
|
|
TenantID: "t-1", Slug: "acme", TenantStatus: "active", Email: "loose@acme.test", Role: "USER",
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if res.Status != InviteStatusInvited || res.Created || res.UserID != "u-loose" {
|
|
t.Fatalf("result: %+v", res)
|
|
}
|
|
attrs := k.puts["u-loose"]
|
|
if attrs == nil {
|
|
t.Fatal("missing attributes must be merged with a PUT")
|
|
}
|
|
if attrs["tenant_id"][0] != "other" {
|
|
t.Errorf("existing attribute overwritten: %v", attrs["tenant_id"])
|
|
}
|
|
if attrs["org_roles"][0] != "USER" || attrs["tenant_slug"][0] != "acme" || attrs["tenant_status"][0] != "active" {
|
|
t.Errorf("missing attributes not filled: %v", attrs)
|
|
}
|
|
if len(k.mails) != 1 {
|
|
t.Errorf("mail: %v", k.mails)
|
|
}
|
|
}
|
|
|
|
func TestHTTPAdapter_InviteMember_errors(t *testing.T) {
|
|
k, a := newMembersKC(t)
|
|
if _, err := a.InviteMember(context.Background(), MemberInviteInput{Slug: "acme"}); err == nil {
|
|
t.Error("empty email must fail")
|
|
}
|
|
if _, err := a.InviteMember(context.Background(), MemberInviteInput{Slug: "ghost", Email: "x@acme.test"}); !errors.Is(err, ErrOrgNotFound) {
|
|
t.Errorf("missing org: %v", err)
|
|
}
|
|
k.createErr = http.StatusInternalServerError
|
|
if _, err := a.InviteMember(context.Background(), MemberInviteInput{Slug: "acme", Email: "boom@acme.test", Role: "USER"}); err == nil || !strings.Contains(err.Error(), "create user: 500") {
|
|
t.Errorf("create failure must surface: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestHTTPAdapter_InviteMember_createConflictFallsBackToLookup(t *testing.T) {
|
|
k, a := newMembersKC(t)
|
|
// A racing creator wins: POST /users answers 409 and the e-mail lookup
|
|
// that follows resolves the id the other caller created.
|
|
k.createErr = http.StatusConflict
|
|
res, err := a.InviteMember(context.Background(), MemberInviteInput{Slug: "acme", Email: "race@acme.test", Role: "USER"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if res.Status != InviteStatusInvited || res.UserID != "u-race" || !res.Created {
|
|
t.Fatalf("result: %+v", res)
|
|
}
|
|
if len(k.mails) != 1 || k.mails[0] != "u-race" {
|
|
t.Errorf("mail: %v", k.mails)
|
|
}
|
|
}
|
|
|
|
// The organization's display name is the company name, its alias is the tenant
|
|
// slug, and a substring neighbour ("stage-demo" beside "demo") exists in every
|
|
// real realm. The lookup must find the org by alias and must not settle for a
|
|
// neighbour — the earlier `search=<slug>&exact=true` found nothing at all, so
|
|
// every Team page was empty and every invite failed.
|
|
func TestListOrgMembers_findsOrgByAliasNotName(t *testing.T) {
|
|
k, a := newMembersKC(t)
|
|
k.mu.Lock()
|
|
k.orgs["demo"] = "org-demo"
|
|
k.orgs["stage-demo"] = "org-stage-demo"
|
|
k.members["org-demo"] = []string{"u-admin"}
|
|
k.members["org-stage-demo"] = []string{"u-loose"}
|
|
k.mu.Unlock()
|
|
|
|
members, err := a.ListOrgMembers(context.Background(), "demo")
|
|
if err != nil {
|
|
t.Fatalf("list members: %v", err)
|
|
}
|
|
if len(members) != 1 || members[0].Email != "admin@acme.test" {
|
|
t.Fatalf("wrong org resolved: %+v", members)
|
|
}
|
|
|
|
// The neighbour still resolves to its own organization.
|
|
other, err := a.ListOrgMembers(context.Background(), "stage-demo")
|
|
if err != nil {
|
|
t.Fatalf("list members (neighbour): %v", err)
|
|
}
|
|
if len(other) != 1 || other[0].Email != "loose@acme.test" {
|
|
t.Fatalf("neighbour org resolved wrongly: %+v", other)
|
|
}
|
|
|
|
if _, err := a.ListOrgMembers(context.Background(), "nope"); !errors.Is(err, ErrOrgNotFound) {
|
|
t.Fatalf("unknown alias: want ErrOrgNotFound, got %v", err)
|
|
}
|
|
}
|
|
|
|
func TestHTTPAdapter_InviteRedirect(t *testing.T) {
|
|
a := NewHTTPAdapter(HTTPConfig{InviteRedirectURI: "https://app.test/{slug}/dashboard"})
|
|
if got := a.inviteRedirect("acme"); got != "https://app.test/acme/dashboard" {
|
|
t.Errorf("slug placeholder: %s", got)
|
|
}
|
|
// A fixed redirect without the placeholder stays as configured.
|
|
b := NewHTTPAdapter(HTTPConfig{InviteRedirectURI: "https://app.test/start"})
|
|
if got := b.inviteRedirect("acme"); got != "https://app.test/start" {
|
|
t.Errorf("fixed redirect: %s", got)
|
|
}
|
|
}
|