feat(roles): who holds a function (RBAC step 5) #124

Merged
sharang merged 3 commits from feat/function-holders into main 2026-11-11 21:44:56 +00:00
7 changed files with 243 additions and 2 deletions

No files matched your search

+40 -2
View File
@@ -861,8 +861,43 @@ func (ds *Dataset) Resolve(dt string, scope Scope, now time.Time) (*Resolution,
if fn == "" {
return res, nil
}
h, err := ds.holdersOf(fn, scope, now, dt)
if err != nil {
return nil, err
}
res.Function, res.Source = fn, src
f, _ := FunctionByKey(fn)
res.AnyMember, res.Holders, res.Deputies, res.Status = h.AnyMember, h.Holders, h.Deputies, h.Status
return res, nil
}
// FunctionHolders answers "who holds this function now" (RBAC plan step 5:
// a Werkmeister step names a function). Deputies are the effective ones of
// the function, whatever decision types they cover; they stand in for
// decisions, so a step that is worked rather than decided counts only the
// holders.
type FunctionHolders struct {
Function string `json:"function"`
Label string `json:"label"`
AnyMember bool `json:"any_member,omitempty"`
Holders []Holder `json:"holders"`
Deputies []ResolutionDeputy `json:"deputies"`
Status string `json:"status"`
}
// HoldersOf finds the holders of function fn in the given scope and its
// effective deputies.
func (ds *Dataset) HoldersOf(fn string, scope Scope, now time.Time) (*FunctionHolders, *Error) {
return ds.holdersOf(fn, scope, now, "")
}
// holdersOf: the assignments of fn matching scope, and the effective
// deputies of fn (covering dt, when dt is set).
func (ds *Dataset) holdersOf(fn string, scope Scope, now time.Time, dt string) (*FunctionHolders, *Error) {
f, ok := FunctionByKey(fn)
if !ok {
return nil, &Error{Status: http.StatusBadRequest, Code: "unknown_function", Message: fmt.Sprintf("unknown function %q", fn)}
}
res := &FunctionHolders{Function: fn, Label: f.Label, Holders: []Holder{}, Deputies: []ResolutionDeputy{}, Status: StatusOpen}
if f.AnyMember {
res.AnyMember, res.Status = true, StatusFilled
return res, nil
@@ -873,6 +908,9 @@ func (ds *Dataset) Resolve(dt string, scope Scope, now time.Time) (*Resolution,
return nil, err
}
}
if ds == nil {
return res, nil
}
match := func(s *Scope) bool { return f.Per == PerCompany || scopeKey(s) == scopeKey(&scope) }
notApplicable := false
for _, a := range ds.Assignments {
@@ -886,7 +924,7 @@ func (ds *Dataset) Resolve(dt string, scope Scope, now time.Time) (*Resolution,
res.Holders = append(res.Holders, a.Holder)
}
for _, d := range ds.Deputies {
if d.Function != fn || !match(d.Scope) || !slices.Contains(d.DecisionTypes, dt) {
if d.Function != fn || !match(d.Scope) || (dt != "" && !slices.Contains(d.DecisionTypes, dt)) {
continue
}
if st := ds.State(d, now); st.State == StateEffective {
+28
View File
@@ -384,3 +384,31 @@ func TestChanges_namesIDsOnly(t *testing.T) {
t.Fatal("no personal data or texts in the changes")
}
}
// RBAC step 5: holders of a function, deputies of any decision type.
func TestHoldersOf(t *testing.T) {
now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC)
var none *Dataset
if h, err := none.HoldersOf(Management, Scope{}, now); err != nil || h.Status != StatusOpen || len(h.Holders) != 0 {
t.Fatalf("no dataset: %+v %v", h, err)
}
if h, err := none.HoldersOf("r1.aenderungsinitiierung", Scope{}, now); err != nil || !h.AnyMember || h.Status != StatusFilled {
t.Fatalf("any member: %+v %v", h, err)
}
if _, err := none.HoldersOf("r1.nope", Scope{}, now); err == nil || err.Code != "unknown_function" {
t.Fatalf("unknown: %v", err)
}
if _, err := none.HoldersOf("r1.produktverantwortung", Scope{}, now); err == nil || err.Code != "scope_required" {
t.Fatalf("scope: %v", err)
}
ds := &Dataset{Assignments: []Assignment{
{ID: "a1", Function: "r1.produktverantwortung", Holder: Holder{Kind: HolderMember, Sub: "u1"}, Scope: &Scope{Product: "Pumpe"}},
{ID: "a2", Function: "r1.produktverantwortung", Holder: Holder{Kind: HolderNotApplicable}, Scope: &Scope{Product: "Ventil"}},
}}
if h, _ := ds.HoldersOf("r1.produktverantwortung", Scope{Product: "Pumpe"}, now); h.Status != StatusFilled || h.Holders[0].Sub != "u1" {
t.Fatalf("per product: %+v", h)
}
if h, _ := ds.HoldersOf("r1.produktverantwortung", Scope{Product: "Ventil"}, now); h.Status != StatusNotApplicable {
t.Fatalf("not applicable: %+v", h)
}
}
+34
View File
@@ -55,6 +55,12 @@ type roleDatasetDerived struct {
Deputies []roles.DeputyState `json:"deputies"`
}
type roleDatasetHoldersResp struct {
Revision int `json:"revision"`
CatalogueVersion string `json:"catalogue_version"`
*roles.FunctionHolders
}
type roleDatasetResolveResp struct {
Revision int `json:"revision"`
CatalogueVersion string `json:"catalogue_version"`
@@ -251,6 +257,34 @@ func (s *Server) getRoleDatasetRevision(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, d)
}
// roleDatasetHolders is GET /v1/tenants/{id}/role-dataset/holders
// ?function=…[&document=…|&product=…|&area=…]: who holds the function now
// (RBAC plan step 5, a Werkmeister step that names a function).
func (s *Server) roleDatasetHolders(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
stored, ds, err := s.currentRoleDataset(ctx, t.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
q := r.URL.Query()
res, rerr := ds.HoldersOf(q.Get("function"), roles.Scope{Document: q.Get("document"), Product: q.Get("product"), Area: q.Get("area")}, s.now())
if rerr != nil {
writeJSON(w, rerr.Status, rerr)
return
}
out := roleDatasetHoldersResp{CatalogueVersion: roles.CatalogueVersion, FunctionHolders: res}
if stored != nil {
out.Revision, out.CatalogueVersion = stored.Revision, stored.CatalogueVersion
}
writeJSON(w, http.StatusOK, out)
}
// resolveRoleDataset is GET /v1/tenants/{id}/role-dataset/resolve
// ?decision_type=…[&document=…|&product=…|&area=…].
func (s *Server) resolveRoleDataset(w http.ResponseWriter, r *http.Request) {
+30
View File
@@ -160,6 +160,35 @@ func TestRoleDataset_lifecycle(t *testing.T) {
if code, _, _ := f.do(t, "werkmeister", "GET", f.path("/resolve?decision_type=r1.nope"), ""); code != http.StatusBadRequest {
t.Fatalf("unknown decision type: %d", code)
}
// Holders of a function (RBAC step 5): the assignment, and the
// effective deputy of the function whatever it covers.
code, out, raw = f.do(t, "werkmeister", "GET", f.path("/holders?function=r1.geschaeftsleitung"), "")
if code != http.StatusOK || out["status"] != roles.StatusFilled || out["revision"].(float64) != 2 || len(out["holders"].([]any)) != 1 || len(out["deputies"].([]any)) != 1 {
t.Fatalf("holders: %d %s", code, raw)
}
if h := out["holders"].([]any)[0].(map[string]any); h["kind"] != "member" || h["sub"] != "u-ceo" || out["label"] != "Geschäftsleitung" {
t.Fatalf("holder: %v", h)
}
if code, out, _ := f.do(t, "werkmeister", "GET", f.path("/holders?function=r1.vorfallkontakt"), ""); code != http.StatusOK || out["status"] != roles.StatusOpen || len(out["holders"].([]any)) != 0 {
t.Fatalf("nobody holds it: %d %v", code, out)
}
if code, _, raw := f.do(t, "werkmeister", "GET", f.path("/holders?function=r1.nope"), ""); code != http.StatusBadRequest || !strings.Contains(raw, "unknown_function") {
t.Fatalf("unknown function: %d %s", code, raw)
}
if code, _, raw := f.do(t, "werkmeister", "GET", f.path("/holders?function=r1.produktverantwortung"), ""); code != http.StatusBadRequest || !strings.Contains(raw, "scope_required") {
t.Fatalf("per product without a product: %d %s", code, raw)
}
if code, out, _ := f.do(t, "werkmeister", "GET", f.path("/holders?function=r1.produktverantwortung&product=Pumpstation"), ""); code != http.StatusOK || out["status"] != roles.StatusOpen {
t.Fatalf("per product: %d %v", code, out)
}
// A person reads it with their own token too; another tenant's never.
if code, _, raw := f.do(t, "staff", "GET", f.path("/holders?function=r1.geschaeftsleitung"), ""); code != http.StatusOK {
t.Fatalf("member: %d %s", code, raw)
}
if code, _, _ := f.do(t, "stranger", "GET", f.path("/holders?function=r1.geschaeftsleitung"), ""); code != http.StatusNotFound {
t.Fatalf("other tenant: %d", code)
}
code, out, raw = f.do(t, "werkmeister", "GET", f.path("/revisions/1"), "")
if code != http.StatusOK || out["revision"].(float64) != 1 || out["updated_by"] != "u-signup" {
t.Fatalf("revision 1: %d %s", code, raw)
@@ -226,6 +255,7 @@ func TestRoleDatasetPath(t *testing.T) {
for path, want := range map[string]bool{
"/v1/tenants/x/role-dataset": true,
"/v1/tenants/x/role-dataset/resolve": true,
"/v1/tenants/x/role-dataset/holders": true,
"/v1/tenants/x/role-dataset/revisions/2": true,
"/v1/tenants/x/members": false,
"/v1/tenants/role-dataset": false,
+1
View File
@@ -167,6 +167,7 @@ func NewRouter(s *Server) http.Handler {
mux.HandleFunc("PUT /v1/tenants/{id}/role-dataset", s.saveRoleDataset)
mux.HandleFunc("GET /v1/tenants/{id}/role-dataset/revisions/{rev}", s.getRoleDatasetRevision)
mux.HandleFunc("GET /v1/tenants/{id}/role-dataset/resolve", s.resolveRoleDataset)
mux.HandleFunc("GET /v1/tenants/{id}/role-dataset/holders", s.roleDatasetHolders)
// Prüfwerk settings (0025, t72): the workspace's Prüftag cap.
// R1 intake (0028, docgen#6 F01): intake.go.
mux.HandleFunc("POST /v1/tenants/{id}/intake/reports", s.createIntakeReport)
+69
View File
@@ -0,0 +1,69 @@
package server
import (
"context"
"io"
"log/slog"
"net/http/httptest"
"testing"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/erp"
"git.breakpilot.com/platform/tenant-registry/internal/mail"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// The background workers idle without their backend and stop with their
// context, after at least one round.
func TestWorkersStopWithTheirContext(t *testing.T) {
s := &Server{Log: slog.New(slog.NewTextHandler(io.Discard, nil)), Store: store.NewMemory()}
ctx := context.Background()
// No mail sender, no ERP: the workers return at once.
s.RunMail(ctx, time.Millisecond)
s.RunOutbox(ctx, time.Millisecond)
run := func(name string, f func(context.Context)) {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, 30*time.Millisecond)
defer cancel()
done := make(chan struct{})
go func() { f(ctx); close(done) }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatalf("%s did not stop with its context", name)
}
}
s.Mail = &mail.Recorder{}
run("mail", func(c context.Context) { s.RunMail(c, time.Millisecond) })
s.ERP = erp.New(erp.Config{BaseURL: "http://127.0.0.1:1"})
run("outbox", func(c context.Context) { s.RunOutbox(c, time.Millisecond) })
s.ERP = nil
run("reconcile", func(c context.Context) { s.RunReconcile(c, time.Millisecond) })
// A zero interval takes the default; the context ends the wait.
run("mail default", func(c context.Context) { s.RunMail(c, 0) })
run("reconcile default", func(c context.Context) { s.RunReconcile(c, 0) })
}
// clientIP: the first X-Forwarded-For entry, else the remote address,
// IPv6 without brackets (Postgres inet rejects them).
func TestClientIP(t *testing.T) {
for _, c := range []struct{ fwd, remote, want string }{
{"203.0.113.7, 10.0.0.1", "10.0.0.2:5000", "203.0.113.7"},
{"[2001:db8::1]", "10.0.0.2:5000", "2001:db8::1"},
{"", "10.0.0.2:5000", "10.0.0.2"},
{"", "[::1]:443", "::1"},
{"", "[::1]", "::1"},
{"", "socket", "socket"},
} {
r := httptest.NewRequest("GET", "/", nil)
r.RemoteAddr = c.remote
if c.fwd != "" {
r.Header.Set("X-Forwarded-For", c.fwd)
}
if got := clientIP(r); got != c.want {
t.Errorf("fwd %q remote %q: %q, want %q", c.fwd, c.remote, got, c.want)
}
}
}
+41
View File
@@ -707,6 +707,29 @@ paths:
"400": { description: "unknown_decision_type or scope_required." }
"404": { $ref: "#/components/responses/NotFound" }
/v1/tenants/{id}/role-dataset/holders:
get:
summary: Who holds a function now.
description: |
The holders of the function in the given scope and its effective
deputies, whatever decision types they cover (RBAC plan step 5: a
Werkmeister step that names a function counts the holders; deputies
stand in for decisions). `rolle_offen` when nobody holds it. A
function per document, product or area needs that scope.
parameters:
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
- { in: query, name: function, required: true, schema: { type: string } }
- { in: query, name: document, schema: { type: string } }
- { in: query, name: product, schema: { type: string } }
- { in: query, name: area, schema: { type: string } }
responses:
"200":
description: The answer.
content:
application/json: { schema: { $ref: "#/components/schemas/RoleDatasetHolders" } }
"400": { description: "unknown_function or scope_required." }
"404": { $ref: "#/components/responses/NotFound" }
/v1/tenants/{id}/products/pruefwerk/settings:
get:
summary: The workspace's Prüfwerk settings (the monthly Prüftag cap).
@@ -2742,6 +2765,24 @@ components:
holder: { $ref: "#/components/schemas/RoleHolder" }
state: { type: string, enum: [wirksam] }
status: { type: string, enum: [besetzt, rolle_offen, nicht_anwendbar] }
RoleDatasetHolders:
type: object
properties:
revision: { type: integer, minimum: 0 }
catalogue_version: { type: string }
function: { type: string }
label: { type: string, description: "the function's name in the catalogue" }
any_member: { type: boolean }
holders: { type: array, items: { $ref: "#/components/schemas/RoleHolder" } }
deputies:
type: array
items:
type: object
properties:
id: { type: string }
holder: { $ref: "#/components/schemas/RoleHolder" }
state: { type: string, enum: [wirksam] }
status: { type: string, enum: [besetzt, rolle_offen, nicht_anwendbar] }
RoleHolder:
type: object
required: [kind]