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 ".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") } // 1. 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 nil, err } switch resp.StatusCode { case http.StatusCreated: // keep going case http.StatusConflict: _ = resp.Body.Close() return nil, fmt.Errorf("%w: alias=%s", ErrOrgConflict, in.Slug) default: body, _ := io.ReadAll(resp.Body) _ = resp.Body.Close() return nil, 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 nil, 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) } // 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": {"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 } // 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:` 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) { 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) { resp, err := a.adminCall(ctx, http.MethodGet, fmt.Sprintf("/users?email=%s&exact=true", url.QueryEscape(email)), nil, nil) if err != nil { return "", err } defer func() { _ = resp.Body.Close() }() if resp.StatusCode/100 != 2 { return "", fmt.Errorf("find user: %d", resp.StatusCode) } var users []struct { ID string `json:"id"` Email string `json:"email"` } if err := json.NewDecoder(resp.Body).Decode(&users); err != nil { return "", err } for _, u := range users { if strings.EqualFold(u.Email, email) { return u.ID, nil } } return "", 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) }