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"` // CompanyRules are rules the company sets for its own decisions. A // dataset without them has every rule off. CompanyRules *CompanyRules `json:"company_rules,omitempty"` } // CompanyRules (docgen#4 Nr. 31, AK-R3-030): rules a company switches on in // its role dataset, maintained by whoever maintains the dataset (AM-3) and // historised with its revisions. A rule not set is off; "not set" never // counts as switched on. type CompanyRules struct { // SeparateApproval: "Festlegung und Freigabe durch verschiedene // Personen". When on, nobody approves what they determined themselves // (Werkmeister checks it); when off, the same authorised person may do // both. SeparateApproval bool `json:"separate_approval"` Stamps } // 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 } // checkDeciding: a known function the company can hold. Under BM-4 only the // company decides, so a function held only outside it decides nothing. func checkDeciding(path, function string) *Error { f, ok := FunctionByKey(function) if !ok { return invalid(path+".function", "unknown function %q", function) } if f.External == ExternalOnly { return &Error{Status: http.StatusBadRequest, Code: "external_decides", Path: path + ".function", Message: "a function held only outside the company decides nothing (BM-4)"} } return nil } 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 err := checkDeciding(path, a.Function); err != nil { return err } if slices.Contains(FirstReleases, a.DecisionType) && a.Function != Management { return &Error{Status: http.StatusBadRequest, Code: "first_release_management", Path: path + ".function", Message: "the first releases of R1-D01 and R1-D02 are management's (A2 §1)"} } 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 err := checkDeciding(path, a.Function); err != nil { return err } 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 } // BootstrapRole is the sign-in role that may make the first entry (S0 spec §6.3, // Q3): CXO, the management sign-in role (decided by Sharang 2026-10-26). Every // tenant's first admin is IT_ADMIN, the technical admin, who does not name // management. It is the only place a sign-in role counts here. const BootstrapRole = "CXO" // MayWrite reports whether w may save the dataset at all, before looking at // what the save changes: B7 management and document owners, or, until // management is recorded, the CXO sign-in role (Q3). The server asks it // before comparing revisions, so a person without the right learns that, // not that someone else changed the dataset. func MayWrite(current *Dataset, w Writer) *Error { if maintains(current, w) || (!current.hasManagementHolder() && slices.Contains(w.OrgRoles, BootstrapRole)) { return nil } return &Error{Status: http.StatusForbidden, Code: "not_permitted", Message: "the dataset is maintained by management and document owners (B7)"} } // maintains: B7, management and document owners maintain the dataset. func maintains(current *Dataset, w Writer) bool { return current.Holds(w.Sub, Management) || current.Holds(w.Sub, DocumentOwner) } // 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 } if err := MayWrite(current, w); err != nil { return nil, err } if !maintains(current, w) { // 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 CXO sign-in role may only record management"} } } 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} } } // The rules keep their stamps while unchanged; a change is recorded now. if incoming.CompanyRules != nil { r := *incoming.CompanyRules if old := prev.CompanyRules; old != nil && old.SeparateApproval == r.SeparateApproval { r.Stamps = old.Stamps } else { r.Stamps = Stamps{RecordedBy: w.Sub, RecordedAt: &at} } out.CompanyRules = &r } 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{} } if ds.CompanyRules != nil { r := *ds.CompanyRules r.Stamps = Stamps{} c.CompanyRules = &r } return &c } // SeparateApproval: the company rule "Festlegung und Freigabe durch // verschiedene Personen" is on. func (ds *Dataset) SeparateApproval() bool { return ds != nil && ds.CompanyRules != nil && ds.CompanyRules.SeparateApproval } 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 } h, err := ds.holdersOf(fn, scope, now, dt) if err != nil { return nil, err } res.Function, res.Source = fn, src res.AnyMember, res.Holders, res.Deputies, res.Status = h.AnyMember, h.Holders, h.Deputies, h.Status return res, nil } // FunctionHolders answers "who holds this function now" (RBAC plan step 5: // a Werkmeister step names a function). Deputies are the effective ones of // the function, whatever decision types they cover; they stand in for // decisions, so a step that is worked rather than decided counts only the // holders. type FunctionHolders struct { Function string `json:"function"` Label string `json:"label"` AnyMember bool `json:"any_member,omitempty"` Holders []Holder `json:"holders"` Deputies []ResolutionDeputy `json:"deputies"` Status string `json:"status"` } // HoldersOf finds the holders of function fn in the given scope and its // effective deputies. func (ds *Dataset) HoldersOf(fn string, scope Scope, now time.Time) (*FunctionHolders, *Error) { return ds.holdersOf(fn, scope, now, "") } // holdersOf: the assignments of fn matching scope, and the effective // deputies of fn (covering dt, when dt is set). func (ds *Dataset) holdersOf(fn string, scope Scope, now time.Time, dt string) (*FunctionHolders, *Error) { f, ok := FunctionByKey(fn) if !ok { return nil, &Error{Status: http.StatusBadRequest, Code: "unknown_function", Message: fmt.Sprintf("unknown function %q", fn)} } res := &FunctionHolders{Function: fn, Label: f.Label, Holders: []Holder{}, Deputies: []ResolutionDeputy{}, Status: StatusOpen} if f.AnyMember { res.AnyMember, res.Status = true, StatusFilled return res, nil } if f.Per != PerCompany { if err := checkScope("scope", f, &scope); err != nil { err.Code = "scope_required" return nil, err } } if ds == nil { return res, nil } match := func(s *Scope) bool { return f.Per == PerCompany || scopeKey(s) == scopeKey(&scope) } notApplicable := false for _, a := range ds.Assignments { 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) || (dt != "" && !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) == "[]" }