feat(onprem): directory users instead of invitations

On-prem every account comes from the customer's AD through Keycloak's
federation, so an AD admin answered email_taken and invitations asked for a
new password. The Keycloak adapter gets a directory mode (DirectoryUsers,
on with APP_ENV=onprem):

- The first admin and invited members are existing directory users,
  attached to the organization with their role. No local user is created,
  no execute-actions mail is sent (invite status "added", audit user.added /
  keycloak.admin_added).
- An unknown address (or one outside the admitted AD groups) answers 404
  not_in_directory. For the workspace's admin it is checked before the
  workspace is created, and the adapter looks the user up before creating
  the organization, so nothing is left behind.
- Resend answers 409 no_invite_mail; directory members are never pending.
- Member lists read the roles from the user when Keycloak lists a federated
  member with its LDAP attributes only (seen with Keycloak 26.8).
- The admin address is normalized once for lookup, store and Keycloak.

Checked against Keycloak 26.8.1 with a Samba AD (the test install in
platform/onprem, realm with UNSYNCED federation and realm-policy.sh).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit b8206c553f)
This commit is contained in:
Sharang Parnerkar committed 2026-11-20 17:08:48 +01:00
1 parent b30b5e3f1c
commit 90ae11ae42
14 files changed
+460 -59

No files matched your search

+1
View File
@@ -120,6 +120,7 @@ State-changing endpoints emit audit events automatically. The OpenAPI contract t
- No trial: a new workspace starts `active`, and the ladder never escalates by time (the licence is the contract). - No trial: a new workspace starts `active`, and the ladder never escalates by time (the licence is the contract).
- No sign-up and no sales requests: the trial-offer, trial-terms, catalog request, trial request and admin trial routes answer 404 `not_available`. - No sign-up and no sales requests: the trial-offer, trial-terms, catalog request, trial request and admin trial routes answer 404 `not_available`.
- Products and URLs only from `PRODUCTS` and `PRODUCT_*_URLS`. The seeded `stage`/`prod` URLs are never used, so provisioning never reaches a Breakpilot host (the test install in `platform/onprem` checks all outbound traffic). Each listed product needs a launch URL; an unknown key stops the start. The catalog offers no trials. - Products and URLs only from `PRODUCTS` and `PRODUCT_*_URLS`. The seeded `stage`/`prod` URLs are never used, so provisioning never reaches a Breakpilot host (the test install in `platform/onprem` checks all outbound traffic). Each listed product needs a launch URL; an unknown key stops the start. The catalog offers no trials.
- Accounts only from the customer's directory (Keycloak federates their AD; the package's `keycloak/realm-policy.sh` keeps passwords in AD). The workspace's first admin (`admin_email`) and every invited member must be an existing directory user: they are added to the organization with their role, get no set-password mail and sign in with their directory password. An unknown address answers `not_in_directory`; there is no invitation to resend (`no_invite_mail`).
- No cloud defaults: the registry refuses to start without `AUTH_ENABLED=true`, `AUTHZ_RULES`, `LICENCE_SIGNING_KEY`, `DATABASE_URL`, the Keycloak admin settings, `PORTAL_URL`, `INVITE_CLIENT_ID`, `INVITE_REDIRECT_URI`, `MAIL_FROM` and `PRODUCTS`, and without `LITELLM_BASE_URL` when `LITELLM_MASTER_KEY` is set. Contract documents stay off. - No cloud defaults: the registry refuses to start without `AUTH_ENABLED=true`, `AUTHZ_RULES`, `LICENCE_SIGNING_KEY`, `DATABASE_URL`, the Keycloak admin settings, `PORTAL_URL`, `INVITE_CLIENT_ID`, `INVITE_REDIRECT_URI`, `MAIL_FROM` and `PRODUCTS`, and without `LITELLM_BASE_URL` when `LITELLM_MASTER_KEY` is set. Contract documents stay off.
## ERP link (M-MIG-7) ## ERP link (M-MIG-7)
+2
View File
@@ -110,6 +110,8 @@ func main() {
InviteClientID: cfg.InviteClientID, InviteClientID: cfg.InviteClientID,
InviteRedirectURI: cfg.InviteRedirectURI, InviteRedirectURI: cfg.InviteRedirectURI,
// On-prem every account comes from the customer's directory.
DirectoryUsers: cfg.OnPrem(),
}) })
slog.Info("keycloak adapter configured", slog.Info("keycloak adapter configured",
"url", cfg.KeycloakAdminURL, "realm", cfg.KeycloakRealm, "client_id", cfg.KeycloakClientID) "url", cfg.KeycloakAdminURL, "realm", cfg.KeycloakRealm, "client_id", cfg.KeycloakClientID)
+10
View File
@@ -28,6 +28,12 @@ var (
ErrUnavailable = errors.New("keycloak: unreachable") ErrUnavailable = errors.New("keycloak: unreachable")
ErrUserNotFound = errors.New("keycloak: user does not exist") ErrUserNotFound = errors.New("keycloak: user does not exist")
ErrOrgNotFound = errors.New("keycloak: organization does not exist") ErrOrgNotFound = errors.New("keycloak: organization does not exist")
// Directory mode (on-prem): accounts come from the customer's directory.
// ErrNotInDirectory: no directory user with this e-mail (or not in the
// groups the realm admits). ErrNoInviteMail: there is no invitation mail
// to resend; directory users sign in with their directory password.
ErrNotInDirectory = errors.New("keycloak: no directory user with this e-mail")
ErrNoInviteMail = errors.New("keycloak: directory users get no invitation mail")
) )
// InviteInput captures the per-tenant onboarding event from POST /v1/tenants. // InviteInput captures the per-tenant onboarding event from POST /v1/tenants.
@@ -47,6 +53,9 @@ type InviteInput struct {
// the invitation only asks to set a password; otherwise Keycloak would // the invitation only asks to set a password; otherwise Keycloak would
// demand a second e-mail confirmation. // demand a second e-mail confirmation.
EmailVerified bool EmailVerified bool
// TenantStatus is written as the admin's tenant_status attribute.
// Empty: "trial" (a new cloud workspace).
TenantStatus string
} }
// InviteResult is what the adapter produces. OrganizationID is what the // InviteResult is what the adapter produces. OrganizationID is what the
@@ -128,6 +137,7 @@ type MemberInviteInput struct {
const ( const (
InviteStatusInvited = "invited" // user added to the org; execute-actions mail sent InviteStatusInvited = "invited" // user added to the org; execute-actions mail sent
InviteStatusMember = "member" // already a member; nothing changed, no mail InviteStatusMember = "member" // already a member; nothing changed, no mail
InviteStatusAdded = "added" // directory mode: an existing directory user added to the org; no mail
) )
// MemberInviteResult reports what InviteMember did. // MemberInviteResult reports what InviteMember did.
+7
View File
@@ -44,6 +44,13 @@ type HTTPConfig struct {
// portal forwards to /<slug>/dashboard; Keycloak only allows /start*). // portal forwards to /<slug>/dashboard; Keycloak only allows /start*).
InviteClientID string InviteClientID string
InviteRedirectURI string InviteRedirectURI string
// DirectoryUsers (on-prem): every account comes from the customer's
// directory through the realm's user federation. The adapter never
// creates a user and never sends the set-password mail: it attaches the
// existing directory user to the organization. Passwords stay in the
// directory.
DirectoryUsers bool
} }
func NewHTTPAdapter(cfg HTTPConfig) *HTTPAdapter { func NewHTTPAdapter(cfg HTTPConfig) *HTTPAdapter {
+112
View File
@@ -0,0 +1,112 @@
package keycloak
import (
"context"
"errors"
"strings"
"testing"
)
// Directory mode (on-prem): the users come from the customer's directory.
func newDirectoryKC(t *testing.T) (*membersKC, *HTTPAdapter) {
t.Helper()
k, a := newMembersKC(t)
a.cfg.DirectoryUsers = true
return k, a
}
func TestDirectory_adminIsAttachedWithoutMail(t *testing.T) {
k, a := newDirectoryKC(t)
res, err := a.CreateOrgAndInvite(context.Background(), InviteInput{
TenantID: "t-2", Slug: "werk", Name: "Werk GmbH", AdminEmail: "loose@acme.test", TenantStatus: "active",
})
if err != nil {
t.Fatal(err)
}
if res.UserID != "u-loose" || res.InviteURL != "" || res.MailError != nil {
t.Fatalf("result: %+v", res)
}
if len(k.created) != 0 || len(k.mails) != 0 {
t.Errorf("directory mode created %d users and sent %d mails", len(k.created), len(k.mails))
}
if got := k.members["org-werk"]; len(got) != 1 || got[0] != "u-loose" {
t.Errorf("membership: %v", got)
}
// The installer named this person the admin: the workspace attributes are set, also over old ones.
want := map[string]string{"tenant_id": "t-2", "tenant_slug": "werk", "org_roles": "IT_ADMIN", "tenant_status": "active"}
for key, val := range want {
if got := k.puts["u-loose"][key]; len(got) != 1 || got[0] != val {
t.Errorf("attribute %s = %v, want %s", key, got, val)
}
}
}
func TestDirectory_unknownAdminLeavesNoOrganization(t *testing.T) {
k, a := newDirectoryKC(t)
_, err := a.CreateOrgAndInvite(context.Background(), InviteInput{TenantID: "t-3", Slug: "nobody", Name: "N", AdminEmail: "ghost@acme.test"})
if !errors.Is(err, ErrNotInDirectory) {
t.Fatalf("err = %v, want ErrNotInDirectory", err)
}
if len(k.orgsCreated) != 0 || len(k.created) != 0 {
t.Errorf("orgs created %v, users created %d", k.orgsCreated, len(k.created))
}
}
func TestDirectory_memberIsAddedWithoutMail(t *testing.T) {
k, a := newDirectoryKC(t)
res, err := a.InviteMember(context.Background(), MemberInviteInput{
TenantID: "t-1", Slug: "acme", TenantStatus: "active", Email: "loose@acme.test", Role: "USER",
})
if err != nil {
t.Fatal(err)
}
if res.Status != InviteStatusAdded || res.Created || len(k.mails) != 0 {
t.Fatalf("result %+v, mails %v", res, k.mails)
}
if got := k.members["org-acme"]; len(got) != 2 || got[1] != "u-loose" {
t.Errorf("membership: %v", got)
}
if _, err := a.InviteMember(context.Background(), MemberInviteInput{Slug: "acme", Email: "ghost@acme.test", Role: "USER"}); !errors.Is(err, ErrNotInDirectory) {
t.Errorf("unknown member: %v", err)
}
if len(k.created) != 0 {
t.Errorf("a local user was created in directory mode")
}
}
func TestDirectory_noResendAndNeverPending(t *testing.T) {
k, a := newDirectoryKC(t)
delete(k.creds, "u-admin") // like an AD user: no password in Keycloak
// Control: the same member without a Keycloak password is pending in the cloud.
kc, cloud := newMembersKC(t)
delete(kc.creds, "u-admin")
if ms, err := cloud.ListOrgMembers(context.Background(), "acme"); err != nil || len(ms) == 0 || !ms[0].Pending {
t.Fatalf("control: cloud member not pending: %+v %v", ms, err)
}
if err := a.ResendInvite(context.Background(), "acme", "admin@acme.test"); !errors.Is(err, ErrNoInviteMail) {
t.Errorf("resend: %v", err)
}
members, err := a.ListOrgMembers(context.Background(), "acme")
if err != nil {
t.Fatal(err)
}
for _, m := range members {
if m.Pending {
t.Errorf("%s pending: a directory user has no Keycloak password and is never pending", m.Email)
}
}
}
// KC 26 lists a federated member with its LDAP attributes only; the roles are
// read from the user itself.
func TestDirectory_memberRolesWhenTheListCarriesOnlyLDAPAttributes(t *testing.T) {
k, a := newDirectoryKC(t)
k.ldapOnly = true
members, err := a.ListOrgMembers(context.Background(), "acme")
if err != nil {
t.Fatal(err)
}
if len(members) != 1 || strings.Join(members[0].OrgRoles, ",") != "IT_ADMIN,OWNER" {
t.Errorf("members = %+v", members)
}
}
+15 -3
View File
@@ -67,8 +67,9 @@ func (a *HTTPAdapter) ListOrgMembers(ctx context.Context, slug string) ([]OrgMem
} }
out := make([]OrgMember, 0, len(members)) out := make([]OrgMember, 0, len(members))
for _, m := range members { for _, m := range members {
if m.Attributes == nil { if m.Attributes == nil || len(attrValues(m.Attributes, "org_roles")) == 0 {
// Brief representation: attributes (org_roles) live on the user. // Brief representation, or a federated (AD) user, whose list entry
// carries only the LDAP attributes: org_roles live on the user.
var u memberRepresentation var u memberRepresentation
resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+m.ID, nil, &u) resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+m.ID, nil, &u)
if err == nil && resp.StatusCode/100 == 2 { if err == nil && resp.StatusCode/100 == 2 {
@@ -78,7 +79,8 @@ func (a *HTTPAdapter) ListOrgMembers(ctx context.Context, slug string) ([]OrgMem
} }
} }
om := m.toOrgMember() om := m.toOrgMember()
om.Pending = !a.hasPassword(ctx, m.ID) // A directory user has no password in Keycloak and is never pending.
om.Pending = !a.cfg.DirectoryUsers && !a.hasPassword(ctx, m.ID)
out = append(out, om) out = append(out, om)
} }
return out, nil return out, nil
@@ -114,6 +116,9 @@ func (a *HTTPAdapter) InviteMember(ctx context.Context, in MemberInviteInput) (*
if aerr := a.ensureUserAttributes(ctx, userID, attrs); aerr != nil { if aerr := a.ensureUserAttributes(ctx, userID, attrs); aerr != nil {
slog.Warn("keycloak user attributes not merged", "user_id", userID, "err", aerr) slog.Warn("keycloak user attributes not merged", "user_id", userID, "err", aerr)
} }
case errors.Is(err, errUserLookupMiss) && a.cfg.DirectoryUsers:
// Never a local account next to the directory.
return nil, fmt.Errorf("%w: %s", ErrNotInDirectory, in.Email)
case errors.Is(err, errUserLookupMiss): case errors.Is(err, errUserLookupMiss):
userID, err = a.createUser(ctx, userCreate{ userID, err = a.createUser(ctx, userCreate{
Username: in.Email, Username: in.Email,
@@ -148,6 +153,10 @@ func (a *HTTPAdapter) InviteMember(ctx context.Context, in MemberInviteInput) (*
} }
_ = resp.Body.Close() _ = resp.Body.Close()
if a.cfg.DirectoryUsers {
// Signs in with the directory password: no set-password mail.
return &MemberInviteResult{UserID: userID, Status: InviteStatusAdded}, nil
}
res := &MemberInviteResult{UserID: userID, Status: InviteStatusInvited, Created: created} res := &MemberInviteResult{UserID: userID, Status: InviteStatusInvited, Created: created}
if _, merr := a.executeActionsEmail(ctx, userID, []string{"VERIFY_EMAIL", "UPDATE_PASSWORD"}, a.inviteRedirect(in.Slug)); merr != nil { if _, merr := a.executeActionsEmail(ctx, userID, []string{"VERIFY_EMAIL", "UPDATE_PASSWORD"}, a.inviteRedirect(in.Slug)); merr != nil {
res.MailError = merr res.MailError = merr
@@ -199,6 +208,9 @@ func (a *HTTPAdapter) ensureUserAttributes(ctx context.Context, userID string, a
} }
func (a *HTTPAdapter) ResendInvite(ctx context.Context, slug, email string) error { func (a *HTTPAdapter) ResendInvite(ctx context.Context, slug, email string) error {
if a.cfg.DirectoryUsers {
return ErrNoInviteMail
}
members, err := a.ListOrgMembers(ctx, slug) members, err := a.ListOrgMembers(ctx, slug)
if err != nil { if err != nil {
return err return err
+25
View File
@@ -32,6 +32,8 @@ type membersKC struct {
logouts []string // user ids logged out logouts []string // user ids logged out
deleted []string // user ids deleted deleted []string // user ids deleted
failWrite int // non-zero: member DELETE / logout answer this status failWrite int // non-zero: member DELETE / logout answer this status
orgsCreated []string // aliases of organizations created
ldapOnly bool // member list carries only LDAP attributes
} }
// orgName is the display name the registry gives an organization: the company // orgName is the display name the registry gives an organization: the company
@@ -100,6 +102,10 @@ func newMembersKC(t *testing.T) (*membersKC, *HTTPAdapter) {
if k.brief { if k.brief {
u.Attributes = nil u.Attributes = nil
} }
if k.ldapOnly {
// KC 26 for a federated user: only the LDAP attributes in the list.
u.Attributes = map[string][]string{"LDAP_ID": {"x"}}
}
out = append(out, u) out = append(out, u)
} }
_ = json.NewEncoder(w).Encode(out) _ = json.NewEncoder(w).Encode(out)
@@ -259,6 +265,25 @@ func newMembersKC(t *testing.T) (*membersKC, *HTTPAdapter) {
k.logouts = append(k.logouts, r.PathValue("id")) k.logouts = append(k.logouts, r.PathValue("id"))
w.WriteHeader(http.StatusNoContent) w.WriteHeader(http.StatusNoContent)
}) })
// Organization create (directory-mode admin path).
mux.HandleFunc("POST /admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) {
k.mu.Lock()
defer k.mu.Unlock()
var body struct {
Alias string `json:"alias"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
if _, taken := k.orgs[body.Alias]; taken {
w.WriteHeader(http.StatusConflict)
return
}
id := "org-" + body.Alias
k.orgs[body.Alias] = id
k.members[id] = []string{}
k.orgsCreated = append(k.orgsCreated, body.Alias)
w.Header().Set("Location", "http://kc/admin/realms/test-realm/organizations/"+id)
w.WriteHeader(http.StatusCreated)
})
srv := httptest.NewServer(mux) srv := httptest.NewServer(mux)
t.Cleanup(srv.Close) t.Cleanup(srv.Close)
a := NewHTTPAdapter(HTTPConfig{ a := NewHTTPAdapter(HTTPConfig{
+34
View File
@@ -37,6 +37,10 @@ type Mock struct {
Removed []string // every RemoveMember call, by user id Removed []string // every RemoveMember call, by user id
Deleted []string // accounts RemoveMember deleted Deleted []string // accounts RemoveMember deleted
LoggedOut []string // every LogoutUser call LoggedOut []string // every LogoutUser call
// Directory mode (on-prem): Users is the customer's directory. No user
// is created, no invitation mail is recorded.
Directory bool
} }
func NewMock() *Mock { func NewMock() *Mock {
@@ -207,6 +211,16 @@ func (m *Mock) InviteMember(_ context.Context, in MemberInviteInput) (*MemberInv
} }
} }
userID, created := m.Users[in.Email] userID, created := m.Users[in.Email]
if m.Directory {
if userID == "" {
return nil, ErrNotInDirectory
}
now := time.Now().UTC()
m.Members[in.Slug] = append(members, OrgMember{
UserID: userID, Email: in.Email, OrgRoles: []string{in.Role}, Enabled: true, CreatedAt: &now,
})
return &MemberInviteResult{UserID: userID, Status: InviteStatusAdded}, nil
}
if userID == "" { if userID == "" {
userID = "mock-user-" + in.Email userID = "mock-user-" + in.Email
m.Users[in.Email] = userID m.Users[in.Email] = userID
@@ -231,6 +245,9 @@ func (m *Mock) UserExists(_ context.Context, email string) (bool, error) {
func (m *Mock) ResendInvite(_ context.Context, slug, email string) error { func (m *Mock) ResendInvite(_ context.Context, slug, email string) error {
m.mu.Lock() m.mu.Lock()
defer m.mu.Unlock() defer m.mu.Unlock()
if m.Directory {
return ErrNoInviteMail
}
if m.FailNext != nil { if m.FailNext != nil {
err := m.FailNext err := m.FailNext
m.FailNext = nil m.FailNext = nil
@@ -277,6 +294,23 @@ func (m *Mock) CreateOrgAndInvite(_ context.Context, in InviteInput) (*InviteRes
if _, taken := m.Orgs[in.TenantID]; taken { if _, taken := m.Orgs[in.TenantID]; taken {
return nil, ErrOrgConflict return nil, ErrOrgConflict
} }
if m.Directory {
userID, ok := m.Users[in.AdminEmail]
if !ok {
return nil, ErrNotInDirectory
}
orgID := "mock-org-" + in.Slug
m.Orgs[in.TenantID] = orgID
now := time.Now().UTC()
if m.Members == nil {
m.Members = map[string][]OrgMember{}
}
m.Members[in.Slug] = append(m.Members[in.Slug], OrgMember{
UserID: userID, Email: in.AdminEmail, OrgRoles: []string{"IT_ADMIN"}, Enabled: true, CreatedAt: &now,
})
m.Created = append(m.Created, in)
return &InviteResult{OrganizationID: orgID, UserID: userID}, nil
}
if _, taken := m.Users[in.AdminEmail]; taken { if _, taken := m.Users[in.AdminEmail]; taken {
return nil, ErrUserConflict return nil, ErrUserConflict
} }
+123 -49
View File
@@ -50,57 +50,13 @@ func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (*
if in.AdminEmail == "" { if in.AdminEmail == "" {
return nil, fmt.Errorf("keycloak: admin email required") return nil, fmt.Errorf("keycloak: admin email required")
} }
if a.cfg.DirectoryUsers {
// 1. Create org with tenant_id baked in as an attribute so we can return a.attachDirectoryAdmin(ctx, in)
// 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) orgID, err := a.createOrg(ctx, in)
if err != nil { if err != nil {
return nil, err 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). // 2. Create the user (disabled until they set a password).
first, last := splitName(in.AdminName) first, last := splitName(in.AdminName)
@@ -118,10 +74,10 @@ func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (*
"tenant_id": {in.TenantID}, "tenant_id": {in.TenantID},
"tenant_slug": {in.Slug}, "tenant_slug": {in.Slug},
"org_roles": {"IT_ADMIN"}, "org_roles": {"IT_ADMIN"},
"tenant_status": {"trial"}, "tenant_status": {statusOr(in.TenantStatus, "trial")},
}, },
} }
resp, err = a.adminCall(ctx, http.MethodPost, "/users", userPayload, nil) resp, err := a.adminCall(ctx, http.MethodPost, "/users", userPayload, nil)
if err != nil { if err != nil {
return nil, fmt.Errorf("create user: %w", err) return nil, fmt.Errorf("create user: %w", err)
} }
@@ -176,6 +132,124 @@ func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (*
return &InviteResult{OrganizationID: orgID, UserID: userID, InviteURL: inviteURL}, 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.findUserByEmail(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 // SyncClaims pushes the up-to-date claim bundle into the user's KC
// attributes. Called by tenant-registry whenever entitlements change. // attributes. Called by tenant-registry whenever entitlements change.
func (a *HTTPAdapter) SyncClaims(ctx context.Context, userID string, c Claims) error { func (a *HTTPAdapter) SyncClaims(ctx context.Context, userID string, c Claims) error {
+14 -4
View File
@@ -56,7 +56,7 @@ func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) {
_, lerr := s.Keycloak.ListOrgMembers(ctx, t.Slug) _, lerr := s.Keycloak.ListOrgMembers(ctx, t.Slug)
switch { switch {
case errors.Is(lerr, keycloak.ErrOrgNotFound): case errors.Is(lerr, keycloak.ErrOrgNotFound):
res, err := s.Keycloak.CreateOrgAndInvite(ctx, keycloak.InviteInput{TenantID: t.ID, Slug: t.Slug, Name: t.Name, AdminEmail: email}) res, err := s.Keycloak.CreateOrgAndInvite(ctx, keycloak.InviteInput{TenantID: t.ID, Slug: t.Slug, Name: t.Name, AdminEmail: email, TenantStatus: t.Status})
if err != nil { if err != nil {
if errors.Is(err, keycloak.ErrUserConflict) { if errors.Is(err, keycloak.ErrUserConflict) {
writeError(w, http.StatusConflict, "email_taken", "an account with this e-mail exists outside this tenant") writeError(w, http.StatusConflict, "email_taken", "an account with this e-mail exists outside this tenant")
@@ -67,6 +67,8 @@ func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) {
} }
if res.MailError != nil { if res.MailError != nil {
outcome = "created_mail_failed" outcome = "created_mail_failed"
} else if s.onPrem() {
outcome = "added"
} }
case lerr != nil: case lerr != nil:
s.writeKeycloakError(w, t.ID, "reprovision", lerr) s.writeKeycloakError(w, t.ID, "reprovision", lerr)
@@ -77,14 +79,22 @@ func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) {
s.writeKeycloakError(w, t.ID, "reprovision", err) s.writeKeycloakError(w, t.ID, "reprovision", err)
return return
} }
if res.Status == keycloak.InviteStatusMember { switch {
if err := s.Keycloak.ResendInvite(ctx, t.Slug, email); err != nil { case res.Status == keycloak.InviteStatusAdded:
outcome = "added"
case res.Status == keycloak.InviteStatusMember:
err := s.Keycloak.ResendInvite(ctx, t.Slug, email)
switch {
case errors.Is(err, keycloak.ErrNoInviteMail):
outcome = "member" // a directory user: nothing to resend
case err != nil:
s.writeKeycloakError(w, t.ID, "reprovision", err) s.writeKeycloakError(w, t.ID, "reprovision", err)
return return
} default:
outcome = "resent" outcome = "resent"
} }
} }
}
if err := s.Keycloak.SyncTenantStatus(ctx, t.Slug, t.Status); err != nil { if err := s.Keycloak.SyncTenantStatus(ctx, t.Slug, t.Status); err != nil {
s.Log.Warn("keycloak status sync after reprovision failed", "tenant_id", t.ID, "err", err) s.Log.Warn("keycloak status sync after reprovision failed", "tenant_id", t.ID, "err", err)
} }
+14 -1
View File
@@ -190,13 +190,17 @@ func (s *Server) inviteTenantMember(w http.ResponseWriter, r *http.Request) {
return return
} }
action := "user.invited"
if res.Status == keycloak.InviteStatusAdded {
action = "user.added" // a directory user: no mail, signs in at once
}
meta := map[string]interface{}{"role": in.Role, "user_id": res.UserID, "user_created": res.Created} meta := map[string]interface{}{"role": in.Role, "user_id": res.UserID, "user_created": res.Created}
if res.MailError != nil { if res.MailError != nil {
s.Log.Warn("invite mail failed", "tenant_id", t.ID, "user_id", res.UserID, "err", res.MailError) s.Log.Warn("invite mail failed", "tenant_id", t.ID, "user_id", res.UserID, "err", res.MailError)
meta["mail_error"] = res.MailError.Error() meta["mail_error"] = res.MailError.Error()
} }
ev := store.AuditEvent{ ev := store.AuditEvent{
TenantID: t.ID, Action: "user.invited", TenantID: t.ID, Action: action,
TargetID: in.Email, TargetType: "user", TargetName: in.Email, TargetID: in.Email, TargetType: "user", TargetName: in.Email,
Metadata: meta, Metadata: meta,
} }
@@ -223,6 +227,15 @@ func (s *Server) inviteTenantMember(w http.ResponseWriter, r *http.Request) {
// writeKeycloakError maps adapter failures: unreachable/unauthorized are a // writeKeycloakError maps adapter failures: unreachable/unauthorized are a
// 503 (the portal shows "identity provider unavailable"), anything else 502. // 503 (the portal shows "identity provider unavailable"), anything else 502.
func (s *Server) writeKeycloakError(w http.ResponseWriter, tenantID, op string, err error) { func (s *Server) writeKeycloakError(w http.ResponseWriter, tenantID, op string, err error) {
// Directory mode (on-prem): answers, not failures.
switch {
case errors.Is(err, keycloak.ErrNotInDirectory):
writeError(w, http.StatusNotFound, "not_in_directory", "no directory account with this e-mail in the groups that may use the platform")
return
case errors.Is(err, keycloak.ErrNoInviteMail):
writeError(w, http.StatusConflict, "no_invite_mail", "directory users sign in with their directory password; there is no invitation to resend")
return
}
s.Log.Error("keycloak "+op+" failed", "tenant_id", tenantID, "err", err) s.Log.Error("keycloak "+op+" failed", "tenant_id", tenantID, "err", err)
if errors.Is(err, keycloak.ErrUnavailable) || errors.Is(err, keycloak.ErrUnauthorized) { if errors.Is(err, keycloak.ErrUnavailable) || errors.Is(err, keycloak.ErrUnauthorized) {
writeError(w, http.StatusServiceUnavailable, "keycloak_unavailable", err.Error()) writeError(w, http.StatusServiceUnavailable, "keycloak_unavailable", err.Error())
+74
View File
@@ -19,6 +19,11 @@ import (
// Werkmeister ship (Werkmeister's row is disabled in the seed), with local URLs. // Werkmeister ship (Werkmeister's row is disabled in the seed), with local URLs.
func onPremHarness(h *testHarness, provision map[string]string) { func onPremHarness(h *testHarness, provision map[string]string) {
h.app.Cfg = &config.Config{Env: config.EnvOnPrem, LicenceTTLDays: 30} h.app.Cfg = &config.Config{Env: config.EnvOnPrem, LicenceTTLDays: 30}
// The adapter runs in directory mode on-prem (main.go: DirectoryUsers);
// the mock's Users are then the customer's directory.
h.kcMock.Directory = true
h.kcMock.Users["anna.admin@onprem.test"] = "u-anna"
h.kcMock.Users["ben.user@onprem.test"] = "u-ben"
h.app.Store = store.WithProductOverrides(h.store, h.app.Cfg.CatalogEnv(), h.app.Store = store.WithProductOverrides(h.store, h.app.Cfg.CatalogEnv(),
[]string{"pruefwerk", "werkmeister"}, []string{"pruefwerk", "werkmeister"},
map[string]string{"pruefwerk": "https://pruefwerk.onprem.test", "werkmeister": "https://werkmeister.onprem.test"}, map[string]string{"pruefwerk": "https://pruefwerk.onprem.test", "werkmeister": "https://werkmeister.onprem.test"},
@@ -290,3 +295,72 @@ func TestOnPrem_catalogOffersNoTrials(t *testing.T) {
} }
}) })
} }
func TestOnPrem_workspaceAdminIsTheDirectoryUser(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
onPremHarness(h, nil)
resp, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "werk", "name": "Werk GmbH", "admin_email": "Anna.Admin@onprem.test"})
if resp.StatusCode != http.StatusCreated {
t.Fatalf("create = %d %s", resp.StatusCode, body)
}
out := decode[createResp](t, body)
if out.InviteURL != "" {
t.Errorf("invite URL on-prem: %s", out.InviteURL)
}
members := h.kcMock.Members["werk"]
if len(members) != 1 || members[0].UserID != "u-anna" || members[0].OrgRoles[0] != "IT_ADMIN" {
t.Errorf("members = %+v", members)
}
if n := auditCount(t, h, "action=keycloak.admin_added&tenant_id="+out.Tenant.ID); n != 1 {
t.Errorf("admin_added audits = %d", n)
}
if n := auditCount(t, h, "action=keycloak.invite_sent&tenant_id="+out.Tenant.ID); n != 0 {
t.Errorf("invite_sent audits = %d", n)
}
})
}
func TestOnPrem_unknownAdminCreatesNoWorkspace(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
onPremHarness(h, nil)
resp, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "werk", "name": "Werk GmbH", "admin_email": "ghost@onprem.test"})
if resp.StatusCode != http.StatusNotFound || !strings.Contains(string(body), "not_in_directory") {
t.Fatalf("create = %d %s, want 404 not_in_directory", resp.StatusCode, body)
}
if resp, _ := h.do("GET", "/v1/tenants/by-slug/werk", nil); resp.StatusCode != http.StatusNotFound {
t.Errorf("workspace left behind: %d", resp.StatusCode)
}
})
}
func TestOnPrem_membersAreAddedFromTheDirectory(t *testing.T) {
eachStore(t, func(t *testing.T, h *testHarness) {
onPremHarness(h, nil)
_, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "werk", "name": "Werk GmbH", "admin_email": "anna.admin@onprem.test"})
ws := decode[createResp](t, body).Tenant
resp, body := h.do("POST", "/v1/tenants/"+ws.ID+"/invites", map[string]any{"email": "ben.user@onprem.test", "role": "USER"})
if resp.StatusCode != http.StatusAccepted || !strings.Contains(string(body), `"status":"added"`) {
t.Fatalf("invite = %d %s, want 202 added", resp.StatusCode, body)
}
if len(h.kcMock.Invites) != 0 {
t.Errorf("invitation mails recorded: %+v", h.kcMock.Invites)
}
if n := auditCount(t, h, "action=user.added&tenant_id="+ws.ID); n != 1 {
t.Errorf("user.added audits = %d", n)
}
resp, body = h.do("POST", "/v1/tenants/"+ws.ID+"/invites", map[string]any{"email": "ghost@onprem.test", "role": "USER"})
if resp.StatusCode != http.StatusNotFound || !strings.Contains(string(body), "not_in_directory") {
t.Errorf("unknown member = %d %s, want 404 not_in_directory", resp.StatusCode, body)
}
resp, body = h.do("POST", "/v1/admin/tenants/"+ws.ID+"/invites/resend", map[string]any{"email": "ben.user@onprem.test"})
if resp.StatusCode != http.StatusConflict || !strings.Contains(string(body), "no_invite_mail") {
t.Errorf("resend = %d %s, want 409 no_invite_mail", resp.StatusCode, body)
}
})
}
type createResp struct {
Tenant *store.Tenant `json:"tenant"`
InviteURL string `json:"invite_url"`
}
+21 -1
View File
@@ -104,11 +104,24 @@ type apiError struct {
// and the ERP customer (each best effort, audited). Shared by POST // and the ERP customer (each best effort, audited). Shared by POST
// /v1/tenants and the trial activation. // /v1/tenants and the trial activation.
func (s *Server) createTenantCore(ctx context.Context, r *http.Request, in createTenantReq) (*store.Tenant, kcInvite, *apiError) { func (s *Server) createTenantCore(ctx context.Context, r *http.Request, in createTenantReq) (*store.Tenant, kcInvite, *apiError) {
// One spelling of the address for the lookup, the store and Keycloak.
in.AdminEmail = strings.ToLower(strings.TrimSpace(in.AdminEmail))
// An address with an account already belongs to a workspace (or to // An address with an account already belongs to a workspace (or to
// staff): reject before anything is created, so no admin-less tenant and // staff): reject before anything is created, so no admin-less tenant and
// no orphan organization are left behind. A lookup failure falls through // no orphan organization are left behind. A lookup failure falls through
// to the best-effort provisioning below. // to the best-effort provisioning below.
if email := strings.ToLower(strings.TrimSpace(in.AdminEmail)); email != "" && s.Keycloak != nil { if email := strings.ToLower(strings.TrimSpace(in.AdminEmail)); email != "" && s.Keycloak != nil && s.onPrem() {
// On-prem the admin is an existing directory user (the realm's AD
// federation finds them by e-mail); a wrong address must not leave a
// workspace without an admin behind.
exists, err := s.Keycloak.UserExists(ctx, email)
if err != nil {
return nil, kcInvite{}, &apiError{http.StatusServiceUnavailable, "keycloak_unavailable", "directory lookup failed"}
}
if !exists {
return nil, kcInvite{}, &apiError{http.StatusNotFound, "not_in_directory", "no directory account with this e-mail in the groups that may use the platform"}
}
} else if email != "" && s.Keycloak != nil {
if taken, err := s.Keycloak.UserExists(ctx, email); err == nil && taken { if taken, err := s.Keycloak.UserExists(ctx, email); err == nil && taken {
return nil, kcInvite{}, &apiError{http.StatusConflict, "email_taken", "an account with this email already exists"} return nil, kcInvite{}, &apiError{http.StatusConflict, "email_taken", "an account with this email already exists"}
} else if err != nil { } else if err != nil {
@@ -152,6 +165,7 @@ func (s *Server) createTenantCore(ctx context.Context, r *http.Request, in creat
// tenant back — the operator can resend the invite via the KC admin UI. // tenant back — the operator can resend the invite via the KC admin UI.
// We emit an audit event regardless so the failure is traceable. // We emit an audit event regardless so the failure is traceable.
invite, kcErr := s.provisionKeycloak(ctx, t, keycloak.InviteInput{ invite, kcErr := s.provisionKeycloak(ctx, t, keycloak.InviteInput{
TenantStatus: t.Status,
AdminEmail: in.AdminEmail, AdminName: in.AdminName, AdminEmail: in.AdminEmail, AdminName: in.AdminName,
AdminFirst: in.adminFirst, AdminLast: in.adminLast, EmailVerified: in.emailVerified, AdminFirst: in.adminFirst, AdminLast: in.adminLast, EmailVerified: in.emailVerified,
}) })
@@ -167,6 +181,12 @@ func (s *Server) createTenantCore(ctx context.Context, r *http.Request, in creat
TargetID: in.AdminEmail, TargetType: "user", TargetName: in.AdminEmail, TargetID: in.AdminEmail, TargetType: "user", TargetName: in.AdminEmail,
Metadata: map[string]interface{}{"err": invite.MailErr.Error()}, Metadata: map[string]interface{}{"err": invite.MailErr.Error()},
}) })
} else if in.AdminEmail != "" && s.onPrem() {
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "keycloak.admin_added",
TargetID: in.AdminEmail, TargetType: "user", TargetName: in.AdminEmail,
Metadata: map[string]interface{}{"role": "IT_ADMIN", "directory": true},
})
} else if in.AdminEmail != "" { } else if in.AdminEmail != "" {
s.emitAudit(ctx, r, store.AuditEvent{ s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "keycloak.invite_sent", TenantID: t.ID, Action: "keycloak.invite_sent",
+8 -1
View File
@@ -27,6 +27,13 @@ info:
PRODUCT_LAUNCH_URLS / PRODUCT_PROVISION_URLS. The trial-offer, trial-terms, PRODUCT_LAUNCH_URLS / PRODUCT_PROVISION_URLS. The trial-offer, trial-terms,
catalog request, trial request, admin trial and ERP webhook routes answer catalog request, trial request, admin trial and ERP webhook routes answer
404 `not_available`. 404 `not_available`.
On-prem every account comes from the customer's directory (Keycloak's AD
federation). Creating a workspace with `admin_email` and inviting a member
attach the existing directory user (no local account, no set-password
mail; invite status `added`). An address with no directory account in the
admitted groups answers 404 `not_in_directory`; resending an invitation
answers 409 `no_invite_mail`.
contact: contact:
email: oncall@breakpilot.com email: oncall@breakpilot.com
license: license:
@@ -3366,7 +3373,7 @@ components:
properties: properties:
user_id: { type: string } user_id: { type: string }
email: { type: string, format: email } email: { type: string, format: email }
status: { type: string, enum: [invited, member] } status: { type: string, enum: [invited, member, added], description: "added: on-prem, an existing directory user joined; no mail" }
TenantCreate: TenantCreate:
type: object type: object