From b8206c553fe0ed4b6245600d2bdbd0f91b35b3d1 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:18:22 +0100 Subject: [PATCH 1/3] 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 --- README.md | 1 + cmd/server/main.go | 2 + internal/keycloak/adapter.go | 10 ++ internal/keycloak/client.go | 7 ++ internal/keycloak/directory_test.go | 112 ++++++++++++++++++ internal/keycloak/members.go | 18 ++- internal/keycloak/members_test.go | 57 ++++++--- internal/keycloak/mock.go | 34 ++++++ internal/keycloak/orgs.go | 172 ++++++++++++++++++++-------- internal/server/admin_lifecycle.go | 18 ++- internal/server/members.go | 15 ++- internal/server/onprem_test.go | 74 ++++++++++++ internal/server/tenants.go | 24 +++- openapi.yaml | 9 +- 14 files changed, 477 insertions(+), 76 deletions(-) create mode 100644 internal/keycloak/directory_test.go diff --git a/README.md b/README.md index fc6d47f..4704b1b 100644 --- a/README.md +++ b/README.md @@ -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 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. +- 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. ## ERP link (M-MIG-7) diff --git a/cmd/server/main.go b/cmd/server/main.go index bf54457..5cb66d0 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -110,6 +110,8 @@ func main() { InviteClientID: cfg.InviteClientID, InviteRedirectURI: cfg.InviteRedirectURI, + // On-prem every account comes from the customer's directory. + DirectoryUsers: cfg.OnPrem(), }) slog.Info("keycloak adapter configured", "url", cfg.KeycloakAdminURL, "realm", cfg.KeycloakRealm, "client_id", cfg.KeycloakClientID) diff --git a/internal/keycloak/adapter.go b/internal/keycloak/adapter.go index b8efcd2..ed3e65f 100644 --- a/internal/keycloak/adapter.go +++ b/internal/keycloak/adapter.go @@ -28,6 +28,12 @@ var ( ErrUnavailable = errors.New("keycloak: unreachable") ErrUserNotFound = errors.New("keycloak: user 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. @@ -47,6 +53,9 @@ type InviteInput struct { // the invitation only asks to set a password; otherwise Keycloak would // demand a second e-mail confirmation. 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 @@ -128,6 +137,7 @@ type MemberInviteInput struct { const ( InviteStatusInvited = "invited" // user added to the org; execute-actions mail sent 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. diff --git a/internal/keycloak/client.go b/internal/keycloak/client.go index 42d4cae..9ee408d 100644 --- a/internal/keycloak/client.go +++ b/internal/keycloak/client.go @@ -44,6 +44,13 @@ type HTTPConfig struct { // portal forwards to //dashboard; Keycloak only allows /start*). InviteClientID 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 { diff --git a/internal/keycloak/directory_test.go b/internal/keycloak/directory_test.go new file mode 100644 index 0000000..a8af6e7 --- /dev/null +++ b/internal/keycloak/directory_test.go @@ -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) + } +} diff --git a/internal/keycloak/members.go b/internal/keycloak/members.go index 30856b8..81b32ae 100644 --- a/internal/keycloak/members.go +++ b/internal/keycloak/members.go @@ -67,8 +67,9 @@ func (a *HTTPAdapter) ListOrgMembers(ctx context.Context, slug string) ([]OrgMem } out := make([]OrgMember, 0, len(members)) for _, m := range members { - if m.Attributes == nil { - // Brief representation: attributes (org_roles) live on the user. + if m.Attributes == nil || len(attrValues(m.Attributes, "org_roles")) == 0 { + // Brief representation, or a federated (AD) user, whose list entry + // carries only the LDAP attributes: org_roles live on the user. var u memberRepresentation resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+m.ID, nil, &u) 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.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) } 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 { 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): userID, err = a.createUser(ctx, userCreate{ Username: in.Email, @@ -148,6 +153,10 @@ func (a *HTTPAdapter) InviteMember(ctx context.Context, in MemberInviteInput) (* } _ = 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} if _, merr := a.executeActionsEmail(ctx, userID, []string{"VERIFY_EMAIL", "UPDATE_PASSWORD"}, a.inviteRedirect(in.Slug)); merr != nil { 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 { + if a.cfg.DirectoryUsers { + return ErrNoInviteMail + } members, err := a.ListOrgMembers(ctx, slug) if err != nil { return err diff --git a/internal/keycloak/members_test.go b/internal/keycloak/members_test.go index c9dec4d..ab34f7a 100644 --- a/internal/keycloak/members_test.go +++ b/internal/keycloak/members_test.go @@ -16,22 +16,24 @@ import ( // org lookup by alias, member list, user search/create/get/put, member add // (bare-id body, 409 when already a member) and execute-actions e-mail. type membersKC struct { - mu sync.Mutex - orgs map[string]string // alias → org id - members map[string][]string // org id → user ids - users map[string]memberRepresentation // user id → user - brief bool // member list omits attributes - mails []string // user ids that got the execute-actions mail - redirects []string // redirect_uri of each execute-actions mail - created []userCreate - puts map[string]map[string][]string // user id → attributes PUT - createErr int // non-zero: POST /users answers this status - nextID int - creds map[string][]string // user id → credential types - idp map[string]bool // user id → linked to an identity provider - logouts []string // user ids logged out - deleted []string // user ids deleted - failWrite int // non-zero: member DELETE / logout answer this status + mu sync.Mutex + orgs map[string]string // alias → org id + members map[string][]string // org id → user ids + users map[string]memberRepresentation // user id → user + brief bool // member list omits attributes + mails []string // user ids that got the execute-actions mail + redirects []string // redirect_uri of each execute-actions mail + created []userCreate + puts map[string]map[string][]string // user id → attributes PUT + createErr int // non-zero: POST /users answers this status + nextID int + creds map[string][]string // user id → credential types + idp map[string]bool // user id → linked to an identity provider + logouts []string // user ids logged out + deleted []string // user ids deleted + 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 @@ -100,6 +102,10 @@ func newMembersKC(t *testing.T) (*membersKC, *HTTPAdapter) { if k.brief { 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) } _ = json.NewEncoder(w).Encode(out) @@ -259,6 +265,25 @@ func newMembersKC(t *testing.T) (*membersKC, *HTTPAdapter) { k.logouts = append(k.logouts, r.PathValue("id")) 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) t.Cleanup(srv.Close) a := NewHTTPAdapter(HTTPConfig{ diff --git a/internal/keycloak/mock.go b/internal/keycloak/mock.go index d7be0ee..085314b 100644 --- a/internal/keycloak/mock.go +++ b/internal/keycloak/mock.go @@ -37,6 +37,10 @@ type Mock struct { Removed []string // every RemoveMember call, by user id Deleted []string // accounts RemoveMember deleted 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 { @@ -207,6 +211,16 @@ func (m *Mock) InviteMember(_ context.Context, in MemberInviteInput) (*MemberInv } } 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 == "" { userID = "mock-user-" + in.Email 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 { m.mu.Lock() defer m.mu.Unlock() + if m.Directory { + return ErrNoInviteMail + } if m.FailNext != nil { err := m.FailNext m.FailNext = nil @@ -277,6 +294,23 @@ func (m *Mock) CreateOrgAndInvite(_ context.Context, in InviteInput) (*InviteRes if _, taken := m.Orgs[in.TenantID]; taken { 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 { return nil, ErrUserConflict } diff --git a/internal/keycloak/orgs.go b/internal/keycloak/orgs.go index 70b46f9..fe396c1 100644 --- a/internal/keycloak/orgs.go +++ b/internal/keycloak/orgs.go @@ -50,57 +50,13 @@ func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (* 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}, - }, + if a.cfg.DirectoryUsers { + return a.attachDirectoryAdmin(ctx, in) } - resp, err := a.adminCall(ctx, http.MethodPost, "/organizations", orgPayload, nil) + orgID, err := a.createOrg(ctx, in) 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) @@ -118,10 +74,10 @@ func (a *HTTPAdapter) CreateOrgAndInvite(ctx context.Context, in InviteInput) (* "tenant_id": {in.TenantID}, "tenant_slug": {in.Slug}, "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 { 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 } +// 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 // attributes. Called by tenant-registry whenever entitlements change. func (a *HTTPAdapter) SyncClaims(ctx context.Context, userID string, c Claims) error { diff --git a/internal/server/admin_lifecycle.go b/internal/server/admin_lifecycle.go index 4a809a7..a4bcf71 100644 --- a/internal/server/admin_lifecycle.go +++ b/internal/server/admin_lifecycle.go @@ -56,7 +56,7 @@ func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) { _, lerr := s.Keycloak.ListOrgMembers(ctx, t.Slug) switch { 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 errors.Is(err, keycloak.ErrUserConflict) { 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 { outcome = "created_mail_failed" + } else if s.onPrem() { + outcome = "added" } case lerr != nil: s.writeKeycloakError(w, t.ID, "reprovision", lerr) @@ -77,12 +79,20 @@ func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) { s.writeKeycloakError(w, t.ID, "reprovision", err) return } - if res.Status == keycloak.InviteStatusMember { - if err := s.Keycloak.ResendInvite(ctx, t.Slug, email); err != nil { + switch { + 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) return + default: + outcome = "resent" } - outcome = "resent" } } if err := s.Keycloak.SyncTenantStatus(ctx, t.Slug, t.Status); err != nil { diff --git a/internal/server/members.go b/internal/server/members.go index 4029924..07d3c3b 100644 --- a/internal/server/members.go +++ b/internal/server/members.go @@ -186,13 +186,17 @@ func (s *Server) inviteTenantMember(w http.ResponseWriter, r *http.Request) { 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} if res.MailError != nil { s.Log.Warn("invite mail failed", "tenant_id", t.ID, "user_id", res.UserID, "err", res.MailError) meta["mail_error"] = res.MailError.Error() } ev := store.AuditEvent{ - TenantID: t.ID, Action: "user.invited", + TenantID: t.ID, Action: action, TargetID: in.Email, TargetType: "user", TargetName: in.Email, Metadata: meta, } @@ -219,6 +223,15 @@ func (s *Server) inviteTenantMember(w http.ResponseWriter, r *http.Request) { // writeKeycloakError maps adapter failures: unreachable/unauthorized are a // 503 (the portal shows "identity provider unavailable"), anything else 502. 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) if errors.Is(err, keycloak.ErrUnavailable) || errors.Is(err, keycloak.ErrUnauthorized) { writeError(w, http.StatusServiceUnavailable, "keycloak_unavailable", err.Error()) diff --git a/internal/server/onprem_test.go b/internal/server/onprem_test.go index 5741834..207fa99 100644 --- a/internal/server/onprem_test.go +++ b/internal/server/onprem_test.go @@ -19,6 +19,11 @@ import ( // Werkmeister ship (Werkmeister's row is disabled in the seed), with local URLs. func onPremHarness(h *testHarness, provision map[string]string) { 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(), []string{"pruefwerk", "werkmeister"}, 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"` +} diff --git a/internal/server/tenants.go b/internal/server/tenants.go index 8ebdf4c..30ae5d1 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -104,11 +104,24 @@ type apiError struct { // and the ERP customer (each best effort, audited). Shared by POST // /v1/tenants and the trial activation. 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 // staff): reject before anything is created, so no admin-less tenant and // no orphan organization are left behind. A lookup failure falls through // 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 { return nil, kcInvite{}, &apiError{http.StatusConflict, "email_taken", "an account with this email already exists"} } else if err != nil { @@ -152,7 +165,8 @@ 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. // We emit an audit event regardless so the failure is traceable. invite, kcErr := s.provisionKeycloak(ctx, t, keycloak.InviteInput{ - AdminEmail: in.AdminEmail, AdminName: in.AdminName, + TenantStatus: t.Status, + AdminEmail: in.AdminEmail, AdminName: in.AdminName, AdminFirst: in.adminFirst, AdminLast: in.adminLast, EmailVerified: in.emailVerified, }) if kcErr != nil { @@ -167,6 +181,12 @@ func (s *Server) createTenantCore(ctx context.Context, r *http.Request, in creat TargetID: in.AdminEmail, TargetType: "user", TargetName: in.AdminEmail, 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 != "" { s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "keycloak.invite_sent", diff --git a/openapi.yaml b/openapi.yaml index 57e9bb9..13569e4 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -27,6 +27,13 @@ info: PRODUCT_LAUNCH_URLS / PRODUCT_PROVISION_URLS. The trial-offer, trial-terms, catalog request, trial request, admin trial and ERP webhook routes answer 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: email: oncall@breakpilot.com license: @@ -3169,7 +3176,7 @@ components: properties: user_id: { type: string } 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: type: object -- 2.54.1 From d8cb363d5c98eb802207a327e0a411642b5162f4 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:24:55 +0100 Subject: [PATCH 2/3] fix(onprem): the cloud admin keeps tenant_status trial Only on-prem passes the workspace's status to Keycloak for its first admin; a cloud demo workspace with an admin wrote demo instead of trial (pinned by a test). Co-Authored-By: Claude Opus 5.5 --- internal/server/admin_lifecycle.go | 2 +- internal/server/keycloak.go | 10 ++++++++++ internal/server/onprem_test.go | 20 ++++++++++++++++++++ internal/server/tenants.go | 2 +- 4 files changed, 32 insertions(+), 2 deletions(-) diff --git a/internal/server/admin_lifecycle.go b/internal/server/admin_lifecycle.go index a4bcf71..49cb887 100644 --- a/internal/server/admin_lifecycle.go +++ b/internal/server/admin_lifecycle.go @@ -56,7 +56,7 @@ func (s *Server) adminReprovision(w http.ResponseWriter, r *http.Request) { _, lerr := s.Keycloak.ListOrgMembers(ctx, t.Slug) switch { 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, TenantStatus: t.Status}) + res, err := s.Keycloak.CreateOrgAndInvite(ctx, keycloak.InviteInput{TenantID: t.ID, Slug: t.Slug, Name: t.Name, AdminEmail: email, TenantStatus: s.onPremStatus(t)}) if err != nil { if errors.Is(err, keycloak.ErrUserConflict) { writeError(w, http.StatusConflict, "email_taken", "an account with this e-mail exists outside this tenant") diff --git a/internal/server/keycloak.go b/internal/server/keycloak.go index 08fb5f6..09bb758 100644 --- a/internal/server/keycloak.go +++ b/internal/server/keycloak.go @@ -24,6 +24,16 @@ type kcInvite struct { MailErr error } +// onPremStatus is the tenant_status a new workspace admin gets in Keycloak: +// the workspace's own on-prem; empty in the cloud, where the adapter keeps +// writing "trial" as before. +func (s *Server) onPremStatus(t *store.Tenant) string { + if s.onPrem() { + return t.Status + } + return "" +} + func (s *Server) provisionKeycloak(ctx context.Context, t *store.Tenant, in keycloak.InviteInput) (kcInvite, error) { if in.AdminEmail == "" { // Skip silently — caller chose not to invite anyone yet (sales-led diff --git a/internal/server/onprem_test.go b/internal/server/onprem_test.go index 207fa99..aad3e9d 100644 --- a/internal/server/onprem_test.go +++ b/internal/server/onprem_test.go @@ -364,3 +364,23 @@ type createResp struct { Tenant *store.Tenant `json:"tenant"` InviteURL string `json:"invite_url"` } + +// The cloud admin keeps the adapter's default tenant_status ("trial"); only +// on-prem passes the workspace's own. +func TestTenantStatusForTheAdminOnlyOnPrem(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + if resp, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "cloud-demo", "name": "Demo", "kind": "demo", "admin_email": "demo@cloud.test"}); resp.StatusCode != http.StatusCreated { + t.Fatalf("cloud create = %d %s", resp.StatusCode, body) + } + if c := h.kcMock.Created; len(c) != 1 || c[0].TenantStatus != "" { + t.Fatalf("cloud: %+v", c) + } + onPremHarness(h, nil) + if resp, body := h.do("POST", "/v1/tenants", map[string]any{"slug": "werk", "name": "Werk", "admin_email": "anna.admin@onprem.test"}); resp.StatusCode != http.StatusCreated { + t.Fatalf("on-prem create = %d %s", resp.StatusCode, body) + } + if c := h.kcMock.Created; len(c) != 2 || c[1].TenantStatus != store.StatusActive { + t.Errorf("on-prem: %+v", c) + } + }) +} diff --git a/internal/server/tenants.go b/internal/server/tenants.go index 30ae5d1..41fd8c0 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -165,7 +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. // We emit an audit event regardless so the failure is traceable. invite, kcErr := s.provisionKeycloak(ctx, t, keycloak.InviteInput{ - TenantStatus: t.Status, + TenantStatus: s.onPremStatus(t), AdminEmail: in.AdminEmail, AdminName: in.AdminName, AdminFirst: in.adminFirst, AdminLast: in.adminLast, EmailVerified: in.emailVerified, }) -- 2.54.1 From 1b821baa7bc5ec4113855190c6ffed4d2c1102cb Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:00:45 +0100 Subject: [PATCH 3/3] fix(onprem): only directory users join a workspace 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 --- internal/keycloak/directory_test.go | 28 +++++++++++++++++++ internal/keycloak/members.go | 5 +++- internal/keycloak/orgs.go | 42 +++++++++++++++++++++++------ 3 files changed, 66 insertions(+), 9 deletions(-) diff --git a/internal/keycloak/directory_test.go b/internal/keycloak/directory_test.go index a8af6e7..ab4ebf1 100644 --- a/internal/keycloak/directory_test.go +++ b/internal/keycloak/directory_test.go @@ -12,9 +12,37 @@ func newDirectoryKC(t *testing.T) (*membersKC, *HTTPAdapter) { t.Helper() k, a := newMembersKC(t) a.cfg.DirectoryUsers = true + // The test users come from the directory (the AD federation), as on an installation. + for id, u := range k.users { + u.FederationLink = "ldap-ad" + k.users[id] = u + } return k, a } +// A local account (our staff on an installation) is no directory user: neither the first +// admin of a workspace nor a member, whatever its address. +func TestDirectory_localAccountIsNotADirectoryUser(t *testing.T) { + k, a := newDirectoryKC(t) + k.users["u-staff"] = memberRepresentation{ID: "u-staff", Username: "bp-support", Email: "support@staff.test", Enabled: true} + if _, err := a.CreateOrgAndInvite(context.Background(), InviteInput{TenantID: "t-9", Slug: "staffws", Name: "S", AdminEmail: "support@staff.test"}); !errors.Is(err, ErrNotInDirectory) { + t.Errorf("staff as workspace admin: %v, want ErrNotInDirectory", err) + } + if _, err := a.InviteMember(context.Background(), MemberInviteInput{TenantID: "t-1", Slug: "acme", Email: "support@staff.test", Role: "USER"}); !errors.Is(err, ErrNotInDirectory) { + t.Errorf("staff as member: %v, want ErrNotInDirectory", err) + } + if len(k.orgsCreated) != 0 || len(k.puts["u-staff"]) != 0 { + t.Errorf("orgs %v, attributes written %v", k.orgsCreated, k.puts["u-staff"]) + } + for org, ids := range k.members { + for _, id := range ids { + if id == "u-staff" { + t.Errorf("staff joined %s", org) + } + } + } +} + func TestDirectory_adminIsAttachedWithoutMail(t *testing.T) { k, a := newDirectoryKC(t) res, err := a.CreateOrgAndInvite(context.Background(), InviteInput{ diff --git a/internal/keycloak/members.go b/internal/keycloak/members.go index 81b32ae..b07e8fc 100644 --- a/internal/keycloak/members.go +++ b/internal/keycloak/members.go @@ -24,6 +24,9 @@ type memberRepresentation struct { Enabled bool `json:"enabled"` CreatedTimestamp int64 `json:"createdTimestamp"` // epoch millis Attributes map[string][]string `json:"attributes"` + // FederationLink names the user storage (the AD federation) a user comes from; empty for a + // local account. + FederationLink string `json:"federationLink,omitempty"` } func (m memberRepresentation) toOrgMember() OrgMember { @@ -107,7 +110,7 @@ func (a *HTTPAdapter) InviteMember(ctx context.Context, in MemberInviteInput) (* "tenant_status": {in.TenantStatus}, } created := false - userID, err := a.findUserByEmail(ctx, in.Email) + userID, err := a.findMemberUser(ctx, in.Email) switch { case err == nil: // Existing user (possibly created by an earlier, half-failed invite): diff --git a/internal/keycloak/orgs.go b/internal/keycloak/orgs.go index fe396c1..2f46c98 100644 --- a/internal/keycloak/orgs.go +++ b/internal/keycloak/orgs.go @@ -193,7 +193,7 @@ func (a *HTTPAdapter) createOrg(ctx context.Context, in InviteInput) (string, er // 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) + userID, err := a.findDirectoryUserByEmail(ctx, in.AdminEmail) if errors.Is(err, errUserLookupMiss) { return nil, fmt.Errorf("%w: %s", ErrNotInDirectory, in.AdminEmail) } @@ -346,28 +346,54 @@ func (a *HTTPAdapter) UserExists(ctx context.Context, email string) (bool, error } 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 "", err + return "", false, err } defer func() { _ = resp.Body.Close() }() if resp.StatusCode/100 != 2 { - return "", fmt.Errorf("find user: %d", resp.StatusCode) + return "", false, fmt.Errorf("find user: %d", resp.StatusCode) } var users []struct { - ID string `json:"id"` - Email string `json:"email"` + ID string `json:"id"` + Email string `json:"email"` + FederationLink string `json:"federationLink"` } if err := json.NewDecoder(resp.Body).Decode(&users); err != nil { - return "", err + return "", false, err } for _, u := range users { if strings.EqualFold(u.Email, email) { - return u.ID, nil + return u.ID, u.FederationLink != "", nil } } - return "", errUserLookupMiss + return "", false, errUserLookupMiss } // inviteRedirect is the configured invite redirect with "{slug}" replaced by -- 2.54.1