Files
tenant-registry/internal/server/members.go
T
Sharang ParnerkarandClaude Opus 5.5 2c758749dc
ci / shared (pull_request) Failing after 4s
ci / test (pull_request) Successful in 24m34s
ci / image (pull_request) Skipped
feat: role and authority dataset (R1 S0)
One Rollen- und Befugnisdatensatz per company (docgen#1 plan 13781 §3.2
no. 2, owner addendum 13791): functions, who holds them, deputies with
their basis, the deciding function per decision type, immediate
authority, standard releases, named editors and the contact path for
critical security events.

- internal/roles: the catalogue in code (version r1-2026-10-26.1), the
  union of A1 §2.3 and A4 §4 = 21 functions, 14 customer decision types;
  only the three releases carry an owner default (management), the rest
  must be set by the company.
- Rules: a deputy is wirksam only with a documented basis, within its
  validity and, where it covers management authority, with management's
  authorization (B7 wording: what management records it has authorized);
  another release body for R1-D02 updates only with the R1-D02 provision
  (B8); management and document owners write, the OWNER sign-in role may
  only record the first management holder; recorded_*/authorized_* are
  stamped from the token, never from the body; no self-authorization.
- Routes: GET/PUT /v1/tenants/{id}/role-dataset, GET …/revisions/{rev},
  GET …/resolve. Writes need the user's token; user tokens on these
  routes form route group role-dataset.user, so the portal's sign-in
  client needs no tenants grant.
- Migration 0024: role_datasets and role_dataset_revisions, versioned as
  the company profile (expected_revision, 409 on conflict).
- Audit role_dataset.saved with revision and changed entry ids only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014aRnCGqELxoix5TfpX8Ejf
2026-10-26 21:25:08 +01:00

220 lines
7.6 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) {
switch r.PathValue("sub") {
case "members":
s.listTenantMembers(w, r)
case "documents":
s.listTenantDocuments(w, r)
case "projects":
s.listTenantProjects(w, r)
case "contracts":
s.listTenantContracts(w, r)
case "managed-services":
s.listTenantManagedServices(w, r)
case "company-profile":
s.getCompanyProfile(w, r)
case "role-dataset":
s.getRoleDataset(w, r)
case "store":
s.listStore(w, r)
default:
writeError(w, http.StatusNotFound, "not_found", "no such tenant sub-resource")
}
}
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{}
}
decorateMembers(members, t.ID)
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())
}