Files
tenant-registry/internal/server/role_dataset.go
Sharang ParnerkarandClaude Opus 5.5 bef4e31c05
ci / shared (pull_request) Successful in 11s
ci / test (pull_request) Failing after 37s
ci / image (pull_request) Skipped
feat(roles): functions of owner decision Nr. 2 in the catalogue
Catalogue r1-2026-11-16.1 adds the functions owner decision Nr. 2
(docgen#6 17878, 18011) names and that no R1 function already covers:
CVD-Verantwortung and Veröffentlichungsverantwortung (R5), Meldefreigabe,
Fristführung, Vorabprüfung, Weitergabe von Informationen and
Datenschutzfunktion (R2), and the R1 functions Erstzuordnung, Eskalation
and Einsichtsprotokollkontrolle. External holders as proposed in 18110
K-4. The safety check and product measures wait for the owner (K-1, K-2).

GET /role-dataset now names the current catalogue as catalogue_version
and the stored one as stored_catalogue_version. It named the stored one,
which the portal sends back on save: after any catalogue change every
save of an existing dataset was refused as catalogue_outdated, and
reloading answered the same version again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014aRnCGqELxoix5TfpX8Ejf
2026-11-16 12:48:02 +01:00

355 lines
12 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
// GET /v1/tenants/{id}/role-dataset/rules the company rules now (docgen#4 Nr. 31)
//
// 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 is the catalogue the answer is edited against: the
// current one, which a save must name. The stored dataset may have been
// saved against an older one (StoredCatalogueVersion); answering that
// instead would refuse every save after a catalogue change for good,
// since reloading answered it again.
CatalogueVersion string `json:"catalogue_version"`
StoredCatalogueVersion string `json:"stored_catalogue_version,omitempty"`
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 roleDatasetHoldersResp struct {
Revision int `json:"revision"`
CatalogueVersion string `json:"catalogue_version"`
*roles.FunctionHolders
}
type roleDatasetRulesResp struct {
Revision int `json:"revision"`
CatalogueVersion string `json:"catalogue_version"`
// SeparateApproval: "Festlegung und Freigabe durch verschiedene
// Personen" is on. Off when the company never set it.
SeparateApproval bool `json:"separate_approval"`
RecordedAt *time.Time `json:"recorded_at,omitempty"`
}
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.StoredCatalogueVersion, 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
var prev *roles.Dataset
if stored != nil {
currentRev, prev = stored.Revision, current
}
writer := roles.Writer{Sub: p.Subject, OrgRoles: p.OrgRoles}
// Who may save comes before the revision: someone without the right gets
// not_permitted, also from a stale page.
if rerr := roles.MayWrite(prev, writer); rerr != nil {
writeJSON(w, rerr.Status, rerr)
return
}
if *in.ExpectedRevision != currentRev {
s.writeRoleDatasetConflict(w, currentRev)
return
}
at := s.now()
next, rerr := roles.Prepare(prev, incoming, in.Authorize, writer, 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)
}
// roleDatasetHolders is GET /v1/tenants/{id}/role-dataset/holders
// ?function=…[&document=…|&product=…|&area=…]: who holds the function now
// (RBAC plan step 5, a Werkmeister step that names a function).
func (s *Server) roleDatasetHolders(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
stored, ds, err := s.currentRoleDataset(ctx, t.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
q := r.URL.Query()
res, rerr := ds.HoldersOf(q.Get("function"), roles.Scope{Document: q.Get("document"), Product: q.Get("product"), Area: q.Get("area")}, s.now())
if rerr != nil {
writeJSON(w, rerr.Status, rerr)
return
}
out := roleDatasetHoldersResp{CatalogueVersion: roles.CatalogueVersion, FunctionHolders: res}
if stored != nil {
out.Revision, out.CatalogueVersion = stored.Revision, stored.CatalogueVersion
}
writeJSON(w, http.StatusOK, out)
}
// roleDatasetRules is GET /v1/tenants/{id}/role-dataset/rules: the
// company rules now, for a Werkmeister check that applies only while a rule
// is on.
func (s *Server) roleDatasetRules(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
}
out := roleDatasetRulesResp{CatalogueVersion: roles.CatalogueVersion, SeparateApproval: ds.SeparateApproval()}
if stored != nil {
out.Revision, out.CatalogueVersion = stored.Revision, stored.CatalogueVersion
}
if ds.CompanyRules != nil {
out.RecordedAt = ds.CompanyRules.RecordedAt
}
writeJSON(w, http.StatusOK, out)
}
// resolveRoleDataset is GET /v1/tenants/{id}/role-dataset/resolve
// ?decision_type=…[&document=…|&product=…|&area=…].
func (s *Server) resolveRoleDataset(w http.ResponseWriter, r *http.Request) {
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)
}