A member can hold capabilities on top of their bundle. They live in the
Keycloak user attribute extra_capabilities, which the tenant-context
mapper puts into the token; the registry writes it like org_roles and
clears it when the member leaves.
- POST/DELETE /v1/tenants/{id}/members/{uid}/capabilities[/{cap}]
- a person who holds registry:members.manage grants, never on
themselves, and only what they hold themselves
- an administration capability waits for a second person: open
requests in capability_requests (0029), approve or reject under
/v1/tenants/{id}/capability-requests
- a role change keeps the extras; the principal parses the claim, the
registry's own checks still go by org_roles
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014aRnCGqELxoix5TfpX8Ejf
327 lines
12 KiB
Go
327 lines
12 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/authz"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
)
|
|
|
|
// Individual capabilities (RBAC plan step 3): what one member may do on top
|
|
// of their bundle. They live in the member's Keycloak attribute
|
|
// extra_capabilities, which the tenant-context mapper puts into the token,
|
|
// so a change takes effect at the member's next token refresh.
|
|
//
|
|
// POST /v1/tenants/{id}/members/{uid}/capabilities {"capability"}
|
|
// DELETE /v1/tenants/{id}/members/{uid}/capabilities/{cap}
|
|
// GET /v1/tenants/{id}/capability-requests (tenantSubresource)
|
|
// POST /v1/tenants/{id}/capability-requests/{rid}/approve
|
|
// DELETE /v1/tenants/{id}/capability-requests/{rid} reject or withdraw
|
|
//
|
|
// Who may (plan §4): a person of the workspace who holds
|
|
// registry:members.manage (the IT_ADMIN and OWNER bundles), never on
|
|
// themselves, and only a capability they hold themselves. Granting an
|
|
// administration capability (Capability.Admin) is not applied at once: it
|
|
// becomes a request that a second such person approves (four-eyes); the
|
|
// requester cannot approve it, nor can the member it is for. Revoking takes
|
|
// effect at once and drops an open request for the same capability.
|
|
//
|
|
// The caller is resolved like the other team routes (teamActor): the portal
|
|
// calls as its service client and names the person in X-Portal-User-*; a
|
|
// user token speaks for itself. Staff and plain service clients cannot
|
|
// grant: the rule "only what you hold" needs a person of the workspace.
|
|
//
|
|
// A role change leaves the extras as they are; removing a member clears
|
|
// them (keycloak.tenantAttrs) and drops their open requests.
|
|
|
|
// capManage is the capability that lets a person manage the team.
|
|
const capManage = "registry:members.manage"
|
|
|
|
type capabilityReq struct {
|
|
Capability string `json:"capability"`
|
|
}
|
|
|
|
type capabilityResp struct {
|
|
// Status: capability_granted | capability_revoked | unchanged |
|
|
// approval_requested | request_rejected | request_withdrawn.
|
|
Status string `json:"status"`
|
|
Member *keycloak.OrgMember `json:"member,omitempty"`
|
|
Request *store.CapabilityRequest `json:"request,omitempty"`
|
|
}
|
|
|
|
type capabilityRequestsResp struct {
|
|
Requests []store.CapabilityRequest `json:"requests"`
|
|
}
|
|
|
|
// effective is what member m may do: the capabilities of their bundle and
|
|
// their individual ones the catalogue knows.
|
|
func effective(m keycloak.OrgMember) map[string]bool {
|
|
roles := m.OrgRoles
|
|
if len(roles) == 0 {
|
|
roles = []string{""}
|
|
}
|
|
out := map[string]bool{}
|
|
for _, role := range roles {
|
|
for c := range authz.Effective(role, m.ExtraCapabilities) {
|
|
out[c] = true
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// inBundle reports whether one of m's bundles grants capability.
|
|
func inBundle(m keycloak.OrgMember, capability string) bool {
|
|
for _, role := range m.OrgRoles {
|
|
if authz.Grants(role, capability) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// granter finds the acting person among the members and checks that they
|
|
// may manage capabilities. It writes the error and returns false otherwise.
|
|
func (s *Server) granter(w http.ResponseWriter, r *http.Request, members []keycloak.OrgMember) (teamActor, *keycloak.OrgMember, bool) {
|
|
actor := s.teamActor(r)
|
|
if actor.Type == "user" {
|
|
for i := range members {
|
|
if actor.is(members[i]) && members[i].Status == keycloak.MemberActive {
|
|
if !effective(members[i])[capManage] {
|
|
break
|
|
}
|
|
return actor, &members[i], true
|
|
}
|
|
}
|
|
}
|
|
writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "managing capabilities requires an active member of this workspace who holds "+capManage)
|
|
return actor, nil, false
|
|
}
|
|
|
|
// capabilityTarget loads the tenant, the member the path names and the
|
|
// acting person, and refuses acting on oneself.
|
|
func (s *Server) capabilityTarget(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, []keycloak.OrgMember, *keycloak.OrgMember, teamActor, *keycloak.OrgMember, bool) {
|
|
t, members, m, ok := s.teamTarget(ctx, w, r, s.teamTenantFromUser)
|
|
if !ok {
|
|
return nil, nil, nil, teamActor{}, nil, false
|
|
}
|
|
actor, me, ok := s.granter(w, r, members)
|
|
if !ok {
|
|
return nil, nil, nil, teamActor{}, nil, false
|
|
}
|
|
if actor.is(*m) {
|
|
writeError(w, http.StatusConflict, "self", "you cannot change your own capabilities")
|
|
return nil, nil, nil, teamActor{}, nil, false
|
|
}
|
|
return t, members, m, actor, me, true
|
|
}
|
|
|
|
func (s *Server) grantCapability(w http.ResponseWriter, r *http.Request) {
|
|
var in capabilityReq
|
|
if !decodeJSON(w, r, &in) {
|
|
return
|
|
}
|
|
code := strings.TrimSpace(in.Capability)
|
|
c, known := authz.CapabilityByCode(code)
|
|
if !known {
|
|
writeError(w, http.StatusBadRequest, "unknown_capability", "no such capability in the catalogue")
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
|
defer cancel()
|
|
t, _, m, actor, me, ok := s.capabilityTarget(ctx, w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
if !effective(*me)[code] {
|
|
writeError(w, http.StatusForbidden, "not_held", "you cannot grant a capability you do not hold")
|
|
return
|
|
}
|
|
if inBundle(*m, code) {
|
|
writeError(w, http.StatusConflict, "in_bundle", "the member's bundle grants this capability already")
|
|
return
|
|
}
|
|
if slices.Contains(m.ExtraCapabilities, code) {
|
|
writeJSON(w, http.StatusOK, capabilityResp{Status: "unchanged", Member: m})
|
|
return
|
|
}
|
|
|
|
if c.Admin {
|
|
req, created, err := s.Store.CreateCapabilityRequest(ctx, store.CapabilityRequest{TenantID: t.ID, UserID: m.UserID, UserEmail: m.Email,
|
|
Capability: code, RequestedBy: actor.ID, RequestedEmail: actor.Email})
|
|
if err != nil {
|
|
if !mapStoreError(w, err) {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
}
|
|
return
|
|
}
|
|
if created {
|
|
s.teamAudit(ctx, r, t, actor, "user.capability_requested", m, map[string]interface{}{"capability": code, "request_id": req.ID})
|
|
}
|
|
writeJSON(w, http.StatusAccepted, capabilityResp{Status: "approval_requested", Member: m, Request: req})
|
|
return
|
|
}
|
|
|
|
if !s.setExtras(ctx, w, t, m, append(slices.Clone(m.ExtraCapabilities), code)) {
|
|
return
|
|
}
|
|
s.teamAudit(ctx, r, t, actor, "user.capability_granted", m, map[string]interface{}{"capability": code})
|
|
writeJSON(w, http.StatusOK, capabilityResp{Status: "capability_granted", Member: m})
|
|
}
|
|
|
|
func (s *Server) revokeCapability(w http.ResponseWriter, r *http.Request) {
|
|
code := strings.TrimSpace(r.PathValue("cap"))
|
|
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
|
defer cancel()
|
|
t, _, m, actor, _, ok := s.capabilityTarget(ctx, w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
dropped, err := s.Store.DeleteMemberCapabilityRequests(ctx, t.ID, m.UserID, code)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
if !slices.Contains(m.ExtraCapabilities, code) {
|
|
status := "unchanged"
|
|
if dropped > 0 {
|
|
status = "request_withdrawn"
|
|
s.teamAudit(ctx, r, t, actor, "user.capability_request_withdrawn", m, map[string]interface{}{"capability": code})
|
|
}
|
|
writeJSON(w, http.StatusOK, capabilityResp{Status: status, Member: m})
|
|
return
|
|
}
|
|
next := slices.DeleteFunc(slices.Clone(m.ExtraCapabilities), func(v string) bool { return v == code })
|
|
if !s.setExtras(ctx, w, t, m, next) {
|
|
return
|
|
}
|
|
s.teamAudit(ctx, r, t, actor, "user.capability_revoked", m, map[string]interface{}{"capability": code})
|
|
writeJSON(w, http.StatusOK, capabilityResp{Status: "capability_revoked", Member: m})
|
|
}
|
|
|
|
// setExtras writes the member's extras to Keycloak and onto m.
|
|
func (s *Server) setExtras(ctx context.Context, w http.ResponseWriter, t *store.Tenant, m *keycloak.OrgMember, caps []string) bool {
|
|
slices.Sort(caps)
|
|
caps = slices.Compact(caps)
|
|
if err := s.Keycloak.SetMemberExtras(ctx, m.UserID, caps); err != nil {
|
|
s.writeKeycloakError(w, t.ID, "set member capabilities", err)
|
|
return false
|
|
}
|
|
m.ExtraCapabilities = caps
|
|
return true
|
|
}
|
|
|
|
// listCapabilityRequests is GET /v1/tenants/{id}/capability-requests.
|
|
func (s *Server) listCapabilityRequests(w http.ResponseWriter, r *http.Request) {
|
|
t, ok := s.teamTenantFromUser(r.Context(), w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
reqs, err := s.Store.ListCapabilityRequests(r.Context(), t.ID)
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, capabilityRequestsResp{Requests: reqs})
|
|
}
|
|
|
|
// capabilityRequest loads the tenant, its members, the acting person and
|
|
// the request the path names.
|
|
func (s *Server) capabilityRequest(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, []keycloak.OrgMember, teamActor, *keycloak.OrgMember, *store.CapabilityRequest, bool) {
|
|
t, ok := s.teamTenantFromUser(ctx, w, r)
|
|
if !ok {
|
|
return nil, nil, teamActor{}, 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, teamActor{}, nil, nil, false
|
|
}
|
|
decorateMembers(members, t.ID)
|
|
actor, me, ok := s.granter(w, r, members)
|
|
if !ok {
|
|
return nil, nil, teamActor{}, nil, nil, false
|
|
}
|
|
req, err := s.Store.GetCapabilityRequest(ctx, t.ID, r.PathValue("rid"))
|
|
if err != nil {
|
|
if !mapStoreError(w, err) {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
}
|
|
return nil, nil, teamActor{}, nil, nil, false
|
|
}
|
|
return t, members, actor, me, req, true
|
|
}
|
|
|
|
// approveCapabilityRequest is the second person's yes.
|
|
func (s *Server) approveCapabilityRequest(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
|
defer cancel()
|
|
t, members, actor, me, req, ok := s.capabilityRequest(ctx, w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
if actor.ID == req.RequestedBy || (actor.Email != "" && strings.EqualFold(actor.Email, req.RequestedEmail)) {
|
|
writeError(w, http.StatusConflict, "four_eyes", "a second person must approve the request")
|
|
return
|
|
}
|
|
var m *keycloak.OrgMember
|
|
for i := range members {
|
|
if members[i].UserID == req.UserID {
|
|
m = &members[i]
|
|
}
|
|
}
|
|
if m == nil {
|
|
_ = s.Store.DeleteCapabilityRequest(ctx, t.ID, req.ID)
|
|
writeError(w, http.StatusNotFound, "not_a_member", "the member has left the workspace; the request is dropped")
|
|
return
|
|
}
|
|
if actor.is(*m) {
|
|
writeError(w, http.StatusConflict, "self", "you cannot approve a capability for yourself")
|
|
return
|
|
}
|
|
if !effective(*me)[req.Capability] {
|
|
writeError(w, http.StatusForbidden, "not_held", "you cannot grant a capability you do not hold")
|
|
return
|
|
}
|
|
if !slices.Contains(m.ExtraCapabilities, req.Capability) && !inBundle(*m, req.Capability) {
|
|
if !s.setExtras(ctx, w, t, m, append(slices.Clone(m.ExtraCapabilities), req.Capability)) {
|
|
return
|
|
}
|
|
}
|
|
if err := s.Store.DeleteCapabilityRequest(ctx, t.ID, req.ID); err != nil && !errors.Is(err, store.ErrNotFound) {
|
|
s.Log.Warn("approved capability request not deleted", "tenant_id", t.ID, "request_id", req.ID, "err", err)
|
|
}
|
|
s.teamAudit(ctx, r, t, actor, "user.capability_granted", m, map[string]interface{}{
|
|
"capability": req.Capability, "request_id": req.ID, "requested_by": req.RequestedBy, "requested_email": req.RequestedEmail})
|
|
writeJSON(w, http.StatusOK, capabilityResp{Status: "capability_granted", Member: m, Request: req})
|
|
}
|
|
|
|
// deleteCapabilityRequest rejects a request, or withdraws it when the
|
|
// requester deletes it.
|
|
func (s *Server) deleteCapabilityRequest(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
|
defer cancel()
|
|
t, _, actor, _, req, ok := s.capabilityRequest(ctx, w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
if err := s.Store.DeleteCapabilityRequest(ctx, t.ID, req.ID); err != nil {
|
|
if !mapStoreError(w, err) {
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
}
|
|
return
|
|
}
|
|
status, action := "request_rejected", "user.capability_request_rejected"
|
|
if actor.ID == req.RequestedBy {
|
|
status, action = "request_withdrawn", "user.capability_request_withdrawn"
|
|
}
|
|
target := keycloak.OrgMember{UserID: req.UserID, Email: req.UserEmail}
|
|
s.teamAudit(ctx, r, t, actor, action, &target, map[string]interface{}{"capability": req.Capability, "request_id": req.ID})
|
|
writeJSON(w, http.StatusOK, capabilityResp{Status: status, Request: req})
|
|
}
|