Merge pull request 'feat(authz): individual capabilities per member (RBAC step 3)' (#122) from feat/extra-capabilities into main
This commit was merged in pull request #122.
This commit is contained in:
commit
c18f0dc945
22 files changed
+1242
-21
No files matched your search
@@ -41,6 +41,11 @@ type Principal struct {
|
||||
// OrgBlocked is the `org_blocked` claim, when a mapper projects it: the
|
||||
// tenant ids the user is blocked in (portal#74).
|
||||
OrgBlocked []string
|
||||
// ExtraCapabilities is the `extra_capabilities` claim (RBAC step 3):
|
||||
// the capabilities the person holds on top of their bundle. The
|
||||
// registry's own checks still go by OrgRoles; the portal and Werkmeister
|
||||
// read it.
|
||||
ExtraCapabilities []string
|
||||
}
|
||||
|
||||
// IsUser reports whether the token carries a tenant context (a person
|
||||
@@ -128,11 +133,13 @@ func (v *Verifier) Verify(ctx context.Context, authorization string) (*Principal
|
||||
Email string `json:"email"`
|
||||
OrgRoles roles `json:"org_roles"`
|
||||
OrgBlocked roles `json:"org_blocked"`
|
||||
Extra roles `json:"extra_capabilities"`
|
||||
}
|
||||
_ = 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,
|
||||
OrgRoles: []string(claims.OrgRoles), OrgBlocked: []string(claims.OrgBlocked)}, nil
|
||||
OrgRoles: []string(claims.OrgRoles), OrgBlocked: []string(claims.OrgBlocked),
|
||||
ExtraCapabilities: []string(claims.Extra)}, nil
|
||||
}
|
||||
|
||||
// roles decodes the org_roles claim in either shape the Keycloak mapper
|
||||
|
||||
@@ -155,6 +155,18 @@ func TestVerifier(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("extra_capabilities claim", func(t *testing.T) {
|
||||
p, err := v.Verify(ctx, "Bearer "+iss.sign(t, iss.claims(map[string]any{
|
||||
"extra_capabilities": []string{"werkmeister:process.publish", "portal:billing.view"}, "org_roles": []string{"USER"}, "tenant_id": "t-1"})))
|
||||
if err != nil || len(p.ExtraCapabilities) != 2 || p.ExtraCapabilities[0] != "werkmeister:process.publish" || p.IsTenantAdmin() {
|
||||
t.Errorf("extra_capabilities: err=%v p=%+v", err, p)
|
||||
}
|
||||
p, err = v.Verify(ctx, "Bearer "+iss.sign(t, iss.claims(map[string]any{"tenant_id": "t-1"})))
|
||||
if err != nil || len(p.ExtraCapabilities) != 0 {
|
||||
t.Errorf("no claim, no extras: 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() {
|
||||
|
||||
@@ -85,6 +85,9 @@ type OrgMember struct {
|
||||
// BlockedTenants is the user's org_blocked attribute: the tenant ids the
|
||||
// member is blocked in. Internal; the API exposes Status.
|
||||
BlockedTenants []string `json:"-"`
|
||||
// ExtraCapabilities is the user attribute AttrExtraCapabilities: the
|
||||
// capabilities the member holds on top of their bundle (RBAC step 3).
|
||||
ExtraCapabilities []string `json:"extra_capabilities"`
|
||||
}
|
||||
|
||||
// Member status values (portal#74).
|
||||
@@ -210,6 +213,11 @@ type Adapter interface {
|
||||
// org_blocked attribute — a per-workspace block, never enabled=false.
|
||||
SetMemberBlocked(ctx context.Context, userID, tenantID string, blocked bool) error
|
||||
|
||||
// SetMemberExtras replaces the user's extra_capabilities attribute with
|
||||
// caps (none: the attribute is dropped). It takes effect at the user's
|
||||
// next login or token refresh.
|
||||
SetMemberExtras(ctx context.Context, userID string, caps []string) error
|
||||
|
||||
// MemberBlocked reports whether userID is blocked in tenantID.
|
||||
// ErrUserNotFound for an unknown user.
|
||||
MemberBlocked(ctx context.Context, userID, tenantID string) (bool, error)
|
||||
|
||||
@@ -26,9 +26,14 @@ import (
|
||||
// blocked in.
|
||||
const AttrOrgBlocked = "org_blocked"
|
||||
|
||||
// tenantAttrs are the tenant-context user attributes the registry writes at
|
||||
// invitation; removing a member clears them when they name that tenant.
|
||||
var tenantAttrs = []string{"tenant_id", "tenant_slug", "org_roles", "tenant_status", "products", "plan"}
|
||||
// AttrExtraCapabilities is the user attribute listing the capabilities a
|
||||
// member holds on top of their bundle (RBAC step 3). Like org_roles it is
|
||||
// admin-only and projected into the token by the tenant-context mapper.
|
||||
const AttrExtraCapabilities = "extra_capabilities"
|
||||
|
||||
// tenantAttrs are the tenant-context user attributes the registry writes;
|
||||
// removing a member clears them when they name that tenant.
|
||||
var tenantAttrs = []string{"tenant_id", "tenant_slug", "org_roles", "tenant_status", "products", "plan", AttrExtraCapabilities}
|
||||
|
||||
// SetMemberRole implements Adapter: org_roles becomes exactly [role].
|
||||
func (a *HTTPAdapter) SetMemberRole(ctx context.Context, userID, role string) error {
|
||||
@@ -41,6 +46,24 @@ func (a *HTTPAdapter) SetMemberRole(ctx context.Context, userID, role string) er
|
||||
})
|
||||
}
|
||||
|
||||
// SetMemberExtras implements Adapter: extra_capabilities becomes exactly
|
||||
// caps, and is dropped when caps is empty. The other attributes are read
|
||||
// and written back unchanged (updateUserAttributes).
|
||||
func (a *HTTPAdapter) SetMemberExtras(ctx context.Context, userID string, caps []string) error {
|
||||
return a.updateUserAttributes(ctx, userID, func(attrs map[string][]string) bool {
|
||||
cur := attrValues(attrs, AttrExtraCapabilities)
|
||||
if slices.Equal(cur, caps) {
|
||||
return false
|
||||
}
|
||||
if len(caps) == 0 {
|
||||
delete(attrs, AttrExtraCapabilities)
|
||||
} else {
|
||||
attrs[AttrExtraCapabilities] = slices.Clone(caps)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// SetMemberBlocked implements Adapter: adds or removes tenantID in the
|
||||
// user's org_blocked attribute.
|
||||
func (a *HTTPAdapter) SetMemberBlocked(ctx context.Context, userID, tenantID string, blocked bool) error {
|
||||
|
||||
@@ -65,6 +65,43 @@ func TestHTTPAdapter_SetMemberRole(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPAdapter_SetMemberExtras(t *testing.T) {
|
||||
k, a := newMembersKC(t)
|
||||
ctx := context.Background()
|
||||
caps := []string{"werkmeister:process.publish", "portal:billing.view"}
|
||||
if err := a.SetMemberExtras(ctx, "u-admin", caps); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := k.puts["u-admin"][AttrExtraCapabilities]; !slices.Equal(got, caps) {
|
||||
t.Errorf("extra_capabilities: %v", got)
|
||||
}
|
||||
if k.puts["u-admin"]["tenant_slug"][0] != "acme" || k.puts["u-admin"]["org_roles"] == nil {
|
||||
t.Errorf("other attributes must survive: %v", k.puts["u-admin"])
|
||||
}
|
||||
members, err := a.ListOrgMembers(ctx, "acme")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, m := range members {
|
||||
if m.UserID == "u-admin" && !slices.Equal(m.ExtraCapabilities, caps) {
|
||||
t.Errorf("listed extras: %+v", m)
|
||||
}
|
||||
}
|
||||
delete(k.puts, "u-admin")
|
||||
if err := a.SetMemberExtras(ctx, "u-admin", slices.Clone(caps)); err != nil || k.puts["u-admin"] != nil {
|
||||
t.Errorf("same extras must not write: %v %v", err, k.puts)
|
||||
}
|
||||
if err := a.SetMemberExtras(ctx, "u-admin", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := k.users["u-admin"].Attributes[AttrExtraCapabilities]; ok {
|
||||
t.Errorf("no extras must drop the attribute: %v", k.users["u-admin"].Attributes)
|
||||
}
|
||||
if err := a.SetMemberExtras(ctx, "u-ghost", caps); err == nil {
|
||||
t.Error("unknown user must fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPAdapter_SetMemberBlocked(t *testing.T) {
|
||||
k, a := newMembersKC(t)
|
||||
ctx := context.Background()
|
||||
@@ -113,7 +150,7 @@ func TestHTTPAdapter_RemoveMember(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
k.users["u-fin"] = memberRepresentation{ID: "u-fin", Email: "fin@acme.test", Attributes: map[string][]string{
|
||||
"tenant_id": {"t-acme"}, "tenant_slug": {"acme"}, "org_roles": {"FINANCE"}, "tenant_status": {"active"},
|
||||
AttrOrgBlocked: {"t-acme", "t-other"}, "locale": {"de"},
|
||||
AttrOrgBlocked: {"t-acme", "t-other"}, "locale": {"de"}, AttrExtraCapabilities: {"portal:billing.view"},
|
||||
}}
|
||||
k.members["org-acme"] = append(k.members["org-acme"], "u-fin")
|
||||
deleted, err := a.RemoveMember(ctx, "acme", "t-acme", "u-fin", false)
|
||||
@@ -124,7 +161,7 @@ func TestHTTPAdapter_RemoveMember(t *testing.T) {
|
||||
t.Error("membership not removed")
|
||||
}
|
||||
attrs := k.users["u-fin"].Attributes
|
||||
for _, key := range []string{"tenant_id", "tenant_slug", "org_roles", "tenant_status"} {
|
||||
for _, key := range []string{"tenant_id", "tenant_slug", "org_roles", "tenant_status", AttrExtraCapabilities} {
|
||||
if _, ok := attrs[key]; ok {
|
||||
t.Errorf("%s must be cleared: %v", key, attrs)
|
||||
}
|
||||
|
||||
@@ -37,14 +37,15 @@ func (m memberRepresentation) toOrgMember() OrgMember {
|
||||
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,
|
||||
BlockedTenants: attrValues(m.Attributes, AttrOrgBlocked),
|
||||
UserID: m.ID,
|
||||
Email: email,
|
||||
FirstName: m.FirstName,
|
||||
LastName: m.LastName,
|
||||
OrgRoles: attrValues(m.Attributes, "org_roles"),
|
||||
Enabled: m.Enabled,
|
||||
CreatedAt: created,
|
||||
BlockedTenants: attrValues(m.Attributes, AttrOrgBlocked),
|
||||
ExtraCapabilities: attrValues(m.Attributes, AttrExtraCapabilities),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ type Mock struct {
|
||||
// Team management (portal#74).
|
||||
Blocked map[string][]string // userID → tenant ids the user is blocked in
|
||||
RoleSet map[string]string // userID → last SetMemberRole
|
||||
ExtrasSet map[string][]string // userID → last SetMemberExtras
|
||||
Removed []string // every RemoveMember call, by user id
|
||||
Deleted []string // accounts RemoveMember deleted
|
||||
LoggedOut []string // every LogoutUser call
|
||||
@@ -40,13 +41,14 @@ type Mock struct {
|
||||
|
||||
func NewMock() *Mock {
|
||||
return &Mock{
|
||||
Orgs: map[string]string{},
|
||||
Users: map[string]string{},
|
||||
Claims: map[string]Claims{},
|
||||
Status: map[string]string{},
|
||||
Members: map[string][]OrgMember{},
|
||||
Blocked: map[string][]string{},
|
||||
RoleSet: map[string]string{},
|
||||
Orgs: map[string]string{},
|
||||
Users: map[string]string{},
|
||||
Claims: map[string]Claims{},
|
||||
Status: map[string]string{},
|
||||
Members: map[string][]OrgMember{},
|
||||
Blocked: map[string][]string{},
|
||||
RoleSet: map[string]string{},
|
||||
ExtrasSet: map[string][]string{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +78,25 @@ func (m *Mock) SetMemberRole(_ context.Context, userID, role string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetMemberExtras implements Adapter: the extras land on every org
|
||||
// membership of the user (extra_capabilities is a user attribute).
|
||||
func (m *Mock) SetMemberExtras(_ context.Context, userID string, caps []string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if err := m.failNext(); err != nil {
|
||||
return err
|
||||
}
|
||||
m.ExtrasSet[userID] = slices.Clone(caps)
|
||||
for slug, members := range m.Members {
|
||||
for i := range members {
|
||||
if members[i].UserID == userID {
|
||||
m.Members[slug][i].ExtraCapabilities = slices.Clone(caps)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetMemberBlocked implements Adapter.
|
||||
func (m *Mock) SetMemberBlocked(_ context.Context, userID, tenantID string, blocked bool) error {
|
||||
m.mu.Lock()
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
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})
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
||||
)
|
||||
|
||||
// capFixture is the team fixture plus an active OWNER (u-own), CXO (u-cxo)
|
||||
// and a USER who was given registry:members.manage (u-user).
|
||||
func capFixture(t *testing.T, p *authn.Principal) *teamFixture {
|
||||
t.Helper()
|
||||
f := newTeamFixture(t, p)
|
||||
f.kc.Members["acme"] = append(f.kc.Members["acme"],
|
||||
keycloak.OrgMember{UserID: "u-own", Email: "own@acme.test", OrgRoles: []string{"OWNER"}, Enabled: true},
|
||||
keycloak.OrgMember{UserID: "u-cxo", Email: "cxo@acme.test", OrgRoles: []string{"CXO"}, Enabled: true},
|
||||
keycloak.OrgMember{UserID: "u-user", Email: "user@acme.test", OrgRoles: []string{"USER"}, Enabled: true,
|
||||
ExtraCapabilities: []string{"registry:members.manage"}},
|
||||
)
|
||||
return f
|
||||
}
|
||||
|
||||
func as(uid string) map[string]string {
|
||||
email := strings.TrimPrefix(uid, "u-") + "@acme.test"
|
||||
return map[string]string{headerPortalUserSubject: uid, headerPortalUserEmail: email}
|
||||
}
|
||||
|
||||
func (f *teamFixture) capCall(t *testing.T, method, path, body string, hdr map[string]string) (int, capabilityResp, string) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
for k, v := range hdr {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
f.h.ServeHTTP(rr, req)
|
||||
var out capabilityResp
|
||||
_ = json.Unmarshal(rr.Body.Bytes(), &out)
|
||||
return rr.Code, out, rr.Body.String()
|
||||
}
|
||||
|
||||
func (f *teamFixture) capPath(uid string) string { return f.memberPath(uid) + "/capabilities" }
|
||||
|
||||
func (f *teamFixture) reqPath(id string) string {
|
||||
return "/v1/tenants/" + f.tenant.ID + "/capability-requests/" + id
|
||||
}
|
||||
|
||||
func (f *teamFixture) member(uid string) keycloak.OrgMember {
|
||||
for _, m := range f.kc.Members["acme"] {
|
||||
if m.UserID == uid {
|
||||
return m
|
||||
}
|
||||
}
|
||||
return keycloak.OrgMember{}
|
||||
}
|
||||
|
||||
func errCode(raw string) string {
|
||||
var e struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
_ = json.Unmarshal([]byte(raw), &e)
|
||||
return e.Error
|
||||
}
|
||||
|
||||
func TestCapabilities_grantAndRevoke(t *testing.T) {
|
||||
f := capFixture(t, portal)
|
||||
const publish = "werkmeister:process.publish"
|
||||
code, out, raw := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"`+publish+`"}`, asAdmin)
|
||||
if code != http.StatusOK || out.Status != "capability_granted" || !slices.Equal(out.Member.ExtraCapabilities, []string{publish}) {
|
||||
t.Fatalf("grant: %d %s", code, raw)
|
||||
}
|
||||
if !slices.Equal(f.kc.ExtrasSet["u-fin"], []string{publish}) {
|
||||
t.Errorf("keycloak: %v", f.kc.ExtrasSet)
|
||||
}
|
||||
ev := f.audit(t, "user.capability_granted")
|
||||
if len(ev) != 1 || ev[0].ActorID != "u-admin" || ev[0].TargetName != "fin@acme.test" || ev[0].Metadata["capability"] != publish {
|
||||
t.Fatalf("audit: %+v", ev)
|
||||
}
|
||||
|
||||
// Again: unchanged, nothing written.
|
||||
if code, out, _ := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"`+publish+`"}`, asAdmin); code != http.StatusOK || out.Status != "unchanged" {
|
||||
t.Errorf("again: %d %+v", code, out)
|
||||
}
|
||||
if len(f.audit(t, "user.capability_granted")) != 1 {
|
||||
t.Error("second grant audited")
|
||||
}
|
||||
|
||||
// Extras are kept in order, without duplicates.
|
||||
f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"portal:infra.view"}`, asAdmin)
|
||||
if got := f.member("u-fin").ExtraCapabilities; !slices.Equal(got, []string{"portal:infra.view", publish}) {
|
||||
t.Errorf("two extras: %v", got)
|
||||
}
|
||||
|
||||
// A role change leaves them as they are.
|
||||
if code, _, raw := f.call(t, http.MethodPatch, f.memberPath("u-fin"), `{"role":"LEGAL"}`, asAdmin); code != http.StatusOK {
|
||||
t.Fatalf("role change: %d %s", code, raw)
|
||||
}
|
||||
if got := f.member("u-fin").ExtraCapabilities; len(got) != 2 {
|
||||
t.Errorf("extras after role change: %v", got)
|
||||
}
|
||||
|
||||
code, out, raw = f.capCall(t, http.MethodDelete, f.capPath("u-fin")+"/"+publish, "", asAdmin)
|
||||
if code != http.StatusOK || out.Status != "capability_revoked" || !slices.Equal(out.Member.ExtraCapabilities, []string{"portal:infra.view"}) {
|
||||
t.Fatalf("revoke: %d %s", code, raw)
|
||||
}
|
||||
if ev := f.audit(t, "user.capability_revoked"); len(ev) != 1 || ev[0].Metadata["capability"] != publish {
|
||||
t.Fatalf("revoke audit: %+v", ev)
|
||||
}
|
||||
if code, out, _ := f.capCall(t, http.MethodDelete, f.capPath("u-fin")+"/"+publish, "", asAdmin); code != http.StatusOK || out.Status != "unchanged" {
|
||||
t.Errorf("revoke again: %d %+v", code, out)
|
||||
}
|
||||
f.capCall(t, http.MethodDelete, f.capPath("u-fin")+"/portal:infra.view", "", asAdmin)
|
||||
if got := f.kc.ExtrasSet["u-fin"]; len(got) != 0 {
|
||||
t.Errorf("last extra revoked: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapabilities_rules(t *testing.T) {
|
||||
f := capFixture(t, portal)
|
||||
for _, c := range []struct {
|
||||
name, uid, body string
|
||||
hdr map[string]string
|
||||
code int
|
||||
err string
|
||||
}{
|
||||
{"unknown capability", "u-fin", `{"capability":"portal:god.mode"}`, asAdmin, http.StatusBadRequest, "unknown_capability"},
|
||||
{"bad body", "u-fin", `nope`, asAdmin, http.StatusBadRequest, ""},
|
||||
{"in the bundle already", "u-fin", `{"capability":"portal:billing.view"}`, asAdmin, http.StatusConflict, "in_bundle"},
|
||||
{"on oneself", "u-admin", `{"capability":"portal:billing.view"}`, asAdmin, http.StatusConflict, "self"},
|
||||
{"granter without members.manage", "u-fin", `{"capability":"portal:infra.view"}`, as("u-cxo"), http.StatusForbidden, "FORBIDDEN_ROLE"},
|
||||
{"granter does not hold it", "u-fin", `{"capability":"portal:infra.view"}`, as("u-user"), http.StatusForbidden, "not_held"},
|
||||
{"no person named", "u-fin", `{"capability":"portal:infra.view"}`, nil, http.StatusForbidden, "FORBIDDEN_ROLE"},
|
||||
{"a pending member cannot grant", "u-fin", `{"capability":"portal:infra.view"}`, as("u-inv"), http.StatusForbidden, "FORBIDDEN_ROLE"},
|
||||
{"unknown member", "u-ghost", `{"capability":"portal:infra.view"}`, asAdmin, http.StatusNotFound, "not_a_member"},
|
||||
} {
|
||||
code, _, raw := f.capCall(t, http.MethodPost, f.capPath(c.uid), c.body, c.hdr)
|
||||
if code != c.code || (c.err != "" && errCode(raw) != c.err) {
|
||||
t.Errorf("%s: %d %s", c.name, code, raw)
|
||||
}
|
||||
}
|
||||
// A USER who was given members.manage grants what they hold.
|
||||
if code, out, raw := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"werkmeister:task.work"}`, as("u-user")); code != http.StatusOK || out.Status != "capability_granted" {
|
||||
t.Errorf("extra-held members.manage: %d %s", code, raw)
|
||||
}
|
||||
if code, _, raw := f.capCall(t, http.MethodDelete, f.capPath("u-fin")+"/werkmeister:task.work", "", as("u-cxo")); code != http.StatusForbidden {
|
||||
t.Errorf("revoke without members.manage: %d %s", code, raw)
|
||||
}
|
||||
|
||||
f.kc.FailNext = errors.New("keycloak down")
|
||||
if code, _, raw := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"portal:infra.view"}`, asAdmin); code < 500 {
|
||||
t.Errorf("keycloak failure: %d %s", code, raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapabilities_fourEyes(t *testing.T) {
|
||||
f := capFixture(t, portal)
|
||||
const manage = "registry:members.manage"
|
||||
code, out, raw := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"`+manage+`"}`, asAdmin)
|
||||
if code != http.StatusAccepted || out.Status != "approval_requested" || out.Request == nil || out.Request.RequestedBy != "u-admin" {
|
||||
t.Fatalf("request: %d %s", code, raw)
|
||||
}
|
||||
if _, set := f.kc.ExtrasSet["u-fin"]; set {
|
||||
t.Fatal("an administration capability must wait for a second person")
|
||||
}
|
||||
reqID := out.Request.ID
|
||||
if code, again, _ := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"`+manage+`"}`, asAdmin); code != http.StatusAccepted || again.Request.ID != reqID {
|
||||
t.Errorf("second request: %d %+v", code, again)
|
||||
}
|
||||
if ev := f.audit(t, "user.capability_requested"); len(ev) != 1 || ev[0].Metadata["request_id"] != reqID {
|
||||
t.Fatalf("request audit: %+v", ev)
|
||||
}
|
||||
|
||||
// The list.
|
||||
rr := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/tenants/"+f.tenant.ID+"/capability-requests", nil)
|
||||
for k, v := range asAdmin {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
f.h.ServeHTTP(rr, req)
|
||||
var list capabilityRequestsResp
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &list); err != nil || rr.Code != http.StatusOK || len(list.Requests) != 1 || list.Requests[0].ID != reqID {
|
||||
t.Fatalf("list: %d %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
if code, _, raw := f.capCall(t, http.MethodPost, f.reqPath(reqID)+"/approve", "", asAdmin); code != http.StatusConflict || errCode(raw) != "four_eyes" {
|
||||
t.Errorf("the requester approves: %d %s", code, raw)
|
||||
}
|
||||
if code, _, raw := f.capCall(t, http.MethodPost, f.reqPath(reqID)+"/approve", "", as("u-cxo")); code != http.StatusForbidden {
|
||||
t.Errorf("approver without members.manage: %d %s", code, raw)
|
||||
}
|
||||
code, out, raw = f.capCall(t, http.MethodPost, f.reqPath(reqID)+"/approve", "", as("u-own"))
|
||||
if code != http.StatusOK || out.Status != "capability_granted" || !slices.Contains(out.Member.ExtraCapabilities, manage) {
|
||||
t.Fatalf("approve: %d %s", code, raw)
|
||||
}
|
||||
ev := f.audit(t, "user.capability_granted")
|
||||
if len(ev) != 1 || ev[0].ActorID != "u-own" || ev[0].Metadata["requested_by"] != "u-admin" {
|
||||
t.Fatalf("approve audit: %+v", ev)
|
||||
}
|
||||
if code, _, _ := f.capCall(t, http.MethodPost, f.reqPath(reqID)+"/approve", "", as("u-own")); code != http.StatusNotFound {
|
||||
t.Errorf("an approved request is gone: %d", code)
|
||||
}
|
||||
|
||||
// The member cannot approve their own; the requester withdraws by revoking.
|
||||
_, out, _ = f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"portal:infra.write"}`, asAdmin)
|
||||
if code, _, raw := f.capCall(t, http.MethodPost, f.reqPath(out.Request.ID)+"/approve", "", as("u-fin")); code != http.StatusConflict || errCode(raw) != "self" {
|
||||
t.Errorf("approving one's own: %d %s", code, raw)
|
||||
}
|
||||
if code, out, raw := f.capCall(t, http.MethodDelete, f.capPath("u-fin")+"/portal:infra.write", "", asAdmin); code != http.StatusOK || out.Status != "request_withdrawn" {
|
||||
t.Errorf("revoke a pending grant: %d %s", code, raw)
|
||||
}
|
||||
|
||||
// Reject and withdraw.
|
||||
_, out, _ = f.capCall(t, http.MethodPost, f.capPath("u-cxo"), `{"capability":"werkmeister:connection.manage"}`, asAdmin)
|
||||
if code, out, raw := f.capCall(t, http.MethodDelete, f.reqPath(out.Request.ID), "", as("u-own")); code != http.StatusOK || out.Status != "request_rejected" {
|
||||
t.Errorf("reject: %d %s", code, raw)
|
||||
}
|
||||
_, out, _ = f.capCall(t, http.MethodPost, f.capPath("u-cxo"), `{"capability":"werkmeister:connection.manage"}`, asAdmin)
|
||||
if code, out, raw := f.capCall(t, http.MethodDelete, f.reqPath(out.Request.ID), "", asAdmin); code != http.StatusOK || out.Status != "request_withdrawn" {
|
||||
t.Errorf("withdraw: %d %s", code, raw)
|
||||
}
|
||||
if ev := f.audit(t, "user.capability_request_rejected"); len(ev) != 1 || ev[0].TargetName != "cxo@acme.test" {
|
||||
t.Errorf("reject audit: %+v", ev)
|
||||
}
|
||||
if code, _, _ := f.capCall(t, http.MethodDelete, f.reqPath("00000000-0000-0000-0000-000000000000"), "", asAdmin); code != http.StatusNotFound {
|
||||
t.Errorf("unknown request: %d", code)
|
||||
}
|
||||
|
||||
// A member who left: their request is dropped at approval.
|
||||
_, out, _ = f.capCall(t, http.MethodPost, f.capPath("u-cxo"), `{"capability":"werkmeister:connection.manage"}`, asAdmin)
|
||||
f.kc.Members["acme"] = slices.DeleteFunc(f.kc.Members["acme"], func(m keycloak.OrgMember) bool { return m.UserID == "u-cxo" })
|
||||
if code, _, raw := f.capCall(t, http.MethodPost, f.reqPath(out.Request.ID)+"/approve", "", as("u-own")); code != http.StatusNotFound || errCode(raw) != "not_a_member" {
|
||||
t.Errorf("left: %d %s", code, raw)
|
||||
}
|
||||
if reqs, _ := f.s.Store.ListCapabilityRequests(context.Background(), f.tenant.ID); len(reqs) != 0 {
|
||||
t.Errorf("left member's request kept: %+v", reqs)
|
||||
}
|
||||
|
||||
// Removing a member drops their open requests.
|
||||
f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"portal:infra.write"}`, asAdmin)
|
||||
if code, _, raw := f.call(t, http.MethodDelete, f.memberPath("u-fin"), "", asAdmin); code != http.StatusOK {
|
||||
t.Fatalf("remove: %d %s", code, raw)
|
||||
}
|
||||
if reqs, _ := f.s.Store.ListCapabilityRequests(context.Background(), f.tenant.ID); len(reqs) != 0 {
|
||||
t.Errorf("removed member's request kept: %+v", reqs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapabilities_userTokens(t *testing.T) {
|
||||
// A person's own token: the registry still asks for a tenant-admin role
|
||||
// first (teamTenantFromUser), then applies the same rules.
|
||||
user := &authn.Principal{Subject: "u-cxo", ClientID: "portal", TenantID: "", OrgRoles: []string{"CXO"}}
|
||||
f := capFixture(t, user)
|
||||
user.TenantID = f.tenant.ID
|
||||
user.Email = "cxo@acme.test"
|
||||
if code, _, raw := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"portal:infra.view"}`, nil); code != http.StatusForbidden {
|
||||
t.Errorf("CXO token: %d %s", code, raw)
|
||||
}
|
||||
admin := &authn.Principal{Subject: "u-admin", ClientID: "portal", Email: "admin@acme.test", OrgRoles: []string{"IT_ADMIN"}}
|
||||
f = capFixture(t, admin)
|
||||
admin.TenantID = f.tenant.ID
|
||||
if code, out, raw := f.capCall(t, http.MethodPost, f.capPath("u-fin"), `{"capability":"portal:infra.view"}`, nil); code != http.StatusOK || out.Status != "capability_granted" {
|
||||
t.Errorf("admin token: %d %s", code, raw)
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
f.h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/v1/tenants/"+f.tenant.ID+"/capability-requests", nil))
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Errorf("admin token list: %d %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package server_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// The four-eyes requests on both stores: one open request per member and
|
||||
// capability, listed oldest first, deleted one by one or per member.
|
||||
func TestCapabilityRequestStore(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
ctx := context.Background()
|
||||
create := func(user, capability string) (*store.CapabilityRequest, bool) {
|
||||
t.Helper()
|
||||
r, created, err := h.store.CreateCapabilityRequest(ctx, store.CapabilityRequest{TenantID: h.tenant.ID, UserID: user,
|
||||
UserEmail: user + "@acme.test", Capability: capability, RequestedBy: "u-admin", RequestedEmail: "admin@acme.test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r, created
|
||||
}
|
||||
r1, created := create("u-fin", "registry:members.manage")
|
||||
if !created || r1.ID == "" || r1.CreatedAt.IsZero() || r1.UserEmail != "u-fin@acme.test" || r1.RequestedEmail != "admin@acme.test" {
|
||||
t.Fatalf("create: %+v %v", r1, created)
|
||||
}
|
||||
again, created := create("u-fin", "registry:members.manage")
|
||||
if created || again.ID != r1.ID {
|
||||
t.Fatalf("the open request is returned, not a second one: %+v %v", again, created)
|
||||
}
|
||||
r2, _ := create("u-fin", "portal:infra.write")
|
||||
r3, _ := create("u-cxo", "registry:members.manage")
|
||||
|
||||
list, err := h.store.ListCapabilityRequests(ctx, h.tenant.ID)
|
||||
if err != nil || len(list) != 3 || list[0].ID != r1.ID {
|
||||
t.Fatalf("list: %+v %v", list, err)
|
||||
}
|
||||
if got, err := h.store.GetCapabilityRequest(ctx, h.tenant.ID, r2.ID); err != nil || got.Capability != "portal:infra.write" {
|
||||
t.Fatalf("get: %+v %v", got, err)
|
||||
}
|
||||
for _, id := range []string{"no-uuid", "00000000-0000-0000-0000-000000000000"} {
|
||||
if _, err := h.store.GetCapabilityRequest(ctx, h.tenant.ID, id); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Errorf("get %s: %v", id, err)
|
||||
}
|
||||
if err := h.store.DeleteCapabilityRequest(ctx, h.tenant.ID, id); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Errorf("delete %s: %v", id, err)
|
||||
}
|
||||
}
|
||||
if _, err := h.store.GetCapabilityRequest(ctx, "00000000-0000-0000-0000-000000000000", r1.ID); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Errorf("another tenant's request: %v", err)
|
||||
}
|
||||
|
||||
if err := h.store.DeleteCapabilityRequest(ctx, h.tenant.ID, r3.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, err := h.store.DeleteMemberCapabilityRequests(ctx, h.tenant.ID, "u-fin", "portal:infra.write"); err != nil || n != 1 {
|
||||
t.Fatalf("per capability: %d %v", n, err)
|
||||
}
|
||||
create("u-fin", "portal:infra.write")
|
||||
if n, err := h.store.DeleteMemberCapabilityRequests(ctx, h.tenant.ID, "u-fin", ""); err != nil || n != 2 {
|
||||
t.Fatalf("all of a member's: %d %v", n, err)
|
||||
}
|
||||
if list, _ := h.store.ListCapabilityRequests(ctx, h.tenant.ID); len(list) != 0 {
|
||||
t.Fatalf("left: %+v", list)
|
||||
}
|
||||
if n, err := h.store.DeleteMemberCapabilityRequests(ctx, "no-uuid", "u-fin", ""); err != nil || n != 0 {
|
||||
t.Errorf("bad tenant id: %d %v", n, err)
|
||||
}
|
||||
if list, err := h.store.ListCapabilityRequests(ctx, "no-uuid"); err != nil || len(list) != 0 {
|
||||
t.Errorf("bad tenant id list: %v %v", list, err)
|
||||
}
|
||||
|
||||
for _, bad := range []store.CapabilityRequest{
|
||||
{TenantID: h.tenant.ID, UserID: "u", Capability: "Nope", RequestedBy: "a"},
|
||||
{TenantID: h.tenant.ID, UserID: "", Capability: "portal:billing.view", RequestedBy: "a"},
|
||||
{TenantID: h.tenant.ID, UserID: "u", Capability: "portal:billing.view", RequestedBy: " "},
|
||||
} {
|
||||
if _, _, err := h.store.CreateCapabilityRequest(ctx, bad); !errors.Is(err, store.ErrInvalidInput) {
|
||||
t.Errorf("%+v: %v", bad, err)
|
||||
}
|
||||
}
|
||||
for _, tenant := range []string{"00000000-0000-0000-0000-000000000000", "no-uuid"} {
|
||||
if _, _, err := h.store.CreateCapabilityRequest(ctx, store.CapabilityRequest{TenantID: tenant, UserID: "u",
|
||||
Capability: "portal:billing.view", RequestedBy: "a"}); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Errorf("unknown tenant %s: %v", tenant, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -98,6 +98,8 @@ func (s *Server) tenantSubresource(w http.ResponseWriter, r *http.Request) {
|
||||
s.getRoleDataset(w, r)
|
||||
case "store":
|
||||
s.listStore(w, r)
|
||||
case "capability-requests":
|
||||
s.listCapabilityRequests(w, r)
|
||||
default:
|
||||
writeError(w, http.StatusNotFound, "not_found", "no such tenant sub-resource")
|
||||
}
|
||||
|
||||
@@ -50,6 +50,11 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
|
||||
{"GET", "/v1/tenants?limit=10"},
|
||||
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/members"},
|
||||
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset"},
|
||||
{"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1/capabilities"},
|
||||
{"DELETE", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1/capabilities/portal:billing.view"},
|
||||
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/capability-requests"},
|
||||
{"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/capability-requests/00000000-0000-0000-0000-000000000002/approve"},
|
||||
{"DELETE", "/v1/tenants/00000000-0000-0000-0000-000000000001/capability-requests/00000000-0000-0000-0000-000000000002"},
|
||||
{"PUT", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset"},
|
||||
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset/revisions/2"},
|
||||
{"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/intake/reports"},
|
||||
|
||||
@@ -135,6 +135,12 @@ func NewRouter(s *Server) http.Handler {
|
||||
mux.HandleFunc("PATCH /v1/tenants/{id}/members/{uid}", s.patchTenantMember)
|
||||
mux.HandleFunc("DELETE /v1/tenants/{id}/members/{uid}", s.deleteTenantMember)
|
||||
mux.HandleFunc("POST /v1/tenants/{id}/members/{uid}/resend", s.resendTenantMember)
|
||||
// Individual capabilities (RBAC step 3, capabilities.go); the list of
|
||||
// open requests is a {sub} of tenantSubresource.
|
||||
mux.HandleFunc("POST /v1/tenants/{id}/members/{uid}/capabilities", s.grantCapability)
|
||||
mux.HandleFunc("DELETE /v1/tenants/{id}/members/{uid}/capabilities/{cap}", s.revokeCapability)
|
||||
mux.HandleFunc("POST /v1/tenants/{id}/capability-requests/{rid}/approve", s.approveCapabilityRequest)
|
||||
mux.HandleFunc("DELETE /v1/tenants/{id}/capability-requests/{rid}", s.deleteCapabilityRequest)
|
||||
// Trial signup (portal#64): offer, confirmation/activation, new link; the
|
||||
// contract documents of a tenant.
|
||||
mux.HandleFunc("POST /v1/trial-offers", s.createTrialOffer)
|
||||
|
||||
@@ -329,6 +329,7 @@ func (s *Server) deleteMember(w http.ResponseWriter, r *http.Request, resolve te
|
||||
return
|
||||
}
|
||||
s.blocks.forget(m.UserID)
|
||||
s.dropCapabilityRequests(ctx, t.ID, 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
|
||||
@@ -339,12 +340,22 @@ func (s *Server) deleteMember(w http.ResponseWriter, r *http.Request, resolve te
|
||||
return
|
||||
}
|
||||
s.blocks.forget(m.UserID)
|
||||
s.dropCapabilityRequests(ctx, t.ID, 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})
|
||||
}
|
||||
|
||||
// dropCapabilityRequests drops the open capability requests of a member who
|
||||
// leaves; a failure is logged (an approval of a stale request finds no
|
||||
// member and drops it then).
|
||||
func (s *Server) dropCapabilityRequests(ctx context.Context, tenantID, userID string) {
|
||||
if _, err := s.Store.DeleteMemberCapabilityRequests(ctx, tenantID, userID, ""); err != nil {
|
||||
s.Log.Warn("capability requests not dropped", "tenant_id", tenantID, "user_id", userID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CapabilityRequest is a grant of an administration capability to one
|
||||
// member that waits for a second person (RBAC step 3, four-eyes; 0029).
|
||||
type CapabilityRequest struct {
|
||||
ID string `json:"id"`
|
||||
TenantID string `json:"tenant_id"`
|
||||
UserID string `json:"user_id"`
|
||||
UserEmail string `json:"user_email"`
|
||||
Capability string `json:"capability"`
|
||||
RequestedBy string `json:"requested_by"`
|
||||
RequestedEmail string `json:"requested_email"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// capabilityRE is the shape of a capability code, as the table checks it.
|
||||
var capabilityRE = regexp.MustCompile(`^[a-z]+:[a-z0-9-]+\.[a-z0-9-]+$`)
|
||||
|
||||
func (r CapabilityRequest) valid() bool {
|
||||
return r.TenantID != "" && r.UserID != "" && len(r.UserID) <= 200 && capabilityRE.MatchString(r.Capability) &&
|
||||
strings.TrimSpace(r.RequestedBy) != "" && len(r.RequestedBy) <= 200 && len(r.UserEmail) <= 320 && len(r.RequestedEmail) <= 320
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package store
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -55,6 +56,8 @@ type Memory struct {
|
||||
intakeCounters map[string]int // tenant_id → last seq
|
||||
intakeEntryID int64
|
||||
contractDocID int64
|
||||
|
||||
capRequests []CapabilityRequest // pending four-eyes grants, oldest first (0029)
|
||||
}
|
||||
|
||||
type apiKeyWithHash struct {
|
||||
@@ -614,6 +617,7 @@ func (m *Memory) DeleteTenant(_ context.Context, id string) error {
|
||||
}
|
||||
m.contractDocs = kept
|
||||
m.deleteIntake(id)
|
||||
m.capRequests = slices.DeleteFunc(m.capRequests, func(r CapabilityRequest) bool { return r.TenantID == id })
|
||||
for kid, k := range m.apiKeys {
|
||||
if k.TenantID == id {
|
||||
delete(m.apiKeys, kid)
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func (m *Memory) CreateCapabilityRequest(_ context.Context, r CapabilityRequest) (*CapabilityRequest, bool, error) {
|
||||
if !r.valid() {
|
||||
return nil, false, ErrInvalidInput
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if _, ok := m.tenants[r.TenantID]; !ok {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
for _, cur := range m.capRequests {
|
||||
if cur.TenantID == r.TenantID && cur.UserID == r.UserID && cur.Capability == r.Capability {
|
||||
cp := cur
|
||||
return &cp, false, nil
|
||||
}
|
||||
}
|
||||
r.ID = uuid.NewString()
|
||||
r.CreatedAt = time.Now().UTC().Truncate(time.Microsecond)
|
||||
m.capRequests = append(m.capRequests, r)
|
||||
cp := r
|
||||
return &cp, true, nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListCapabilityRequests(_ context.Context, tenantID string) ([]CapabilityRequest, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
out := []CapabilityRequest{}
|
||||
for _, r := range m.capRequests {
|
||||
if r.TenantID == tenantID {
|
||||
out = append(out, r)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Memory) GetCapabilityRequest(_ context.Context, tenantID, id string) (*CapabilityRequest, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
for _, r := range m.capRequests {
|
||||
if r.TenantID == tenantID && r.ID == id {
|
||||
cp := r
|
||||
return &cp, nil
|
||||
}
|
||||
}
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
func (m *Memory) DeleteCapabilityRequest(_ context.Context, tenantID, id string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
n := len(m.capRequests)
|
||||
m.capRequests = slices.DeleteFunc(m.capRequests, func(r CapabilityRequest) bool { return r.TenantID == tenantID && r.ID == id })
|
||||
if len(m.capRequests) == n {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) DeleteMemberCapabilityRequests(_ context.Context, tenantID, userID, capability string) (int, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
n := len(m.capRequests)
|
||||
m.capRequests = slices.DeleteFunc(m.capRequests, func(r CapabilityRequest) bool {
|
||||
return r.TenantID == tenantID && r.UserID == userID && (capability == "" || r.Capability == capability)
|
||||
})
|
||||
return n - len(m.capRequests), nil
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const capRequestSelect = `
|
||||
SELECT id::text, tenant_id::text, user_id, user_email, capability, requested_by, requested_email, created_at
|
||||
FROM capability_requests `
|
||||
|
||||
func scanCapRequest(row pgx.Row) (*CapabilityRequest, error) {
|
||||
var r CapabilityRequest
|
||||
if err := row.Scan(&r.ID, &r.TenantID, &r.UserID, &r.UserEmail, &r.Capability, &r.RequestedBy, &r.RequestedEmail, &r.CreatedAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
r.CreatedAt = r.CreatedAt.UTC()
|
||||
return &r, nil
|
||||
}
|
||||
|
||||
func (p *Postgres) CreateCapabilityRequest(ctx context.Context, r CapabilityRequest) (*CapabilityRequest, bool, error) {
|
||||
if !r.valid() {
|
||||
return nil, false, ErrInvalidInput
|
||||
}
|
||||
got, err := scanCapRequest(p.pool.QueryRow(ctx, `
|
||||
INSERT INTO capability_requests (tenant_id, user_id, user_email, capability, requested_by, requested_email)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5, $6)
|
||||
ON CONFLICT (tenant_id, user_id, capability) DO NOTHING
|
||||
RETURNING id::text, tenant_id::text, user_id, user_email, capability, requested_by, requested_email, created_at`,
|
||||
r.TenantID, r.UserID, r.UserEmail, r.Capability, r.RequestedBy, r.RequestedEmail))
|
||||
switch {
|
||||
case err == nil:
|
||||
return got, true, nil
|
||||
case errors.Is(err, ErrNotFound):
|
||||
// The request exists already.
|
||||
cur, err := scanCapRequest(p.pool.QueryRow(ctx, capRequestSelect+`WHERE tenant_id = $1::uuid AND user_id = $2 AND capability = $3`,
|
||||
r.TenantID, r.UserID, r.Capability))
|
||||
return cur, false, err
|
||||
case isFKViolation(err), isInvalidUUID(err):
|
||||
return nil, false, ErrNotFound
|
||||
case isCheckViolation(err):
|
||||
return nil, false, ErrInvalidInput
|
||||
default:
|
||||
return nil, false, err
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Postgres) ListCapabilityRequests(ctx context.Context, tenantID string) ([]CapabilityRequest, error) {
|
||||
rows, err := p.pool.Query(ctx, capRequestSelect+`WHERE tenant_id = $1::uuid ORDER BY created_at, id`, tenantID)
|
||||
if isInvalidUUID(err) {
|
||||
return []CapabilityRequest{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []CapabilityRequest{}
|
||||
for rows.Next() {
|
||||
r, err := scanCapRequest(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, *r)
|
||||
}
|
||||
if err := rows.Err(); isInvalidUUID(err) {
|
||||
return []CapabilityRequest{}, nil
|
||||
} else if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (p *Postgres) GetCapabilityRequest(ctx context.Context, tenantID, id string) (*CapabilityRequest, error) {
|
||||
r, err := scanCapRequest(p.pool.QueryRow(ctx, capRequestSelect+`WHERE tenant_id = $1::uuid AND id = $2::uuid`, tenantID, id))
|
||||
if isInvalidUUID(err) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return r, err
|
||||
}
|
||||
|
||||
func (p *Postgres) DeleteCapabilityRequest(ctx context.Context, tenantID, id string) error {
|
||||
tag, err := p.pool.Exec(ctx, `DELETE FROM capability_requests WHERE tenant_id = $1::uuid AND id = $2::uuid`, tenantID, id)
|
||||
switch {
|
||||
case isInvalidUUID(err):
|
||||
return ErrNotFound
|
||||
case err != nil:
|
||||
return err
|
||||
case tag.RowsAffected() == 0:
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Postgres) DeleteMemberCapabilityRequests(ctx context.Context, tenantID, userID, capability string) (int, error) {
|
||||
tag, err := p.pool.Exec(ctx, `DELETE FROM capability_requests WHERE tenant_id = $1::uuid AND user_id = $2 AND ($3 = '' OR capability = $3)`,
|
||||
tenantID, userID, capability)
|
||||
if isInvalidUUID(err) {
|
||||
return 0, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int(tag.RowsAffected()), nil
|
||||
}
|
||||
@@ -267,6 +267,21 @@ type Store interface {
|
||||
PendingIntake(ctx context.Context, after int64, limit int) ([]PendingIntake, error)
|
||||
AddIntakeReceipt(ctx context.Context, r IntakeReceipt) (added bool, err error)
|
||||
|
||||
// Capability requests (0029, RBAC step 3): grants of an administration
|
||||
// capability waiting for a second person. CreateCapabilityRequest
|
||||
// returns the open request for the same member and capability instead
|
||||
// of a second one (created=false); ErrNotFound for an unknown tenant,
|
||||
// ErrInvalidInput for a malformed row. ListCapabilityRequests lists a
|
||||
// tenant's open requests, oldest first. GetCapabilityRequest and
|
||||
// DeleteCapabilityRequest are ErrNotFound for an unknown id.
|
||||
// DeleteMemberCapabilityRequests drops a member's open requests for
|
||||
// capability, or all of them when capability is "".
|
||||
CreateCapabilityRequest(ctx context.Context, r CapabilityRequest) (req *CapabilityRequest, created bool, err error)
|
||||
ListCapabilityRequests(ctx context.Context, tenantID string) ([]CapabilityRequest, error)
|
||||
GetCapabilityRequest(ctx context.Context, tenantID, id string) (*CapabilityRequest, error)
|
||||
DeleteCapabilityRequest(ctx context.Context, tenantID, id string) error
|
||||
DeleteMemberCapabilityRequests(ctx context.Context, tenantID, userID, capability string) (int, error)
|
||||
|
||||
// Product settings (0025): the workspace's own choices per product,
|
||||
// untouched by the ERP recompute. GetTenantProductSettings is
|
||||
// ErrNotFound when none were saved; PutTenantProductSettings replaces
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS capability_requests;
|
||||
@@ -0,0 +1,16 @@
|
||||
-- RBAC step 3: a request to grant an administration capability to one
|
||||
-- member waits here for a second person (four-eyes). A grant of any other
|
||||
-- capability is written to Keycloak at once and never lands here. The row
|
||||
-- is deleted when the request is approved, rejected or withdrawn, or the
|
||||
-- member leaves; the audit log keeps the history.
|
||||
CREATE TABLE capability_requests (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
user_id TEXT NOT NULL CHECK (char_length(user_id) BETWEEN 1 AND 200),
|
||||
user_email TEXT NOT NULL DEFAULT '' CHECK (char_length(user_email) <= 320),
|
||||
capability TEXT NOT NULL CHECK (capability ~ '^[a-z]+:[a-z0-9-]+\.[a-z0-9-]+$'),
|
||||
requested_by TEXT NOT NULL CHECK (char_length(requested_by) BETWEEN 1 AND 200),
|
||||
requested_email TEXT NOT NULL DEFAULT '' CHECK (char_length(requested_email) <= 320),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (tenant_id, user_id, capability)
|
||||
);
|
||||
+146
@@ -974,6 +974,127 @@ paths:
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/Conflict" }
|
||||
|
||||
/v1/tenants/{id}/members/{uid}/capabilities:
|
||||
post:
|
||||
summary: Give a member an individual capability on top of their bundle (RBAC step 3).
|
||||
description: |
|
||||
User tokens need IT_ADMIN or OWNER in their own tenant; service clients the `tenants.write` route group. The portal names the acting person in `X-Portal-User-Subject` / `X-Portal-User-Email`.
|
||||
The acting person must be an active member of the workspace who holds
|
||||
`registry:members.manage` (bundle or individual), and must hold the
|
||||
capability themselves (403 `not_held`). Staff and plain service
|
||||
clients cannot grant. The capability lands in the member's
|
||||
`extra_capabilities` user attribute, which the tenant-context mapper
|
||||
puts into the token, so it takes effect at the member's next token
|
||||
refresh. An administration capability (`admin` in the catalogue) is
|
||||
not applied: it becomes a request a second person approves (202,
|
||||
four-eyes). 400 `unknown_capability`; 409 `self`, `in_bundle` (the
|
||||
member's bundle grants it already). Audit:
|
||||
`user.capability_granted`, `user.capability_requested`.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: uid, required: true, schema: { type: string }, description: Keycloak user id of the member }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [capability]
|
||||
properties:
|
||||
capability: { type: string, example: "werkmeister:process.publish" }
|
||||
responses:
|
||||
"200":
|
||||
description: Granted (or `unchanged`).
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/CapabilityAction" } }
|
||||
"202":
|
||||
description: An administration capability; waits for a second person.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/CapabilityAction" } }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/Conflict" }
|
||||
|
||||
/v1/tenants/{id}/members/{uid}/capabilities/{cap}:
|
||||
delete:
|
||||
summary: Take an individual capability back, or withdraw its open request.
|
||||
description: |
|
||||
Same caller rules as the grant, except that the actor need not hold
|
||||
the capability. Takes effect at the member's next token refresh.
|
||||
Audit: `user.capability_revoked`, `user.capability_request_withdrawn`.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: uid, required: true, schema: { type: string }, description: Keycloak user id of the member }
|
||||
- { in: path, name: cap, required: true, schema: { type: string }, description: the capability code }
|
||||
responses:
|
||||
"200":
|
||||
description: Revoked, withdrawn or `unchanged`.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/CapabilityAction" } }
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/Conflict" }
|
||||
|
||||
/v1/tenants/{id}/capability-requests:
|
||||
get:
|
||||
summary: Open requests for administration capabilities (four-eyes), oldest first.
|
||||
description: |
|
||||
User tokens need IT_ADMIN or OWNER in their own tenant; service clients the `tenants.read` route group.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"200":
|
||||
description: The open requests.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [requests]
|
||||
properties:
|
||||
requests:
|
||||
type: array
|
||||
items: { $ref: "#/components/schemas/CapabilityRequest" }
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/capability-requests/{rid}/approve:
|
||||
post:
|
||||
summary: The second person approves a request; the capability is granted.
|
||||
description: |
|
||||
Same caller rules as the grant. 409 `four_eyes` when the requester
|
||||
approves, `self` when the member approves their own. 404
|
||||
`not_a_member` when the member has left (the request is dropped).
|
||||
Audit: `user.capability_granted` with `requested_by`.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: rid, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"200":
|
||||
description: Granted.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/CapabilityAction" } }
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/Conflict" }
|
||||
|
||||
/v1/tenants/{id}/capability-requests/{rid}:
|
||||
delete:
|
||||
summary: Reject a request, or withdraw it (the requester).
|
||||
description: |
|
||||
Same caller rules as the grant. Audit:
|
||||
`user.capability_request_rejected`, `user.capability_request_withdrawn`.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: rid, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"200":
|
||||
description: Rejected or withdrawn.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/CapabilityAction" } }
|
||||
"403": { $ref: "#/components/responses/Forbidden" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/admin/tenants:
|
||||
get:
|
||||
summary: Staff tenant list with search and 30-day activity.
|
||||
@@ -2760,6 +2881,10 @@ components:
|
||||
created_at: { type: string, format: date-time, nullable: true }
|
||||
pending: { type: boolean, description: "invitation not accepted yet (no password, no identity-provider link)" }
|
||||
status: { type: string, enum: [invited, active, blocked], description: "status in this tenant (portal#74)" }
|
||||
extra_capabilities:
|
||||
type: array
|
||||
description: Individual capabilities on top of the bundle (RBAC step 3).
|
||||
items: { type: string }
|
||||
|
||||
MemberAction:
|
||||
type: object
|
||||
@@ -2774,6 +2899,27 @@ components:
|
||||
description: The member's active API keys in this tenant, offered for revocation.
|
||||
items: { $ref: "#/components/schemas/APIKey" }
|
||||
|
||||
CapabilityRequest:
|
||||
type: object
|
||||
required: [id, tenant_id, user_id, capability, requested_by, created_at]
|
||||
properties:
|
||||
id: { type: string, format: uuid }
|
||||
tenant_id: { type: string, format: uuid }
|
||||
user_id: { type: string }
|
||||
user_email: { type: string }
|
||||
capability: { type: string }
|
||||
requested_by: { type: string }
|
||||
requested_email: { type: string }
|
||||
created_at: { type: string, format: date-time }
|
||||
|
||||
CapabilityAction:
|
||||
type: object
|
||||
required: [status]
|
||||
properties:
|
||||
status: { type: string, enum: [capability_granted, capability_revoked, unchanged, approval_requested, request_rejected, request_withdrawn] }
|
||||
member: { $ref: "#/components/schemas/OrgMember" }
|
||||
request: { $ref: "#/components/schemas/CapabilityRequest" }
|
||||
|
||||
Invite:
|
||||
type: object
|
||||
required: [user_id, email, status]
|
||||
|
||||
Reference in new issue
Block a user