diff --git a/internal/keycloak/members_test.go b/internal/keycloak/members_test.go index 1d003ed..cdca589 100644 --- a/internal/keycloak/members_test.go +++ b/internal/keycloak/members_test.go @@ -28,6 +28,13 @@ type membersKC struct { nextID int } +// 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{ @@ -44,10 +51,35 @@ func newMembersKC(t *testing.T) (*membersKC, *HTTPAdapter) { } 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{} - if id, ok := k.orgs[r.URL.Query().Get("search")]; ok { - out = append(out, map[string]string{"id": id, "alias": r.URL.Query().Get("search")}) + 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) }) @@ -297,3 +329,39 @@ func TestHTTPAdapter_InviteMember_createConflictFallsBackToLookup(t *testing.T) 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=&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) + } +} diff --git a/internal/keycloak/orgs.go b/internal/keycloak/orgs.go index be998e0..3c55527 100644 --- a/internal/keycloak/orgs.go +++ b/internal/keycloak/orgs.go @@ -197,9 +197,41 @@ func (a *HTTPAdapter) SyncClaims(ctx context.Context, userID string, c Claims) e // ─── helpers ───────────────────────────────────────────────────────────── +// findOrgByAlias resolves a tenant slug to its Keycloak organization id. +// +// Two queries, because neither is sufficient alone in KC 26: +// +// - `?q=alias:` searches the organization's attributes and is exact, +// but returns nothing on a realm where the alias is not indexed. +// - `?search=` is a substring match over name, alias and domains, so +// it finds the organization but also its neighbours ("demo" matches +// "stage-demo"), which is why the alias is compared again below. +// +// What must NOT be used is `?search=&exact=true`: exact matches the +// display *name*, and the registry names organizations after the company +// ("Breakpilot Demo GmbH") while the alias carries the slug. That combination +// answered zero results for every tenant, which surfaced as an empty Team page +// and a failing invite. func (a *HTTPAdapter) findOrgByAlias(ctx context.Context, alias string) (string, error) { - resp, err := a.adminCall(ctx, http.MethodGet, - fmt.Sprintf("/organizations?search=%s&exact=true", alias), nil, nil) + for _, query := range []string{ + "/organizations?q=" + url.QueryEscape("alias:"+alias), + "/organizations?search=" + url.QueryEscape(alias) + "&max=500", + } { + id, err := a.orgIDFrom(ctx, query, alias) + if err != nil { + return "", err + } + if id != "" { + return id, nil + } + } + return "", fmt.Errorf("%w: alias=%s", ErrOrgNotFound, alias) +} + +// orgIDFrom runs one organization query and returns the id whose alias matches +// exactly, or "" when the query found none. +func (a *HTTPAdapter) orgIDFrom(ctx context.Context, query, alias string) (string, error) { + resp, err := a.adminCall(ctx, http.MethodGet, query, nil, nil) if err != nil { return "", err } @@ -219,7 +251,7 @@ func (a *HTTPAdapter) findOrgByAlias(ctx context.Context, alias string) (string, return o.ID, nil } } - return "", fmt.Errorf("%w: alias=%s", ErrOrgNotFound, alias) + return "", nil } // errUserLookupMiss distinguishes "no such user" from a failed lookup in