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
276 lines
9.1 KiB
Go
276 lines
9.1 KiB
Go
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)
|
|
}
|