feat: role and authority dataset (R1 S0)
One Rollen- und Befugnisdatensatz per company (docgen#1 plan 13781 §3.2
no. 2, owner addendum 13791): functions, who holds them, deputies with
their basis, the deciding function per decision type, immediate
authority, standard releases, named editors and the contact path for
critical security events.
- internal/roles: the catalogue in code (version r1-2026-10-26.1), the
union of A1 §2.3 and A4 §4 = 21 functions, 14 customer decision types;
only the three releases carry an owner default (management), the rest
must be set by the company.
- Rules: a deputy is wirksam only with a documented basis, within its
validity and, where it covers management authority, with management's
authorization (B7 wording: what management records it has authorized);
another release body for R1-D02 updates only with the R1-D02 provision
(B8); management and document owners write, the OWNER sign-in role may
only record the first management holder; recorded_*/authorized_* are
stamped from the token, never from the body; no self-authorization.
- Routes: GET/PUT /v1/tenants/{id}/role-dataset, GET …/revisions/{rev},
GET …/resolve. Writes need the user's token; user tokens on these
routes form route group role-dataset.user, so the portal's sign-in
client needs no tenants grant.
- Migration 0024: role_datasets and role_dataset_revisions, versioned as
the company profile (expected_revision, 409 on conflict).
- Audit role_dataset.saved with revision and changed entry ids only.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014aRnCGqELxoix5TfpX8Ejf
This commit is contained in:
1 parent
9129e95538
commit
898fab93bb
20 files changed
+2426
-3
No files matched your search
@@ -83,7 +83,7 @@ jobs:
|
||||
# own test binary — and including it triggers a covdata-tool error
|
||||
# on packages with no _test.go files. -coverpkg makes the server's
|
||||
# exercise of store/* count toward coverage.
|
||||
run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/... ./internal/erpsetup/... ./internal/scopes/... ./internal/secretbox/...
|
||||
run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/... ./internal/erpsetup/... ./internal/scopes/... ./internal/secretbox/... ./internal/roles/...
|
||||
|
||||
- name: coverage gate
|
||||
run: |
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
// Package roles is the role and authority dataset of a company (R1 S0,
|
||||
// docgen#1 plan 13781 §3.2 no. 2, owner addendum 13791): functions, who holds
|
||||
// them, deputies with their basis, and which function decides which decision
|
||||
// type. The catalogue of functions and decision types lives here, in code and
|
||||
// versioned; the registry stores one dataset document per tenant and checks
|
||||
// it against the catalogue and the rules of B7 and B8 (dataset.go).
|
||||
package roles
|
||||
|
||||
// CatalogueVersion names this catalogue. A save names the version it was
|
||||
// made against; another version is refused, so the portal reloads.
|
||||
const CatalogueVersion = "r1-2026-10-26.1"
|
||||
|
||||
// Per is the scope an assignment of a function needs.
|
||||
type Per string
|
||||
|
||||
const (
|
||||
PerCompany Per = "company" // no scope
|
||||
PerDocument Per = "document" // an R1 document key (Documents)
|
||||
PerProduct Per = "product" // an opaque product id (not checked yet: product states are not built, N-3)
|
||||
PerArea Per = "area" // free text naming the area of a review
|
||||
)
|
||||
|
||||
// External says whether a person outside the company may hold a function.
|
||||
type External string
|
||||
|
||||
const (
|
||||
ExternalNo External = "no"
|
||||
ExternalAllowed External = "allowed"
|
||||
ExternalOnly External = "only"
|
||||
)
|
||||
|
||||
// Function is one entry of the catalogue. Labels are the owner's wording.
|
||||
type Function struct {
|
||||
Code string `json:"key"`
|
||||
Label string `json:"label"`
|
||||
// Sources: A1 (R1 frontend spec v4 §2.3) and/or A4 (document contract
|
||||
// R1-D01/R1-D02 §4, the seven functions of R1-D02 §18).
|
||||
Sources []string `json:"sources"`
|
||||
Per Per `json:"per"`
|
||||
Multiple bool `json:"multiple"`
|
||||
External External `json:"external"`
|
||||
// AnyMember: held by every customer person with an account; no
|
||||
// assignment is recorded (Änderungsinitiierung).
|
||||
AnyMember bool `json:"any_member,omitempty"`
|
||||
// NotApplicable: may be recorded as "nicht anwendbar" (R1-D02 §18 only
|
||||
// for product safety, tied to the module decision).
|
||||
NotApplicable bool `json:"not_applicable,omitempty"`
|
||||
// D02Row is the row of the function in R1-D02 §18 (1–7), 0 for none.
|
||||
D02Row int `json:"d02_row,omitempty"`
|
||||
}
|
||||
|
||||
// Management is the function B7 and B8 single out.
|
||||
const Management = "r1.geschaeftsleitung"
|
||||
|
||||
// DocumentOwner is the second function that may maintain the dataset (B7).
|
||||
const DocumentOwner = "r1.dokumentenverantwortung"
|
||||
|
||||
// Functions is the union of A1 §2.3 and A4 §4 (B14): the same name in both
|
||||
// lists is one entry, different names stay apart even where they sound alike
|
||||
// (Technischer Ansprechpartner vs. Technischer Produktverantwortlicher).
|
||||
var Functions = []Function{
|
||||
{Code: Management, Label: "Geschäftsleitung", Sources: []string{"A1", "A4"}, Per: PerCompany, Multiple: true, External: ExternalNo, D02Row: 1},
|
||||
{Code: "r1.produkt_cybersecurity", Label: "Produkt-Cybersecurity-Verantwortlicher", Sources: []string{"A1", "A4"}, Per: PerCompany, Multiple: true, External: ExternalNo, D02Row: 2},
|
||||
{Code: "r1.technischer_produktverantwortlicher", Label: "Technischer Produktverantwortlicher", Sources: []string{"A4"}, Per: PerCompany, Multiple: true, External: ExternalNo, D02Row: 3},
|
||||
{Code: "r1.externer_cybersecurity_dienstleister", Label: "Externer Cybersecurity-Dienstleister", Sources: []string{"A4"}, Per: PerCompany, Multiple: true, External: ExternalOnly, D02Row: 4},
|
||||
{Code: "r1.produktsicherheit", Label: "Produktsicherheitsverantwortlicher", Sources: []string{"A1", "A4"}, Per: PerCompany, Multiple: true, External: ExternalNo, NotApplicable: true, D02Row: 5},
|
||||
{Code: "r1.konformitaet", Label: "Konformitätsverantwortlicher / autorisierte Herstellerfunktion", Sources: []string{"A4"}, Per: PerCompany, Multiple: true, External: ExternalNo, D02Row: 6},
|
||||
{Code: "r1.meldeberechtigt", Label: "Regulatorisch Meldeberechtigter", Sources: []string{"A1", "A4"}, Per: PerCompany, Multiple: true, External: ExternalNo, D02Row: 7},
|
||||
{Code: "r1.technischer_ansprechpartner", Label: "Technischer Ansprechpartner", Sources: []string{"A1"}, Per: PerCompany, Multiple: true, External: ExternalAllowed},
|
||||
{Code: "r1.vorfallkontakt", Label: "Vorfallkontakt", Sources: []string{"A1"}, Per: PerCompany, Multiple: true, External: ExternalAllowed},
|
||||
{Code: DocumentOwner, Label: "Dokumentenverantwortlicher", Sources: []string{"A1"}, Per: PerDocument, Multiple: false, External: ExternalNo},
|
||||
{Code: "r1.freigabestelle", Label: "Freigabestelle", Sources: []string{"A1"}, Per: PerDocument, Multiple: true, External: ExternalNo},
|
||||
{Code: "r1.aenderungsinitiierung", Label: "Änderungsinitiierung", Sources: []string{"A1"}, Per: PerCompany, External: ExternalNo, AnyMember: true},
|
||||
{Code: "r1.produktverantwortung", Label: "Produktverantwortung", Sources: []string{"A1"}, Per: PerProduct, Multiple: true, External: ExternalNo},
|
||||
{Code: "r1.aenderungskoordination", Label: "Änderungskoordination", Sources: []string{"A1"}, Per: PerCompany, Multiple: true, External: ExternalNo},
|
||||
{Code: "r1.fachpruefung", Label: "Fachprüfung", Sources: []string{"A1"}, Per: PerArea, Multiple: true, External: ExternalAllowed},
|
||||
{Code: "r1.freigabe_produktaenderung", Label: "Freigabe von Produktänderungen", Sources: []string{"A1"}, Per: PerCompany, Multiple: true, External: ExternalNo},
|
||||
{Code: "r1.dokumentenlenkung", Label: "Dokumentenlenkung", Sources: []string{"A1"}, Per: PerCompany, Multiple: true, External: ExternalNo},
|
||||
{Code: "r1.massnahmenausfuehrer", Label: "Maßnahmenausführer", Sources: []string{"A1"}, Per: PerCompany, Multiple: true, External: ExternalAllowed},
|
||||
{Code: "r1.prueffunktion", Label: "Prüffunktion", Sources: []string{"A1"}, Per: PerCompany, Multiple: true, External: ExternalAllowed},
|
||||
{Code: "r1.abschlussverantwortung", Label: "Abschlussverantwortlicher", Sources: []string{"A1"}, Per: PerCompany, Multiple: true, External: ExternalNo},
|
||||
{Code: "r1.fachlich_verantwortliche_stelle", Label: "Fachlich verantwortliche Stelle", Sources: []string{"A1"}, Per: PerCompany, Multiple: true, External: ExternalNo},
|
||||
}
|
||||
|
||||
// DecisionType is a customer decision (BM-4: Breakpilot's own steps are
|
||||
// execution, not decisions, and do not appear here). Default is the deciding
|
||||
// function where the owner has fixed one; "" means the company must set it,
|
||||
// and until then resolve answers rolle_offen (BM-5, AM-3).
|
||||
type DecisionType struct {
|
||||
Code string `json:"key"`
|
||||
Label string `json:"label"`
|
||||
Default string `json:"default,omitempty"`
|
||||
}
|
||||
|
||||
// ReleaseD02Update is the decision type of B8.
|
||||
const ReleaseD02Update = "r1.release_d02_update"
|
||||
|
||||
// DecisionTypes: only the three releases carry a default (A2 §1, §5; B8).
|
||||
// The defaults the process data suggests for the others need the owner's
|
||||
// confirmation (S0 spec Q9) and are not preset, so the platform preselects
|
||||
// no customer authority (13791 Nr. 5).
|
||||
var DecisionTypes = []DecisionType{
|
||||
{Code: "r1.release_d01", Label: "Freigabe R1-D01", Default: Management},
|
||||
{Code: "r1.release_d02", Label: "Freigabe R1-D02", Default: Management},
|
||||
{Code: ReleaseD02Update, Label: "Freigabe einer Aktualisierung der R1-D02", Default: Management},
|
||||
{Code: "r1.new_version_needed", Label: "Neue Fassung nötig"},
|
||||
{Code: "r1.measure_close", Label: "Maßnahme abschließen"},
|
||||
{Code: "r1.measure_not_applicable", Label: "Nichtanwendbarkeit einer Maßnahme"},
|
||||
{Code: "r1.product_responsibility", Label: "Produktverantwortung eindeutig"},
|
||||
{Code: "r1.simplified_procedure", Label: "Vereinfachtes Verfahren"},
|
||||
{Code: "r1.release_product_change", Label: "Freigabe einer Produktänderung"},
|
||||
{Code: "r1.standard_release_applies", Label: "Standardfreigabe deckt den Vorgang"},
|
||||
{Code: "r1.escalation", Label: "Eskalationskriterium erfüllt"},
|
||||
{Code: "r1.procedure_choice", Label: "Wahl des Verfahrens"},
|
||||
{Code: "r1.event_takeover", Label: "Übernahme eines Sicherheitsereignisses"},
|
||||
{Code: "r1.acceptance", Label: "Abnahme"},
|
||||
}
|
||||
|
||||
// Documents are the R1 document keys a document-scoped function refers to.
|
||||
var Documents = []string{"r1_d01", "r1_d02"}
|
||||
|
||||
var (
|
||||
functionIndex = map[string]Function{}
|
||||
decisionTypeIndex = map[string]DecisionType{}
|
||||
)
|
||||
|
||||
func init() {
|
||||
for _, f := range Functions {
|
||||
functionIndex[f.Code] = f
|
||||
}
|
||||
for _, d := range DecisionTypes {
|
||||
decisionTypeIndex[d.Code] = d
|
||||
}
|
||||
}
|
||||
|
||||
// FunctionByKey looks a function up in the catalogue.
|
||||
func FunctionByKey(key string) (Function, bool) {
|
||||
f, ok := functionIndex[key]
|
||||
return f, ok
|
||||
}
|
||||
|
||||
// DecisionTypeByKey looks a decision type up in the catalogue.
|
||||
func DecisionTypeByKey(key string) (DecisionType, bool) {
|
||||
d, ok := decisionTypeIndex[key]
|
||||
return d, ok
|
||||
}
|
||||
|
||||
// Catalogue is the catalogue as the GET answer carries it, so the portal
|
||||
// needs no copy of its own.
|
||||
type Catalogue struct {
|
||||
Version string `json:"version"`
|
||||
Functions []Function `json:"functions"`
|
||||
DecisionTypes []DecisionType `json:"decision_types"`
|
||||
Documents []string `json:"documents"`
|
||||
}
|
||||
|
||||
// CurrentCatalogue returns the catalogue of this build.
|
||||
func CurrentCatalogue() Catalogue {
|
||||
return Catalogue{Version: CatalogueVersion, Functions: Functions, DecisionTypes: DecisionTypes, Documents: Documents}
|
||||
}
|
||||
@@ -0,0 +1,929 @@
|
||||
package roles
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Dataset is a company's role and authority dataset, one JSON document. Its
|
||||
// sections follow the components of A1 §2.3: Besetzung, Vertretung with
|
||||
// Vertretungsbefugnis, Befugnis je Entscheidungsart, Sofortbefugnis,
|
||||
// Standardfreigaben, Bearbeitungsbefugnis, Kontaktweg.
|
||||
type Dataset struct {
|
||||
Assignments []Assignment `json:"assignments"`
|
||||
Deputies []Deputy `json:"deputies"`
|
||||
Authority []Authority `json:"authority"`
|
||||
ImmediateAuthority []ImmediateAuthority `json:"immediate_authority"`
|
||||
StandardReleases []StandardRelease `json:"standard_releases"`
|
||||
Editors []Editors `json:"editors"`
|
||||
CriticalContact []Contact `json:"critical_contact"`
|
||||
}
|
||||
|
||||
// Holder kinds.
|
||||
const (
|
||||
HolderMember = "member" // a person with an account: Keycloak sub only
|
||||
HolderExternal = "external" // a person or organisation outside the company
|
||||
HolderNotApplicable = "not_applicable" // "nicht anwendbar" (product safety only)
|
||||
)
|
||||
|
||||
// Holder is who holds a function. Internal persons are kept by Keycloak sub
|
||||
// only; the portal shows the name from the member list.
|
||||
type Holder struct {
|
||||
Kind string `json:"kind"`
|
||||
Sub string `json:"sub,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Organisation string `json:"organisation,omitempty"`
|
||||
Contact string `json:"contact,omitempty"`
|
||||
ModuleDecisionRef string `json:"module_decision_ref,omitempty"`
|
||||
}
|
||||
|
||||
// Scope narrows a function to a document, a product or an area (Function.Per).
|
||||
type Scope struct {
|
||||
Document string `json:"document,omitempty"`
|
||||
Product string `json:"product,omitempty"`
|
||||
Area string `json:"area,omitempty"`
|
||||
}
|
||||
|
||||
// Stamps are set by the registry from the writer's token, never taken from
|
||||
// the request (S0 spec §5).
|
||||
type Stamps struct {
|
||||
RecordedBy string `json:"recorded_by,omitempty"`
|
||||
RecordedAt *time.Time `json:"recorded_at,omitempty"`
|
||||
}
|
||||
|
||||
// Authorization stamps: who of management authorized an entry (B7).
|
||||
type Authorization struct {
|
||||
AuthorizedBy string `json:"authorized_by,omitempty"`
|
||||
AuthorizedAt *time.Time `json:"authorized_at,omitempty"`
|
||||
}
|
||||
|
||||
type Assignment struct {
|
||||
ID string `json:"id"`
|
||||
Function string `json:"function"`
|
||||
Holder Holder `json:"holder"`
|
||||
Scope *Scope `json:"scope"`
|
||||
Stamps
|
||||
}
|
||||
|
||||
// Basis is the binding basis of a deputyship (B7: effective only when
|
||||
// documented).
|
||||
type Basis struct {
|
||||
Text string `json:"text"`
|
||||
StoreDocumentID string `json:"store_document_id,omitempty"`
|
||||
}
|
||||
|
||||
type Deputy struct {
|
||||
ID string `json:"id"`
|
||||
Function string `json:"function"`
|
||||
Holder Holder `json:"holder"`
|
||||
Scope *Scope `json:"scope"`
|
||||
DecisionTypes []string `json:"decision_types"`
|
||||
Basis Basis `json:"basis"`
|
||||
ValidFrom string `json:"valid_from,omitempty"` // YYYY-MM-DD
|
||||
ValidUntil string `json:"valid_until,omitempty"` // YYYY-MM-DD
|
||||
MayEdit bool `json:"may_edit"`
|
||||
Stamps
|
||||
Authorization
|
||||
}
|
||||
|
||||
type Authority struct {
|
||||
DecisionType string `json:"decision_type"`
|
||||
Function string `json:"function"`
|
||||
// D02Reference is the provision in the current R1-D02 version that names
|
||||
// another release body (B8); only for ReleaseD02Update.
|
||||
D02Reference string `json:"d02_reference,omitempty"`
|
||||
}
|
||||
|
||||
type ImmediateAuthority struct {
|
||||
DecisionType string `json:"decision_type"`
|
||||
Function string `json:"function"`
|
||||
Basis Basis `json:"basis"`
|
||||
}
|
||||
|
||||
type StandardRelease struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
DecisionType string `json:"decision_type"`
|
||||
ScopeText string `json:"scope_text"`
|
||||
Stamps
|
||||
Authorization
|
||||
}
|
||||
|
||||
type Editors struct {
|
||||
Document string `json:"document"`
|
||||
Holders []Holder `json:"holders"`
|
||||
}
|
||||
|
||||
type Contact struct {
|
||||
Function string `json:"function"`
|
||||
Order int `json:"order"`
|
||||
Channel string `json:"channel"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// Error is a refusal with the HTTP status, a stable code and, for invalid
|
||||
// documents, the path of the faulty entry.
|
||||
type Error struct {
|
||||
Status int `json:"-"`
|
||||
Code string `json:"error"`
|
||||
Message string `json:"message"`
|
||||
Path string `json:"path,omitempty"`
|
||||
}
|
||||
|
||||
func (e *Error) Error() string { return e.Code + ": " + e.Message }
|
||||
|
||||
func invalid(path, format string, a ...any) *Error {
|
||||
return &Error{Status: http.StatusBadRequest, Code: "invalid_role_dataset", Message: fmt.Sprintf(format, a...), Path: path}
|
||||
}
|
||||
|
||||
const (
|
||||
maxEntries = 500
|
||||
maxText = 200
|
||||
maxBasis = 2000
|
||||
)
|
||||
|
||||
var (
|
||||
idPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,40}$`)
|
||||
channels = []string{"phone", "email", "sms", "messenger", "fallback", "other"}
|
||||
)
|
||||
|
||||
// Decode reads a dataset document strictly: unknown keys are refused at any
|
||||
// level.
|
||||
func Decode(raw []byte) (*Dataset, *Error) {
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
var ds Dataset
|
||||
if err := dec.Decode(&ds); err != nil {
|
||||
return nil, invalid("", "data: %v", err)
|
||||
}
|
||||
if dec.More() {
|
||||
return nil, invalid("", "data: one JSON object expected")
|
||||
}
|
||||
return &ds, nil
|
||||
}
|
||||
|
||||
// Validate checks the document against the catalogue (S0 spec §6.5, §6.2).
|
||||
func Validate(ds *Dataset) *Error {
|
||||
sections := map[string]int{
|
||||
"assignments": len(ds.Assignments), "deputies": len(ds.Deputies), "authority": len(ds.Authority),
|
||||
"immediate_authority": len(ds.ImmediateAuthority), "standard_releases": len(ds.StandardReleases),
|
||||
"editors": len(ds.Editors), "critical_contact": len(ds.CriticalContact),
|
||||
}
|
||||
for name, n := range sections {
|
||||
if n > maxEntries {
|
||||
return invalid(name, "at most %d entries", maxEntries)
|
||||
}
|
||||
}
|
||||
ids := map[string]string{}
|
||||
useID := func(path, id string) *Error {
|
||||
if !idPattern.MatchString(id) {
|
||||
return invalid(path+".id", "id must be 1-40 letters, digits, - or _")
|
||||
}
|
||||
if prev, dup := ids[id]; dup {
|
||||
return invalid(path+".id", "id %q is also used at %s", id, prev)
|
||||
}
|
||||
ids[id] = path
|
||||
return nil
|
||||
}
|
||||
|
||||
single := map[string]bool{} // function+scope with a holder, for Multiple=false
|
||||
for i, a := range ds.Assignments {
|
||||
path := fmt.Sprintf("assignments[%d]", i)
|
||||
if err := useID(path, a.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
f, ok := FunctionByKey(a.Function)
|
||||
if !ok {
|
||||
return invalid(path+".function", "unknown function %q", a.Function)
|
||||
}
|
||||
if f.AnyMember {
|
||||
return invalid(path+".function", "%s is held by every customer person; it has no assignments", f.Code)
|
||||
}
|
||||
if err := checkScope(path, f, a.Scope); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkHolder(path+".holder", f, a.Holder, true); err != nil {
|
||||
return err
|
||||
}
|
||||
if !f.Multiple {
|
||||
k := a.Function + "|" + scopeKey(a.Scope)
|
||||
if single[k] {
|
||||
return invalid(path, "%s has one holder only", f.Code)
|
||||
}
|
||||
single[k] = true
|
||||
}
|
||||
}
|
||||
for i, d := range ds.Deputies {
|
||||
path := fmt.Sprintf("deputies[%d]", i)
|
||||
if err := useID(path, d.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
f, ok := FunctionByKey(d.Function)
|
||||
if !ok {
|
||||
return invalid(path+".function", "unknown function %q", d.Function)
|
||||
}
|
||||
if f.AnyMember {
|
||||
return invalid(path+".function", "%s has no deputies", f.Code)
|
||||
}
|
||||
if err := checkScope(path, f, d.Scope); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkHolder(path+".holder", f, d.Holder, false); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(d.DecisionTypes) == 0 {
|
||||
return invalid(path+".decision_types", "a deputyship names the decision types it covers")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for j, k := range d.DecisionTypes {
|
||||
if _, ok := DecisionTypeByKey(k); !ok || seen[k] {
|
||||
return invalid(fmt.Sprintf("%s.decision_types[%d]", path, j), "unknown or repeated decision type %q", k)
|
||||
}
|
||||
seen[k] = true
|
||||
}
|
||||
if err := checkBasis(path+".basis", d.Basis, false); err != nil {
|
||||
return err
|
||||
}
|
||||
from, err := optDate(path+".valid_from", d.ValidFrom)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
until, err := optDate(path+".valid_until", d.ValidUntil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !from.IsZero() && !until.IsZero() && until.Before(from) {
|
||||
return invalid(path+".valid_until", "valid_until is before valid_from")
|
||||
}
|
||||
}
|
||||
authority := map[string]bool{}
|
||||
for i, a := range ds.Authority {
|
||||
path := fmt.Sprintf("authority[%d]", i)
|
||||
if _, ok := DecisionTypeByKey(a.DecisionType); !ok {
|
||||
return invalid(path+".decision_type", "unknown decision type %q", a.DecisionType)
|
||||
}
|
||||
if authority[a.DecisionType] {
|
||||
return invalid(path+".decision_type", "%s is set twice", a.DecisionType)
|
||||
}
|
||||
authority[a.DecisionType] = true
|
||||
if _, ok := FunctionByKey(a.Function); !ok {
|
||||
return invalid(path+".function", "unknown function %q", a.Function)
|
||||
}
|
||||
if len(a.D02Reference) > maxText {
|
||||
return invalid(path+".d02_reference", "at most %d characters", maxText)
|
||||
}
|
||||
if a.DecisionType != ReleaseD02Update && a.D02Reference != "" {
|
||||
return invalid(path+".d02_reference", "only the release of an R1-D02 update takes a d02_reference")
|
||||
}
|
||||
// B8: another release body only where R1-D02 names it.
|
||||
if a.DecisionType == ReleaseD02Update && a.Function != Management && strings.TrimSpace(a.D02Reference) == "" {
|
||||
return &Error{Status: http.StatusBadRequest, Code: "d02_reference_required", Path: path + ".d02_reference",
|
||||
Message: "another release body than management needs the provision of R1-D02 that names it (B8)"}
|
||||
}
|
||||
}
|
||||
for i, a := range ds.ImmediateAuthority {
|
||||
path := fmt.Sprintf("immediate_authority[%d]", i)
|
||||
if _, ok := DecisionTypeByKey(a.DecisionType); !ok {
|
||||
return invalid(path+".decision_type", "unknown decision type %q", a.DecisionType)
|
||||
}
|
||||
if _, ok := FunctionByKey(a.Function); !ok {
|
||||
return invalid(path+".function", "unknown function %q", a.Function)
|
||||
}
|
||||
if err := checkBasis(path+".basis", a.Basis, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for i, s := range ds.StandardReleases {
|
||||
path := fmt.Sprintf("standard_releases[%d]", i)
|
||||
if err := useID(path, s.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := text(path+".title", s.Title, true, maxText); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, ok := DecisionTypeByKey(s.DecisionType); !ok {
|
||||
return invalid(path+".decision_type", "unknown decision type %q", s.DecisionType)
|
||||
}
|
||||
if err := text(path+".scope_text", s.ScopeText, false, maxBasis); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
docs := map[string]bool{}
|
||||
for i, e := range ds.Editors {
|
||||
path := fmt.Sprintf("editors[%d]", i)
|
||||
if !slices.Contains(Documents, e.Document) || docs[e.Document] {
|
||||
return invalid(path+".document", "unknown or repeated document %q", e.Document)
|
||||
}
|
||||
docs[e.Document] = true
|
||||
if len(e.Holders) > 50 {
|
||||
return invalid(path+".holders", "at most 50 editors")
|
||||
}
|
||||
for j, h := range e.Holders {
|
||||
if h.Kind != HolderMember || !validSub(h.Sub) || h.Name != "" || h.Organisation != "" || h.Contact != "" || h.ModuleDecisionRef != "" {
|
||||
return invalid(fmt.Sprintf("%s.holders[%d]", path, j), "editors are persons with an account (kind member, sub)")
|
||||
}
|
||||
}
|
||||
}
|
||||
for i, c := range ds.CriticalContact {
|
||||
path := fmt.Sprintf("critical_contact[%d]", i)
|
||||
if _, ok := FunctionByKey(c.Function); !ok {
|
||||
return invalid(path+".function", "unknown function %q", c.Function)
|
||||
}
|
||||
if c.Order < 1 || c.Order > 10 {
|
||||
return invalid(path+".order", "order is 1-10")
|
||||
}
|
||||
if !slices.Contains(channels, c.Channel) {
|
||||
return invalid(path+".channel", "channel is one of %v", channels)
|
||||
}
|
||||
if err := text(path+".value", c.Value, true, maxText); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkScope(path string, f Function, s *Scope) *Error {
|
||||
switch f.Per {
|
||||
case PerCompany:
|
||||
if s != nil && *s != (Scope{}) {
|
||||
return invalid(path+".scope", "%s is per company and takes no scope", f.Code)
|
||||
}
|
||||
return nil
|
||||
case PerDocument:
|
||||
if s == nil || !slices.Contains(Documents, s.Document) || s.Product != "" || s.Area != "" {
|
||||
return invalid(path+".scope", "%s is per document: scope.document is one of %v", f.Code, Documents)
|
||||
}
|
||||
case PerProduct:
|
||||
if s == nil || s.Document != "" || s.Area != "" {
|
||||
return invalid(path+".scope", "%s is per product: scope.product is required", f.Code)
|
||||
}
|
||||
return text(path+".scope.product", s.Product, true, 80)
|
||||
case PerArea:
|
||||
if s == nil || s.Document != "" || s.Product != "" {
|
||||
return invalid(path+".scope", "%s is per area: scope.area is required", f.Code)
|
||||
}
|
||||
return text(path+".scope.area", s.Area, true, 80)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkHolder(path string, f Function, h Holder, assignment bool) *Error {
|
||||
switch h.Kind {
|
||||
case HolderMember:
|
||||
if f.External == ExternalOnly {
|
||||
return invalid(path+".kind", "%s is held by an external organisation", f.Code)
|
||||
}
|
||||
if !validSub(h.Sub) || h.Name != "" || h.Organisation != "" || h.Contact != "" || h.ModuleDecisionRef != "" {
|
||||
return invalid(path, "a member is named by sub only")
|
||||
}
|
||||
case HolderExternal:
|
||||
if f.External == ExternalNo {
|
||||
return invalid(path+".kind", "%s is held inside the company", f.Code)
|
||||
}
|
||||
if h.Sub != "" || h.ModuleDecisionRef != "" {
|
||||
return invalid(path, "an external holder has name, organisation and contact")
|
||||
}
|
||||
if err := text(path+".name", h.Name, true, maxText); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := text(path+".organisation", h.Organisation, false, maxText); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := text(path+".contact", h.Contact, false, maxText); err != nil {
|
||||
return err
|
||||
}
|
||||
case HolderNotApplicable:
|
||||
if !assignment || !f.NotApplicable {
|
||||
return invalid(path+".kind", "only %s may be recorded as not applicable", "r1.produktsicherheit")
|
||||
}
|
||||
if h.Sub != "" || h.Name != "" || h.Organisation != "" || h.Contact != "" {
|
||||
return invalid(path, "not applicable names no person")
|
||||
}
|
||||
return text(path+".module_decision_ref", h.ModuleDecisionRef, false, maxText)
|
||||
default:
|
||||
return invalid(path+".kind", "kind is member, external or not_applicable")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkBasis(path string, b Basis, required bool) *Error {
|
||||
if err := text(path+".text", b.Text, required, maxBasis); err != nil {
|
||||
return err
|
||||
}
|
||||
return text(path+".store_document_id", b.StoreDocumentID, false, 64)
|
||||
}
|
||||
|
||||
func text(path, s string, required bool, max int) *Error {
|
||||
if required && strings.TrimSpace(s) == "" {
|
||||
return invalid(path, "required")
|
||||
}
|
||||
if len([]rune(s)) > max {
|
||||
return invalid(path, "at most %d characters", max)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validSub(s string) bool { return strings.TrimSpace(s) != "" && len(s) <= 64 }
|
||||
|
||||
func optDate(path, s string) (time.Time, *Error) {
|
||||
if s == "" {
|
||||
return time.Time{}, nil
|
||||
}
|
||||
t, err := time.Parse(time.DateOnly, s)
|
||||
if err != nil {
|
||||
return time.Time{}, invalid(path, "a date YYYY-MM-DD")
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func scopeKey(s *Scope) string {
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
return s.Document + "|" + s.Product + "|" + s.Area
|
||||
}
|
||||
|
||||
// Holds reports whether the person sub holds the function (any scope).
|
||||
func (ds *Dataset) Holds(sub, function string) bool {
|
||||
if ds == nil || sub == "" {
|
||||
return false
|
||||
}
|
||||
for _, a := range ds.Assignments {
|
||||
if a.Function == function && a.Holder.Kind == HolderMember && a.Holder.Sub == sub {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (ds *Dataset) hasManagementHolder() bool {
|
||||
if ds == nil {
|
||||
return false
|
||||
}
|
||||
for _, a := range ds.Assignments {
|
||||
if a.Function == Management && a.Holder.Kind == HolderMember {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// DecidingFunction is the function that decides dt for this company: the
|
||||
// company's own entry, else the catalogue default, else "" (not set).
|
||||
func (ds *Dataset) DecidingFunction(dt string) (function, source string) {
|
||||
if ds != nil {
|
||||
for _, a := range ds.Authority {
|
||||
if a.DecisionType == dt {
|
||||
return a.Function, "company"
|
||||
}
|
||||
}
|
||||
}
|
||||
if d, ok := DecisionTypeByKey(dt); ok && d.Default != "" {
|
||||
return d.Default, "default"
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
// coversManagement: the deputy stands in for management authority, as the
|
||||
// function itself or through a decision type management decides.
|
||||
func (ds *Dataset) coversManagement(d Deputy) bool {
|
||||
if d.Function == Management {
|
||||
return true
|
||||
}
|
||||
for _, dt := range d.DecisionTypes {
|
||||
if f, _ := ds.DecidingFunction(dt); f == Management {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Writer is the person saving, from the user token only.
|
||||
type Writer struct {
|
||||
Sub string
|
||||
OrgRoles []string
|
||||
}
|
||||
|
||||
// OwnerRole is the sign-in role that may make the first entry (S0 spec §6.3,
|
||||
// owner question Q3). It is the only place a sign-in role counts here.
|
||||
const OwnerRole = "OWNER"
|
||||
|
||||
// Prepare checks a save against the current dataset and returns the dataset
|
||||
// to store, with the registry's stamps (S0 spec §5, §6). current is nil when
|
||||
// the company has none yet. authorize lists the ids of deputies and standard
|
||||
// releases the writer authorizes with this save.
|
||||
func Prepare(current, incoming *Dataset, authorize []string, w Writer, now time.Time) (*Dataset, *Error) {
|
||||
if err := Validate(incoming); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch {
|
||||
case current.Holds(w.Sub, Management) || current.Holds(w.Sub, DocumentOwner):
|
||||
// B7: management and document owners maintain the dataset.
|
||||
case !current.hasManagementHolder() && slices.Contains(w.OrgRoles, OwnerRole):
|
||||
// First entry: only management assignments, nothing else.
|
||||
if len(authorize) > 0 || !onlyAddsManagement(current, incoming) {
|
||||
return nil, &Error{Status: http.StatusForbidden, Code: "bootstrap_only",
|
||||
Message: "until management is recorded, the OWNER sign-in role may only record management"}
|
||||
}
|
||||
default:
|
||||
return nil, &Error{Status: http.StatusForbidden, Code: "not_permitted",
|
||||
Message: "the dataset is maintained by management and document owners (B7)"}
|
||||
}
|
||||
|
||||
out := *incoming
|
||||
at := now.UTC()
|
||||
var prev Dataset
|
||||
if current != nil {
|
||||
prev = *current
|
||||
}
|
||||
writerIsManagement := current.Holds(w.Sub, Management)
|
||||
|
||||
out.Assignments = slices.Clone(incoming.Assignments)
|
||||
for i := range out.Assignments {
|
||||
a := &out.Assignments[i]
|
||||
old, ok := findAssignment(prev.Assignments, a.ID)
|
||||
if ok && sameAssignment(old, *a) {
|
||||
a.Stamps = old.Stamps
|
||||
} else {
|
||||
a.Stamps = Stamps{RecordedBy: w.Sub, RecordedAt: &at}
|
||||
}
|
||||
}
|
||||
out.Deputies = slices.Clone(incoming.Deputies)
|
||||
for i := range out.Deputies {
|
||||
d := &out.Deputies[i]
|
||||
old, ok := findDeputy(prev.Deputies, d.ID)
|
||||
if ok && sameDeputy(old, *d) {
|
||||
d.Stamps, d.Authorization = old.Stamps, old.Authorization
|
||||
continue
|
||||
}
|
||||
// New or changed: recorded now, any earlier authorization is gone.
|
||||
d.Stamps = Stamps{RecordedBy: w.Sub, RecordedAt: &at}
|
||||
d.Authorization = Authorization{}
|
||||
// B7: what management records, management has authorized.
|
||||
if writerIsManagement && d.Holder.Sub != w.Sub && out.coversManagement(*d) {
|
||||
d.Authorization = Authorization{AuthorizedBy: w.Sub, AuthorizedAt: &at}
|
||||
}
|
||||
}
|
||||
out.StandardReleases = slices.Clone(incoming.StandardReleases)
|
||||
for i := range out.StandardReleases {
|
||||
s := &out.StandardReleases[i]
|
||||
old, ok := findStandardRelease(prev.StandardReleases, s.ID)
|
||||
if ok && sameStandardRelease(old, *s) {
|
||||
s.Stamps, s.Authorization = old.Stamps, old.Authorization
|
||||
continue
|
||||
}
|
||||
s.Stamps = Stamps{RecordedBy: w.Sub, RecordedAt: &at}
|
||||
s.Authorization = Authorization{}
|
||||
if writerIsManagement {
|
||||
s.Authorization = Authorization{AuthorizedBy: w.Sub, AuthorizedAt: &at}
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range authorize {
|
||||
if !writerIsManagement {
|
||||
return nil, &Error{Status: http.StatusForbidden, Code: "not_authorizer",
|
||||
Message: "only a holder of management authorizes (B7)"}
|
||||
}
|
||||
found := false
|
||||
for i := range out.Deputies {
|
||||
if d := &out.Deputies[i]; d.ID == id {
|
||||
if d.Holder.Kind == HolderMember && d.Holder.Sub == w.Sub {
|
||||
return nil, &Error{Status: http.StatusForbidden, Code: "self_authorization",
|
||||
Message: "nobody authorizes their own deputyship"}
|
||||
}
|
||||
d.Authorization = Authorization{AuthorizedBy: w.Sub, AuthorizedAt: &at}
|
||||
found = true
|
||||
}
|
||||
}
|
||||
for i := range out.StandardReleases {
|
||||
if s := &out.StandardReleases[i]; s.ID == id {
|
||||
s.Authorization = Authorization{AuthorizedBy: w.Sub, AuthorizedAt: &at}
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil, invalid("authorize", "no deputy or standard release with id %q", id)
|
||||
}
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
// onlyAddsManagement: incoming equals current apart from added management
|
||||
// assignments.
|
||||
func onlyAddsManagement(current, incoming *Dataset) bool {
|
||||
var cur Dataset
|
||||
if current != nil {
|
||||
cur = *current
|
||||
}
|
||||
rest := *incoming
|
||||
rest.Assignments = nil
|
||||
for _, a := range incoming.Assignments {
|
||||
if old, ok := findAssignment(cur.Assignments, a.ID); ok && sameAssignment(old, a) {
|
||||
rest.Assignments = append(rest.Assignments, old)
|
||||
continue
|
||||
}
|
||||
if _, existed := findAssignment(cur.Assignments, a.ID); existed {
|
||||
return false // a changed entry is not an addition
|
||||
}
|
||||
if a.Function != Management {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return Canonical(withoutStamps(&rest)) == Canonical(withoutStamps(&cur))
|
||||
}
|
||||
|
||||
// withoutStamps copies a dataset without the registry's stamps, so a client
|
||||
// that leaves them out compares equal.
|
||||
func withoutStamps(ds *Dataset) *Dataset {
|
||||
c := *ds
|
||||
c.Assignments = slices.Clone(ds.Assignments)
|
||||
for i := range c.Assignments {
|
||||
c.Assignments[i].Stamps = Stamps{}
|
||||
}
|
||||
c.Deputies = slices.Clone(ds.Deputies)
|
||||
for i := range c.Deputies {
|
||||
c.Deputies[i].Stamps, c.Deputies[i].Authorization = Stamps{}, Authorization{}
|
||||
}
|
||||
c.StandardReleases = slices.Clone(ds.StandardReleases)
|
||||
for i := range c.StandardReleases {
|
||||
c.StandardReleases[i].Stamps, c.StandardReleases[i].Authorization = Stamps{}, Authorization{}
|
||||
}
|
||||
return &c
|
||||
}
|
||||
|
||||
func findAssignment(list []Assignment, id string) (Assignment, bool) {
|
||||
for _, a := range list {
|
||||
if a.ID == id {
|
||||
return a, true
|
||||
}
|
||||
}
|
||||
return Assignment{}, false
|
||||
}
|
||||
|
||||
func findDeputy(list []Deputy, id string) (Deputy, bool) {
|
||||
for _, d := range list {
|
||||
if d.ID == id {
|
||||
return d, true
|
||||
}
|
||||
}
|
||||
return Deputy{}, false
|
||||
}
|
||||
|
||||
func findStandardRelease(list []StandardRelease, id string) (StandardRelease, bool) {
|
||||
for _, s := range list {
|
||||
if s.ID == id {
|
||||
return s, true
|
||||
}
|
||||
}
|
||||
return StandardRelease{}, false
|
||||
}
|
||||
|
||||
func sameAssignment(a, b Assignment) bool {
|
||||
a.Stamps, b.Stamps = Stamps{}, Stamps{}
|
||||
return jsonEqual(a, b)
|
||||
}
|
||||
|
||||
func sameDeputy(a, b Deputy) bool {
|
||||
a.Stamps, b.Stamps = Stamps{}, Stamps{}
|
||||
a.Authorization, b.Authorization = Authorization{}, Authorization{}
|
||||
return jsonEqual(a, b)
|
||||
}
|
||||
|
||||
func sameStandardRelease(a, b StandardRelease) bool {
|
||||
a.Stamps, b.Stamps = Stamps{}, Stamps{}
|
||||
a.Authorization, b.Authorization = Authorization{}, Authorization{}
|
||||
return jsonEqual(a, b)
|
||||
}
|
||||
|
||||
func jsonEqual(a, b any) bool {
|
||||
x, _ := json.Marshal(a)
|
||||
y, _ := json.Marshal(b)
|
||||
return bytes.Equal(x, y)
|
||||
}
|
||||
|
||||
// Canonical is the stored form of a dataset: nil sections as empty lists.
|
||||
func Canonical(ds *Dataset) string {
|
||||
c := *ds
|
||||
if c.Assignments == nil {
|
||||
c.Assignments = []Assignment{}
|
||||
}
|
||||
if c.Deputies == nil {
|
||||
c.Deputies = []Deputy{}
|
||||
}
|
||||
if c.Authority == nil {
|
||||
c.Authority = []Authority{}
|
||||
}
|
||||
if c.ImmediateAuthority == nil {
|
||||
c.ImmediateAuthority = []ImmediateAuthority{}
|
||||
}
|
||||
if c.StandardReleases == nil {
|
||||
c.StandardReleases = []StandardRelease{}
|
||||
}
|
||||
if c.Editors == nil {
|
||||
c.Editors = []Editors{}
|
||||
}
|
||||
if c.CriticalContact == nil {
|
||||
c.CriticalContact = []Contact{}
|
||||
}
|
||||
b, _ := json.Marshal(c)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// Deputy states (B7).
|
||||
const (
|
||||
StateEffective = "wirksam"
|
||||
StateRecorded = "hinterlegt"
|
||||
)
|
||||
|
||||
// DeputyState is the derived state of one deputyship, computed on every
|
||||
// read and never stored.
|
||||
type DeputyState struct {
|
||||
ID string `json:"id"`
|
||||
State string `json:"state"`
|
||||
Reasons []string `json:"reasons,omitempty"`
|
||||
}
|
||||
|
||||
// berlin is the company's calendar for validity dates.
|
||||
var berlin = func() *time.Location {
|
||||
if l, err := time.LoadLocation("Europe/Berlin"); err == nil {
|
||||
return l
|
||||
}
|
||||
return time.FixedZone("CET", 3600)
|
||||
}()
|
||||
|
||||
// State derives whether a deputyship is effective (S0 spec §6.1): a
|
||||
// documented basis, today within its validity, and, where it covers
|
||||
// management authority, management's authorization.
|
||||
func (ds *Dataset) State(d Deputy, now time.Time) DeputyState {
|
||||
st := DeputyState{ID: d.ID}
|
||||
if strings.TrimSpace(d.Basis.Text) == "" {
|
||||
st.Reasons = append(st.Reasons, "basis_missing")
|
||||
}
|
||||
today := now.In(berlin).Format(time.DateOnly)
|
||||
if d.ValidFrom != "" && today < d.ValidFrom {
|
||||
st.Reasons = append(st.Reasons, "not_yet_valid")
|
||||
}
|
||||
if d.ValidUntil != "" && today > d.ValidUntil {
|
||||
st.Reasons = append(st.Reasons, "expired")
|
||||
}
|
||||
if ds.coversManagement(d) && d.AuthorizedBy == "" {
|
||||
st.Reasons = append(st.Reasons, "authorization_missing")
|
||||
}
|
||||
st.State = StateEffective
|
||||
if len(st.Reasons) > 0 {
|
||||
st.State = StateRecorded
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// States derives the state of every deputyship.
|
||||
func (ds *Dataset) States(now time.Time) []DeputyState {
|
||||
out := make([]DeputyState, 0, len(ds.Deputies))
|
||||
for _, d := range ds.Deputies {
|
||||
out = append(out, ds.State(d, now))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Resolution statuses.
|
||||
const (
|
||||
StatusFilled = "besetzt"
|
||||
StatusOpen = "rolle_offen"
|
||||
StatusNotApplicable = "nicht_anwendbar"
|
||||
)
|
||||
|
||||
// Resolution answers "who may decide this now" (S0 spec §6.6).
|
||||
type Resolution struct {
|
||||
DecisionType string `json:"decision_type"`
|
||||
Function string `json:"function,omitempty"`
|
||||
Source string `json:"source,omitempty"` // company | default
|
||||
AnyMember bool `json:"any_member,omitempty"`
|
||||
Holders []Holder `json:"holders"`
|
||||
Deputies []ResolutionDeputy `json:"deputies"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type ResolutionDeputy struct {
|
||||
ID string `json:"id"`
|
||||
Holder Holder `json:"holder"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
|
||||
// Resolve finds the deciding function of dt, its holders in the given scope
|
||||
// and the effective deputies covering dt.
|
||||
func (ds *Dataset) Resolve(dt string, scope Scope, now time.Time) (*Resolution, *Error) {
|
||||
if _, ok := DecisionTypeByKey(dt); !ok {
|
||||
return nil, &Error{Status: http.StatusBadRequest, Code: "unknown_decision_type", Message: fmt.Sprintf("unknown decision type %q", dt)}
|
||||
}
|
||||
res := &Resolution{DecisionType: dt, Holders: []Holder{}, Deputies: []ResolutionDeputy{}, Status: StatusOpen}
|
||||
fn, src := ds.DecidingFunction(dt)
|
||||
if fn == "" {
|
||||
return res, nil
|
||||
}
|
||||
res.Function, res.Source = fn, src
|
||||
f, _ := FunctionByKey(fn)
|
||||
if f.AnyMember {
|
||||
res.AnyMember, res.Status = true, StatusFilled
|
||||
return res, nil
|
||||
}
|
||||
if f.Per != PerCompany {
|
||||
if err := checkScope("scope", f, &scope); err != nil {
|
||||
err.Code = "scope_required"
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
match := func(s *Scope) bool { return f.Per == PerCompany || scopeKey(s) == scopeKey(&scope) }
|
||||
notApplicable := false
|
||||
for _, a := range ds.Assignments {
|
||||
if a.Function != fn || !match(a.Scope) {
|
||||
continue
|
||||
}
|
||||
if a.Holder.Kind == HolderNotApplicable {
|
||||
notApplicable = true
|
||||
continue
|
||||
}
|
||||
res.Holders = append(res.Holders, a.Holder)
|
||||
}
|
||||
for _, d := range ds.Deputies {
|
||||
if d.Function != fn || !match(d.Scope) || !slices.Contains(d.DecisionTypes, dt) {
|
||||
continue
|
||||
}
|
||||
if st := ds.State(d, now); st.State == StateEffective {
|
||||
res.Deputies = append(res.Deputies, ResolutionDeputy{ID: d.ID, Holder: d.Holder, State: st.State})
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case len(res.Holders) > 0:
|
||||
res.Status = StatusFilled
|
||||
case notApplicable:
|
||||
res.Status = StatusNotApplicable
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// Changes lists the entry ids that differ between two states, per section,
|
||||
// for the audit (no names, contacts or texts).
|
||||
func Changes(prev, next *Dataset) map[string][]string {
|
||||
var p Dataset
|
||||
if prev != nil {
|
||||
p = *prev
|
||||
}
|
||||
out := map[string][]string{}
|
||||
diff := func(section string, before, after map[string]string) {
|
||||
var ids []string
|
||||
for id, v := range after {
|
||||
if before[id] != v {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
for id := range before {
|
||||
if _, ok := after[id]; !ok {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
if len(ids) > 0 {
|
||||
slices.Sort(ids)
|
||||
out[section] = ids
|
||||
}
|
||||
}
|
||||
byID := func(n int, id func(int) string, v func(int) any) map[string]string {
|
||||
m := map[string]string{}
|
||||
for i := 0; i < n; i++ {
|
||||
b, _ := json.Marshal(v(i))
|
||||
m[id(i)] = string(b)
|
||||
}
|
||||
return m
|
||||
}
|
||||
diff("assignments",
|
||||
byID(len(p.Assignments), func(i int) string { return p.Assignments[i].ID }, func(i int) any { return p.Assignments[i] }),
|
||||
byID(len(next.Assignments), func(i int) string { return next.Assignments[i].ID }, func(i int) any { return next.Assignments[i] }))
|
||||
diff("deputies",
|
||||
byID(len(p.Deputies), func(i int) string { return p.Deputies[i].ID }, func(i int) any { return p.Deputies[i] }),
|
||||
byID(len(next.Deputies), func(i int) string { return next.Deputies[i].ID }, func(i int) any { return next.Deputies[i] }))
|
||||
diff("standard_releases",
|
||||
byID(len(p.StandardReleases), func(i int) string { return p.StandardReleases[i].ID }, func(i int) any { return p.StandardReleases[i] }),
|
||||
byID(len(next.StandardReleases), func(i int) string { return next.StandardReleases[i].ID }, func(i int) any { return next.StandardReleases[i] }))
|
||||
// The keyless sections are reported by name when they changed.
|
||||
for name, pair := range map[string][2]any{
|
||||
"authority": {p.Authority, next.Authority},
|
||||
"immediate_authority": {p.ImmediateAuthority, next.ImmediateAuthority},
|
||||
"editors": {p.Editors, next.Editors},
|
||||
"critical_contact": {p.CriticalContact, next.CriticalContact},
|
||||
} {
|
||||
if !jsonEqual(pair[0], pair[1]) && (!isEmpty(pair[0]) || !isEmpty(pair[1])) {
|
||||
out[name] = []string{"changed"}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func isEmpty(v any) bool {
|
||||
b, _ := json.Marshal(v)
|
||||
return string(b) == "null" || string(b) == "[]"
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
package roles
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var now = time.Date(2026, 11, 10, 9, 0, 0, 0, time.UTC)
|
||||
|
||||
const (
|
||||
ceo = "u-ceo"
|
||||
owner = "u-docowner"
|
||||
staff = "u-staff"
|
||||
)
|
||||
|
||||
func member(sub string) Holder { return Holder{Kind: HolderMember, Sub: sub} }
|
||||
|
||||
// base: management and the owner of R1-D01 are recorded.
|
||||
func base(t *testing.T) *Dataset {
|
||||
t.Helper()
|
||||
ds, err := Prepare(nil, &Dataset{Assignments: []Assignment{{ID: "a-ceo", Function: Management, Holder: member(ceo)}}},
|
||||
nil, Writer{Sub: ceo, OrgRoles: []string{OwnerRole}}, now)
|
||||
if err != nil {
|
||||
t.Fatalf("bootstrap: %v", err)
|
||||
}
|
||||
next := *ds
|
||||
next.Assignments = append(next.Assignments, Assignment{ID: "a-own", Function: DocumentOwner, Holder: member(owner), Scope: &Scope{Document: "r1_d01"}})
|
||||
ds, err = Prepare(ds, &next, nil, Writer{Sub: ceo}, now)
|
||||
if err != nil {
|
||||
t.Fatalf("document owner: %v", err)
|
||||
}
|
||||
return ds
|
||||
}
|
||||
|
||||
func withDeputy(ds *Dataset, d Deputy) *Dataset {
|
||||
next := *ds
|
||||
next.Deputies = append(append([]Deputy(nil), ds.Deputies...), d)
|
||||
return &next
|
||||
}
|
||||
|
||||
func mgmtDeputy() Deputy {
|
||||
return Deputy{ID: "d-1", Function: Management, Holder: member(staff), DecisionTypes: []string{"r1.release_d01"},
|
||||
Basis: Basis{Text: "Vertretungsregelung der Geschäftsführung"}}
|
||||
}
|
||||
|
||||
func code(err *Error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
return err.Code
|
||||
}
|
||||
|
||||
func TestCatalogue_unionOfA1AndA4(t *testing.T) {
|
||||
seen := map[string]bool{}
|
||||
labels := map[string]bool{}
|
||||
rows := map[int]bool{}
|
||||
for _, f := range Functions {
|
||||
if seen[f.Code] || labels[f.Label] {
|
||||
t.Errorf("twice: %s / %s", f.Code, f.Label)
|
||||
}
|
||||
seen[f.Code], labels[f.Label] = true, true
|
||||
if f.D02Row > 0 {
|
||||
rows[f.D02Row] = true
|
||||
}
|
||||
if !strings.HasPrefix(f.Code, "r1.") {
|
||||
t.Errorf("%s: R1 keys are namespaced r1.*", f.Code)
|
||||
}
|
||||
}
|
||||
a1 := []string{"Geschäftsleitung", "Produkt-Cybersecurity-Verantwortlicher", "Technischer Ansprechpartner", "Vorfallkontakt",
|
||||
"Regulatorisch Meldeberechtigter", "Produktsicherheitsverantwortlicher", "Dokumentenverantwortlicher", "Freigabestelle",
|
||||
"Änderungsinitiierung", "Produktverantwortung", "Änderungskoordination", "Fachprüfung", "Freigabe von Produktänderungen",
|
||||
"Dokumentenlenkung", "Maßnahmenausführer", "Prüffunktion", "Abschlussverantwortlicher", "Fachlich verantwortliche Stelle"}
|
||||
a4 := []string{"Geschäftsleitung", "Produkt-Cybersecurity-Verantwortlicher", "Technischer Produktverantwortlicher",
|
||||
"Externer Cybersecurity-Dienstleister", "Produktsicherheitsverantwortlicher",
|
||||
"Konformitätsverantwortlicher / autorisierte Herstellerfunktion", "Regulatorisch Meldeberechtigter"}
|
||||
for _, l := range append(a1, a4...) {
|
||||
if !labels[l] {
|
||||
t.Errorf("missing %q", l)
|
||||
}
|
||||
}
|
||||
if len(a1) != 18 || len(a4) != 7 || len(Functions) != 21 {
|
||||
t.Errorf("union of 18 and 7 with 4 shared is 21, got %d", len(Functions))
|
||||
}
|
||||
for i := 1; i <= 7; i++ {
|
||||
if !rows[i] {
|
||||
t.Errorf("R1-D02 §18 row %d unmapped", i)
|
||||
}
|
||||
}
|
||||
for _, d := range DecisionTypes {
|
||||
if d.Default != "" && d.Default != Management {
|
||||
t.Errorf("%s: only the releases carry an owner default", d.Code)
|
||||
}
|
||||
if _, ok := FunctionByKey(d.Default); d.Default != "" && !ok {
|
||||
t.Errorf("%s: unknown default", d.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepare_whoMayWrite(t *testing.T) {
|
||||
ds := base(t)
|
||||
next := *ds
|
||||
next.Assignments = append(next.Assignments, Assignment{ID: "a-x", Function: "r1.vorfallkontakt", Holder: member(staff)})
|
||||
if _, err := Prepare(ds, &next, nil, Writer{Sub: staff}, now); code(err) != "not_permitted" {
|
||||
t.Fatalf("a person without function: %v", err)
|
||||
}
|
||||
if _, err := Prepare(ds, &next, nil, Writer{Sub: staff, OrgRoles: []string{OwnerRole}}, now); code(err) != "not_permitted" {
|
||||
t.Fatalf("OWNER once management is recorded: %v", err)
|
||||
}
|
||||
if _, err := Prepare(ds, &next, nil, Writer{Sub: owner}, now); err != nil {
|
||||
t.Fatalf("document owner: %v", err)
|
||||
}
|
||||
if _, err := Prepare(ds, &next, nil, Writer{Sub: ceo}, now); err != nil {
|
||||
t.Fatalf("management: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepare_bootstrapOnlyRecordsManagement(t *testing.T) {
|
||||
w := Writer{Sub: "u-signup", OrgRoles: []string{OwnerRole}}
|
||||
other := &Dataset{Assignments: []Assignment{{ID: "a-1", Function: "r1.vorfallkontakt", Holder: member(staff)}}}
|
||||
if _, err := Prepare(nil, other, nil, w, now); code(err) != "bootstrap_only" {
|
||||
t.Fatalf("bootstrap with another function: %v", err)
|
||||
}
|
||||
mgmt := &Dataset{Assignments: []Assignment{{ID: "a-1", Function: Management, Holder: member(ceo)}}}
|
||||
if _, err := Prepare(nil, mgmt, []string{"a-1"}, w, now); code(err) != "bootstrap_only" {
|
||||
t.Fatalf("no authorizing in the bootstrap: %v", err)
|
||||
}
|
||||
if _, err := Prepare(nil, mgmt, nil, Writer{Sub: "u-signup", OrgRoles: []string{"CXO"}}, now); code(err) != "not_permitted" {
|
||||
t.Fatalf("bootstrap needs OWNER: %v", err)
|
||||
}
|
||||
ds, err := Prepare(nil, mgmt, nil, w, now)
|
||||
if err != nil || ds.Assignments[0].RecordedBy != "u-signup" {
|
||||
t.Fatalf("bootstrap: %+v %v", ds, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepare_stampsComeFromTheWriter(t *testing.T) {
|
||||
ds := base(t)
|
||||
forged := mgmtDeputy()
|
||||
forged.AuthorizedBy, forged.RecordedBy = ceo, ceo
|
||||
got, err := Prepare(ds, withDeputy(ds, forged), nil, Writer{Sub: owner}, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d := got.Deputies[0]
|
||||
if d.RecordedBy != owner || d.AuthorizedBy != "" {
|
||||
t.Fatalf("stamps from the body: %+v", d)
|
||||
}
|
||||
if st := got.State(d, now); st.State != StateRecorded || st.Reasons[0] != "authorization_missing" {
|
||||
t.Fatalf("B7: a document owner's management deputy without authorization: %+v", st)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepare_managementAuthorizes(t *testing.T) {
|
||||
ds := base(t)
|
||||
byOwner, err := Prepare(ds, withDeputy(ds, mgmtDeputy()), nil, Writer{Sub: owner}, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Prepare(byOwner, byOwner, []string{"d-1"}, Writer{Sub: owner}, now); code(err) != "not_authorizer" {
|
||||
t.Fatalf("document owner authorizing: %v", err)
|
||||
}
|
||||
auth, err := Prepare(byOwner, byOwner, []string{"d-1"}, Writer{Sub: ceo}, now)
|
||||
if err != nil || auth.Deputies[0].AuthorizedBy != ceo {
|
||||
t.Fatalf("management authorizes: %+v %v", auth.Deputies, err)
|
||||
}
|
||||
if st := auth.State(auth.Deputies[0], now); st.State != StateEffective {
|
||||
t.Fatalf("authorized with basis: %+v", st)
|
||||
}
|
||||
// Unchanged on the next save, by anyone.
|
||||
again, err := Prepare(auth, auth, nil, Writer{Sub: owner}, now.Add(time.Hour))
|
||||
if err != nil || again.Deputies[0].AuthorizedBy != ceo || !again.Deputies[0].RecordedAt.Equal(*auth.Deputies[0].RecordedAt) {
|
||||
t.Fatalf("stamps kept: %+v %v", again.Deputies[0], err)
|
||||
}
|
||||
// Changing the scope of the deputyship drops the authorization.
|
||||
changed := *auth
|
||||
changed.Deputies = []Deputy{auth.Deputies[0]}
|
||||
changed.Deputies[0].DecisionTypes = []string{"r1.release_d01", "r1.release_d02"}
|
||||
got, err := Prepare(auth, &changed, nil, Writer{Sub: owner}, now)
|
||||
if err != nil || got.Deputies[0].AuthorizedBy != "" {
|
||||
t.Fatalf("changed deputyship keeps its authorization: %+v %v", got.Deputies[0], err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepare_managementRecordingIsTheAuthorization(t *testing.T) {
|
||||
ds := base(t)
|
||||
got, err := Prepare(ds, withDeputy(ds, mgmtDeputy()), nil, Writer{Sub: ceo}, now)
|
||||
if err != nil || got.Deputies[0].AuthorizedBy != ceo {
|
||||
t.Fatalf("B7 wording: management's own record authorizes: %+v %v", got.Deputies, err)
|
||||
}
|
||||
self := mgmtDeputy()
|
||||
self.Holder = member(ceo)
|
||||
if _, err := Prepare(ds, withDeputy(ds, self), []string{"d-1"}, Writer{Sub: ceo}, now); code(err) != "self_authorization" {
|
||||
t.Fatalf("self authorization: %v", err)
|
||||
}
|
||||
got, err = Prepare(ds, withDeputy(ds, self), nil, Writer{Sub: ceo}, now)
|
||||
if err != nil || got.Deputies[0].AuthorizedBy != "" {
|
||||
t.Fatalf("no automatic self authorization: %+v %v", got.Deputies, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestState_basisAndValidity(t *testing.T) {
|
||||
ds := base(t)
|
||||
d := Deputy{ID: "d-2", Function: "r1.vorfallkontakt", Holder: member(staff), DecisionTypes: []string{"r1.escalation"}}
|
||||
if st := ds.State(d, now); st.State != StateRecorded || st.Reasons[0] != "basis_missing" {
|
||||
t.Fatalf("without basis: %+v", st)
|
||||
}
|
||||
d.Basis.Text = "Bestellung vom 1.10."
|
||||
if st := ds.State(d, now); st.State != StateEffective {
|
||||
t.Fatalf("with basis: %+v", st)
|
||||
}
|
||||
d.ValidFrom = "2026-12-01"
|
||||
if st := ds.State(d, now); st.State != StateRecorded || st.Reasons[0] != "not_yet_valid" {
|
||||
t.Fatalf("before valid_from: %+v", st)
|
||||
}
|
||||
d.ValidFrom, d.ValidUntil = "2026-01-01", "2026-11-09"
|
||||
if st := ds.State(d, now); st.State != StateRecorded || st.Reasons[0] != "expired" {
|
||||
t.Fatalf("after valid_until: %+v", st)
|
||||
}
|
||||
// The last day still counts, in Berlin: 23:30 UTC on 9 Nov is 10 Nov there.
|
||||
if st := ds.State(d, time.Date(2026, 11, 9, 22, 30, 0, 0, time.UTC)); st.State != StateEffective {
|
||||
t.Fatalf("on the last day: %+v", st)
|
||||
}
|
||||
if st := ds.State(d, time.Date(2026, 11, 9, 23, 30, 0, 0, time.UTC)); st.State != StateRecorded {
|
||||
t.Fatalf("after the last day in Berlin: %+v", st)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate_B8(t *testing.T) {
|
||||
ds := base(t)
|
||||
next := *ds
|
||||
next.Authority = []Authority{{DecisionType: ReleaseD02Update, Function: "r1.freigabestelle"}}
|
||||
if _, err := Prepare(ds, &next, nil, Writer{Sub: ceo}, now); code(err) != "d02_reference_required" {
|
||||
t.Fatalf("B8 without reference: %v", err)
|
||||
}
|
||||
next.Authority[0].D02Reference = "R1-D02 §16 Abs. 2"
|
||||
got, err := Prepare(ds, &next, nil, Writer{Sub: ceo}, now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f, src := got.DecidingFunction(ReleaseD02Update); f != "r1.freigabestelle" || src != "company" {
|
||||
t.Fatalf("company's release body: %s %s", f, src)
|
||||
}
|
||||
if f, src := ds.DecidingFunction(ReleaseD02Update); f != Management || src != "default" {
|
||||
t.Fatalf("default release body: %s %s", f, src)
|
||||
}
|
||||
next.Authority = []Authority{{DecisionType: "r1.escalation", Function: "r1.vorfallkontakt", D02Reference: "x"}}
|
||||
if _, err := Prepare(ds, &next, nil, Writer{Sub: ceo}, now); code(err) != "invalid_role_dataset" {
|
||||
t.Fatalf("d02_reference elsewhere: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate_catalogueRules(t *testing.T) {
|
||||
cases := map[string]Assignment{
|
||||
"unknown function": {ID: "a", Function: "r1.nope", Holder: member(staff)},
|
||||
"scope on company": {ID: "a", Function: "r1.vorfallkontakt", Holder: member(staff), Scope: &Scope{Document: "r1_d01"}},
|
||||
"document without": {ID: "a", Function: DocumentOwner, Holder: member(staff)},
|
||||
"unknown document": {ID: "a", Function: DocumentOwner, Holder: member(staff), Scope: &Scope{Document: "r9"}},
|
||||
"external management": {ID: "a", Function: Management, Holder: Holder{Kind: HolderExternal, Name: "X GmbH"}},
|
||||
"member as provider": {ID: "a", Function: "r1.externer_cybersecurity_dienstleister", Holder: member(staff)},
|
||||
"not applicable here": {ID: "a", Function: Management, Holder: Holder{Kind: HolderNotApplicable}},
|
||||
"any member assigned": {ID: "a", Function: "r1.aenderungsinitiierung", Holder: member(staff)},
|
||||
"member with a name": {ID: "a", Function: Management, Holder: Holder{Kind: HolderMember, Sub: staff, Name: "X"}},
|
||||
"bad id": {ID: "a b", Function: Management, Holder: member(staff)},
|
||||
"product without scope": {ID: "a", Function: "r1.produktverantwortung", Holder: member(staff)},
|
||||
}
|
||||
for name, a := range cases {
|
||||
if err := Validate(&Dataset{Assignments: []Assignment{a}}); code(err) != "invalid_role_dataset" || err.Status != http.StatusBadRequest || err.Path == "" {
|
||||
t.Errorf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
two := &Dataset{Assignments: []Assignment{
|
||||
{ID: "a", Function: DocumentOwner, Holder: member(staff), Scope: &Scope{Document: "r1_d01"}},
|
||||
{ID: "b", Function: DocumentOwner, Holder: member(ceo), Scope: &Scope{Document: "r1_d01"}},
|
||||
}}
|
||||
if err := Validate(two); code(err) != "invalid_role_dataset" {
|
||||
t.Errorf("two document owners: %v", err)
|
||||
}
|
||||
two.Assignments[1].Scope = &Scope{Document: "r1_d02"}
|
||||
if err := Validate(two); err != nil {
|
||||
t.Errorf("one owner per document: %v", err)
|
||||
}
|
||||
ok := &Dataset{Assignments: []Assignment{
|
||||
{ID: "a", Function: "r1.produktsicherheit", Holder: Holder{Kind: HolderNotApplicable, ModuleDecisionRef: "D-R1-01 vom 2.11."}},
|
||||
{ID: "b", Function: "r1.externer_cybersecurity_dienstleister", Holder: Holder{Kind: HolderExternal, Name: "Dienstleister", Organisation: "X GmbH", Contact: "soc@x.test"}},
|
||||
}}
|
||||
if err := Validate(ok); err != nil {
|
||||
t.Errorf("valid: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecode_refusesUnknownKeys(t *testing.T) {
|
||||
if _, err := Decode([]byte(`{"assignments":[],"owner":"me"}`)); code(err) != "invalid_role_dataset" {
|
||||
t.Fatalf("unknown top key: %v", err)
|
||||
}
|
||||
if _, err := Decode([]byte(`{"assignments":[{"id":"a","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u","role":"x"},"scope":null}]}`)); code(err) != "invalid_role_dataset" {
|
||||
t.Fatalf("unknown nested key: %v", err)
|
||||
}
|
||||
if _, err := Decode([]byte(`{}`)); err != nil {
|
||||
t.Fatalf("empty: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolve(t *testing.T) {
|
||||
ds := base(t)
|
||||
r, err := ds.Resolve("r1.escalation", Scope{}, now)
|
||||
if err != nil || r.Status != StatusOpen || r.Function != "" {
|
||||
t.Fatalf("not set: %+v %v", r, err)
|
||||
}
|
||||
r, err = ds.Resolve("r1.release_d01", Scope{}, now)
|
||||
if err != nil || r.Status != StatusFilled || r.Source != "default" || len(r.Holders) != 1 || r.Holders[0].Sub != ceo {
|
||||
t.Fatalf("default management: %+v %v", r, err)
|
||||
}
|
||||
byOwner, _ := Prepare(ds, withDeputy(ds, mgmtDeputy()), nil, Writer{Sub: owner}, now)
|
||||
if r, _ := byOwner.Resolve("r1.release_d01", Scope{}, now); len(r.Deputies) != 0 {
|
||||
t.Fatalf("a recorded (not effective) deputy is listed: %+v", r.Deputies)
|
||||
}
|
||||
auth, _ := Prepare(byOwner, byOwner, []string{"d-1"}, Writer{Sub: ceo}, now)
|
||||
if r, _ := auth.Resolve("r1.release_d01", Scope{}, now); len(r.Deputies) != 1 || r.Deputies[0].State != StateEffective {
|
||||
t.Fatalf("effective deputy: %+v", r.Deputies)
|
||||
}
|
||||
if r, _ := auth.Resolve("r1.release_d02", Scope{}, now); len(r.Deputies) != 0 {
|
||||
t.Fatalf("deputy outside its decision types: %+v", r.Deputies)
|
||||
}
|
||||
next := *ds
|
||||
next.Authority = []Authority{{DecisionType: "r1.new_version_needed", Function: DocumentOwner}}
|
||||
set, _ := Prepare(ds, &next, nil, Writer{Sub: ceo}, now)
|
||||
if _, err := set.Resolve("r1.new_version_needed", Scope{}, now); code(err) != "scope_required" {
|
||||
t.Fatalf("document-scoped without document: %v", err)
|
||||
}
|
||||
r, err = set.Resolve("r1.new_version_needed", Scope{Document: "r1_d01"}, now)
|
||||
if err != nil || r.Status != StatusFilled || r.Holders[0].Sub != owner {
|
||||
t.Fatalf("owner of R1-D01: %+v %v", r, err)
|
||||
}
|
||||
if r, _ := set.Resolve("r1.new_version_needed", Scope{Document: "r1_d02"}, now); r.Status != StatusOpen {
|
||||
t.Fatalf("R1-D02 has no owner: %+v", r)
|
||||
}
|
||||
if _, err := ds.Resolve("r1.nope", Scope{}, now); code(err) != "unknown_decision_type" {
|
||||
t.Fatalf("unknown type: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChanges_namesIDsOnly(t *testing.T) {
|
||||
ds := base(t)
|
||||
got, _ := Prepare(ds, withDeputy(ds, mgmtDeputy()), nil, Writer{Sub: ceo}, now)
|
||||
ch := Changes(ds, got)
|
||||
b, _ := json.Marshal(ch)
|
||||
if string(b) != `{"deputies":["d-1"]}` {
|
||||
t.Fatalf("changes: %s", b)
|
||||
}
|
||||
if strings.Contains(string(b), staff) || strings.Contains(string(b), "Vertretung") {
|
||||
t.Fatal("no personal data or texts in the changes")
|
||||
}
|
||||
}
|
||||
@@ -131,6 +131,12 @@ func (s *Server) requireAuthz(next http.Handler) http.Handler {
|
||||
if group == "api-keys" && p.IsUser() {
|
||||
group = "api-keys.integration"
|
||||
}
|
||||
// A user token on the role dataset (R1 S0) reaches only these
|
||||
// routes: the handlers check tenant and function themselves, so the
|
||||
// portal's sign-in client needs no tenants grant.
|
||||
if p.IsUser() && isRoleDatasetPath(r.URL.Path) {
|
||||
group = "role-dataset.user"
|
||||
}
|
||||
if !s.Authz.Allowed(p.ClientID, group) {
|
||||
s.Log.Warn("client not authorized for route group", "azp", p.ClientID, "group", group, "path", r.URL.Path)
|
||||
writeError(w, http.StatusForbidden, "FORBIDDEN_CLIENT", "client "+p.ClientID+" may not call "+group)
|
||||
|
||||
@@ -86,6 +86,8 @@ func (s *Server) tenantSubresource(w http.ResponseWriter, r *http.Request) {
|
||||
s.listTenantManagedServices(w, r)
|
||||
case "company-profile":
|
||||
s.getCompanyProfile(w, r)
|
||||
case "role-dataset":
|
||||
s.getRoleDataset(w, r)
|
||||
case "store":
|
||||
s.listStore(w, r)
|
||||
default:
|
||||
|
||||
@@ -49,6 +49,10 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
|
||||
{"POST", "/v1/internal/keycloak/claims"},
|
||||
{"GET", "/v1/tenants?limit=10"},
|
||||
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/members"},
|
||||
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset"},
|
||||
{"PUT", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset"},
|
||||
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset/revisions/2"},
|
||||
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset/resolve?decision_type=r1.release_d01"},
|
||||
{"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/invites"},
|
||||
{"PATCH", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1"},
|
||||
{"DELETE", "/v1/tenants/00000000-0000-0000-0000-000000000001/members/u-1"},
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/roles"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// Rollen- und Befugnisdatensatz (0024, R1 S0; docgen#1 13781 §3.2 no. 2,
|
||||
// owner addendum 13791): one dataset per company with functions, who holds
|
||||
// them, deputies and the authority per decision type. internal/roles holds
|
||||
// the catalogue and the rules of B7/B8; the store versions the document.
|
||||
//
|
||||
// GET /v1/tenants/{id}/role-dataset current state, derived deputy states, catalogue
|
||||
// PUT /v1/tenants/{id}/role-dataset save (user token only)
|
||||
// GET /v1/tenants/{id}/role-dataset/revisions/{rev} the dataset a decision was made under
|
||||
// GET /v1/tenants/{id}/role-dataset/resolve who may decide a decision type now
|
||||
//
|
||||
// Reads: a user token of the tenant, or a service with tenants.read
|
||||
// (Werkmeister). Writes come only from a user token: the writer is the
|
||||
// token's subject, never a body field or an X-Portal-User-* header. User
|
||||
// tokens on these routes form the route group role-dataset.user (requireAuthz).
|
||||
|
||||
// maxRoleDatasetBytes caps a dataset document.
|
||||
const maxRoleDatasetBytes = 256 << 10
|
||||
|
||||
type roleDatasetSaveReq struct {
|
||||
Data json.RawMessage `json:"data"`
|
||||
CatalogueVersion string `json:"catalogue_version"`
|
||||
ExpectedRevision *int `json:"expected_revision"`
|
||||
Authorize []string `json:"authorize"`
|
||||
}
|
||||
|
||||
type roleDatasetResp struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
Revision int `json:"revision"`
|
||||
CatalogueVersion string `json:"catalogue_version"`
|
||||
UpdatedBy string `json:"updated_by,omitempty"`
|
||||
UpdatedAt *time.Time `json:"updated_at,omitempty"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
Derived roleDatasetDerived `json:"derived"`
|
||||
Catalogue roles.Catalogue `json:"catalogue"`
|
||||
}
|
||||
|
||||
type roleDatasetDerived struct {
|
||||
Deputies []roles.DeputyState `json:"deputies"`
|
||||
}
|
||||
|
||||
type roleDatasetResolveResp struct {
|
||||
Revision int `json:"revision"`
|
||||
CatalogueVersion string `json:"catalogue_version"`
|
||||
*roles.Resolution
|
||||
}
|
||||
|
||||
// isRoleDatasetPath reports whether path is /v1/tenants/{id}/role-dataset or
|
||||
// below it.
|
||||
func isRoleDatasetPath(path string) bool {
|
||||
rest, ok := strings.CutPrefix(path, "/v1/tenants/")
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
parts := strings.Split(rest, "/")
|
||||
return len(parts) >= 2 && parts[1] == "role-dataset"
|
||||
}
|
||||
|
||||
// currentRoleDataset loads the stored dataset; a company without one gets
|
||||
// revision 0 and an empty dataset.
|
||||
func (s *Server) currentRoleDataset(ctx context.Context, tenantID string) (*store.RoleDataset, *roles.Dataset, error) {
|
||||
stored, err := s.Store.GetRoleDataset(ctx, tenantID)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return nil, &roles.Dataset{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
ds, derr := roles.Decode(stored.Data)
|
||||
if derr != nil {
|
||||
return nil, nil, fmt.Errorf("stored role dataset of %s: %v", tenantID, derr)
|
||||
}
|
||||
return stored, ds, nil
|
||||
}
|
||||
|
||||
func (s *Server) roleDatasetAnswer(tenantID string, stored *store.RoleDataset, ds *roles.Dataset) roleDatasetResp {
|
||||
out := roleDatasetResp{
|
||||
TenantID: tenantID, CatalogueVersion: roles.CatalogueVersion,
|
||||
Data: json.RawMessage(roles.Canonical(ds)),
|
||||
Derived: roleDatasetDerived{Deputies: ds.States(s.now())},
|
||||
Catalogue: roles.CurrentCatalogue(),
|
||||
}
|
||||
if stored != nil {
|
||||
out.Revision, out.CatalogueVersion, out.UpdatedBy = stored.Revision, stored.CatalogueVersion, stored.UpdatedBy
|
||||
at := stored.UpdatedAt
|
||||
out.UpdatedAt = &at
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// getRoleDataset is GET /v1/tenants/{id}/role-dataset.
|
||||
func (s *Server) getRoleDataset(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
|
||||
}
|
||||
writeJSON(w, http.StatusOK, s.roleDatasetAnswer(t.ID, stored, ds))
|
||||
}
|
||||
|
||||
// saveRoleDataset is PUT /v1/tenants/{id}/role-dataset.
|
||||
func (s *Server) saveRoleDataset(w http.ResponseWriter, r *http.Request) {
|
||||
p, has := authn.PrincipalFrom(r.Context())
|
||||
if !has || !p.IsUser() {
|
||||
writeError(w, http.StatusForbidden, "user_token_required", "the role dataset is saved with the token of the person saving it")
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxRoleDatasetBytes+4096)
|
||||
var in roleDatasetSaveReq
|
||||
if !decodeJSON(w, r, &in) {
|
||||
return
|
||||
}
|
||||
if in.ExpectedRevision == nil {
|
||||
writeError(w, http.StatusBadRequest, "expected_revision_required", "expected_revision is required (0 when there is no dataset yet)")
|
||||
return
|
||||
}
|
||||
if len(in.Data) > maxRoleDatasetBytes {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, "too_large", "role dataset exceeds 256 KiB")
|
||||
return
|
||||
}
|
||||
if in.CatalogueVersion != roles.CatalogueVersion {
|
||||
writeJSON(w, http.StatusConflict, map[string]string{
|
||||
"error": "catalogue_outdated", "message": "the catalogue has changed; reload the role dataset",
|
||||
"catalogue_version": roles.CatalogueVersion,
|
||||
})
|
||||
return
|
||||
}
|
||||
incoming, derr := roles.Decode(in.Data)
|
||||
if derr != nil {
|
||||
writeJSON(w, derr.Status, derr)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
t, ok := s.tenantInScope(ctx, w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
stored, current, err := s.currentRoleDataset(ctx, t.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
currentRev := 0
|
||||
if stored != nil {
|
||||
currentRev = stored.Revision
|
||||
}
|
||||
if *in.ExpectedRevision != currentRev {
|
||||
s.writeRoleDatasetConflict(w, currentRev)
|
||||
return
|
||||
}
|
||||
var prev *roles.Dataset
|
||||
if stored != nil {
|
||||
prev = current
|
||||
}
|
||||
at := s.now()
|
||||
next, rerr := roles.Prepare(prev, incoming, in.Authorize, roles.Writer{Sub: p.Subject, OrgRoles: p.OrgRoles}, at)
|
||||
if rerr != nil {
|
||||
writeJSON(w, rerr.Status, rerr)
|
||||
return
|
||||
}
|
||||
saved, changed, err := s.Store.SaveRoleDataset(ctx, store.RoleDatasetWrite{
|
||||
TenantID: t.ID, Data: json.RawMessage(roles.Canonical(next)), CatalogueVersion: roles.CatalogueVersion,
|
||||
ExpectedRevision: currentRev, By: p.Subject, At: at,
|
||||
})
|
||||
var rc *store.RevisionConflict
|
||||
switch {
|
||||
case errors.As(err, &rc):
|
||||
s.writeRoleDatasetConflict(w, rc.Current)
|
||||
return
|
||||
case err != nil:
|
||||
if mapStoreError(w, err) {
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
if changed {
|
||||
// Entry ids only: names, contacts and basis texts stay in the
|
||||
// dataset; the revision points to them.
|
||||
meta := map[string]interface{}{
|
||||
"revision": saved.Revision, "catalogue_version": saved.CatalogueVersion,
|
||||
"changes": roles.Changes(prev, next),
|
||||
}
|
||||
if len(in.Authorize) > 0 {
|
||||
meta["authorized"] = in.Authorize
|
||||
}
|
||||
s.emitAudit(ctx, r, store.AuditEvent{
|
||||
TenantID: t.ID, Action: "role_dataset.saved", TargetID: t.ID, TargetType: "role_dataset",
|
||||
TargetName: "Rollen- und Befugnisdatensatz", ActorID: p.Subject, ActorName: p.Email, ActorType: "user",
|
||||
Metadata: meta,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, s.roleDatasetAnswer(t.ID, saved, next))
|
||||
}
|
||||
|
||||
func (s *Server) writeRoleDatasetConflict(w http.ResponseWriter, current int) {
|
||||
writeJSON(w, http.StatusConflict, profileConflict{
|
||||
Error: "revision_conflict", CurrentRevision: current,
|
||||
Message: fmt.Sprintf("the role dataset was changed in the meantime (current revision %d); reload it", current),
|
||||
})
|
||||
}
|
||||
|
||||
// getRoleDatasetRevision is GET /v1/tenants/{id}/role-dataset/revisions/{rev}.
|
||||
func (s *Server) getRoleDatasetRevision(w http.ResponseWriter, r *http.Request) {
|
||||
rev, err := strconv.Atoi(r.PathValue("rev"))
|
||||
if err != nil || rev < 1 {
|
||||
writeError(w, http.StatusNotFound, "not_found", "resource does not exist")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
t, ok := s.tenantInScope(ctx, w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
d, err := s.Store.GetRoleDatasetRevision(ctx, t.ID, rev)
|
||||
if err != nil {
|
||||
if mapStoreError(w, err) {
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, d)
|
||||
}
|
||||
|
||||
// resolveRoleDataset is GET /v1/tenants/{id}/role-dataset/resolve
|
||||
// ?decision_type=…[&document=…|&product=…|&area=…].
|
||||
func (s *Server) resolveRoleDataset(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.Resolve(q.Get("decision_type"), 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 := roleDatasetResolveResp{CatalogueVersion: roles.CatalogueVersion, Resolution: res}
|
||||
if stored != nil {
|
||||
out.Revision, out.CatalogueVersion = stored.Revision, stored.CatalogueVersion
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package server_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// The store contract on both stores: revisions, the unchanged save, conflicts
|
||||
// with the current revision, the revision history and unknown tenants.
|
||||
func TestRoleDatasetStore(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
ctx := context.Background()
|
||||
doc := json.RawMessage(`{"assignments":[{"id":"a-1","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-1"},"scope":null}],"deputies":[]}`)
|
||||
write := func(data json.RawMessage, expected int) (*store.RoleDataset, bool, error) {
|
||||
return h.store.SaveRoleDataset(ctx, store.RoleDatasetWrite{
|
||||
TenantID: h.tenant.ID, Data: data, CatalogueVersion: "r1-test", ExpectedRevision: expected, By: "u-1", At: time.Now(),
|
||||
})
|
||||
}
|
||||
if _, err := h.store.GetRoleDataset(ctx, h.tenant.ID); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("none yet: %v", err)
|
||||
}
|
||||
d, changed, err := write(doc, 0)
|
||||
if err != nil || !changed || d.Revision != 1 || d.UpdatedBy != "u-1" || mustCanon(t, d.Data) != mustCanon(t, doc) {
|
||||
t.Fatalf("first save: %+v %v %v", d, changed, err)
|
||||
}
|
||||
reordered := json.RawMessage(`{"deputies":[],"assignments":[{"scope":null,"holder":{"sub":"u-1","kind":"member"},"function":"r1.geschaeftsleitung","id":"a-1"}]}`)
|
||||
if d, changed, err := write(reordered, 1); err != nil || changed || d.Revision != 1 {
|
||||
t.Fatalf("unchanged save: %+v %v %v", d, changed, err)
|
||||
}
|
||||
var rc *store.RevisionConflict
|
||||
if _, _, err := write(json.RawMessage(`{}`), 0); !errors.As(err, &rc) || rc.Current != 1 {
|
||||
t.Fatalf("stale save: %v", err)
|
||||
}
|
||||
if d, changed, err := write(json.RawMessage(`{"assignments":[]}`), 1); err != nil || !changed || d.Revision != 2 {
|
||||
t.Fatalf("second save: %+v %v %v", d, changed, err)
|
||||
}
|
||||
r1, err := h.store.GetRoleDatasetRevision(ctx, h.tenant.ID, 1)
|
||||
if err != nil || r1.Revision != 1 || mustCanon(t, r1.Data) != mustCanon(t, doc) || r1.UpdatedBy != "u-1" {
|
||||
t.Fatalf("revision 1: %+v %v", r1, err)
|
||||
}
|
||||
if _, err := h.store.GetRoleDatasetRevision(ctx, h.tenant.ID, 3); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("revision 3: %v", err)
|
||||
}
|
||||
if _, _, err := h.store.SaveRoleDataset(ctx, store.RoleDatasetWrite{
|
||||
TenantID: "00000000-0000-0000-0000-00000000beef", Data: doc, CatalogueVersion: "r1-test", By: "u-1", At: time.Now(),
|
||||
}); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("unknown tenant: %v", err)
|
||||
}
|
||||
if _, err := h.store.GetRoleDataset(ctx, "not-a-uuid"); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("bad id: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/roles"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// roleFixture: tenant acme, the stage AUTHZ_RULES shape, and principals by
|
||||
// name: the portal's sign-in client for users, its service client, and
|
||||
// Werkmeister's service client.
|
||||
type roleFixture struct {
|
||||
s *Server
|
||||
h http.Handler
|
||||
tenant *store.Tenant
|
||||
as map[string]*authn.Principal
|
||||
}
|
||||
|
||||
func newRoleFixture(t *testing.T) *roleFixture {
|
||||
t.Helper()
|
||||
mem := store.NewMemory()
|
||||
tenant, _ := mem.GetTenantBySlug(context.Background(), "acme")
|
||||
other, err := mem.CreateTenant(context.Background(), store.TenantCreate{Slug: "other", Name: "Other"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user := func(sub, tenantID string, roles ...string) *authn.Principal {
|
||||
return &authn.Principal{Subject: sub, ClientID: "portal-stage", TenantID: tenantID, Email: sub + "@acme.test", OrgRoles: roles}
|
||||
}
|
||||
f := &roleFixture{tenant: tenant, as: map[string]*authn.Principal{
|
||||
"signup": user("u-signup", tenant.ID, "OWNER"),
|
||||
"ceo": user("u-ceo", tenant.ID, "CXO"),
|
||||
"staff": user("u-staff", tenant.ID, "USER"),
|
||||
"stranger": user("u-x", other.ID, "OWNER"),
|
||||
"portal": {Subject: "svc-portal", ClientID: "portal-svc"},
|
||||
"werkmeister": {Subject: "svc-wm", ClientID: "werkmeister-svc"},
|
||||
}}
|
||||
f.s = &Server{Log: slog.New(slog.NewTextHandler(io.Discard, nil)), Store: mem, Keycloak: keycloak.NewMock(),
|
||||
Authz: ParseAuthzRules("portal-svc:tenants,users;portal-stage:role-dataset.user;werkmeister-svc:tenants.read")}
|
||||
router := NewRouter(f.s)
|
||||
f.h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if p := f.as[r.Header.Get("X-Test-As")]; p != nil {
|
||||
r = r.WithContext(authn.WithPrincipal(r.Context(), p))
|
||||
}
|
||||
router.ServeHTTP(w, r)
|
||||
})
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *roleFixture) do(t *testing.T, as, method, path, body string, hdr ...string) (int, map[string]any, string) {
|
||||
t.Helper()
|
||||
var rd io.Reader
|
||||
if body != "" {
|
||||
rd = strings.NewReader(body)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, rd)
|
||||
req.Header.Set("X-Test-As", as)
|
||||
for i := 0; i+1 < len(hdr); i += 2 {
|
||||
req.Header.Set(hdr[i], hdr[i+1])
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
f.h.ServeHTTP(rr, req)
|
||||
var out map[string]any
|
||||
_ = json.Unmarshal(rr.Body.Bytes(), &out)
|
||||
return rr.Code, out, rr.Body.String()
|
||||
}
|
||||
|
||||
func (f *roleFixture) path(sub string) string {
|
||||
return "/v1/tenants/" + f.tenant.ID + "/role-dataset" + sub
|
||||
}
|
||||
|
||||
func saveBody(data string, expected int, authorize ...string) string {
|
||||
a, _ := json.Marshal(authorize)
|
||||
if authorize == nil {
|
||||
a = []byte("[]")
|
||||
}
|
||||
return `{"catalogue_version":"` + roles.CatalogueVersion + `","expected_revision":` + itoa(expected) + `,"authorize":` + string(a) + `,"data":` + data + `}`
|
||||
}
|
||||
|
||||
const (
|
||||
mgmtOnly = `{"assignments":[{"id":"a-ceo","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-ceo"},"scope":null}]}`
|
||||
withDeputyDS = `{"assignments":[{"id":"a-ceo","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-ceo"},"scope":null}],` +
|
||||
`"deputies":[{"id":"d-1","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-staff"},"scope":null,` +
|
||||
`"decision_types":["r1.release_d01"],"basis":{"text":"Vertretungsregelung"},"may_edit":false,"authorized_by":"u-ceo"}]}`
|
||||
)
|
||||
|
||||
func TestRoleDataset_lifecycle(t *testing.T) {
|
||||
f := newRoleFixture(t)
|
||||
|
||||
code, out, raw := f.do(t, "werkmeister", "GET", f.path(""), "")
|
||||
if code != http.StatusOK || out["revision"].(float64) != 0 || out["catalogue"] == nil {
|
||||
t.Fatalf("empty dataset: %d %s", code, raw)
|
||||
}
|
||||
if code, _, raw := f.do(t, "signup", "PUT", f.path(""), `{"catalogue_version":"`+roles.CatalogueVersion+`","data":{}}`); code != http.StatusBadRequest || !strings.Contains(raw, "expected_revision_required") {
|
||||
t.Fatalf("without expected_revision: %d %s", code, raw)
|
||||
}
|
||||
if code, _, raw := f.do(t, "signup", "PUT", f.path(""), strings.Replace(saveBody(mgmtOnly, 0), roles.CatalogueVersion, "r1-old", 1)); code != http.StatusConflict || !strings.Contains(raw, "catalogue_outdated") {
|
||||
t.Fatalf("old catalogue: %d %s", code, raw)
|
||||
}
|
||||
// First entry by the OWNER sign-in role: management only.
|
||||
code, out, raw = f.do(t, "signup", "PUT", f.path(""), saveBody(mgmtOnly, 0))
|
||||
if code != http.StatusOK || out["revision"].(float64) != 1 || out["updated_by"] != "u-signup" {
|
||||
t.Fatalf("bootstrap: %d %s", code, raw)
|
||||
}
|
||||
if code, _, raw := f.do(t, "ceo", "PUT", f.path(""), saveBody(mgmtOnly, 0)); code != http.StatusConflict || !strings.Contains(raw, "revision_conflict") {
|
||||
t.Fatalf("stale revision: %d %s", code, raw)
|
||||
}
|
||||
if code, _, raw := f.do(t, "staff", "PUT", f.path(""), saveBody(withDeputyDS, 1)); code != http.StatusForbidden || !strings.Contains(raw, "not_permitted") {
|
||||
t.Fatalf("person without function: %d %s", code, raw)
|
||||
}
|
||||
// Management records a deputy: the body's authorized_by is ignored, the
|
||||
// save itself is the authorization (B7).
|
||||
code, out, raw = f.do(t, "ceo", "PUT", f.path(""), saveBody(withDeputyDS, 1))
|
||||
if code != http.StatusOK || out["revision"].(float64) != 2 {
|
||||
t.Fatalf("deputy: %d %s", code, raw)
|
||||
}
|
||||
data := out["data"].(map[string]any)
|
||||
dep := data["deputies"].([]any)[0].(map[string]any)
|
||||
if dep["recorded_by"] != "u-ceo" || dep["authorized_by"] != "u-ceo" {
|
||||
t.Fatalf("stamps: %v", dep)
|
||||
}
|
||||
states := out["derived"].(map[string]any)["deputies"].([]any)
|
||||
if states[0].(map[string]any)["state"] != roles.StateEffective {
|
||||
t.Fatalf("derived: %v", states)
|
||||
}
|
||||
// Saving the same again creates no revision.
|
||||
if code, out, _ := f.do(t, "ceo", "PUT", f.path(""), saveBody(withDeputyDS, 2)); code != http.StatusOK || out["revision"].(float64) != 2 {
|
||||
t.Fatalf("unchanged save: %d %v", code, out["revision"])
|
||||
}
|
||||
|
||||
code, out, raw = f.do(t, "werkmeister", "GET", f.path("/resolve?decision_type=r1.release_d01"), "")
|
||||
if code != http.StatusOK || out["status"] != roles.StatusFilled || out["revision"].(float64) != 2 || len(out["deputies"].([]any)) != 1 {
|
||||
t.Fatalf("resolve: %d %s", code, raw)
|
||||
}
|
||||
if code, out, _ := f.do(t, "werkmeister", "GET", f.path("/resolve?decision_type=r1.escalation"), ""); code != http.StatusOK || out["status"] != roles.StatusOpen {
|
||||
t.Fatalf("unset decision type: %d %v", code, out)
|
||||
}
|
||||
if code, _, _ := f.do(t, "werkmeister", "GET", f.path("/resolve?decision_type=r1.nope"), ""); code != http.StatusBadRequest {
|
||||
t.Fatalf("unknown decision type: %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)
|
||||
}
|
||||
if code, _, _ := f.do(t, "werkmeister", "GET", f.path("/revisions/9"), ""); code != http.StatusNotFound {
|
||||
t.Fatalf("unknown revision: %d", code)
|
||||
}
|
||||
|
||||
items, _, err := f.s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: f.tenant.ID, Action: "role_dataset.saved"})
|
||||
if err != nil || len(items) != 2 {
|
||||
t.Fatalf("audit: %v %v", items, err)
|
||||
}
|
||||
ev := items[0]
|
||||
if ev.ActorID != "u-ceo" {
|
||||
ev = items[1]
|
||||
}
|
||||
b, _ := json.Marshal(ev.Metadata)
|
||||
if ev.ActorID != "u-ceo" || ev.ActorType != "user" || !strings.Contains(string(b), `"deputies":["d-1"]`) || strings.Contains(string(b), "Vertretungsregelung") {
|
||||
t.Fatalf("audit entry: %+v %s", ev, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoleDataset_writesNeedTheUsersToken(t *testing.T) {
|
||||
f := newRoleFixture(t)
|
||||
// The portal's service client, naming a user: refused, the header counts for nothing.
|
||||
if code, _, raw := f.do(t, "portal", "PUT", f.path(""), saveBody(mgmtOnly, 0), headerPortalUserSubject, "u-signup"); code != http.StatusForbidden || !strings.Contains(raw, "user_token_required") {
|
||||
t.Fatalf("service token write: %d %s", code, raw)
|
||||
}
|
||||
// Werkmeister reads but cannot write (tenants.read only).
|
||||
if code, _, _ := f.do(t, "werkmeister", "PUT", f.path(""), saveBody(mgmtOnly, 0)); code != http.StatusForbidden {
|
||||
t.Fatalf("werkmeister write: %d", code)
|
||||
}
|
||||
// A user of another tenant sees nothing.
|
||||
if code, _, _ := f.do(t, "stranger", "GET", f.path(""), ""); code != http.StatusNotFound {
|
||||
t.Fatalf("cross-tenant read: %d", code)
|
||||
}
|
||||
if code, _, _ := f.do(t, "stranger", "PUT", f.path(""), saveBody(mgmtOnly, 0)); code != http.StatusNotFound {
|
||||
t.Fatalf("cross-tenant write: %d", code)
|
||||
}
|
||||
// The portal's sign-in client reaches the role dataset only.
|
||||
if code, _, _ := f.do(t, "ceo", "GET", f.path(""), ""); code != http.StatusOK {
|
||||
t.Fatalf("user read: %d", code)
|
||||
}
|
||||
if code, _, raw := f.do(t, "ceo", "GET", "/v1/tenants/"+f.tenant.ID+"/members", ""); code != http.StatusForbidden || !strings.Contains(raw, "FORBIDDEN_CLIENT") {
|
||||
t.Fatalf("user token elsewhere: %d %s", code, raw)
|
||||
}
|
||||
if code, _, raw := f.do(t, "ceo", "GET", "/v1/tenants/"+f.tenant.ID+"/company-profile", ""); code != http.StatusForbidden || !strings.Contains(raw, "FORBIDDEN_CLIENT") {
|
||||
t.Fatalf("user token on the company profile: %d %s", code, raw)
|
||||
}
|
||||
// B8 through the API.
|
||||
if code, _, _ := f.do(t, "signup", "PUT", f.path(""), saveBody(mgmtOnly, 0)); code != http.StatusOK {
|
||||
t.Fatal("bootstrap")
|
||||
}
|
||||
b8 := `{"assignments":[{"id":"a-ceo","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-ceo"},"scope":null}],"authority":[{"decision_type":"r1.release_d02_update","function":"r1.freigabestelle"}]}`
|
||||
if code, _, raw := f.do(t, "ceo", "PUT", f.path(""), saveBody(b8, 1)); code != http.StatusBadRequest || !strings.Contains(raw, "d02_reference_required") {
|
||||
t.Fatalf("B8: %d %s", code, raw)
|
||||
}
|
||||
if code, _, raw := f.do(t, "ceo", "PUT", f.path(""), saveBody(`{"assignments":[],"owner":"x"}`, 1)); code != http.StatusBadRequest || !strings.Contains(raw, "invalid_role_dataset") {
|
||||
t.Fatalf("unknown key: %d %s", code, raw)
|
||||
}
|
||||
}
|
||||
|
||||
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/revisions/2": true,
|
||||
"/v1/tenants/x/members": false,
|
||||
"/v1/tenants/role-dataset": false,
|
||||
"/v1/admin/tenants/x/role-dataset": false,
|
||||
"/v1/tenants/x/projects/role-dataset/targets": false,
|
||||
} {
|
||||
if got := isRoleDatasetPath(path); got != want {
|
||||
t.Errorf("%s: %v", path, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -148,6 +148,10 @@ func NewRouter(s *Server) http.Handler {
|
||||
// Unternehmensprofil (0021): the GET is a {sub} of tenantSubresource.
|
||||
mux.HandleFunc("PUT /v1/tenants/{id}/company-profile", s.saveCompanyProfile)
|
||||
mux.HandleFunc("POST /v1/tenants/{id}/company-profile/submit", s.submitCompanyProfile)
|
||||
// Rollen- und Befugnisdatensatz (0024): the GET is a {sub} of tenantSubresource.
|
||||
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)
|
||||
|
||||
// entitlements
|
||||
mux.HandleFunc("GET /v1/entitlements", s.listTenantProducts)
|
||||
|
||||
@@ -42,6 +42,7 @@ type Memory struct {
|
||||
assets map[string]*StoreAsset // tenant_id + "/" + sha256 (0022)
|
||||
profiles map[string]*CompanyProfile // tenant_id → current
|
||||
profRevs map[string][]CompanyProfile // tenant_id → every revision
|
||||
roleSets map[string][]RoleDataset // tenant_id → every revision, oldest first (0024)
|
||||
mail []*MailItem
|
||||
mailID int64
|
||||
}
|
||||
@@ -71,6 +72,7 @@ func NewMemory() *Memory {
|
||||
preparations: make(map[string]*Preparation),
|
||||
assets: make(map[string]*StoreAsset),
|
||||
profRevs: make(map[string][]CompanyProfile),
|
||||
roleSets: make(map[string][]RoleDataset),
|
||||
|
||||
documents: make(map[string]*Document),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
func (m *Memory) GetRoleDataset(_ context.Context, tenantID string) (*RoleDataset, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
revs := m.roleSets[tenantID]
|
||||
if len(revs) == 0 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
cp := revs[len(revs)-1]
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
func (m *Memory) SaveRoleDataset(_ context.Context, w RoleDatasetWrite) (*RoleDataset, bool, error) {
|
||||
if !json.Valid(w.Data) || w.CatalogueVersion == "" || w.By == "" {
|
||||
return nil, false, ErrInvalidInput
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if _, ok := m.tenants[w.TenantID]; !ok {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
revs := m.roleSets[w.TenantID]
|
||||
current := len(revs)
|
||||
if w.ExpectedRevision != current {
|
||||
return nil, false, &RevisionConflict{Current: current}
|
||||
}
|
||||
if current > 0 {
|
||||
cur := revs[current-1]
|
||||
if cur.CatalogueVersion == w.CatalogueVersion && sameJSON(cur.Data, w.Data) {
|
||||
return &cur, false, nil
|
||||
}
|
||||
}
|
||||
next := RoleDataset{
|
||||
TenantID: w.TenantID, Data: append(json.RawMessage(nil), w.Data...), CatalogueVersion: w.CatalogueVersion,
|
||||
Revision: current + 1, UpdatedBy: w.By, UpdatedAt: w.At.UTC(),
|
||||
}
|
||||
m.roleSets[w.TenantID] = append(revs, next)
|
||||
cp := next
|
||||
return &cp, true, nil
|
||||
}
|
||||
|
||||
func (m *Memory) GetRoleDatasetRevision(_ context.Context, tenantID string, revision int) (*RoleDataset, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
revs := m.roleSets[tenantID]
|
||||
if revision < 1 || revision > len(revs) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
cp := revs[revision-1]
|
||||
return &cp, nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func scanRoleDataset(row pgx.Row) (*RoleDataset, error) {
|
||||
var d RoleDataset
|
||||
var data []byte
|
||||
if err := row.Scan(&d.TenantID, &data, &d.CatalogueVersion, &d.Revision, &d.UpdatedBy, &d.UpdatedAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
d.Data = json.RawMessage(data)
|
||||
return &d, nil
|
||||
}
|
||||
|
||||
const roleDatasetSelect = `
|
||||
SELECT tenant_id::text, data, catalogue_version, revision, updated_by, updated_at
|
||||
FROM role_datasets `
|
||||
|
||||
func (p *Postgres) GetRoleDataset(ctx context.Context, tenantID string) (*RoleDataset, error) {
|
||||
d, err := scanRoleDataset(p.pool.QueryRow(ctx, roleDatasetSelect+`WHERE tenant_id = $1::uuid`, tenantID))
|
||||
if isInvalidUUID(err) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return d, err
|
||||
}
|
||||
|
||||
func (p *Postgres) GetRoleDatasetRevision(ctx context.Context, tenantID string, revision int) (*RoleDataset, error) {
|
||||
d, err := scanRoleDataset(p.pool.QueryRow(ctx, `
|
||||
SELECT tenant_id::text, data, catalogue_version, revision, changed_by, changed_at
|
||||
FROM role_dataset_revisions WHERE tenant_id = $1::uuid AND revision = $2`, tenantID, revision))
|
||||
if isInvalidUUID(err) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return d, err
|
||||
}
|
||||
|
||||
// SaveRoleDataset writes the dataset and its revision row in one
|
||||
// transaction, with the row locked against a concurrent save.
|
||||
func (p *Postgres) SaveRoleDataset(ctx context.Context, w RoleDatasetWrite) (*RoleDataset, bool, error) {
|
||||
if !json.Valid(w.Data) || w.CatalogueVersion == "" || w.By == "" {
|
||||
return nil, false, ErrInvalidInput
|
||||
}
|
||||
tx, err := p.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
cur, err := scanRoleDataset(tx.QueryRow(ctx, roleDatasetSelect+`WHERE tenant_id = $1::uuid FOR UPDATE`, w.TenantID))
|
||||
switch {
|
||||
case errors.Is(err, ErrNotFound):
|
||||
cur = nil
|
||||
case isInvalidUUID(err):
|
||||
return nil, false, ErrNotFound
|
||||
case err != nil:
|
||||
return nil, false, err
|
||||
}
|
||||
current := 0
|
||||
if cur != nil {
|
||||
current = cur.Revision
|
||||
}
|
||||
if w.ExpectedRevision != current {
|
||||
return nil, false, &RevisionConflict{Current: current}
|
||||
}
|
||||
if cur != nil && cur.CatalogueVersion == w.CatalogueVersion && sameJSON(cur.Data, w.Data) {
|
||||
return cur, false, nil
|
||||
}
|
||||
next := current + 1
|
||||
if cur == nil {
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO role_datasets (tenant_id, data, catalogue_version, revision, updated_by, updated_at)
|
||||
VALUES ($1::uuid, $2::jsonb, $3, $4, $5, $6)`,
|
||||
w.TenantID, string(w.Data), w.CatalogueVersion, next, w.By, w.At.UTC())
|
||||
} else {
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE role_datasets SET data = $2::jsonb, catalogue_version = $3, revision = $4, updated_by = $5, updated_at = $6
|
||||
WHERE tenant_id = $1::uuid`,
|
||||
w.TenantID, string(w.Data), w.CatalogueVersion, next, w.By, w.At.UTC())
|
||||
}
|
||||
switch {
|
||||
case err == nil:
|
||||
case isFKViolation(err):
|
||||
return nil, false, ErrNotFound
|
||||
case isUniqueViolation(err):
|
||||
// A concurrent first save won: report its revision.
|
||||
return nil, false, &RevisionConflict{Current: 1}
|
||||
case isCheckViolation(err):
|
||||
return nil, false, ErrInvalidInput
|
||||
default:
|
||||
return nil, false, err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO role_dataset_revisions (tenant_id, revision, data, catalogue_version, changed_by, changed_at)
|
||||
SELECT tenant_id, revision, data, catalogue_version, updated_by, updated_at
|
||||
FROM role_datasets WHERE tenant_id = $1::uuid AND revision = $2`, w.TenantID, next); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
saved, err := p.GetRoleDataset(ctx, w.TenantID)
|
||||
return saved, true, err
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Role and authority dataset (0024, R1 S0): one document per tenant, checked
|
||||
// by internal/roles before it reaches the store. The store only versions it;
|
||||
// a decision record names the revision it was made under.
|
||||
type RoleDataset struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
CatalogueVersion string `json:"catalogue_version"`
|
||||
Revision int `json:"revision"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// RoleDatasetWrite is one save. ExpectedRevision is the revision the writer
|
||||
// last read, 0 when there was none; By is the writer's Keycloak sub.
|
||||
type RoleDatasetWrite struct {
|
||||
TenantID string
|
||||
Data json.RawMessage
|
||||
CatalogueVersion string
|
||||
ExpectedRevision int
|
||||
By string
|
||||
At time.Time
|
||||
}
|
||||
@@ -236,6 +236,16 @@ type Store interface {
|
||||
SaveCompanyProfile(ctx context.Context, w CompanyProfileWrite) (profile *CompanyProfile, changed bool, err error)
|
||||
SubmitCompanyProfile(ctx context.Context, tenantID string, expectedRevision int, by string, at time.Time) (*CompanyProfile, error)
|
||||
|
||||
// Role and authority dataset (0024): one per tenant, versioned like the
|
||||
// company profile. GetRoleDataset is ErrNotFound when the tenant has
|
||||
// none; SaveRoleDataset writes a new revision unless data and catalogue
|
||||
// version are unchanged (changed=false) and returns a *RevisionConflict
|
||||
// when the expected revision is not the stored one.
|
||||
// GetRoleDatasetRevision returns one stored revision (ErrNotFound).
|
||||
GetRoleDataset(ctx context.Context, tenantID string) (*RoleDataset, error)
|
||||
SaveRoleDataset(ctx context.Context, w RoleDatasetWrite) (dataset *RoleDataset, changed bool, err error)
|
||||
GetRoleDatasetRevision(ctx context.Context, tenantID string, revision int) (*RoleDataset, error)
|
||||
|
||||
// Managed services (0012, portal#77), listed by created_at. One row per
|
||||
// (tenant, kind, url): ErrConflict otherwise.
|
||||
ListManagedServices(ctx context.Context, tenantID string) ([]ManagedService, error)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
DROP TABLE IF EXISTS role_dataset_revisions;
|
||||
DROP TABLE IF EXISTS role_datasets;
|
||||
@@ -0,0 +1,25 @@
|
||||
-- Rollen- und Befugnisdatensatz (R1 S0, docgen#1 13781 §3.2 no. 2, owner
|
||||
-- addendum 13791): one document per company with functions, assignments,
|
||||
-- deputies and the authority per decision type. The registry checks the
|
||||
-- structure and the rules of B7/B8; the catalogue of functions lives in code
|
||||
-- (internal/roles).
|
||||
CREATE TABLE role_datasets (
|
||||
tenant_id UUID PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
data JSONB NOT NULL CHECK (jsonb_typeof(data) = 'object'),
|
||||
catalogue_version TEXT NOT NULL CHECK (char_length(catalogue_version) BETWEEN 1 AND 40),
|
||||
revision INTEGER NOT NULL CHECK (revision >= 1),
|
||||
updated_by TEXT NOT NULL, -- Keycloak sub of the writer
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Every saved state, never changed afterwards. A decision record names the
|
||||
-- revision it was made under (AK-G7, AK-V5).
|
||||
CREATE TABLE role_dataset_revisions (
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
revision INTEGER NOT NULL CHECK (revision >= 1),
|
||||
data JSONB NOT NULL,
|
||||
catalogue_version TEXT NOT NULL,
|
||||
changed_by TEXT NOT NULL,
|
||||
changed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (tenant_id, revision)
|
||||
);
|
||||
@@ -101,6 +101,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
|
||||
"audit_log",
|
||||
"products",
|
||||
"managed_services",
|
||||
"role_datasets",
|
||||
"role_dataset_revisions",
|
||||
}
|
||||
for _, table := range wantTables {
|
||||
var exists bool
|
||||
@@ -116,8 +118,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services).
|
||||
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}} {
|
||||
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets).
|
||||
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}} {
|
||||
var exists bool
|
||||
err := db.QueryRow(
|
||||
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name=$2)",
|
||||
|
||||
+164
@@ -493,6 +493,87 @@ paths:
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/ProfileRevisionConflict" }
|
||||
|
||||
/v1/tenants/{id}/role-dataset:
|
||||
get:
|
||||
summary: The company's role and authority dataset (Rollen- und Befugnisdatensatz), current revision.
|
||||
description: |
|
||||
Served by the `{id}/{sub}` route. User tokens reach their own tenant
|
||||
only (route group `role-dataset.user`); services read with
|
||||
`tenants.read`. A company without a dataset gets revision 0 and an
|
||||
empty dataset. The answer carries the derived state of every
|
||||
deputyship (`wirksam` or `hinterlegt` with reasons, computed now)
|
||||
and the catalogue of functions and decision types.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"200":
|
||||
description: The dataset.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/RoleDatasetState" } }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
put:
|
||||
summary: Save the role dataset (a new revision).
|
||||
description: |
|
||||
Only with the user token of the person saving (`user_token_required`
|
||||
otherwise); `X-Portal-User-*` headers are ignored. The writer must
|
||||
hold management or a document owner function; while no management
|
||||
holder is recorded, the OWNER sign-in role may record management and
|
||||
nothing else (`bootstrap_only`). `recorded_*` and `authorized_*` are
|
||||
set by the registry, never taken from the body; `authorize` lists
|
||||
deputies and standard releases management authorizes with this save.
|
||||
expected_revision is the revision the writer last read (0 for none).
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/RoleDatasetWrite" } }
|
||||
responses:
|
||||
"200":
|
||||
description: Saved (or unchanged).
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/RoleDatasetState" } }
|
||||
"400": { description: "invalid_role_dataset (with path), d02_reference_required, expected_revision_required." }
|
||||
"403": { description: "user_token_required, not_permitted, bootstrap_only, not_authorizer, self_authorization." }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { description: "revision_conflict (with current_revision) or catalogue_outdated (with catalogue_version)." }
|
||||
"413": { description: The document exceeds 256 KiB (too_large). }
|
||||
|
||||
/v1/tenants/{id}/role-dataset/revisions/{rev}:
|
||||
get:
|
||||
summary: One stored revision of the role dataset, as a decision was made under it.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: path, name: rev, required: true, schema: { type: integer, minimum: 1 } }
|
||||
responses:
|
||||
"200":
|
||||
description: The revision.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/RoleDatasetRevision" } }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/role-dataset/resolve:
|
||||
get:
|
||||
summary: Who may decide a decision type now.
|
||||
description: |
|
||||
The deciding function (the company's entry, else the catalogue
|
||||
default), its holders in the given scope and the effective deputies
|
||||
covering the decision type. `rolle_offen` when no function is set or
|
||||
nobody holds it.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
- { in: query, name: decision_type, 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/RoleDatasetResolution" } }
|
||||
"400": { description: "unknown_decision_type or scope_required." }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/managed-services:
|
||||
get:
|
||||
summary: A tenant's managed services (Verwaltete Infrastruktur), oldest first.
|
||||
@@ -2112,6 +2193,89 @@ components:
|
||||
updated_at: { type: string, format: date-time }
|
||||
submitted_by: { type: string }
|
||||
submitted_at: { type: string, format: date-time }
|
||||
RoleDatasetWrite:
|
||||
type: object
|
||||
required: [data, catalogue_version, expected_revision]
|
||||
properties:
|
||||
data: { $ref: "#/components/schemas/RoleDataset" }
|
||||
catalogue_version: { type: string, description: "The catalogue the client read; another one is refused (catalogue_outdated)." }
|
||||
expected_revision: { type: integer, minimum: 0 }
|
||||
authorize: { type: array, items: { type: string }, description: "Ids of deputies and standard releases management authorizes." }
|
||||
RoleDatasetState:
|
||||
type: object
|
||||
required: [tenant_id, revision, catalogue_version, data, derived, catalogue]
|
||||
properties:
|
||||
tenant_id: { type: string, format: uuid }
|
||||
revision: { type: integer, minimum: 0 }
|
||||
catalogue_version: { type: string }
|
||||
updated_by: { type: string, description: "Keycloak sub of the last writer." }
|
||||
updated_at: { type: string, format: date-time }
|
||||
data: { $ref: "#/components/schemas/RoleDataset" }
|
||||
derived:
|
||||
type: object
|
||||
properties:
|
||||
deputies:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
id: { type: string }
|
||||
state: { type: string, enum: [wirksam, hinterlegt] }
|
||||
reasons: { type: array, items: { type: string, enum: [basis_missing, not_yet_valid, expired, authorization_missing] } }
|
||||
catalogue: { type: object, description: "Functions (key, label, sources, per, multiple, external, d02_row), decision types (key, label, default) and document keys." }
|
||||
RoleDatasetRevision:
|
||||
type: object
|
||||
properties:
|
||||
tenant_id: { type: string, format: uuid }
|
||||
revision: { type: integer, minimum: 1 }
|
||||
catalogue_version: { type: string }
|
||||
updated_by: { type: string }
|
||||
updated_at: { type: string, format: date-time }
|
||||
data: { $ref: "#/components/schemas/RoleDataset" }
|
||||
RoleDatasetResolution:
|
||||
type: object
|
||||
properties:
|
||||
revision: { type: integer, minimum: 0 }
|
||||
catalogue_version: { type: string }
|
||||
decision_type: { type: string }
|
||||
function: { type: string }
|
||||
source: { type: string, enum: [company, default] }
|
||||
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]
|
||||
properties:
|
||||
kind: { type: string, enum: [member, external, not_applicable] }
|
||||
sub: { type: string }
|
||||
name: { type: string }
|
||||
organisation: { type: string }
|
||||
contact: { type: string }
|
||||
module_decision_ref: { type: string }
|
||||
RoleDataset:
|
||||
type: object
|
||||
description: |
|
||||
One document per company; sections follow A1 §2.3. Unknown keys are
|
||||
refused at any level. Keys of functions and decision types come from
|
||||
the catalogue (internal/roles).
|
||||
additionalProperties: false
|
||||
properties:
|
||||
assignments: { type: array, maxItems: 500, items: { type: object } }
|
||||
deputies: { type: array, maxItems: 500, items: { type: object } }
|
||||
authority: { type: array, maxItems: 500, items: { type: object } }
|
||||
immediate_authority: { type: array, maxItems: 500, items: { type: object } }
|
||||
standard_releases: { type: array, maxItems: 500, items: { type: object } }
|
||||
editors: { type: array, maxItems: 500, items: { type: object } }
|
||||
critical_contact: { type: array, maxItems: 500, items: { type: object } }
|
||||
CompanyProfileWrite:
|
||||
type: object
|
||||
required: [data, schema_version, expected_revision]
|
||||
|
||||
Reference in new issue
Block a user