From 9f393b728ff683f4975fbf807b0b1b0be08bb189 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Sat, 12 Sep 2026 20:59:32 +0200 Subject: [PATCH] feat(members): tenant organization members, invites, admin email The portal's Settings/Users page showed design fixtures because the registry had no membership surface. Two endpoints close that: - GET /v1/tenants/{id}/members lists the Keycloak organization members (user id, email, name, org_roles, enabled). A tenant without an organization answers an empty list, not an error. - POST /v1/tenants/{id}/invites creates the user if needed, adds the org member (KC 26: bare user id body), writes the tenant-context attributes, sends the execute-actions mail and audits user.invited. Idempotent: an existing member answers 200 with status=member. User tokens are confined to their own tenant (cross-tenant is a 404) and need IT_ADMIN or OWNER to invite; service clients are gated per route group as before. Principal gains the org_roles claim for that check. Tenants carry admin_email (migration 0006, backfilled from the invite audit trail) so Settings can show a real contact instead of an em dash. The members route is registered as GET /v1/tenants/{id}/{sub}: ServeMux rejects /v1/tenants/{id}/members as conflicting with the by-slug lookup, because both match /v1/tenants/by-slug/members and neither pattern is more specific. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB --- internal/authn/authn.go | 63 +++++- internal/authn/authn_test.go | 30 +++ internal/keycloak/adapter.go | 58 +++++ internal/keycloak/members.go | 218 +++++++++++++++++++ internal/keycloak/members_test.go | 299 ++++++++++++++++++++++++++ internal/keycloak/mock.go | 65 +++++- internal/keycloak/orgs.go | 13 +- internal/keycloak/status_test.go | 3 +- internal/server/members.go | 203 +++++++++++++++++ internal/server/members_scope_test.go | 136 ++++++++++++ internal/server/members_test.go | 225 +++++++++++++++++++ internal/server/openapi_test.go | 2 + internal/server/server.go | 11 + internal/server/server_test.go | 19 ++ internal/server/tenants.go | 1 + internal/store/memory.go | 4 + internal/store/postgres.go | 20 +- internal/store/store.go | 2 + internal/store/types.go | 4 + migrations/0006_admin_email.down.sql | 1 + migrations/0006_admin_email.up.sql | 37 ++++ openapi.yaml | 99 +++++++++ 22 files changed, 1495 insertions(+), 18 deletions(-) create mode 100644 internal/keycloak/members.go create mode 100644 internal/keycloak/members_test.go create mode 100644 internal/server/members.go create mode 100644 internal/server/members_scope_test.go create mode 100644 internal/server/members_test.go create mode 100644 migrations/0006_admin_email.down.sql create mode 100644 migrations/0006_admin_email.up.sql diff --git a/internal/authn/authn.go b/internal/authn/authn.go index 124a7f5..3794616 100644 --- a/internal/authn/authn.go +++ b/internal/authn/authn.go @@ -11,6 +11,7 @@ package authn import ( "context" + "encoding/json" "errors" "fmt" "strings" @@ -34,12 +35,38 @@ type Principal struct { TenantSlug string TenantStatus string Email string + // OrgRoles is the `org_roles` claim (the tenant-context mapper projects + // the Keycloak user attribute of the same name). Empty on service tokens. + OrgRoles []string } // IsUser reports whether the token carries a tenant context (a person // logged in through the portal / a CLI device flow) rather than a service. func (p *Principal) IsUser() bool { return p != nil && p.TenantID != "" } +// Tenant-admin org roles: the registry seeds IT_ADMIN for the first admin +// (keycloak.CreateOrgAndInvite); OWNER is the portal's owner role. Both may +// manage the tenant's users. +const ( + RoleITAdmin = "IT_ADMIN" + RoleOwner = "OWNER" +) + +// IsTenantAdmin reports whether a user token carries an org role that may +// administer the tenant (invite users, create API keys). Always false for +// service tokens — those are authorized per client via AUTHZ_RULES instead. +func (p *Principal) IsTenantAdmin() bool { + if !p.IsUser() { + return false + } + for _, r := range p.OrgRoles { + if r == RoleITAdmin || r == RoleOwner { + return true + } + } + return false +} + type ctxKey struct{} // WithPrincipal returns ctx carrying p. @@ -96,8 +123,42 @@ func (v *Verifier) Verify(ctx context.Context, authorization string) (*Principal TenantSlug string `json:"tenant_slug"` TenantStatus string `json:"tenant_status"` Email string `json:"email"` + OrgRoles roles `json:"org_roles"` } _ = tok.Claims(&claims) // azp is informational; absence is not an error return &Principal{Subject: tok.Subject, ClientID: claims.Azp, Issuer: tok.Issuer, - TenantID: claims.TenantID, TenantSlug: claims.TenantSlug, TenantStatus: claims.TenantStatus, Email: claims.Email}, nil + TenantID: claims.TenantID, TenantSlug: claims.TenantSlug, TenantStatus: claims.TenantStatus, Email: claims.Email, + OrgRoles: []string(claims.OrgRoles)}, nil +} + +// roles decodes the org_roles claim in either shape the Keycloak mapper +// produces: a JSON array when the attribute mapper is multivalued, or a +// single string (possibly "##"- or comma-joined) when it is not. +type roles []string + +func (r *roles) UnmarshalJSON(b []byte) error { + var list []string + if err := json.Unmarshal(b, &list); err == nil { + *r = normalizeRoles(list) + return nil + } + var one string + if err := json.Unmarshal(b, &one); err != nil { + *r = nil + return nil // unknown shape: no roles rather than a rejected token + } + *r = normalizeRoles([]string{one}) + return nil +} + +func normalizeRoles(in []string) []string { + out := []string{} + for _, entry := range in { + for _, v := range strings.FieldsFunc(entry, func(c rune) bool { return c == '#' || c == ',' }) { + if v = strings.TrimSpace(v); v != "" { + out = append(out, v) + } + } + } + return out } diff --git a/internal/authn/authn_test.go b/internal/authn/authn_test.go index 99fbc28..69e1305 100644 --- a/internal/authn/authn_test.go +++ b/internal/authn/authn_test.go @@ -125,6 +125,36 @@ func TestVerifier(t *testing.T) { fail("wrong audience", "Bearer "+iss.sign(t, iss.claims(map[string]any{"aud": "someone-else"}))) fail("wrong issuer", "Bearer "+iss.sign(t, iss.claims(map[string]any{"iss": "https://evil.example"}))) + t.Run("org_roles claim: array, ##-joined string, comma string", func(t *testing.T) { + for name, raw := range map[string]any{ + "array": []string{"IT_ADMIN", "USER"}, + "joined": "IT_ADMIN##USER", + "comma": "IT_ADMIN, USER", + } { + p, err := v.Verify(ctx, "Bearer "+iss.sign(t, iss.claims(map[string]any{"org_roles": raw, "tenant_id": "t-1", "email": "a@b.c"}))) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if len(p.OrgRoles) != 2 || p.OrgRoles[0] != "IT_ADMIN" || p.OrgRoles[1] != "USER" { + t.Errorf("%s: org_roles = %v", name, p.OrgRoles) + } + if !p.IsUser() || !p.IsTenantAdmin() || p.Email != "a@b.c" { + t.Errorf("%s: principal %+v", name, p) + } + } + p, err := v.Verify(ctx, "Bearer "+iss.sign(t, iss.claims(map[string]any{"org_roles": 42, "tenant_id": "t-1"}))) + if err != nil || len(p.OrgRoles) != 0 || p.IsTenantAdmin() { + t.Errorf("unknown shape must yield no roles: err=%v p=%+v", err, p) + } + }) + + t.Run("service token is never a tenant admin", func(t *testing.T) { + p, err := v.Verify(ctx, "Bearer "+iss.sign(t, iss.claims(map[string]any{"org_roles": []string{"OWNER"}}))) + if err != nil || p.IsUser() || p.IsTenantAdmin() { + t.Errorf("service principal: err=%v p=%+v", err, p) + } + }) + t.Run("missing header is ErrNoToken", func(t *testing.T) { if _, err := v.Verify(ctx, ""); err != authn.ErrNoToken { t.Fatalf("want ErrNoToken, got %v", err) diff --git a/internal/keycloak/adapter.go b/internal/keycloak/adapter.go index ef3fb7e..51bc29c 100644 --- a/internal/keycloak/adapter.go +++ b/internal/keycloak/adapter.go @@ -17,6 +17,7 @@ package keycloak import ( "context" "errors" + "time" ) // Sentinel errors. @@ -26,6 +27,7 @@ var ( ErrUserConflict = errors.New("keycloak: user already exists") ErrUnavailable = errors.New("keycloak: unreachable") ErrUserNotFound = errors.New("keycloak: user does not exist") + ErrOrgNotFound = errors.New("keycloak: organization does not exist") ) // InviteInput captures the per-tenant onboarding event from POST /v1/tenants. @@ -50,6 +52,49 @@ type InviteResult struct { InviteURL string } +// OrgMember is one member of a tenant's Keycloak organization as the portal +// Settings/Users page renders it. OrgRoles is the user attribute of the +// same name (what the tenant-context mapper projects into the token) — +// the registry exposes it, Keycloak owns it. +type OrgMember struct { + UserID string `json:"user_id"` + Email string `json:"email"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + OrgRoles []string `json:"org_roles"` + Enabled bool `json:"enabled"` + CreatedAt *time.Time `json:"created_at"` +} + +// MemberInviteInput is POST /v1/tenants/{id}/invites as the adapter sees +// it. TenantID/Slug/TenantStatus become the tenant-context attributes of a +// newly created user (the same set CreateOrgAndInvite writes for the admin). +type MemberInviteInput struct { + TenantID string + Slug string // KC org alias + TenantStatus string + Email string + FirstName string + LastName string + Role string // org_roles value for a NEW user (existing roles are never overwritten) +} + +// Member invite outcomes. +const ( + InviteStatusInvited = "invited" // user added to the org; execute-actions mail sent + InviteStatusMember = "member" // already a member; nothing changed, no mail +) + +// MemberInviteResult reports what InviteMember did. +type MemberInviteResult struct { + UserID string + Status string // InviteStatusInvited | InviteStatusMember + Created bool // the Keycloak user was created by this call + // MailError is set when the user was added but the execute-actions + // e-mail could not be sent (non-fatal; the admin can resend from KC). + MailError error +} + // Claims is the tenant-scoped claim bundle the protocol-mapper would push // into a JWT at token issuance. Returned by Adapter.ClaimsFor so the user- // attributes can be refreshed on subscription change. @@ -83,6 +128,19 @@ type Adapter interface { // Returns ErrUserNotFound for an unknown user id. Memberships(ctx context.Context, userID string) ([]Claims, error) + // ListOrgMembers lists the members of the organization whose alias is + // slug (portal Settings/Users). ErrOrgNotFound when the tenant has no + // organization yet (sales-led tenant, nobody invited). + ListOrgMembers(ctx context.Context, slug string) ([]OrgMember, error) + + // InviteMember adds in.Email to the organization whose alias is + // in.Slug: creates the user when missing (with the tenant-context + // attributes), adds the membership and sends the verify-email + + // set-password mail. Idempotent — an existing member yields + // InviteStatusMember and no mail. ErrOrgNotFound when the org is + // missing. + InviteMember(ctx context.Context, in MemberInviteInput) (*MemberInviteResult, error) + // SyncTenantStatus writes the coarse tenant_status attribute on every // member of the organization whose alias is slug (ERP/02: Keycloak // carries only the coarse flag; entitlements stay in the registry). diff --git a/internal/keycloak/members.go b/internal/keycloak/members.go new file mode 100644 index 0000000..73df540 --- /dev/null +++ b/internal/keycloak/members.go @@ -0,0 +1,218 @@ +package keycloak + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/url" + "time" +) + +// memberRepresentation is the slice of KC 26's MemberRepresentation (a +// UserRepresentation plus membershipType) the portal needs. Attributes are +// present in the full representation; a nil map means KC answered with a +// brief representation and we fetch the user separately. +type memberRepresentation struct { + ID string `json:"id"` + Username string `json:"username"` + Email string `json:"email"` + FirstName string `json:"firstName"` + LastName string `json:"lastName"` + Enabled bool `json:"enabled"` + CreatedTimestamp int64 `json:"createdTimestamp"` // epoch millis + Attributes map[string][]string `json:"attributes"` +} + +func (m memberRepresentation) toOrgMember() OrgMember { + var created *time.Time + if m.CreatedTimestamp > 0 { + t := time.UnixMilli(m.CreatedTimestamp).UTC() + created = &t + } + email := m.Email + if email == "" { + email = m.Username // registry-created users use the e-mail as username + } + return OrgMember{ + UserID: m.ID, + Email: email, + FirstName: m.FirstName, + LastName: m.LastName, + OrgRoles: attrValues(m.Attributes, "org_roles"), + Enabled: m.Enabled, + CreatedAt: created, + } +} + +// ListOrgMembers implements Adapter: GET /organizations/{id}/members for +// the org whose alias is slug. +func (a *HTTPAdapter) ListOrgMembers(ctx context.Context, slug string) ([]OrgMember, error) { + orgID, err := a.findOrgByAlias(ctx, slug) + if err != nil { + return nil, err + } + var members []memberRepresentation + resp, err := a.adminCall(ctx, http.MethodGet, fmt.Sprintf("/organizations/%s/members?max=500", orgID), nil, &members) + if err != nil { + return nil, err + } + if resp.StatusCode/100 != 2 { + _ = resp.Body.Close() + return nil, fmt.Errorf("list members: %d", resp.StatusCode) + } + out := make([]OrgMember, 0, len(members)) + for _, m := range members { + if m.Attributes == nil { + // Brief representation: 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 { + m.Attributes = u.Attributes + } else if err == nil { + _ = resp.Body.Close() + } + } + out = append(out, m.toOrgMember()) + } + return out, nil +} + +// InviteMember implements Adapter. Steps mirror CreateOrgAndInvite minus the +// org creation: find user by e-mail (create if missing, with the same +// tenant-context attributes the admin path writes), add as org member (KC 26: +// bare user id string body; 409 = already a member), then execute-actions +// e-mail. Best-effort atomicity, same as the admin path. +func (a *HTTPAdapter) InviteMember(ctx context.Context, in MemberInviteInput) (*MemberInviteResult, error) { + if in.Email == "" { + return nil, fmt.Errorf("keycloak: member email required") + } + orgID, err := a.findOrgByAlias(ctx, in.Slug) + if err != nil { + return nil, err + } + + attrs := map[string][]string{ + "tenant_id": {in.TenantID}, + "tenant_slug": {in.Slug}, + "org_roles": {in.Role}, + "tenant_status": {in.TenantStatus}, + } + created := false + userID, err := a.findUserByEmail(ctx, in.Email) + switch { + case err == nil: + // Existing user (possibly created by an earlier, half-failed invite): + // fill in missing tenant-context attributes, never overwrite — roles + // stay Keycloak-owned. + 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): + userID, err = a.createUser(ctx, userCreate{ + Username: in.Email, + Email: in.Email, + FirstName: in.FirstName, + LastName: in.LastName, + Enabled: true, + EmailVerified: false, + Attributes: attrs, + }) + if err != nil { + return nil, err + } + created = true + default: + return nil, err + } + + // KC 26: the member endpoint takes the bare user id as the JSON body. + resp, err := a.adminCall(ctx, http.MethodPost, fmt.Sprintf("/organizations/%s/members", orgID), userID, nil) + if err != nil { + return nil, fmt.Errorf("add member: %w", err) + } + if resp.StatusCode == http.StatusConflict { + _ = resp.Body.Close() + return &MemberInviteResult{UserID: userID, Status: InviteStatusMember, Created: created}, nil + } + if resp.StatusCode/100 != 2 { + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + return nil, fmt.Errorf("add member: %d %s", resp.StatusCode, body) + } + _ = resp.Body.Close() + + res := &MemberInviteResult{UserID: userID, Status: InviteStatusInvited, Created: created} + if _, merr := a.executeActionsEmail(ctx, userID, []string{"VERIFY_EMAIL", "UPDATE_PASSWORD"}, a.cfg.InviteRedirectURI); merr != nil { + res.MailError = merr + } + return res, nil +} + +// createUser POSTs a user and returns its id (Location header, falling back +// to an e-mail lookup). A 409 means another caller created it first. +func (a *HTTPAdapter) createUser(ctx context.Context, u userCreate) (string, error) { + resp, err := a.adminCall(ctx, http.MethodPost, "/users", u, nil) + if err != nil { + return "", fmt.Errorf("create user: %w", err) + } + switch resp.StatusCode { + case http.StatusCreated: + userID := lastSegment(resp.Header.Get("Location")) + _ = resp.Body.Close() + if userID != "" { + return userID, nil + } + case http.StatusConflict: + _ = resp.Body.Close() + default: + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + return "", fmt.Errorf("create user: %d %s", resp.StatusCode, body) + } + userID, err := a.findUserByEmail(ctx, u.Email) + if err != nil { + return "", fmt.Errorf("create user: lookup after create failed: %w", err) + } + return userID, nil +} + +// ensureUserAttributes merges attrs into the user's attributes, adding only +// keys that are absent (same contract as ensureOrgAttributes). +func (a *HTTPAdapter) ensureUserAttributes(ctx context.Context, userID string, attrs map[string][]string) error { + var u userRepresentation + resp, err := a.adminCall(ctx, http.MethodGet, "/users/"+url.PathEscape(userID), nil, &u) + if err != nil { + return err + } + if resp.StatusCode/100 != 2 { + _ = resp.Body.Close() + return fmt.Errorf("get user: %d", resp.StatusCode) + } + existing := u.Attributes + if existing == nil { + existing = map[string][]string{} + } + changed := false + for k, v := range attrs { + if len(attrValues(existing, k)) == 0 { + existing[k] = v + changed = true + } + } + if !changed { + return nil + } + resp, err = a.adminCall(ctx, http.MethodPut, "/users/"+url.PathEscape(userID), map[string]any{"attributes": existing}, nil) + if err != nil { + return err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode/100 != 2 { + body, _ := io.ReadAll(resp.Body) + return fmt.Errorf("put user: %d %s", resp.StatusCode, body) + } + return nil +} diff --git a/internal/keycloak/members_test.go b/internal/keycloak/members_test.go new file mode 100644 index 0000000..1d003ed --- /dev/null +++ b/internal/keycloak/members_test.go @@ -0,0 +1,299 @@ +package keycloak + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// membersKC is a KC 26 look-alike for the organization-membership surface: +// 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 + created []userCreate + puts map[string]map[string][]string // user id → attributes PUT + createErr int // non-zero: POST /users answers this status + nextID int +} + +func newMembersKC(t *testing.T) (*membersKC, *HTTPAdapter) { + t.Helper() + k := &membersKC{ + orgs: map[string]string{"acme": "org-acme"}, + members: map[string][]string{"org-acme": {"u-admin"}}, + users: map[string]memberRepresentation{ + "u-admin": {ID: "u-admin", Username: "admin@acme.test", Email: "admin@acme.test", FirstName: "Ada", LastName: "Admin", + Enabled: true, CreatedTimestamp: 1_700_000_000_000, + Attributes: map[string][]string{"org_roles": {"IT_ADMIN##OWNER"}, "tenant_slug": {"acme"}}}, + "u-loose": {ID: "u-loose", Username: "loose@acme.test", Email: "loose@acme.test", Enabled: true, + Attributes: map[string][]string{"tenant_id": {"other"}}}, + }, + puts: map[string]map[string][]string{}, + } + mux := http.NewServeMux() + mux.HandleFunc("/realms/test-realm/protocol/openid-connect/token", tokenOK) + mux.HandleFunc("GET /admin/realms/test-realm/organizations", func(w http.ResponseWriter, r *http.Request) { + out := []map[string]string{} + if id, ok := k.orgs[r.URL.Query().Get("search")]; ok { + out = append(out, map[string]string{"id": id, "alias": r.URL.Query().Get("search")}) + } + _ = json.NewEncoder(w).Encode(out) + }) + mux.HandleFunc("GET /admin/realms/test-realm/organizations/{id}/members", func(w http.ResponseWriter, r *http.Request) { + k.mu.Lock() + defer k.mu.Unlock() + out := []memberRepresentation{} + for _, id := range k.members[r.PathValue("id")] { + u := k.users[id] + if k.brief { + u.Attributes = nil + } + out = append(out, u) + } + _ = json.NewEncoder(w).Encode(out) + }) + mux.HandleFunc("POST /admin/realms/test-realm/organizations/{id}/members", func(w http.ResponseWriter, r *http.Request) { + k.mu.Lock() + defer k.mu.Unlock() + var id string + if err := json.NewDecoder(r.Body).Decode(&id); err != nil { + http.Error(w, `{"errorMessage":"User does not exist"}`, http.StatusBadRequest) + return + } + if _, ok := k.users[id]; !ok { + http.Error(w, `{"errorMessage":"User does not exist"}`, http.StatusBadRequest) + return + } + for _, m := range k.members[r.PathValue("id")] { + if m == id { + http.Error(w, `{"errorMessage":"User is already a member"}`, http.StatusConflict) + return + } + } + k.members[r.PathValue("id")] = append(k.members[r.PathValue("id")], id) + w.WriteHeader(http.StatusCreated) + }) + mux.HandleFunc("GET /admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) { + k.mu.Lock() + defer k.mu.Unlock() + out := []memberRepresentation{} + for _, u := range k.users { + if strings.EqualFold(u.Email, r.URL.Query().Get("email")) { + out = append(out, u) + } + } + _ = json.NewEncoder(w).Encode(out) + }) + mux.HandleFunc("POST /admin/realms/test-realm/users", func(w http.ResponseWriter, r *http.Request) { + k.mu.Lock() + defer k.mu.Unlock() + var u userCreate + _ = json.NewDecoder(r.Body).Decode(&u) + k.created = append(k.created, u) + if k.createErr != 0 { + if k.createErr == http.StatusConflict { + // A racing creator won: the user exists by the time we look again. + k.users["u-race"] = memberRepresentation{ID: "u-race", Username: u.Username, Email: u.Email, Enabled: true} + } + w.WriteHeader(k.createErr) + return + } + k.nextID++ + id := "u-new-" + string(rune('0'+k.nextID)) + k.users[id] = memberRepresentation{ID: id, Username: u.Username, Email: u.Email, FirstName: u.FirstName, LastName: u.LastName, Enabled: u.Enabled, Attributes: u.Attributes} + w.Header().Set("Location", "http://kc/admin/realms/test-realm/users/"+id) + w.WriteHeader(http.StatusCreated) + }) + mux.HandleFunc("GET /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, r *http.Request) { + k.mu.Lock() + defer k.mu.Unlock() + u, ok := k.users[r.PathValue("id")] + if !ok { + w.WriteHeader(http.StatusNotFound) + return + } + _ = json.NewEncoder(w).Encode(u) + }) + mux.HandleFunc("PUT /admin/realms/test-realm/users/{id}", func(w http.ResponseWriter, r *http.Request) { + k.mu.Lock() + defer k.mu.Unlock() + var body struct { + Attributes map[string][]string `json:"attributes"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + k.puts[r.PathValue("id")] = body.Attributes + u := k.users[r.PathValue("id")] + u.Attributes = body.Attributes + k.users[r.PathValue("id")] = u + w.WriteHeader(http.StatusNoContent) + }) + mux.HandleFunc("PUT /admin/realms/test-realm/users/{id}/execute-actions-email", func(w http.ResponseWriter, r *http.Request) { + k.mu.Lock() + defer k.mu.Unlock() + if r.URL.Query().Get("client_id") != "portal-test" || r.URL.Query().Get("redirect_uri") != "https://portal.test/onboard" { + http.Error(w, "bad invite client", http.StatusBadRequest) + return + } + k.mails = append(k.mails, r.PathValue("id")) + w.WriteHeader(http.StatusNoContent) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + a := NewHTTPAdapter(HTTPConfig{ + BaseURL: srv.URL, Realm: "test-realm", ClientID: "c", ClientSecret: "s", Timeout: 5 * time.Second, + InviteClientID: "portal-test", InviteRedirectURI: "https://portal.test/onboard", + }) + return k, a +} + +func TestHTTPAdapter_ListOrgMembers(t *testing.T) { + k, a := newMembersKC(t) + members, err := a.ListOrgMembers(context.Background(), "acme") + if err != nil { + t.Fatal(err) + } + if len(members) != 1 { + t.Fatalf("want 1 member, got %+v", members) + } + m := members[0] + if m.UserID != "u-admin" || m.Email != "admin@acme.test" || m.FirstName != "Ada" || m.LastName != "Admin" || !m.Enabled { + t.Errorf("identity fields: %+v", m) + } + if strings.Join(m.OrgRoles, ",") != "IT_ADMIN,OWNER" { + t.Errorf("org_roles must split ## joined values: %v", m.OrgRoles) + } + if m.CreatedAt == nil || m.CreatedAt.UnixMilli() != 1_700_000_000_000 { + t.Errorf("created_at from createdTimestamp: %v", m.CreatedAt) + } + + // Brief member representation → attributes fetched per user. + k.brief = true + members, err = a.ListOrgMembers(context.Background(), "acme") + if err != nil || len(members) != 1 || len(members[0].OrgRoles) != 2 { + t.Fatalf("brief fallback: err=%v members=%+v", err, members) + } + + if _, err := a.ListOrgMembers(context.Background(), "ghost"); !errors.Is(err, ErrOrgNotFound) { + t.Fatalf("missing org must be ErrOrgNotFound, got %v", err) + } +} + +func TestHTTPAdapter_InviteMember_newUser(t *testing.T) { + k, a := newMembersKC(t) + res, err := a.InviteMember(context.Background(), MemberInviteInput{ + TenantID: "t-1", Slug: "acme", TenantStatus: "trial", + Email: "new@acme.test", FirstName: "New", LastName: "Person", Role: "USER", + }) + if err != nil { + t.Fatal(err) + } + if res.Status != InviteStatusInvited || !res.Created || res.UserID == "" || res.MailError != nil { + t.Fatalf("result: %+v", res) + } + if len(k.created) != 1 { + t.Fatalf("want one user created, got %d", len(k.created)) + } + u := k.created[0] + if u.Username != "new@acme.test" || !u.Enabled || u.EmailVerified { + t.Errorf("user payload: %+v", u) + } + want := map[string]string{"tenant_id": "t-1", "tenant_slug": "acme", "org_roles": "USER", "tenant_status": "trial"} + for key, val := range want { + if got := u.Attributes[key]; len(got) != 1 || got[0] != val { + t.Errorf("attribute %s = %v, want %s", key, got, val) + } + } + if len(k.mails) != 1 || k.mails[0] != res.UserID { + t.Errorf("execute-actions mail: %v", k.mails) + } + if got := k.members["org-acme"]; len(got) != 2 || got[1] != res.UserID { + t.Errorf("membership: %v", got) + } +} + +func TestHTTPAdapter_InviteMember_existingMemberIsIdempotent(t *testing.T) { + k, a := newMembersKC(t) + res, err := a.InviteMember(context.Background(), MemberInviteInput{Slug: "acme", Email: "Admin@acme.test", Role: "USER"}) + if err != nil { + t.Fatal(err) + } + if res.Status != InviteStatusMember || res.UserID != "u-admin" || res.Created { + t.Fatalf("result: %+v", res) + } + if len(k.mails) != 0 || len(k.created) != 0 { + t.Errorf("existing member must get no mail and no user: mails=%v created=%d", k.mails, len(k.created)) + } + // Existing attributes are never overwritten. + if roles := k.users["u-admin"].Attributes["org_roles"]; len(roles) != 1 || roles[0] != "IT_ADMIN##OWNER" { + t.Errorf("org_roles must stay untouched: %v", roles) + } +} + +func TestHTTPAdapter_InviteMember_existingUserNotMember(t *testing.T) { + k, a := newMembersKC(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 != InviteStatusInvited || res.Created || res.UserID != "u-loose" { + t.Fatalf("result: %+v", res) + } + attrs := k.puts["u-loose"] + if attrs == nil { + t.Fatal("missing attributes must be merged with a PUT") + } + if attrs["tenant_id"][0] != "other" { + t.Errorf("existing attribute overwritten: %v", attrs["tenant_id"]) + } + if attrs["org_roles"][0] != "USER" || attrs["tenant_slug"][0] != "acme" || attrs["tenant_status"][0] != "active" { + t.Errorf("missing attributes not filled: %v", attrs) + } + if len(k.mails) != 1 { + t.Errorf("mail: %v", k.mails) + } +} + +func TestHTTPAdapter_InviteMember_errors(t *testing.T) { + k, a := newMembersKC(t) + if _, err := a.InviteMember(context.Background(), MemberInviteInput{Slug: "acme"}); err == nil { + t.Error("empty email must fail") + } + if _, err := a.InviteMember(context.Background(), MemberInviteInput{Slug: "ghost", Email: "x@acme.test"}); !errors.Is(err, ErrOrgNotFound) { + t.Errorf("missing org: %v", err) + } + k.createErr = http.StatusInternalServerError + if _, err := a.InviteMember(context.Background(), MemberInviteInput{Slug: "acme", Email: "boom@acme.test", Role: "USER"}); err == nil || !strings.Contains(err.Error(), "create user: 500") { + t.Errorf("create failure must surface: %v", err) + } +} + +func TestHTTPAdapter_InviteMember_createConflictFallsBackToLookup(t *testing.T) { + k, a := newMembersKC(t) + // A racing creator wins: POST /users answers 409 and the e-mail lookup + // that follows resolves the id the other caller created. + k.createErr = http.StatusConflict + res, err := a.InviteMember(context.Background(), MemberInviteInput{Slug: "acme", Email: "race@acme.test", Role: "USER"}) + if err != nil { + t.Fatal(err) + } + if res.Status != InviteStatusInvited || res.UserID != "u-race" || !res.Created { + t.Fatalf("result: %+v", res) + } + if len(k.mails) != 1 || k.mails[0] != "u-race" { + t.Errorf("mail: %v", k.mails) + } +} diff --git a/internal/keycloak/mock.go b/internal/keycloak/mock.go index f9ba3d6..060798b 100644 --- a/internal/keycloak/mock.go +++ b/internal/keycloak/mock.go @@ -3,7 +3,9 @@ package keycloak import ( "context" "errors" + "strings" "sync" + "time" ) // Mock is the test-friendly Adapter. Records every call; predictable IDs. @@ -16,17 +18,72 @@ type Mock struct { Claims map[string]Claims // userID → last synced Status map[string]string // tenant slug → last synced tenant_status FailNext error // set to force the next call to fail + + // Members is the org membership per tenant slug. A slug with no entry + // has no organization (ListOrgMembers/InviteMember → ErrOrgNotFound); + // seed an empty slice for an org with no members. + Members map[string][]OrgMember + Invites []MemberInviteInput // every InviteMember call that sent a mail } func NewMock() *Mock { return &Mock{ - Orgs: map[string]string{}, - Users: map[string]string{}, - Claims: map[string]Claims{}, - Status: map[string]string{}, + Orgs: map[string]string{}, + Users: map[string]string{}, + Claims: map[string]Claims{}, + Status: map[string]string{}, + Members: map[string][]OrgMember{}, } } +func (m *Mock) ListOrgMembers(_ context.Context, slug string) ([]OrgMember, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.FailNext != nil { + err := m.FailNext + m.FailNext = nil + return nil, err + } + members, ok := m.Members[slug] + if !ok { + return nil, ErrOrgNotFound + } + out := make([]OrgMember, len(members)) + copy(out, members) + return out, nil +} + +func (m *Mock) InviteMember(_ context.Context, in MemberInviteInput) (*MemberInviteResult, error) { + m.mu.Lock() + defer m.mu.Unlock() + if m.FailNext != nil { + err := m.FailNext + m.FailNext = nil + return nil, err + } + members, ok := m.Members[in.Slug] + if !ok { + return nil, ErrOrgNotFound + } + for _, mem := range members { + if strings.EqualFold(mem.Email, in.Email) { + return &MemberInviteResult{UserID: mem.UserID, Status: InviteStatusMember}, nil + } + } + userID, created := m.Users[in.Email] + if userID == "" { + userID = "mock-user-" + in.Email + m.Users[in.Email] = userID + } + now := time.Now().UTC() + m.Members[in.Slug] = append(members, OrgMember{ + UserID: userID, Email: in.Email, FirstName: in.FirstName, LastName: in.LastName, + OrgRoles: []string{in.Role}, Enabled: true, CreatedAt: &now, + }) + m.Invites = append(m.Invites, in) + return &MemberInviteResult{UserID: userID, Status: InviteStatusInvited, Created: !created}, nil +} + func (m *Mock) SyncTenantStatus(_ context.Context, slug, status string) error { m.mu.Lock() defer m.mu.Unlock() diff --git a/internal/keycloak/orgs.go b/internal/keycloak/orgs.go index 3979487..be998e0 100644 --- a/internal/keycloak/orgs.go +++ b/internal/keycloak/orgs.go @@ -219,16 +219,23 @@ func (a *HTTPAdapter) findOrgByAlias(ctx context.Context, alias string) (string, return o.ID, nil } } - return "", errors.New("org not found") + return "", fmt.Errorf("%w: alias=%s", ErrOrgNotFound, alias) } +// errUserLookupMiss distinguishes "no such user" from a failed lookup in +// findUserByEmail so callers can create the user on a miss only. +var errUserLookupMiss = errors.New("user not found") + func (a *HTTPAdapter) findUserByEmail(ctx context.Context, email string) (string, error) { resp, err := a.adminCall(ctx, http.MethodGet, - fmt.Sprintf("/users?email=%s&exact=true", email), nil, nil) + fmt.Sprintf("/users?email=%s&exact=true", url.QueryEscape(email)), nil, nil) if err != nil { return "", err } defer func() { _ = resp.Body.Close() }() + if resp.StatusCode/100 != 2 { + return "", fmt.Errorf("find user: %d", resp.StatusCode) + } var users []struct { ID string `json:"id"` Email string `json:"email"` @@ -241,7 +248,7 @@ func (a *HTTPAdapter) findUserByEmail(ctx context.Context, email string) (string return u.ID, nil } } - return "", errors.New("user not found") + return "", errUserLookupMiss } func (a *HTTPAdapter) executeActionsEmail(ctx context.Context, userID string, actions []string, redirectURI string) (string, error) { diff --git a/internal/keycloak/status_test.go b/internal/keycloak/status_test.go index efd7352..8fd2ef2 100644 --- a/internal/keycloak/status_test.go +++ b/internal/keycloak/status_test.go @@ -3,6 +3,7 @@ package keycloak import ( "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "strings" @@ -95,7 +96,7 @@ func TestHTTPAdapter_SyncTenantStatus_errors(t *testing.T) { puts, "u-1") a := usersAdapter(srv) - if err := a.SyncTenantStatus(context.Background(), "nope", "active"); err == nil || !strings.Contains(err.Error(), "org not found") { + if err := a.SyncTenantStatus(context.Background(), "nope", "active"); !errors.Is(err, ErrOrgNotFound) { t.Fatalf("unknown org: %v", err) } if err := a.SyncTenantStatus(context.Background(), "acme", "active"); err == nil || !strings.Contains(err.Error(), "update user u-1: 500") { diff --git a/internal/server/members.go b/internal/server/members.go new file mode 100644 index 0000000..e83a129 --- /dev/null +++ b/internal/server/members.go @@ -0,0 +1,203 @@ +package server + +import ( + "context" + "errors" + "net/http" + "net/mail" + "regexp" + "strings" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// Tenant members (D1): the portal's Settings/Users page reads the Keycloak +// organization membership through the registry and invites new users the +// same way the first admin was invited at tenant creation. +// +// Scope: a user token (tenant context) may only touch its own tenant — a +// mismatch is a 404 like revokeLicence, never a hint that the tenant +// exists. Service clients are gated per route group by AUTHZ_RULES +// (members = tenants.read, invites = tenants.write). + +// roleRE bounds the org_roles value written for a new user. It is a +// Keycloak user attribute the portal projects into the token, not a role +// model the registry owns — any upper-snake identifier is accepted. +var roleRE = regexp.MustCompile(`^[A-Z][A-Z0-9_]{1,31}$`) + +// defaultInviteRole is written when the invite carries no role. The first +// admin gets IT_ADMIN from CreateOrgAndInvite; everyone else is a USER +// unless the portal says otherwise. +const defaultInviteRole = "USER" + +type membersResp struct { + Members []keycloak.OrgMember `json:"members"` +} + +type inviteReq struct { + Email string `json:"email"` + FirstName string `json:"first_name,omitempty"` + LastName string `json:"last_name,omitempty"` + Role string `json:"role,omitempty"` +} + +type inviteResp struct { + UserID string `json:"user_id"` + Email string `json:"email"` + Status string `json:"status"` // invited | member +} + +// tenantInScope loads the tenant and enforces the user-token scope. On a +// miss or a cross-tenant user the response is already written (404). +func (s *Server) tenantInScope(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, bool) { + t, err := s.Store.GetTenant(ctx, r.PathValue("id")) + if err != nil { + if mapStoreError(w, err) { + return nil, false + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return nil, false + } + if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && p.TenantID != t.ID { + writeError(w, http.StatusNotFound, "not_found", "resource does not exist") + return nil, false + } + return t, true +} + +// listTenantMembers is GET /v1/tenants/{id}/members. +// tenantSubresource dispatches GET /v1/tenants/{id}/{sub}. Only the members +// collection exists; anything else is a 404 rather than a route that silently +// swallowed a typo. +func (s *Server) tenantSubresource(w http.ResponseWriter, r *http.Request) { + if r.PathValue("sub") != "members" { + writeError(w, http.StatusNotFound, "not_found", "no such tenant sub-resource") + return + } + s.listTenantMembers(w, r) +} + +func (s *Server) listTenantMembers(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + members, err := s.Keycloak.ListOrgMembers(ctx, t.Slug) + if err != nil { + if errors.Is(err, keycloak.ErrOrgNotFound) { + // Nobody was ever invited (sales-led tenant): an empty list, not + // an error — the portal renders "no users yet". + writeJSON(w, http.StatusOK, membersResp{Members: []keycloak.OrgMember{}}) + return + } + s.writeKeycloakError(w, t.ID, "list members", err) + return + } + if members == nil { + members = []keycloak.OrgMember{} + } + writeJSON(w, http.StatusOK, membersResp{Members: members}) +} + +// inviteTenantMember is POST /v1/tenants/{id}/invites. Tenant admins +// (org_roles IT_ADMIN/OWNER) and service clients on tenants.write only. +func (s *Server) inviteTenantMember(w http.ResponseWriter, r *http.Request) { + var in inviteReq + if !decodeJSON(w, r, &in) { + return + } + in.Email = strings.ToLower(strings.TrimSpace(in.Email)) + if addr, err := mail.ParseAddress(in.Email); err != nil || addr.Address != in.Email || len(in.Email) > 254 { + writeError(w, http.StatusBadRequest, "invalid_email", "email must be a bare, valid address") + return + } + in.FirstName, in.LastName = strings.TrimSpace(in.FirstName), strings.TrimSpace(in.LastName) + if len(in.FirstName) > 100 || len(in.LastName) > 100 { + writeError(w, http.StatusBadRequest, "invalid_name", "first_name and last_name must be at most 100 chars") + return + } + in.Role = strings.ToUpper(strings.TrimSpace(in.Role)) + if in.Role == "" { + in.Role = defaultInviteRole + } + if !roleRE.MatchString(in.Role) { + writeError(w, http.StatusBadRequest, "invalid_role", "role must match ^[A-Z][A-Z0-9_]{1,31}$") + return + } + + p, _ := authn.PrincipalFrom(r.Context()) + if p.IsUser() && !p.IsTenantAdmin() { + writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "inviting users requires the IT_ADMIN or OWNER org role") + return + } + + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + + res, err := s.Keycloak.InviteMember(ctx, keycloak.MemberInviteInput{ + TenantID: t.ID, Slug: t.Slug, TenantStatus: t.Status, + Email: in.Email, FirstName: in.FirstName, LastName: in.LastName, Role: in.Role, + }) + if err != nil { + if errors.Is(err, keycloak.ErrOrgNotFound) { + writeError(w, http.StatusConflict, "org_not_provisioned", "tenant has no Keycloak organization yet — create it by inviting the first admin (POST /v1/tenants admin_email)") + return + } + s.writeKeycloakError(w, t.ID, "invite member", err) + return + } + + if res.Status == keycloak.InviteStatusMember { + writeJSON(w, http.StatusOK, inviteResp{UserID: res.UserID, Email: in.Email, Status: res.Status}) + return + } + + 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", + TargetID: in.Email, TargetType: "user", TargetName: in.Email, + Metadata: meta, + } + if p != nil { + ev.ActorID, ev.ActorName = p.Subject, p.Email + ev.ActorType = "service" + if p.IsUser() { + ev.ActorType = "user" + } + } + s.emitAudit(ctx, r, ev) + + // The first admin invited into a tenant that was created without one + // (sales-led flow) becomes its admin_email. + if t.AdminEmail == "" && (in.Role == authn.RoleITAdmin || in.Role == authn.RoleOwner) { + if _, uerr := s.Store.UpdateTenant(ctx, t.ID, store.TenantUpdate{AdminEmail: ptrStr(in.Email)}); uerr != nil { + s.Log.Warn("admin_email not recorded", "tenant_id", t.ID, "err", uerr) + } + } + + writeJSON(w, http.StatusAccepted, inviteResp{UserID: res.UserID, Email: in.Email, Status: res.Status}) +} + +// 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) { + 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()) + return + } + writeError(w, http.StatusBadGateway, "keycloak_error", err.Error()) +} diff --git a/internal/server/members_scope_test.go b/internal/server/members_scope_test.go new file mode 100644 index 0000000..f24a776 --- /dev/null +++ b/internal/server/members_scope_test.go @@ -0,0 +1,136 @@ +package server + +import ( + "context" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// scopedServer wires the real router (no authn verifier) and injects a +// principal into every request, so the handler-level tenant scope and +// org-role checks run exactly as they would behind requireAuth. +// rules, when non-empty, are parsed into s.Authz *before* the router is built: +// requireAuthz decides once, at construction, whether to enforce at all. +func scopedServer(t *testing.T, p *authn.Principal, rules ...string) (*Server, http.Handler, *store.Tenant) { + t.Helper() + mem := store.NewMemory() + tenant, _ := mem.GetTenantBySlug(context.Background(), "acme") + mock := keycloak.NewMock() + mock.Members["acme"] = []keycloak.OrgMember{{UserID: "u-1", Email: "ada@acme.test", OrgRoles: []string{"IT_ADMIN"}, Enabled: true}} + s := &Server{Log: slog.New(slog.NewTextHandler(io.Discard, nil)), Store: mem, Keycloak: mock} + if len(rules) > 0 && rules[0] != "" { + s.Authz = ParseAuthzRules(rules[0]) + } + router := NewRouter(s) + h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + router.ServeHTTP(w, r.WithContext(authn.WithPrincipal(r.Context(), p))) + }) + return s, h, tenant +} + +func TestMembers_userScope(t *testing.T) { + member := &authn.Principal{Subject: "u-9", ClientID: "portal", TenantID: "00000000-0000-0000-0000-000000000001", Email: "m@acme.test", OrgRoles: []string{"USER"}} + _, h, tenant := scopedServer(t, member) + + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenant.ID+"/members", nil)) + if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), "ada@acme.test") { + t.Fatalf("own tenant members: %d %s", rr.Code, rr.Body.String()) + } + + // Another tenant: 404, never a hint that it exists. + other := &authn.Principal{Subject: "u-x", ClientID: "portal", TenantID: "11111111-1111-1111-1111-111111111111", OrgRoles: []string{"IT_ADMIN"}} + _, h2, _ := scopedServer(t, other) + rr = httptest.NewRecorder() + h2.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenant.ID+"/members", nil)) + if rr.Code != http.StatusNotFound { + t.Fatalf("cross-tenant members: %d %s", rr.Code, rr.Body.String()) + } + rr = httptest.NewRecorder() + h2.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/tenants/"+tenant.ID+"/invites", strings.NewReader(`{"email":"x@acme.test"}`))) + if rr.Code != http.StatusNotFound { + t.Fatalf("cross-tenant invite: %d %s", rr.Code, rr.Body.String()) + } +} + +func TestInvite_requiresTenantAdminRole(t *testing.T) { + tenantID := "00000000-0000-0000-0000-000000000001" + cases := []struct { + name string + roles []string + want int + }{ + {"plain user", []string{"USER"}, http.StatusForbidden}, + {"no roles", nil, http.StatusForbidden}, + {"it admin", []string{"IT_ADMIN"}, http.StatusAccepted}, + {"owner", []string{"USER", "OWNER"}, http.StatusAccepted}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + p := &authn.Principal{Subject: "u-" + c.name, ClientID: "portal", TenantID: tenantID, Email: "caller@acme.test", OrgRoles: c.roles} + s, h, tenant := scopedServer(t, p) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/tenants/"+tenant.ID+"/invites", strings.NewReader(`{"email":"new@acme.test","role":"USER"}`))) + if rr.Code != c.want { + t.Fatalf("status %d, want %d: %s", rr.Code, c.want, rr.Body.String()) + } + if c.want != http.StatusAccepted { + if !strings.Contains(rr.Body.String(), "FORBIDDEN_ROLE") { + t.Errorf("error code: %s", rr.Body.String()) + } + return + } + // Actor is the caller. + items, _, _ := s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: tenant.ID, Action: "user.invited"}) + if len(items) != 1 || items[0].ActorID != p.Subject || items[0].ActorName != "caller@acme.test" || items[0].ActorType != "user" { + t.Errorf("audit actor: %+v", items) + } + }) + } +} + +func TestInvite_serviceClientBypassesRoleCheck(t *testing.T) { + const rules = "portal-svc-stage:tenants;pruefwerk-svc-stage:tenants.read" + svc := &authn.Principal{Subject: "svc", ClientID: "portal-svc-stage"} + s, h, tenant := scopedServer(t, svc, rules) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/tenants/"+tenant.ID+"/invites", strings.NewReader(`{"email":"svc-invited@acme.test"}`))) + if rr.Code != http.StatusAccepted { + t.Fatalf("service invite: %d %s", rr.Code, rr.Body.String()) + } + items, _, _ := s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: tenant.ID, Action: "user.invited"}) + if len(items) != 1 || items[0].ActorType != "service" || items[0].ActorID != "svc" { + t.Errorf("audit actor: %+v", items) + } + + // A read-only client may list members but not invite. + ro := &authn.Principal{Subject: "svc2", ClientID: "pruefwerk-svc-stage"} + _, h2, _ := scopedServer(t, ro, rules) + rr = httptest.NewRecorder() + h2.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+tenant.ID+"/members", nil)) + if rr.Code != http.StatusOK { + t.Errorf("read client members: %d %s", rr.Code, rr.Body.String()) + } + rr = httptest.NewRecorder() + h2.ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/tenants/"+tenant.ID+"/invites", strings.NewReader(`{"email":"x@acme.test"}`))) + if rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), "FORBIDDEN_CLIENT") { + t.Errorf("read client invite: %d %s", rr.Code, rr.Body.String()) + } +} + +func TestRouteGroup_members(t *testing.T) { + if g := routeGroup(http.MethodGet, "/v1/tenants/x/members"); g != "tenants.read" { + t.Errorf("members group %q", g) + } + if g := routeGroup(http.MethodPost, "/v1/tenants/x/invites"); g != "tenants.write" { + t.Errorf("invites group %q", g) + } +} diff --git a/internal/server/members_test.go b/internal/server/members_test.go new file mode 100644 index 0000000..227222c --- /dev/null +++ b/internal/server/members_test.go @@ -0,0 +1,225 @@ +package server_test + +import ( + "net/http" + "testing" + + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +type membersBody struct { + Members []keycloak.OrgMember `json:"members"` +} + +type inviteBody struct { + UserID string `json:"user_id"` + Email string `json:"email"` + Status string `json:"status"` +} + +func TestListTenantMembers(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + h.kcMock.Members["acme"] = []keycloak.OrgMember{ + {UserID: "u-1", Email: "ada@acme.test", FirstName: "Ada", LastName: "Admin", OrgRoles: []string{"IT_ADMIN"}, Enabled: true}, + } + resp, raw := h.do(http.MethodGet, "/v1/tenants/"+h.tenant.ID+"/members", nil) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status %d: %s", resp.StatusCode, raw) + } + body := decode[membersBody](t, raw) + if len(body.Members) != 1 || body.Members[0].Email != "ada@acme.test" || body.Members[0].OrgRoles[0] != "IT_ADMIN" { + t.Fatalf("unexpected body: %s", raw) + } + }) +} + +func TestListTenantMembers_noOrgIsEmpty(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + resp, raw := h.do(http.MethodGet, "/v1/tenants/"+h.tenant.ID+"/members", nil) + if resp.StatusCode != http.StatusOK { + t.Fatalf("status %d: %s", resp.StatusCode, raw) + } + if body := decode[membersBody](t, raw); body.Members == nil || len(body.Members) != 0 { + t.Fatalf("want empty members array, got %s", raw) + } + }) +} + +func TestListTenantMembers_errors(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + resp, _ := h.do(http.MethodGet, "/v1/tenants/00000000-0000-0000-0000-0000000000ff/members", nil) + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("unknown tenant: %d", resp.StatusCode) + } + h.kcMock.Members["acme"] = []keycloak.OrgMember{} + h.kcMock.FailNext = keycloak.ErrUnavailable + resp, raw := h.do(http.MethodGet, "/v1/tenants/"+h.tenant.ID+"/members", nil) + if resp.StatusCode != http.StatusServiceUnavailable { + t.Fatalf("kc down: %d %s", resp.StatusCode, raw) + } + }) +} + +func TestInviteTenantMember(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + h.kcMock.Members["acme"] = []keycloak.OrgMember{} + resp, raw := h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{ + "email": " Bob@Acme.test ", "first_name": "Bob", "last_name": "Builder", + }) + if resp.StatusCode != http.StatusAccepted { + t.Fatalf("status %d: %s", resp.StatusCode, raw) + } + out := decode[inviteBody](t, raw) + if out.Status != "invited" || out.Email != "bob@acme.test" || out.UserID == "" { + t.Fatalf("unexpected body: %s", raw) + } + if len(h.kcMock.Invites) != 1 { + t.Fatalf("want one KC invite, got %d", len(h.kcMock.Invites)) + } + inv := h.kcMock.Invites[0] + if inv.TenantID != h.tenant.ID || inv.Slug != "acme" || inv.TenantStatus != h.tenant.Status || inv.Role != "USER" || inv.FirstName != "Bob" { + t.Errorf("invite input: %+v", inv) + } + + // Audit: user.invited, target = email. + _, araw := h.do(http.MethodGet, "/v1/audit?tenant_id="+h.tenant.ID+"&action=user.invited", nil) + audit := decode[struct { + Items []store.AuditEvent `json:"items"` + }](t, araw) + if len(audit.Items) != 1 || audit.Items[0].TargetID != "bob@acme.test" || audit.Items[0].TargetType != "user" { + t.Errorf("audit: %s", araw) + } + if audit.Items[0].Metadata["role"] != "USER" { + t.Errorf("audit role: %v", audit.Items[0].Metadata) + } + + // Idempotent: second invite is a 200 member, no extra mail, no audit. + resp, raw = h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{"email": "bob@acme.test"}) + if resp.StatusCode != http.StatusOK { + t.Fatalf("repeat status %d: %s", resp.StatusCode, raw) + } + if out := decode[inviteBody](t, raw); out.Status != "member" { + t.Fatalf("repeat body: %s", raw) + } + if len(h.kcMock.Invites) != 1 { + t.Errorf("repeat invite must not send mail: %d", len(h.kcMock.Invites)) + } + _, araw = h.do(http.MethodGet, "/v1/audit?tenant_id="+h.tenant.ID+"&action=user.invited", nil) + if n := len(decode[struct { + Items []store.AuditEvent `json:"items"` + }](t, araw).Items); n != 1 { + t.Errorf("repeat invite must not audit: %d", n) + } + + // Members list now shows the invitee. + _, mraw := h.do(http.MethodGet, "/v1/tenants/"+h.tenant.ID+"/members", nil) + if m := decode[membersBody](t, mraw).Members; len(m) != 1 || m[0].Email != "bob@acme.test" { + t.Errorf("members after invite: %s", mraw) + } + }) +} + +func TestInviteTenantMember_firstAdminSetsAdminEmail(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + h.kcMock.Members["acme"] = []keycloak.OrgMember{} + if h.tenant.AdminEmail != "" { + t.Fatalf("seed tenant must start without admin_email") + } + resp, raw := h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{"email": "owner@acme.test", "role": "owner"}) + if resp.StatusCode != http.StatusAccepted { + t.Fatalf("status %d: %s", resp.StatusCode, raw) + } + _, traw := h.do(http.MethodGet, "/v1/tenants/"+h.tenant.ID, nil) + if tt := decode[store.Tenant](t, traw); tt.AdminEmail != "owner@acme.test" { + t.Fatalf("admin_email not recorded: %s", traw) + } + // A later admin does not displace the first. + h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{"email": "second@acme.test", "role": "IT_ADMIN"}) + _, traw = h.do(http.MethodGet, "/v1/tenants/by-slug/acme", nil) + if tt := decode[store.Tenant](t, traw); tt.AdminEmail != "owner@acme.test" { + t.Fatalf("admin_email displaced: %s", traw) + } + }) +} + +func TestInviteTenantMember_validation(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + h.kcMock.Members["acme"] = []keycloak.OrgMember{} + base := "/v1/tenants/" + h.tenant.ID + "/invites" + cases := []struct { + name string + body any + want int + code string + }{ + {"bad json", "{", http.StatusBadRequest, "invalid_body"}, + {"missing email", map[string]any{}, http.StatusBadRequest, "invalid_email"}, + {"display-name email", map[string]any{"email": "Bob "}, http.StatusBadRequest, "invalid_email"}, + {"bad role", map[string]any{"email": "x@acme.test", "role": "not a role"}, http.StatusBadRequest, "invalid_role"}, + {"long name", map[string]any{"email": "x@acme.test", "first_name": string(make([]byte, 101))}, http.StatusBadRequest, "invalid_name"}, + } + for _, c := range cases { + var resp *http.Response + var raw []byte + if s, ok := c.body.(string); ok { + resp, raw = h.doRaw(http.MethodPost, base, s) + } else { + resp, raw = h.do(http.MethodPost, base, c.body) + } + if resp.StatusCode != c.want { + t.Errorf("%s: status %d: %s", c.name, resp.StatusCode, raw) + continue + } + if e := decode[struct { + Error string `json:"error"` + }](t, raw); e.Error != c.code { + t.Errorf("%s: error %q, want %q", c.name, e.Error, c.code) + } + } + if resp, _ := h.do(http.MethodPost, "/v1/tenants/00000000-0000-0000-0000-0000000000ff/invites", map[string]any{"email": "x@acme.test"}); resp.StatusCode != http.StatusNotFound { + t.Errorf("unknown tenant: %d", resp.StatusCode) + } + }) +} + +func TestInviteTenantMember_keycloakErrors(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + // No org yet (sales-led tenant): the portal must invite the first + // admin through tenant creation. + resp, raw := h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{"email": "x@acme.test"}) + if resp.StatusCode != http.StatusConflict { + t.Fatalf("no org: %d %s", resp.StatusCode, raw) + } + h.kcMock.Members["acme"] = []keycloak.OrgMember{} + h.kcMock.FailNext = keycloak.ErrUnauthorized + if resp, _ := h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{"email": "x@acme.test"}); resp.StatusCode != http.StatusServiceUnavailable { + t.Errorf("kc unauthorized: %d", resp.StatusCode) + } + h.kcMock.FailNext = errAny + if resp, _ := h.do(http.MethodPost, "/v1/tenants/"+h.tenant.ID+"/invites", map[string]any{"email": "x@acme.test"}); resp.StatusCode != http.StatusBadGateway { + t.Errorf("kc generic error: %d", resp.StatusCode) + } + }) +} + +func TestCreateTenant_storesAdminEmail(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + resp, body := h.do("POST", "/v1/tenants", map[string]any{ + "slug": "gamma-co", "name": "Gamma", "admin_email": "Root@Gamma.test", "admin_name": "Root User", + }) + if resp.StatusCode != http.StatusCreated { + t.Fatalf("status = %d, body=%s", resp.StatusCode, body) + } + out := decode[struct { + Tenant *store.Tenant `json:"tenant"` + }](t, body) + if out.Tenant.AdminEmail != "root@gamma.test" { + t.Errorf("admin_email = %q", out.Tenant.AdminEmail) + } + _, traw := h.do("GET", "/v1/tenants/"+out.Tenant.ID, nil) + if tt := decode[store.Tenant](t, traw); tt.AdminEmail != "root@gamma.test" { + t.Errorf("admin_email not persisted: %s", traw) + } + }) +} diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index 8bcfca2..99d0be8 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -46,6 +46,8 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"GET", "/v1/audit?limit=10"}, {"POST", "/v1/internal/keycloak/claims"}, {"GET", "/v1/tenants?limit=10"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/members"}, + {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/invites"}, {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/status"}, {"POST", "/v1/internal/entitlements/check"}, {"POST", "/v1/internal/erp/webhook"}, diff --git a/internal/server/server.go b/internal/server/server.go index 096385e..53f4467 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -91,6 +91,17 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("POST /v1/tenants/{id}/activate", s.activateTenant) mux.HandleFunc("POST /v1/tenants/{id}/cancel", s.cancelTenant) mux.HandleFunc("POST /v1/tenants/{id}/status", s.setTenantStatus) + // tenant members (D1) — portal Settings/Users. Route groups: + // GET members = tenants.read, POST invites = tenants.write. + // + // The GET is registered as a wildcard sub-resource, not as + // "GET /v1/tenants/{id}/members": ServeMux rejects that one as conflicting + // with "GET /v1/tenants/by-slug/{slug}", because both match + // "/v1/tenants/by-slug/members" and neither is the more specific pattern. + // "/v1/tenants/{id}/{sub}" *is* less specific than the by-slug lookup, so + // the two coexist and the lookup keeps winning for its own prefix. + mux.HandleFunc("GET /v1/tenants/{id}/{sub}", s.tenantSubresource) + mux.HandleFunc("POST /v1/tenants/{id}/invites", s.inviteTenantMember) // entitlements mux.HandleFunc("GET /v1/entitlements", s.listTenantProducts) diff --git a/internal/server/server_test.go b/internal/server/server_test.go index adea46c..2ba470f 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -183,6 +183,25 @@ func (h *testHarness) do(method, path string, body any) (*http.Response, []byte) return resp, raw } +// doRaw sends body verbatim (malformed JSON tests). +func (h *testHarness) doRaw(method, path, body string) (*http.Response, []byte) { + h.t.Helper() + req, err := http.NewRequest(method, h.srv.URL+path, bytes.NewReader([]byte(body))) + if err != nil { + h.t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + h.t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + raw, _ := io.ReadAll(resp.Body) + return resp, raw +} + +var errAny = fmt.Errorf("boom") + func decode[T any](t *testing.T, raw []byte) T { t.Helper() var v T diff --git a/internal/server/tenants.go b/internal/server/tenants.go index cb1e438..44ab7c5 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -59,6 +59,7 @@ func (s *Server) createTenant(w http.ResponseWriter, r *http.Request) { defer cancel() t, err := s.Store.CreateTenant(ctx, store.TenantCreate{ Slug: in.Slug, Name: in.Name, Plan: in.Plan, Kind: in.Kind, SalesOwner: in.SalesOwner, + AdminEmail: strings.ToLower(strings.TrimSpace(in.AdminEmail)), }) if err != nil { if mapStoreError(w, err) { diff --git a/internal/store/memory.go b/internal/store/memory.go index 7611779..09ee9d9 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -103,6 +103,7 @@ func (m *Memory) CreateTenant(_ context.Context, in TenantCreate) (*Tenant, erro Kind: kind, Plan: firstNonEmpty(in.Plan, "starter"), SalesOwner: in.SalesOwner, + AdminEmail: in.AdminEmail, TrialEndsAt: trialEnds, StatusChangedAt: now, CreatedAt: now, @@ -186,6 +187,9 @@ func (m *Memory) UpdateTenant(_ context.Context, id string, in TenantUpdate) (*T if in.SalesOwner != nil { t.SalesOwner = *in.SalesOwner } + if in.AdminEmail != nil { + t.AdminEmail = *in.AdminEmail + } t.UpdatedAt = time.Now().UTC() cp := *t return &cp, nil diff --git a/internal/store/postgres.go b/internal/store/postgres.go index d242b1c..7352725 100644 --- a/internal/store/postgres.go +++ b/internal/store/postgres.go @@ -63,7 +63,7 @@ const tenantSelect = ` SELECT id::text, slug, name, status::text, kind::text, plan, COALESCE(erp_customer_id,''), COALESCE(stripe_cust_id,''), trial_ends_at, contract_start, contract_end, COALESCE(sales_owner,''), - status_changed_at, created_at, updated_at + COALESCE(admin_email,''), status_changed_at, created_at, updated_at FROM tenants ` func scanTenant(row pgx.Row) (*Tenant, error) { @@ -73,7 +73,7 @@ func scanTenant(row pgx.Row) (*Tenant, error) { &t.ID, &t.Slug, &t.Name, &t.Status, &t.Kind, &t.Plan, &t.ErpCustomerID, &t.StripeCustID, &trialEnds, &cStart, &cEnd, &t.SalesOwner, - &t.StatusChangedAt, &t.CreatedAt, &t.UpdatedAt, + &t.AdminEmail, &t.StatusChangedAt, &t.CreatedAt, &t.UpdatedAt, ) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound @@ -95,20 +95,21 @@ func (p *Postgres) CreateTenant(ctx context.Context, in TenantCreate) (*Tenant, // (kind=demo) get status='demo' and no trial_ends_at — that's set by // the M13.2 demo provisioning path. row := p.pool.QueryRow(ctx, - `INSERT INTO tenants (slug, name, kind, plan, status, sales_owner, trial_ends_at) + `INSERT INTO tenants (slug, name, kind, plan, status, sales_owner, trial_ends_at, admin_email) VALUES ( $1, $2, $3::tenant_kind, $4, CASE WHEN $3::tenant_kind = 'demo' THEN 'demo'::tenant_status ELSE 'trial'::tenant_status END, NULLIF($5, ''), CASE WHEN $3::tenant_kind = 'demo' THEN NULL - ELSE NOW() + INTERVAL '14 days' END + ELSE NOW() + INTERVAL '14 days' END, + NULLIF($6, '') ) RETURNING id::text, slug, name, status::text, kind::text, plan, COALESCE(erp_customer_id,''), COALESCE(stripe_cust_id,''), trial_ends_at, contract_start, contract_end, COALESCE(sales_owner,''), - status_changed_at, created_at, updated_at`, - in.Slug, in.Name, kind, plan, in.SalesOwner, + COALESCE(admin_email,''), status_changed_at, created_at, updated_at`, + in.Slug, in.Name, kind, plan, in.SalesOwner, in.AdminEmail, ) t, err := scanTenant(row) if err != nil { @@ -150,17 +151,18 @@ func (p *Postgres) UpdateTenant(ctx context.Context, id string, in TenantUpdate) trial_ends_at = COALESCE($6, trial_ends_at), contract_start = COALESCE($7, contract_start), contract_end = COALESCE($8, contract_end), - sales_owner = COALESCE($9, sales_owner) + sales_owner = COALESCE($9, sales_owner), + admin_email = COALESCE($10, admin_email) WHERE id = $1::uuid RETURNING id::text, slug, name, status::text, kind::text, plan, COALESCE(erp_customer_id,''), COALESCE(stripe_cust_id,''), trial_ends_at, contract_start, contract_end, COALESCE(sales_owner,''), - status_changed_at, created_at, updated_at`, + COALESCE(admin_email,''), status_changed_at, created_at, updated_at`, id, nullableStr(in.Status), nullableStr(in.Plan), nullableStr(in.ErpCustomerID), nullableStr(in.StripeCustID), nullableTime(in.TrialEndsAt), nullableTime(in.ContractStart), nullableTime(in.ContractEnd), - nullableStr(in.SalesOwner), + nullableStr(in.SalesOwner), nullableStr(in.AdminEmail), ) t, err := scanTenant(row) if err != nil { diff --git a/internal/store/store.go b/internal/store/store.go index 8f6ae4b..40bbbd9 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -24,6 +24,7 @@ type TenantCreate struct { Plan string // optional, defaults to "starter" Kind string // optional, defaults to "customer" SalesOwner string // optional + AdminEmail string // optional — the first admin invited at creation } // TenantUpdate captures partial mutations. Nil fields are left untouched. @@ -36,6 +37,7 @@ type TenantUpdate struct { ContractStart *time.Time ContractEnd *time.Time SalesOwner *string + AdminEmail *string } // APIKeyCreate is the input shape for Store.CreateAPIKey. diff --git a/internal/store/types.go b/internal/store/types.go index c7244ea..2454c3d 100644 --- a/internal/store/types.go +++ b/internal/store/types.go @@ -22,6 +22,10 @@ type Tenant struct { ContractStart *time.Time `json:"contract_start,omitempty"` ContractEnd *time.Time `json:"contract_end,omitempty"` SalesOwner string `json:"sales_owner,omitempty"` + // AdminEmail — the tenant's first admin (IT_ADMIN/OWNER), recorded at + // creation or on the first admin invite. Empty for sales-led tenants + // that have not invited anyone yet. + AdminEmail string `json:"admin_email,omitempty"` // StatusChangedAt — when the current ladder status was entered (M-MIG-7). StatusChangedAt time.Time `json:"status_changed_at"` CreatedAt time.Time `json:"created_at"` diff --git a/migrations/0006_admin_email.down.sql b/migrations/0006_admin_email.down.sql new file mode 100644 index 0000000..28c2a5a --- /dev/null +++ b/migrations/0006_admin_email.down.sql @@ -0,0 +1 @@ +ALTER TABLE tenants DROP COLUMN IF EXISTS admin_email; diff --git a/migrations/0006_admin_email.up.sql b/migrations/0006_admin_email.up.sql new file mode 100644 index 0000000..5829e22 --- /dev/null +++ b/migrations/0006_admin_email.up.sql @@ -0,0 +1,37 @@ +-- D1: the portal's Settings/Users page shows who the tenant's first admin +-- is. Stored at creation (POST /v1/tenants admin_email) or on the first +-- IT_ADMIN/OWNER invite through POST /v1/tenants/{id}/invites. Nullable — +-- sales-led tenants may not have an admin yet. +ALTER TABLE tenants ADD COLUMN admin_email TEXT; + +-- Backfill from the audit trail: the first successful Keycloak invite per +-- tenant is the first admin (createTenant emits keycloak.invite_sent with +-- target_id = admin email) … +UPDATE tenants t + SET admin_email = a.target_id + FROM ( + SELECT DISTINCT ON (tenant_id) tenant_id, target_id + FROM audit_log + WHERE action = 'keycloak.invite_sent' + AND target_type = 'user' + AND tenant_id IS NOT NULL + AND target_id <> '' + ORDER BY tenant_id, created_at ASC, id ASC + ) a + WHERE a.tenant_id = t.id + AND t.admin_email IS NULL; + +-- … and, where provisioning failed, from the admin_email the failure +-- event recorded (the operator re-sent the invite by hand). +UPDATE tenants t + SET admin_email = a.admin_email + FROM ( + SELECT DISTINCT ON (tenant_id) tenant_id, metadata->>'admin_email' AS admin_email + FROM audit_log + WHERE action = 'keycloak.provision_failed' + AND tenant_id IS NOT NULL + AND COALESCE(metadata->>'admin_email', '') <> '' + ORDER BY tenant_id, created_at ASC, id ASC + ) a + WHERE a.tenant_id = t.id + AND t.admin_email IS NULL; diff --git a/openapi.yaml b/openapi.yaml index d1c2e25..7a8fff2 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -206,6 +206,78 @@ paths: application/json: { schema: { $ref: "#/components/schemas/Tenant" } } "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/members: + get: + summary: List the tenant's Keycloak organization members. + description: | + The portal's Settings/Users page. A user token may only read its own + tenant — another tenant's id answers 404, never a hint that it exists. + Service clients are gated on the `tenants.read` route group. A tenant + whose organization was never created (sales-led) answers with an empty + list rather than an error. + parameters: + - in: path + name: id + required: true + schema: { type: string, format: uuid } + responses: + "200": + description: Members of the organization. + content: + application/json: + schema: + type: object + required: [members] + properties: + members: + type: array + items: { $ref: "#/components/schemas/OrgMember" } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/tenants/{id}/invites: + post: + summary: Invite a user into the tenant's organization. + description: | + Creates the Keycloak user if needed, adds it to the tenant's + organization, writes the tenant-context user attributes and sends the + same execute-actions email the first admin receives. Idempotent: an + existing member answers `200 {status: member}` and sends no mail. + User tokens need the `IT_ADMIN` or `OWNER` org role; service clients + need the `tenants.write` route group. + parameters: + - in: path + name: id + required: true + schema: { type: string, format: uuid } + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [email] + properties: + email: { type: string, format: email } + first_name: { type: string, maxLength: 100 } + last_name: { type: string, maxLength: 100 } + role: + type: string + pattern: '^[A-Z][A-Z0-9_]{1,31}$' + default: USER + description: "org_roles attribute written for the user" + responses: + "202": + description: Invited; the mail is on its way. + content: + application/json: { schema: { $ref: "#/components/schemas/Invite" } } + "200": + description: Already a member; nothing sent. + content: + application/json: { schema: { $ref: "#/components/schemas/Invite" } } + "400": { $ref: "#/components/responses/BadRequest" } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + /v1/entitlements: get: summary: List product entitlements for a tenant. @@ -745,6 +817,10 @@ components: description: Resource already exists / unique violation. content: application/json: { schema: { $ref: "#/components/schemas/Error" } } + Forbidden: + description: The caller may not perform this operation. + content: + application/json: { schema: { $ref: "#/components/schemas/Error" } } schemas: ErpWebhookEvent: @@ -905,9 +981,32 @@ components: contract_start: { type: string, format: date, nullable: true } contract_end: { type: string, format: date, nullable: true } sales_owner: { type: string } + admin_email: { type: string, format: email, description: "the tenant's first admin; empty for sales-led tenants" } created_at: { type: string, format: date-time } updated_at: { type: string, format: date-time } + OrgMember: + type: object + required: [user_id, email, enabled] + properties: + user_id: { type: string } + email: { type: string, format: email } + first_name: { type: string } + last_name: { type: string } + org_roles: + type: array + items: { type: string } + enabled: { type: boolean } + created_at: { type: string, format: date-time, nullable: true } + + Invite: + type: object + required: [user_id, email, status] + properties: + user_id: { type: string } + email: { type: string, format: email } + status: { type: string, enum: [invited, member] } + TenantCreate: type: object required: [slug, name] -- 2.54.1