Demonstration plan, phase D1 (registry side). The portal's Settings/Users page renders design fixtures today and its "Invite member" button posts to a route that does not exist, because the registry had no membership surface.
**`GET /v1/tenants/{id}/members`** lists the tenant's Keycloak organization members — user id, email, first/last name, `org_roles`, `enabled`, `created_at`. A tenant whose organization was never created (sales-led) answers an empty list rather than an error.
**`POST /v1/tenants/{id}/invites`** `{email, first_name?, last_name?, role?}` creates the Keycloak user if missing, adds the organization member (KC 26: the member body is the bare user id), writes the tenant-context user attributes, sends the same execute-actions mail the first admin gets, and audits `user.invited` with the caller as actor. Idempotent: an existing member answers `200 {status:"member"}` and sends no mail; a new one `202 {status:"invited"}`.
**Scope.** A user token may only touch its own tenant — another tenant's id is a 404, never a hint that it exists. Inviting needs the `IT_ADMIN` or `OWNER` org role, so `Principal` now carries the `org_roles` claim and `IsTenantAdmin()`. Service clients stay gated by `AUTHZ_RULES` route groups: members on `tenants.read`, invites on `tenants.write`.
**`admin_email` on the tenant** (migration `0006`, backfilled from the `keycloak.invite_sent` audit trail, and from `keycloak.provision_failed` metadata where the first invite failed) so Settings can show a real contact instead of an em dash. The first `IT_ADMIN`/`OWNER` invite fills it in when it was empty.
**Routing note worth keeping:** `GET /v1/tenants/{id}/members` cannot be registered — Go's ServeMux calls it a conflict with `GET /v1/tenants/by-slug/{slug}`, since both match `/v1/tenants/by-slug/members` and neither pattern is more specific. It is registered as `GET /v1/tenants/{id}/{sub}` instead, which *is* less specific than the by-slug lookup, so the two coexist; anything but `members` answers 404.
`openapi.yaml` documents both endpoints, the `OrgMember`/`Invite` schemas, `admin_email` and a `Forbidden` response.
Verified locally: `go vet ./...`, `gofmt` clean, `go test ./...` green, CI coverage command at **74.3%** (gate 70%).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #28
158 lines
6.8 KiB
Go
158 lines
6.8 KiB
Go
// 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
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
// 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"`
|
|
}
|
|
|
|
// 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)
|
|
|
|
// 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
|
|
|
|
// 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)
|
|
}
|