Files
tenant-registry/internal/server/members.go
T
sharangandSharang Parnerkar 99214c088b
ci / shared (push) Successful in 13s
ci / test (push) Successful in 22m21s
ci / image (push) Successful in 25s
feat(members): tenant organization members, invites, admin email (#28)
Demonstration plan, phase D1 (registry side). The portal's Settings/Users page renders design fixtures today and its "Invite member" button posts to a route that does not exist, because the registry had no membership surface.

**`GET /v1/tenants/{id}/members`** lists the tenant's Keycloak organization members — user id, email, first/last name, `org_roles`, `enabled`, `created_at`. A tenant whose organization was never created (sales-led) answers an empty list rather than an error.

**`POST /v1/tenants/{id}/invites`** `{email, first_name?, last_name?, role?}` creates the Keycloak user if missing, adds the organization member (KC 26: the member body is the bare user id), writes the tenant-context user attributes, sends the same execute-actions mail the first admin gets, and audits `user.invited` with the caller as actor. Idempotent: an existing member answers `200 {status:"member"}` and sends no mail; a new one `202 {status:"invited"}`.

**Scope.** A user token may only touch its own tenant — another tenant's id is a 404, never a hint that it exists. Inviting needs the `IT_ADMIN` or `OWNER` org role, so `Principal` now carries the `org_roles` claim and `IsTenantAdmin()`. Service clients stay gated by `AUTHZ_RULES` route groups: members on `tenants.read`, invites on `tenants.write`.

**`admin_email` on the tenant** (migration `0006`, backfilled from the `keycloak.invite_sent` audit trail, and from `keycloak.provision_failed` metadata where the first invite failed) so Settings can show a real contact instead of an em dash. The first `IT_ADMIN`/`OWNER` invite fills it in when it was empty.

**Routing note worth keeping:** `GET /v1/tenants/{id}/members` cannot be registered — Go's ServeMux calls it a conflict with `GET /v1/tenants/by-slug/{slug}`, since both match `/v1/tenants/by-slug/members` and neither pattern is more specific. It is registered as `GET /v1/tenants/{id}/{sub}` instead, which *is* less specific than the by-slug lookup, so the two coexist; anything but `members` answers 404.

`openapi.yaml` documents both endpoints, the `OrgMember`/`Invite` schemas, `admin_email` and a `Forbidden` response.

Verified locally: `go vet ./...`, `gofmt` clean, `go test ./...` green, CI coverage command at **74.3%** (gate 70%).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #28
2026-09-14 08:27:12 +00:00

204 lines
7.2 KiB
Go

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())
}