Files
sharangandClaude Opus 5.5 1f6236a754
ci / shared (push) Successful in 12s
ci / test (push) Successful in 24m46s
ci / image (push) Successful in 33s
feat(members): team management: role, block, remove, revoke, resend (#64)
portal#74: PATCH/DELETE /v1/tenants/{id}/members/{uid}, POST .../resend and the staff variants; per-workspace block via org_blocked, session logout, last-admin and self guards, audit events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
2026-10-05 18:43:31 +00:00

491 lines
17 KiB
Go

package server
import (
"context"
"errors"
"net/http"
"slices"
"strings"
"sync"
"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"
)
// Team management (portal#74): change a member's role, block or unblock
// them in this workspace, remove them or revoke a pending invitation, and
// resend an invitation.
//
// PATCH /v1/tenants/{id}/members/{uid} {"role"} | {"blocked"}
// DELETE /v1/tenants/{id}/members/{uid} remove / revoke invitation
// POST /v1/tenants/{id}/members/{uid}/resend
//
// and the same three under /v1/admin/tenants/{id}/members/{uid} for staff
// (route group "admin"; the portal lets only BREAKPILOT_ADMIN write).
//
// Who may: a user token needs IT_ADMIN/OWNER in its own tenant; a service
// client needs tenants.write. The portal calls as its service client and
// names the person in X-Portal-User-Subject / X-Portal-User-Email (staff:
// X-Staff-*), which the guards and the audit trail use.
//
// Guards (409): nobody acts on themselves ("self"); the last active
// IT_ADMIN/OWNER is never demoted, blocked or removed ("last_admin").
//
// Block is per workspace: the tenant id goes into the member's org_blocked
// attribute (keycloak.AttrOrgBlocked), never enabled=false — a person can
// belong to several workspaces. Remove and block end the member's Keycloak
// sessions (realm-wide: Keycloak has no per-organization logout).
const headerPortalUserSubject = "X-Portal-User-Subject"
// teamRoles are the org roles a member can be given.
var teamRoles = []string{authn.RoleITAdmin, authn.RoleOwner, "CXO", "FINANCE", "LEGAL", "USER"}
func isAdminRole(roles []string) bool {
return slices.Contains(roles, authn.RoleITAdmin) || slices.Contains(roles, authn.RoleOwner)
}
type memberPatchReq struct {
Role *string `json:"role"`
Blocked *bool `json:"blocked"`
}
type memberActionResp struct {
// Status: role_changed | unchanged | blocked | unblocked | removed |
// invite_revoked | invite_resent.
Status string `json:"status"`
Member *keycloak.OrgMember `json:"member,omitempty"`
// UserDeleted: revoking the invitation also deleted the account (it was
// created by the invitation and belongs to no other workspace).
UserDeleted bool `json:"user_deleted,omitempty"`
// SessionsEnded: the member's Keycloak sessions were ended.
SessionsEnded bool `json:"sessions_ended,omitempty"`
// APIKeys: the member's active API keys in this tenant, offered for
// revocation after a remove or block — never revoked silently.
APIKeys []store.APIKey `json:"api_keys,omitempty"`
}
// teamActor is who performs a team action, for the guards and the audit.
type teamActor struct {
ID, Email, Type string
}
func (s *Server) teamActor(r *http.Request) teamActor {
if sub, email, ok := s.staffActor(r); ok {
return teamActor{ID: sub, Email: email, Type: "staff"}
}
p, _ := authn.PrincipalFrom(r.Context())
if p.IsUser() {
return teamActor{ID: p.Subject, Email: p.Email, Type: "user"}
}
// The portal acting for a signed-in tenant admin.
if sub := strings.TrimSpace(r.Header.Get(headerPortalUserSubject)); sub != "" {
return teamActor{ID: sub, Email: strings.TrimSpace(r.Header.Get(headerPortalUserEmail)), Type: "user"}
}
a := teamActor{Type: "service"}
if p != nil {
a.ID = p.Subject
}
return a
}
func (a teamActor) is(m keycloak.OrgMember) bool {
return (a.ID != "" && a.ID == m.UserID) || (a.Email != "" && strings.EqualFold(a.Email, m.Email))
}
// teamTenantFromUser resolves the tenant for the tenant-scoped routes: a
// user token needs a tenant-admin role and its own tenant.
func (s *Server) teamTenantFromUser(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, bool) {
if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && !p.IsTenantAdmin() {
writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "managing users requires the IT_ADMIN or OWNER org role")
return nil, false
}
return s.tenantInScope(ctx, w, r)
}
// teamTenantFromAdmin resolves the tenant for the staff routes.
func (s *Server) teamTenantFromAdmin(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) {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
}
return nil, false
}
return t, true
}
type tenantResolver func(context.Context, http.ResponseWriter, *http.Request) (*store.Tenant, bool)
// teamTarget loads the tenant, its members and the member the path names.
func (s *Server) teamTarget(ctx context.Context, w http.ResponseWriter, r *http.Request, resolve tenantResolver) (*store.Tenant, []keycloak.OrgMember, *keycloak.OrgMember, bool) {
t, ok := resolve(ctx, w, r)
if !ok {
return nil, nil, nil, false
}
members, err := s.Keycloak.ListOrgMembers(ctx, t.Slug)
if err != nil && !errors.Is(err, keycloak.ErrOrgNotFound) {
s.writeKeycloakError(w, t.ID, "list members", err)
return nil, nil, nil, false
}
decorateMembers(members, t.ID)
uid := r.PathValue("uid")
for i := range members {
if members[i].UserID == uid {
return t, members, &members[i], true
}
}
writeError(w, http.StatusNotFound, "not_a_member", "no such member in this tenant")
return nil, nil, nil, false
}
// decorateMembers sets each member's status for tenantID.
func decorateMembers(members []keycloak.OrgMember, tenantID string) {
for i := range members {
members[i].Status = members[i].MemberStatus(tenantID)
}
}
// lastActiveAdmin reports whether target is the only active (accepted, not
// blocked) IT_ADMIN/OWNER of the tenant.
func lastActiveAdmin(members []keycloak.OrgMember, target *keycloak.OrgMember) bool {
if target.Status != keycloak.MemberActive || !isAdminRole(target.OrgRoles) {
return false
}
for _, m := range members {
if m.UserID != target.UserID && m.Status == keycloak.MemberActive && isAdminRole(m.OrgRoles) {
return false
}
}
return true
}
func (s *Server) teamAudit(ctx context.Context, r *http.Request, t *store.Tenant, actor teamActor, action string, m *keycloak.OrgMember, meta map[string]interface{}) {
if meta == nil {
meta = map[string]interface{}{}
}
meta["user_id"] = m.UserID
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: action,
ActorID: actor.ID, ActorName: actor.Email, ActorType: actor.Type,
TargetID: m.Email, TargetType: "user", TargetName: m.Email,
Metadata: meta,
})
}
// memberAPIKeys lists the tenant's active API keys created by the member.
func (s *Server) memberAPIKeys(ctx context.Context, tenantID string, m *keycloak.OrgMember) []store.APIKey {
keys, err := s.Store.ListAPIKeys(ctx, tenantID)
if err != nil {
s.Log.Warn("api keys not listed", "tenant_id", tenantID, "err", err)
return nil
}
out := []store.APIKey{}
for _, k := range keys {
if k.RevokedAt == nil && k.CreatedBy != "" && (k.CreatedBy == m.UserID || strings.EqualFold(k.CreatedBy, m.Email)) {
out = append(out, k)
}
}
return out
}
// endSessions logs the member out; a failure is logged, not fatal (the
// block or removal already holds, the session dies at token expiry).
func (s *Server) endSessions(ctx context.Context, tenantID, userID string) bool {
if err := s.Keycloak.LogoutUser(ctx, userID); err != nil {
s.Log.Warn("member sessions not ended", "tenant_id", tenantID, "user_id", userID, "err", err)
return false
}
return true
}
func (s *Server) patchTenantMember(w http.ResponseWriter, r *http.Request) {
s.patchMember(w, r, s.teamTenantFromUser)
}
func (s *Server) adminPatchMember(w http.ResponseWriter, r *http.Request) {
s.patchMember(w, r, s.teamTenantFromAdmin)
}
func (s *Server) patchMember(w http.ResponseWriter, r *http.Request, resolve tenantResolver) {
var in memberPatchReq
if !decodeJSON(w, r, &in) {
return
}
if (in.Role == nil) == (in.Blocked == nil) {
writeError(w, http.StatusBadRequest, "invalid_input", "send exactly one of role or blocked")
return
}
role := ""
if in.Role != nil {
role = strings.ToUpper(strings.TrimSpace(*in.Role))
if !slices.Contains(teamRoles, role) {
writeError(w, http.StatusBadRequest, "invalid_role", "role must be one of "+strings.Join(teamRoles, ", "))
return
}
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
t, members, m, ok := s.teamTarget(ctx, w, r, resolve)
if !ok {
return
}
actor := s.teamActor(r)
if actor.is(*m) {
writeError(w, http.StatusConflict, "self", "you cannot change your own membership")
return
}
if in.Role != nil {
s.changeRole(ctx, w, r, t, actor, members, m, role)
return
}
s.setBlocked(ctx, w, r, t, actor, members, m, *in.Blocked)
}
func (s *Server) changeRole(ctx context.Context, w http.ResponseWriter, r *http.Request, t *store.Tenant, actor teamActor, members []keycloak.OrgMember, m *keycloak.OrgMember, role string) {
old := slices.Clone(m.OrgRoles)
if len(old) == 1 && old[0] == role {
writeJSON(w, http.StatusOK, memberActionResp{Status: "unchanged", Member: m})
return
}
if !isAdminRole([]string{role}) && lastActiveAdmin(members, m) {
writeError(w, http.StatusConflict, "last_admin", "the last IT_ADMIN of a workspace cannot be demoted")
return
}
if err := s.Keycloak.SetMemberRole(ctx, m.UserID, role); err != nil {
s.writeKeycloakError(w, t.ID, "set member role", err)
return
}
m.OrgRoles = []string{role}
s.teamAudit(ctx, r, t, actor, "user.role_changed", m, map[string]interface{}{"from": old, "to": role})
writeJSON(w, http.StatusOK, memberActionResp{Status: "role_changed", Member: m})
}
func (s *Server) setBlocked(ctx context.Context, w http.ResponseWriter, r *http.Request, t *store.Tenant, actor teamActor, members []keycloak.OrgMember, m *keycloak.OrgMember, blocked bool) {
if blocked == (m.Status == keycloak.MemberBlocked) {
writeJSON(w, http.StatusOK, memberActionResp{Status: "unchanged", Member: m})
return
}
if blocked && lastActiveAdmin(members, m) {
writeError(w, http.StatusConflict, "last_admin", "the last IT_ADMIN of a workspace cannot be blocked")
return
}
if err := s.Keycloak.SetMemberBlocked(ctx, m.UserID, t.ID, blocked); err != nil {
s.writeKeycloakError(w, t.ID, "set member blocked", err)
return
}
s.blocks.forget(m.UserID)
if !blocked {
m.BlockedTenants = slices.DeleteFunc(m.BlockedTenants, func(v string) bool { return v == t.ID })
m.Status = m.MemberStatus(t.ID)
s.teamAudit(ctx, r, t, actor, "user.unblocked", m, nil)
writeJSON(w, http.StatusOK, memberActionResp{Status: "unblocked", Member: m})
return
}
m.BlockedTenants = append(m.BlockedTenants, t.ID)
m.Status = keycloak.MemberBlocked
ended := s.endSessions(ctx, t.ID, m.UserID)
keys := s.memberAPIKeys(ctx, t.ID, m)
s.teamAudit(ctx, r, t, actor, "user.blocked", m, map[string]interface{}{"sessions_ended": ended, "api_keys": len(keys)})
writeJSON(w, http.StatusOK, memberActionResp{Status: "blocked", Member: m, SessionsEnded: ended, APIKeys: keys})
}
func (s *Server) deleteTenantMember(w http.ResponseWriter, r *http.Request) {
s.deleteMember(w, r, s.teamTenantFromUser)
}
func (s *Server) adminDeleteMember(w http.ResponseWriter, r *http.Request) {
s.deleteMember(w, r, s.teamTenantFromAdmin)
}
// deleteMember removes an accepted member, or revokes a pending invitation.
func (s *Server) deleteMember(w http.ResponseWriter, r *http.Request, resolve tenantResolver) {
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
t, members, m, ok := s.teamTarget(ctx, w, r, resolve)
if !ok {
return
}
actor := s.teamActor(r)
if actor.is(*m) {
writeError(w, http.StatusConflict, "self", "you cannot remove yourself")
return
}
if lastActiveAdmin(members, m) {
writeError(w, http.StatusConflict, "last_admin", "the last IT_ADMIN of a workspace cannot be removed")
return
}
if m.Status == keycloak.MemberInvited {
created := s.inviteCreatedUser(ctx, t.ID, m.UserID)
deleted, err := s.Keycloak.RemoveMember(ctx, t.Slug, t.ID, m.UserID, created)
if err != nil {
s.writeKeycloakError(w, t.ID, "revoke invitation", err)
return
}
s.blocks.forget(m.UserID)
s.teamAudit(ctx, r, t, actor, "user.invite_revoked", m, map[string]interface{}{"user_deleted": deleted})
writeJSON(w, http.StatusOK, memberActionResp{Status: "invite_revoked", UserDeleted: deleted})
return
}
if _, err := s.Keycloak.RemoveMember(ctx, t.Slug, t.ID, m.UserID, false); err != nil {
s.writeKeycloakError(w, t.ID, "remove member", err)
return
}
s.blocks.forget(m.UserID)
ended := s.endSessions(ctx, t.ID, m.UserID)
keys := s.memberAPIKeys(ctx, t.ID, m)
s.teamAudit(ctx, r, t, actor, "user.removed", m, map[string]interface{}{"roles": m.OrgRoles, "sessions_ended": ended, "api_keys": len(keys)})
writeJSON(w, http.StatusOK, memberActionResp{Status: "removed", SessionsEnded: ended, APIKeys: keys})
}
// inviteCreatedUser reports whether a user.invited entry of this tenant
// records that the invitation created the Keycloak account userID. Only
// then may revoking the invitation delete the account.
func (s *Server) inviteCreatedUser(ctx context.Context, tenantID, userID string) bool {
f := store.AuditFilter{TenantID: tenantID, Action: "user.invited", Limit: 500}
for range 20 {
items, next, err := s.Store.ListAudit(ctx, f)
if err != nil {
s.Log.Warn("invite audit not read", "tenant_id", tenantID, "err", err)
return false
}
for _, ev := range items {
if ev.Metadata["user_id"] == userID && ev.Metadata["user_created"] == true {
return true
}
}
if next == 0 {
return false
}
f.Cursor = next
}
return false
}
func (s *Server) resendTenantMember(w http.ResponseWriter, r *http.Request) {
s.resendMember(w, r, s.teamTenantFromUser)
}
func (s *Server) adminResendMember(w http.ResponseWriter, r *http.Request) {
s.resendMember(w, r, s.teamTenantFromAdmin)
}
func (s *Server) resendMember(w http.ResponseWriter, r *http.Request, resolve tenantResolver) {
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
t, _, m, ok := s.teamTarget(ctx, w, r, resolve)
if !ok {
return
}
if m.Status != keycloak.MemberInvited {
writeError(w, http.StatusConflict, "not_pending", "the member has already accepted the invitation")
return
}
if err := s.Keycloak.ResendInvite(ctx, t.Slug, m.Email); err != nil {
s.writeKeycloakError(w, t.ID, "resend invite", err)
return
}
s.teamAudit(ctx, r, t, s.teamActor(r), "user.invite_resent", m, nil)
writeJSON(w, http.StatusAccepted, memberActionResp{Status: "invite_resent", Member: m})
}
// ─── blocked members at the door ────────────────────────────────────────
// blockTTL bounds how long a block decision is cached per (user, tenant).
// Blocks made through this registry instance take effect at once (forget).
const blockTTL = 30 * time.Second
type blockEntry struct {
blocked bool
until time.Time
}
// blockCache remembers MemberBlocked answers for user tokens.
type blockCache struct {
mu sync.Mutex
m map[string]blockEntry
}
func (c *blockCache) get(key string, now time.Time) (bool, bool) {
c.mu.Lock()
defer c.mu.Unlock()
e, ok := c.m[key]
if !ok || now.After(e.until) {
return false, false
}
return e.blocked, true
}
func (c *blockCache) put(key string, blocked bool, now time.Time) {
c.mu.Lock()
defer c.mu.Unlock()
if c.m == nil {
c.m = map[string]blockEntry{}
}
c.m[key] = blockEntry{blocked: blocked, until: now.Add(blockTTL)}
}
// forget drops every cached decision for userID.
func (c *blockCache) forget(userID string) {
c.mu.Lock()
defer c.mu.Unlock()
for k := range c.m {
if strings.HasPrefix(k, userID+"|") {
delete(c.m, k)
}
}
}
// requireMember rejects user tokens of a member blocked in the token's
// tenant (portal#74): by the org_blocked claim when a mapper projects it,
// and — independent of any mapper — by the user's org_blocked attribute in
// Keycloak (cached for blockTTL). Service tokens pass. A Keycloak outage
// does not lock everyone out: the lookup then fails open and logs.
func (s *Server) requireMember(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p, _ := authn.PrincipalFrom(r.Context())
if !p.IsUser() {
next.ServeHTTP(w, r)
return
}
if slices.Contains(p.OrgBlocked, p.TenantID) {
writeError(w, http.StatusForbidden, "MEMBER_BLOCKED", "your access to this workspace is blocked")
return
}
blocked, err := s.memberBlocked(r.Context(), p.Subject, p.TenantID)
switch {
case errors.Is(err, keycloak.ErrUserNotFound):
writeError(w, http.StatusForbidden, "USER_UNKNOWN", "the account no longer exists")
return
case err != nil:
s.Log.Warn("member block check failed; allowing", "user_id", p.Subject, "tenant_id", p.TenantID, "err", err)
case blocked:
writeError(w, http.StatusForbidden, "MEMBER_BLOCKED", "your access to this workspace is blocked")
return
}
next.ServeHTTP(w, r)
})
}
// memberBlocked is Keycloak.MemberBlocked behind the blockCache.
func (s *Server) memberBlocked(ctx context.Context, userID, tenantID string) (bool, error) {
key := userID + "|" + tenantID
now := s.now()
if v, ok := s.blocks.get(key, now); ok {
return v, nil
}
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
v, err := s.Keycloak.MemberBlocked(ctx, userID, tenantID)
if err != nil {
return false, err
}
s.blocks.put(key, v, now)
return v, nil
}