In directory mode the registry attached any Keycloak user found by
e-mail. On an installation the realm also holds our local staff accounts
(onprem keycloak/staff-account.sh): a workspace admin could add one to
their team (201 added), giving our support account workspace attributes
and membership. Found in the test install.
Now only a user with a federation link (from the AD) counts, for the
first admin and for members; a local account answers not_in_directory
like an unknown address. The cloud is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 1b821baa7b)
516 lines
18 KiB
Go
516 lines
18 KiB
Go
package keycloak
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/url"
|
|
"path"
|
|
"strings"
|
|
)
|
|
|
|
// ─── organizations API ───────────────────────────────────────────────────
|
|
|
|
// orgDomainSuffix namespaces the synthetic org domain. The slug is unique in
|
|
// the registry, so "<slug>.tenant.breakpilot.com" is unique per organization
|
|
// and never a real deliverable mail domain we might clash with.
|
|
const orgDomainSuffix = ".tenant.breakpilot.com"
|
|
|
|
type orgCreate struct {
|
|
Name string `json:"name"`
|
|
Alias string `json:"alias"`
|
|
Description string `json:"description,omitempty"`
|
|
Domains []map[string]any `json:"domains,omitempty"`
|
|
Attributes map[string][]string `json:"attributes,omitempty"`
|
|
}
|
|
|
|
type userCreate struct {
|
|
Username string `json:"username"`
|
|
Email string `json:"email"`
|
|
FirstName string `json:"firstName,omitempty"`
|
|
LastName string `json:"lastName,omitempty"`
|
|
Enabled bool `json:"enabled"`
|
|
EmailVerified bool `json:"emailVerified"`
|
|
Attributes map[string][]string `json:"attributes,omitempty"`
|
|
}
|
|
|
|
// CreateOrgAndInvite creates the organization, creates the IT_ADMIN user,
|
|
// adds them as org member, and triggers the verify-email-and-set-password
|
|
// flow (Keycloak's native "invite via email" path).
|
|
//
|
|
// Best-effort atomicity: on partial failure we leave KC in whatever state
|
|
// it's in and surface the error. A follow-up reconciler (M4.x or M14.x)
|
|
// can heal divergence. For local dev where everything either succeeds or
|
|
// the test surfaces the exact failure, this is fine.
|
|
func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (*InviteResult, error) {
|
|
if in.AdminEmail == "" {
|
|
return nil, fmt.Errorf("keycloak: admin email required")
|
|
}
|
|
if a.cfg.DirectoryUsers {
|
|
return a.attachDirectoryAdmin(ctx, in)
|
|
}
|
|
orgID, err := a.createOrg(ctx, in)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 2. Create the user (disabled until they set a password).
|
|
first, last := splitName(in.AdminName)
|
|
if in.AdminFirst != "" || in.AdminLast != "" {
|
|
first, last = in.AdminFirst, in.AdminLast
|
|
}
|
|
userPayload := userCreate{
|
|
Username: in.AdminEmail,
|
|
Email: in.AdminEmail,
|
|
FirstName: first,
|
|
LastName: last,
|
|
Enabled: true,
|
|
EmailVerified: in.EmailVerified,
|
|
Attributes: map[string][]string{
|
|
"tenant_id": {in.TenantID},
|
|
"tenant_slug": {in.Slug},
|
|
"org_roles": {"IT_ADMIN"},
|
|
"tenant_status": {statusOr(in.TenantStatus, "trial")},
|
|
},
|
|
}
|
|
resp, err := a.adminCall(ctx, http.MethodPost, "/users", userPayload, nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create user: %w", err)
|
|
}
|
|
switch resp.StatusCode {
|
|
case http.StatusCreated:
|
|
// keep going
|
|
case http.StatusConflict:
|
|
_ = resp.Body.Close()
|
|
return nil, fmt.Errorf("%w: email=%s", ErrUserConflict, in.AdminEmail)
|
|
default:
|
|
body, _ := io.ReadAll(resp.Body)
|
|
_ = resp.Body.Close()
|
|
return nil, fmt.Errorf("create user: %d %s", resp.StatusCode, body)
|
|
}
|
|
userID := lastSegment(resp.Header.Get("Location"))
|
|
_ = resp.Body.Close()
|
|
if userID == "" {
|
|
userID, err = a.findUserByEmail(ctx, in.AdminEmail)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create user: missing Location and lookup failed: %w", err)
|
|
}
|
|
}
|
|
|
|
// 3. Add user to organization (member).
|
|
// Keycloak 26: the member endpoint takes the bare user id as the JSON
|
|
// body (a string), not an object — an object yields "User does not exist".
|
|
resp, err = a.adminCall(ctx, http.MethodPost,
|
|
fmt.Sprintf("/organizations/%s/members", orgID), userID, nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("add member: %w", err)
|
|
}
|
|
if resp.StatusCode/100 != 2 && resp.StatusCode != http.StatusConflict {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
_ = resp.Body.Close()
|
|
return nil, fmt.Errorf("add member: %d %s", resp.StatusCode, body)
|
|
}
|
|
_ = resp.Body.Close()
|
|
|
|
// 4. Trigger the verify-email + set-password execute-actions email.
|
|
// In dev (no Stalwart) we also surface the action-token URL to
|
|
// the caller so they can hit it directly.
|
|
actions := []string{"VERIFY_EMAIL", "UPDATE_PASSWORD"}
|
|
if in.EmailVerified {
|
|
actions = []string{"UPDATE_PASSWORD"}
|
|
}
|
|
inviteURL, err := a.executeActionsEmail(ctx, userID, actions, a.inviteRedirect(in.Slug))
|
|
if err != nil {
|
|
// Non-fatal: the account exists, the mail can be resent.
|
|
return &InviteResult{OrganizationID: orgID, UserID: userID, MailError: err}, nil
|
|
}
|
|
|
|
return &InviteResult{OrganizationID: orgID, UserID: userID, InviteURL: inviteURL}, nil
|
|
}
|
|
|
|
// createOrg creates the tenant's organization and returns its id.
|
|
func (a *HTTPAdapter) createOrg(ctx context.Context, in InviteInput) (string, error) {
|
|
// Create org with tenant_id baked in as an attribute so we can
|
|
// correlate the two systems with a single Admin API call later.
|
|
orgPayload := orgCreate{
|
|
Name: in.Name,
|
|
Alias: in.Slug,
|
|
Description: fmt.Sprintf("Auto-provisioned from tenant-registry %s", in.TenantID),
|
|
// Keycloak 26 rejects an organization with no domain ("You must
|
|
// provide at least one domain"). Membership is registry-authoritative
|
|
// (model B2), so we do NOT use Keycloak's email-domain auto-join; a
|
|
// synthetic per-tenant domain derived from the unique slug satisfies
|
|
// the constraint without depending on the customer's real mail domain
|
|
// (which may be a shared public domain and would collide across
|
|
// tenants). Unverified is fine — verification only gates auto-join.
|
|
Domains: []map[string]any{
|
|
{"name": in.Slug + orgDomainSuffix, "verified": false},
|
|
},
|
|
Attributes: map[string][]string{
|
|
"tenant_id": {in.TenantID},
|
|
},
|
|
}
|
|
resp, err := a.adminCall(ctx, http.MethodPost, "/organizations", orgPayload, nil)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
switch resp.StatusCode {
|
|
case http.StatusCreated:
|
|
// keep going
|
|
case http.StatusConflict:
|
|
_ = resp.Body.Close()
|
|
return "", fmt.Errorf("%w: alias=%s", ErrOrgConflict, in.Slug)
|
|
default:
|
|
body, _ := io.ReadAll(resp.Body)
|
|
_ = resp.Body.Close()
|
|
return "", fmt.Errorf("create org: %d %s", resp.StatusCode, body)
|
|
}
|
|
// Keycloak returns the id in the Location header.
|
|
orgID := lastSegment(resp.Header.Get("Location"))
|
|
_ = resp.Body.Close()
|
|
if orgID == "" {
|
|
// Fallback: query by alias.
|
|
orgID, err = a.findOrgByAlias(ctx, in.Slug)
|
|
if err != nil {
|
|
return "", fmt.Errorf("create org: missing Location and lookup failed: %w", err)
|
|
}
|
|
}
|
|
// Keycloak 26 ignores attributes on create; write them with a PUT so the
|
|
// org carries tenant_id (non-fatal: the alias stays the correlation key).
|
|
if err := a.ensureOrgAttributes(ctx, orgID, orgPayload.Attributes); err != nil {
|
|
slogWarn("keycloak org attributes not set", orgID, err)
|
|
}
|
|
return orgID, nil
|
|
}
|
|
|
|
// attachDirectoryAdmin is CreateOrgAndInvite in directory mode: the admin is
|
|
// an existing directory user. Looked up first, so a wrong address leaves no
|
|
// organization behind. The workspace attributes are set (the installer named
|
|
// this person the IT admin), the user joins the organization, and no mail is
|
|
// sent: they sign in with their directory password.
|
|
func (a *HTTPAdapter) attachDirectoryAdmin(ctx context.Context, in InviteInput) (*InviteResult, error) {
|
|
userID, err := a.findDirectoryUserByEmail(ctx, in.AdminEmail)
|
|
if errors.Is(err, errUserLookupMiss) {
|
|
return nil, fmt.Errorf("%w: %s", ErrNotInDirectory, in.AdminEmail)
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
orgID, err := a.createOrg(ctx, in)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
attrs := map[string][]string{
|
|
"tenant_id": {in.TenantID},
|
|
"tenant_slug": {in.Slug},
|
|
"org_roles": {"IT_ADMIN"},
|
|
"tenant_status": {statusOr(in.TenantStatus, "active")},
|
|
}
|
|
if err := a.updateUserAttributes(ctx, userID, func(existing map[string][]string) bool {
|
|
for k, v := range attrs {
|
|
existing[k] = v
|
|
}
|
|
return true
|
|
}); err != nil {
|
|
return nil, fmt.Errorf("set admin attributes: %w", err)
|
|
}
|
|
if _, err := a.addOrgMember(ctx, orgID, userID); err != nil {
|
|
return nil, err
|
|
}
|
|
return &InviteResult{OrganizationID: orgID, UserID: userID}, nil
|
|
}
|
|
|
|
// addOrgMember adds userID to the organization; already reports a 409 (the
|
|
// user was a member). KC 26: the body is the bare user id as a JSON string;
|
|
// an object yields "User does not exist".
|
|
func (a *HTTPAdapter) addOrgMember(ctx context.Context, orgID, userID string) (already bool, err error) {
|
|
resp, err := a.adminCall(ctx, http.MethodPost, fmt.Sprintf("/organizations/%s/members", orgID), userID, nil)
|
|
if err != nil {
|
|
return false, fmt.Errorf("add member: %w", err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
if resp.StatusCode == http.StatusConflict {
|
|
return true, nil
|
|
}
|
|
if resp.StatusCode/100 != 2 {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
return false, fmt.Errorf("add member: %d %s", resp.StatusCode, body)
|
|
}
|
|
return false, nil
|
|
}
|
|
|
|
func statusOr(s, fallback string) string {
|
|
if s == "" {
|
|
return fallback
|
|
}
|
|
return s
|
|
}
|
|
|
|
// SyncClaims pushes the up-to-date claim bundle into the user's KC
|
|
// attributes. Called by tenant-registry whenever entitlements change.
|
|
func (a *HTTPAdapter) SyncClaims(ctx context.Context, userID string, c Claims) error {
|
|
attrs := map[string][]string{
|
|
"tenant_id": {c.TenantID},
|
|
"tenant_slug": {c.TenantSlug},
|
|
"org_roles": c.OrgRoles,
|
|
"products": c.Products,
|
|
"plan": {c.Plan},
|
|
"tenant_status": {c.TenantStatus},
|
|
}
|
|
return a.updateUserAttributes(ctx, userID, func(existing map[string][]string) bool {
|
|
for k, v := range attrs {
|
|
existing[k] = v
|
|
}
|
|
return true
|
|
})
|
|
}
|
|
|
|
// ─── helpers ─────────────────────────────────────────────────────────────
|
|
|
|
// findOrgByAlias resolves a tenant slug to its Keycloak organization id.
|
|
//
|
|
// Two queries, because neither is sufficient alone in KC 26:
|
|
//
|
|
// - `?q=alias:<slug>` searches the organization's attributes and is exact,
|
|
// but returns nothing on a realm where the alias is not indexed.
|
|
// - `?search=<slug>` 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=<slug>&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) {
|
|
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
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
if resp.StatusCode/100 != 2 {
|
|
return "", fmt.Errorf("find org: %d", resp.StatusCode)
|
|
}
|
|
var orgs []struct {
|
|
ID string `json:"id"`
|
|
Alias string `json:"alias"`
|
|
}
|
|
if err := json.NewDecoder(resp.Body).Decode(&orgs); err != nil {
|
|
return "", err
|
|
}
|
|
for _, o := range orgs {
|
|
if o.Alias == alias {
|
|
return o.ID, nil
|
|
}
|
|
}
|
|
return "", nil
|
|
}
|
|
|
|
// errUserLookupMiss distinguishes "no such user" from a failed lookup in
|
|
// findUserByEmail so callers can create the user on a miss only.
|
|
var errUserLookupMiss = errors.New("user not found")
|
|
|
|
// UserExists implements Adapter.
|
|
func (a *HTTPAdapter) UserExists(ctx context.Context, email string) (bool, error) {
|
|
_, err := a.findUserByEmail(ctx, email)
|
|
switch {
|
|
case err == nil:
|
|
return true, nil
|
|
case errors.Is(err, errUserLookupMiss):
|
|
return false, nil
|
|
default:
|
|
return false, err
|
|
}
|
|
}
|
|
|
|
func (a *HTTPAdapter) findUserByEmail(ctx context.Context, email string) (string, error) {
|
|
id, _, err := a.lookupUserByEmail(ctx, email)
|
|
return id, err
|
|
}
|
|
|
|
// findDirectoryUserByEmail is findUserByEmail for directory mode: only a user from the
|
|
// directory (a federation link) counts. A local account with that address -- our staff
|
|
// accounts on an installation (onprem keycloak/staff-account.sh) -- is no workspace member:
|
|
// errUserLookupMiss, so callers answer not_in_directory.
|
|
func (a *HTTPAdapter) findDirectoryUserByEmail(ctx context.Context, email string) (string, error) {
|
|
id, federated, err := a.lookupUserByEmail(ctx, email)
|
|
if err == nil && !federated {
|
|
return "", errUserLookupMiss
|
|
}
|
|
return id, err
|
|
}
|
|
|
|
// findMemberUser looks up a member to add: any user in the cloud, a directory user on-prem.
|
|
func (a *HTTPAdapter) findMemberUser(ctx context.Context, email string) (string, error) {
|
|
if a.cfg.DirectoryUsers {
|
|
return a.findDirectoryUserByEmail(ctx, email)
|
|
}
|
|
return a.findUserByEmail(ctx, email)
|
|
}
|
|
|
|
func (a *HTTPAdapter) lookupUserByEmail(ctx context.Context, email string) (id string, federated bool, err error) {
|
|
resp, err := a.adminCall(ctx, http.MethodGet,
|
|
fmt.Sprintf("/users?email=%s&exact=true", url.QueryEscape(email)), nil, nil)
|
|
if err != nil {
|
|
return "", false, err
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
if resp.StatusCode/100 != 2 {
|
|
return "", false, fmt.Errorf("find user: %d", resp.StatusCode)
|
|
}
|
|
var users []struct {
|
|
ID string `json:"id"`
|
|
Email string `json:"email"`
|
|
FederationLink string `json:"federationLink"`
|
|
}
|
|
if err := json.NewDecoder(resp.Body).Decode(&users); err != nil {
|
|
return "", false, err
|
|
}
|
|
for _, u := range users {
|
|
if strings.EqualFold(u.Email, email) {
|
|
return u.ID, u.FederationLink != "", nil
|
|
}
|
|
}
|
|
return "", false, errUserLookupMiss
|
|
}
|
|
|
|
// inviteRedirect is the configured invite redirect with "{slug}" replaced by
|
|
// the workspace slug.
|
|
func (a *HTTPAdapter) inviteRedirect(slug string) string {
|
|
return strings.ReplaceAll(a.cfg.InviteRedirectURI, "{slug}", url.PathEscape(slug))
|
|
}
|
|
|
|
func (a *HTTPAdapter) executeActionsEmail(ctx context.Context, userID string, actions []string, redirectURI string) (string, error) {
|
|
resp, err := a.adminCall(ctx, http.MethodPut,
|
|
fmt.Sprintf("/users/%s/execute-actions-email?client_id=%s&redirect_uri=%s", userID, url.QueryEscape(a.cfg.InviteClientID), url.QueryEscape(redirectURI)),
|
|
actions, nil)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
if resp.StatusCode/100 != 2 {
|
|
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
|
return "", fmt.Errorf("execute-actions: %d %s", resp.StatusCode, strings.TrimSpace(string(body)))
|
|
}
|
|
// KC doesn't return the action-token URL via this endpoint — it sends
|
|
// the email. For dev we surface an admin-portal pointer so the tester
|
|
// has somewhere to land.
|
|
return fmt.Sprintf("%s/realms/%s/account", a.cfg.BaseURL, a.cfg.Realm), nil
|
|
}
|
|
|
|
func lastSegment(loc string) string {
|
|
if loc == "" {
|
|
return ""
|
|
}
|
|
return path.Base(loc)
|
|
}
|
|
|
|
func splitName(full string) (first, last string) {
|
|
full = strings.TrimSpace(full)
|
|
if full == "" {
|
|
return "", ""
|
|
}
|
|
parts := strings.Fields(full)
|
|
if len(parts) == 1 {
|
|
return parts[0], ""
|
|
}
|
|
return parts[0], strings.Join(parts[1:], " ")
|
|
}
|
|
|
|
// SyncTenantStatus finds the organization by alias, lists its members and
|
|
// rewrites only the tenant_status attribute on each (attributes are merged,
|
|
// never replaced wholesale). Other member attributes and org_roles are left
|
|
// untouched — roles stay Keycloak-owned.
|
|
func (a *HTTPAdapter) SyncTenantStatus(ctx context.Context, slug, status string) error {
|
|
orgID, err := a.findOrgByAlias(ctx, slug)
|
|
if err != nil {
|
|
return fmt.Errorf("sync status: %w", err)
|
|
}
|
|
var members []struct {
|
|
ID string `json:"id"`
|
|
}
|
|
resp, err := a.adminCall(ctx, http.MethodGet, fmt.Sprintf("/organizations/%s/members?max=500", orgID), nil, &members)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if resp.StatusCode/100 != 2 {
|
|
_ = resp.Body.Close()
|
|
return fmt.Errorf("sync status: list members %d", resp.StatusCode)
|
|
}
|
|
var firstErr error
|
|
for _, m := range members {
|
|
err := a.updateUserAttributes(ctx, m.ID, func(attrs map[string][]string) bool {
|
|
attrs["tenant_status"] = []string{status}
|
|
return true
|
|
})
|
|
if err != nil && firstErr == nil {
|
|
firstErr = err
|
|
}
|
|
}
|
|
return firstErr
|
|
}
|
|
|
|
// ensureOrgAttributes merges attrs into the organization representation.
|
|
func (a *HTTPAdapter) ensureOrgAttributes(ctx context.Context, orgID string, attrs map[string][]string) error {
|
|
var org map[string]any
|
|
resp, err := a.adminCall(ctx, http.MethodGet, "/organizations/"+orgID, nil, &org)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_ = resp.Body.Close()
|
|
if resp.StatusCode/100 != 2 || org == nil {
|
|
return fmt.Errorf("get org: %d", resp.StatusCode)
|
|
}
|
|
existing, _ := org["attributes"].(map[string]any)
|
|
if existing == nil {
|
|
existing = map[string]any{}
|
|
}
|
|
changed := false
|
|
for k, v := range attrs {
|
|
if _, ok := existing[k]; !ok {
|
|
existing[k] = v
|
|
changed = true
|
|
}
|
|
}
|
|
if !changed {
|
|
return nil
|
|
}
|
|
org["attributes"] = existing
|
|
resp, err = a.adminCall(ctx, http.MethodPut, "/organizations/"+orgID, org, nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
if resp.StatusCode/100 != 2 {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
return fmt.Errorf("put org: %d %s", resp.StatusCode, body)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func slogWarn(msg, orgID string, err error) {
|
|
slog.Warn(msg, "org_id", orgID, "err", err)
|
|
}
|