From 9c2e23a0362467695d8b41934710f02995e627c9 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:14:54 +0100 Subject: [PATCH 1/3] feat(roles): who holds a function (RBAC step 5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /v1/tenants/{id}/role-dataset/holders?function=…[&scope] answers who holds a role-dataset function now: the holders in the scope, the effective deputies of the function and open/filled/not applicable. Werkmeister reads it (tenants.read) when a step names a function. It shares the matching with /resolve, which now goes through it; for a decision type, only deputies covering it count, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014aRnCGqELxoix5TfpX8Ejf --- internal/roles/dataset.go | 41 ++++++++++++++++++++++++++-- internal/roles/dataset_test.go | 28 +++++++++++++++++++ internal/server/role_dataset.go | 34 +++++++++++++++++++++++ internal/server/role_dataset_test.go | 30 ++++++++++++++++++++ internal/server/server.go | 1 + openapi.yaml | 40 +++++++++++++++++++++++++++ 6 files changed, 172 insertions(+), 2 deletions(-) diff --git a/internal/roles/dataset.go b/internal/roles/dataset.go index 491eb91..648417d 100644 --- a/internal/roles/dataset.go +++ b/internal/roles/dataset.go @@ -861,8 +861,42 @@ 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"` + 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, Holders: []Holder{}, Deputies: []ResolutionDeputy{}, Status: StatusOpen} if f.AnyMember { res.AnyMember, res.Status = true, StatusFilled return res, nil @@ -873,6 +907,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 +923,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 { diff --git a/internal/roles/dataset_test.go b/internal/roles/dataset_test.go index 3deeb5c..c70be09 100644 --- a/internal/roles/dataset_test.go +++ b/internal/roles/dataset_test.go @@ -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) + } +} diff --git a/internal/server/role_dataset.go b/internal/server/role_dataset.go index 5a22a90..dbe4882 100644 --- a/internal/server/role_dataset.go +++ b/internal/server/role_dataset.go @@ -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) { diff --git a/internal/server/role_dataset_test.go b/internal/server/role_dataset_test.go index 10aa818..e064a83 100644 --- a/internal/server/role_dataset_test.go +++ b/internal/server/role_dataset_test.go @@ -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" { + 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, diff --git a/internal/server/server.go b/internal/server/server.go index 25ef110..e006209 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -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) diff --git a/openapi.yaml b/openapi.yaml index 8803b18..14a2d62 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -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,23 @@ 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 } + 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] -- 2.54.1 From 79588bef05fc2f768f30ad046f8330a720361ea1 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:15:34 +0100 Subject: [PATCH 2/3] feat(roles): the holders answer names the function Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014aRnCGqELxoix5TfpX8Ejf --- internal/roles/dataset.go | 3 ++- internal/server/role_dataset_test.go | 2 +- openapi.yaml | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/internal/roles/dataset.go b/internal/roles/dataset.go index 648417d..aa43e31 100644 --- a/internal/roles/dataset.go +++ b/internal/roles/dataset.go @@ -877,6 +877,7 @@ func (ds *Dataset) Resolve(dt string, scope Scope, now time.Time) (*Resolution, // 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"` @@ -896,7 +897,7 @@ func (ds *Dataset) holdersOf(fn string, scope Scope, now time.Time, dt string) ( if !ok { return nil, &Error{Status: http.StatusBadRequest, Code: "unknown_function", Message: fmt.Sprintf("unknown function %q", fn)} } - res := &FunctionHolders{Function: fn, Holders: []Holder{}, Deputies: []ResolutionDeputy{}, Status: StatusOpen} + 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 diff --git a/internal/server/role_dataset_test.go b/internal/server/role_dataset_test.go index e064a83..09a3fea 100644 --- a/internal/server/role_dataset_test.go +++ b/internal/server/role_dataset_test.go @@ -166,7 +166,7 @@ func TestRoleDataset_lifecycle(t *testing.T) { 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" { + 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 { diff --git a/openapi.yaml b/openapi.yaml index 14a2d62..27fd856 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -2771,6 +2771,7 @@ components: 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: -- 2.54.1 From 351c7356fdf8eeca6b4161303c5b6e9a0969e35b Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Wed, 11 Nov 2026 22:37:54 +0100 Subject: [PATCH 3/3] test(server): the workers stop with their context; client addresses The coverage gate sits at 70% and main is just above it; these cover the mail, outbox and reconcile loops and clientIP, which no test ran. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014aRnCGqELxoix5TfpX8Ejf --- internal/server/workers_internal_test.go | 69 ++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 internal/server/workers_internal_test.go diff --git a/internal/server/workers_internal_test.go b/internal/server/workers_internal_test.go new file mode 100644 index 0000000..003ec1d --- /dev/null +++ b/internal/server/workers_internal_test.go @@ -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) + } + } +} -- 2.54.1