// Package keycloak adapts the Keycloak Admin API to the tenant-registry's // language of "tenants" and "IT_ADMIN invites". // // The Adapter interface is the seam: tenant-registry handlers depend on // it, never on the concrete HTTP client. Tests use Mock; production uses // HTTPAdapter against the real KC at the configured base URL. // // Required Keycloak features (verified against KC 26): // - Organizations feature enabled in the realm (organizationsEnabled: true) // - Realm roles: BREAKPILOT_ADMIN, SUPPORT_ENGINEER, SALES_REP // - Group `/IT_ADMIN` (used as the org_role marker for invited users) // // All errors are wrapped with %w so callers can errors.Is them against // ErrUnauthorized / ErrOrgConflict / ErrUserConflict. package keycloak import ( "context" "errors" "time" ) // Sentinel errors. var ( ErrUnauthorized = errors.New("keycloak: admin auth failed") ErrOrgConflict = errors.New("keycloak: organization already exists") ErrUserConflict = errors.New("keycloak: user already exists") ErrUnavailable = errors.New("keycloak: unreachable") ErrUserNotFound = errors.New("keycloak: user does not exist") ErrOrgNotFound = errors.New("keycloak: organization does not exist") ) // InviteInput captures the per-tenant onboarding event from POST /v1/tenants. // The adapter creates a Keycloak organization, invites the IT_ADMIN, and // stores the (TenantID, OrganizationID) link back in the caller's Tenant. type InviteInput struct { TenantID string // the tenant_registry id; stored as KC org attribute "tenant_id" Slug string // becomes the KC org alias Name string // human-readable org name AdminEmail string // IT_ADMIN to invite (required) AdminName string // optional display name // AdminFirst/AdminLast, when set, are used instead of splitting AdminName. AdminFirst string AdminLast string // EmailVerified: the address is already proven (trial signup, portal#64: // the registry's own confirmation link). The user is created verified and // the invitation only asks to set a password; otherwise Keycloak would // demand a second e-mail confirmation. EmailVerified bool } // InviteResult is what the adapter produces. OrganizationID is what the // tenant-registry stores so it can later assert tenants.id ↔ kc.org_id 1:1. type InviteResult struct { OrganizationID string UserID string // InviteURL is what the user clicks to set their password. In dev (no // Stalwart yet) we surface it in the response so testers can use it // directly. In prod it's emailed by Keycloak and we discard it. InviteURL string // MailError is set when the org and user exist but Keycloak refused to // send the invitation (e.g. the redirect URI is not allowed for the // invite client). The admin can resend once the cause is fixed. MailError error } // OrgMember is one member of a tenant's Keycloak organization as the portal // Settings/Users page renders it. OrgRoles is the user attribute of the // same name (what the tenant-context mapper projects into the token) — // the registry exposes it, Keycloak owns it. type OrgMember struct { UserID string `json:"user_id"` Email string `json:"email"` FirstName string `json:"first_name"` LastName string `json:"last_name"` OrgRoles []string `json:"org_roles"` Enabled bool `json:"enabled"` CreatedAt *time.Time `json:"created_at"` // Pending: the invitation is not accepted yet (no password set, no // identity-provider link). Filled by ListOrgMembers. Pending bool `json:"pending"` // Status is "invited", "active" or "blocked" for the tenant the list was // read for; the registry sets it (see MemberStatus), the adapter does not. Status string `json:"status,omitempty"` // BlockedTenants is the user's org_blocked attribute: the tenant ids the // member is blocked in. Internal; the API exposes Status. BlockedTenants []string `json:"-"` // ExtraCapabilities is the user attribute AttrExtraCapabilities: the // capabilities the member holds on top of their bundle (RBAC step 3). ExtraCapabilities []string `json:"extra_capabilities"` } // Member status values (portal#74). const ( MemberInvited = "invited" MemberActive = "active" MemberBlocked = "blocked" ) // MemberStatus is the member's status in tenantID: blocked wins over a // pending invitation. func (m OrgMember) MemberStatus(tenantID string) string { for _, t := range m.BlockedTenants { if t == tenantID { return MemberBlocked } } if m.Pending { return MemberInvited } return MemberActive } // MemberInviteInput is POST /v1/tenants/{id}/invites as the adapter sees // it. TenantID/Slug/TenantStatus become the tenant-context attributes of a // newly created user (the same set CreateOrgAndInvite writes for the admin). type MemberInviteInput struct { TenantID string Slug string // KC org alias TenantStatus string Email string FirstName string LastName string Role string // org_roles value for a NEW user (existing roles are never overwritten) } // Member invite outcomes. const ( InviteStatusInvited = "invited" // user added to the org; execute-actions mail sent InviteStatusMember = "member" // already a member; nothing changed, no mail ) // MemberInviteResult reports what InviteMember did. type MemberInviteResult struct { UserID string Status string // InviteStatusInvited | InviteStatusMember Created bool // the Keycloak user was created by this call // MailError is set when the user was added but the execute-actions // e-mail could not be sent (non-fatal; the admin can resend from KC). MailError error } // Claims is the tenant-scoped claim bundle the protocol-mapper would push // into a JWT at token issuance. Returned by Adapter.ClaimsFor so the user- // attributes can be refreshed on subscription change. type Claims struct { TenantID string `json:"tenant_id"` TenantSlug string `json:"tenant_slug"` OrgRoles []string `json:"org_roles"` Products []string `json:"products"` Plan string `json:"plan"` TenantStatus string `json:"tenant_status"` } // Adapter is the shape tenant-registry handlers code against. HTTPAdapter // is the real one; Mock satisfies the same surface for tests. type Adapter interface { // CreateOrgAndInvite is the M4.3 happy path. Atomic from the caller's // PoV: either both org+user land or neither does. CreateOrgAndInvite(ctx context.Context, in InviteInput) (*InviteResult, error) // SyncClaims pushes the current Claims into the user's Keycloak // attributes. Called whenever entitlements change (M4.2 catalog/trial // flows, M14.x cancel, M12.x trial transitions). SyncClaims(ctx context.Context, userID string, c Claims) error // Memberships resolves the tenants user userID (the Keycloak user id, // i.e. the JWT `sub`) belongs to, as Keycloak records them. Since the // realm enabled Organizations (2026-09-01) this is an org-membership // query: one membership per enabled org the user belongs to (alias = // tenant slug, org attribute tenant_id = registry UUID). The legacy // user-attribute projection no longer grants membership on its own. // Returns ErrUserNotFound for an unknown user id. Memberships(ctx context.Context, userID string) ([]Claims, error) // ListOrgMembers lists the members of the organization whose alias is // slug (portal Settings/Users). ErrOrgNotFound when the tenant has no // organization yet (sales-led tenant, nobody invited). ListOrgMembers(ctx context.Context, slug string) ([]OrgMember, error) // InviteMember adds in.Email to the organization whose alias is // in.Slug: creates the user when missing (with the tenant-context // attributes), adds the membership and sends the verify-email + // set-password mail. Idempotent — an existing member yields // InviteStatusMember and no mail. ErrOrgNotFound when the org is // missing. InviteMember(ctx context.Context, in MemberInviteInput) (*MemberInviteResult, error) // ResendInvite mails the invitation again to a member of the organization // whose alias is slug (verify email + set password). ErrOrgNotFound when // the org is missing, ErrUserNotFound when email is not a member of it. ResendInvite(ctx context.Context, slug, email string) error // UserExists reports whether the realm already has an account with this // email. Signup checks it first: an address can belong to one workspace. UserExists(ctx context.Context, email string) (bool, error) // PurgeTenant deletes the organization whose alias is slug and the // accounts that belong to tenantID (org members and the given e-mails). // Returns how many accounts were removed; a missing org is not an error. PurgeTenant(ctx context.Context, slug, tenantID string, emails []string) (int, error) // SyncTenantStatus writes the coarse tenant_status attribute on every // member of the organization whose alias is slug (ERP/02: Keycloak // carries only the coarse flag; entitlements stay in the registry). SyncTenantStatus(ctx context.Context, slug, status string) error // SetMemberRole replaces the user's org_roles attribute with [role]. It // takes effect at the user's next login or token refresh. SetMemberRole(ctx context.Context, userID, role string) error // SetMemberBlocked adds (blocked) or removes tenantID in the user's // org_blocked attribute — a per-workspace block, never enabled=false. SetMemberBlocked(ctx context.Context, userID, tenantID string, blocked bool) error // SetMemberExtras replaces the user's extra_capabilities attribute with // caps (none: the attribute is dropped). It takes effect at the user's // next login or token refresh. SetMemberExtras(ctx context.Context, userID string, caps []string) error // MemberBlocked reports whether userID is blocked in tenantID. // ErrUserNotFound for an unknown user. MemberBlocked(ctx context.Context, userID, tenantID string) (bool, error) // RemoveMember removes userID from the organization whose alias is slug // and clears its tenant-context attributes for tenantID. With // deleteIfOrphan the account is deleted when it belongs to no other // organization; the result reports whether it was. RemoveMember(ctx context.Context, slug, tenantID, userID string, deleteIfOrphan bool) (bool, error) // LogoutUser ends all of the user's sessions in the realm. LogoutUser(ctx context.Context, userID string) error // Health pings the admin endpoint. Used by readyz and the cluster cold- // start sequence (INFRASTRUCTURE.md §10 scenario F). Health(ctx context.Context) error // ServiceToken returns a client_credentials access token of the // registry's own Keycloak client — the bearer for product lifecycle // calls (PRODUCT_INTEGRATION_SPEC 2.0 §4.1; products verify aud + azp). ServiceToken(ctx context.Context) (string, error) }