ZDDC/zddc/internal/zddc/walker.go
ZDDC 54dff4dcd3 feat(zddc): standard roles (document_controller, project_team) + role union/reset
Answers "can roles reset as well as add?" — yes, both now.

Role membership UNIONS across the cascade:
  - A deeper .zddc that defines an inherited role again with one
    extra member ADDS that member (was: deepest definition shadowed
    the ancestor's entirely).
  - New `reset: true` on a role definition breaks the union — that
    level's members are authoritative, ancestor definitions above
    are excluded; descendants below still union on top. Use it to
    give a project its own team independent of a deployment-wide
    default.
  - lookupRoleMembers / RoleMembers reworked: walk deep→shallow,
    union members, stop at the first reset:true; finally fold in
    chain.Embedded.Roles as the baseline so a role declared only in
    defaults.zddc.yaml is "defined" (and a deployment's on-disk
    redefinition unions on top).

Admin checks are now role-aware:
  - IsSubtreeAdmin / CanEditZddc's strict-ancestor scan use
    MatchesPrincipal instead of MatchesPattern, so `admins:
    [document_controller]` resolves to the role's members. The
    strict-ancestor scan resolves roles only up to level i, so a
    role defined at the deepest level (= dirPath) never confers
    self-edit rights.

Two standard roles ship in defaults.zddc.yaml (empty members — a
fresh deployment grants nothing until they're populated):

  document_controller — files into the WORM zones. Gets:
    - rw at the project level (read + overwrite-existing; NOT c, so
      it can't make arbitrary folders)
    - rwc at archive/ (can create party subfolders)
    - subtree-admin at working/ and staging/ (full create + manage,
      including taking over a fenced per-user home) — scoped HERE,
      not at the project root, so the WORM constraint still binds
      it in archive/<party>/received|issued
    - listed in worm: on received/ and issued/ → write-once-create
      survives the WORM mask

  project_team — read-only across the project. The per-user
    working home's fenced auto-own .zddc (rwcda for the creator)
    wins via deepest-match, so "read-only except what I own" falls
    out of the cascade with no special rule. Inside received/issued
    their r is preserved (worm: doesn't strip read).

archive/<party>/ gains `auto_own: true` (UNFENCED) so whoever
creates a party subtree (normally the doc controller) owns it and
can set up that counterparty's .zddc afterward — without fencing,
project_team:r still cascades through to received/issued.

Tests: roles_test (union + reset), standardroles_test (the
doc-controller scoped-create matrix + project-team read-only-except-
owned), ensure_test updated for the new party-folder auto-own.
fileapi_test's WORM doc-controller test already uses worm: [role].
All Go + 248 Playwright tests green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 10:17:46 -05:00

209 lines
5.5 KiB
Go

package zddc
import (
"strings"
)
// matchGlob looks up a path segment in a paths: map. Literal
// (case-insensitive) match first; falls back to a "*" segment-
// wildcard key if present. Returns nil when neither hits.
//
// Phase 2: single-segment globs only. Multi-segment keys (a/b) are
// rejected at the schema level and never reach this lookup.
func matchGlob(m map[string]ZddcFile, seg string) *ZddcFile {
if m == nil {
return nil
}
// Fast path: exact key match (case-sensitive — operator-controlled).
if v, ok := m[seg]; ok {
return &v
}
// Case-insensitive literal match for canonical-folder ergonomics
// (operator writes `archive:`; on-disk dir may be `Archive`).
lower := strings.ToLower(seg)
for k, v := range m {
if k == "*" {
continue
}
if strings.ToLower(k) == lower {
return &v
}
}
// Wildcard fallback.
if v, ok := m["*"]; ok {
return &v
}
return nil
}
// mergeOverlay composes two ZddcFile values into one. `top` overrides
// `base` per-field. Maps merge key-by-key (top wins on key clash);
// scalar fields take top's value when non-zero (allowing base to fill
// in unset fields).
//
// The intended use is a stack of contributions from lowest to highest
// specificity, applied in order:
//
// merged = empty
// for c in ancestor_virtual_contributions { // lowest specificity first
// merged = mergeOverlay(merged, c)
// }
// merged = mergeOverlay(merged, on_disk_at_this_level)
//
// Each successive overlay overrides what came before for the same key.
func mergeOverlay(base, top ZddcFile) ZddcFile {
out := base
if top.Title != "" {
out.Title = top.Title
}
if top.AppsPubKey != "" {
out.AppsPubKey = top.AppsPubKey
}
if top.CreatedBy != "" {
out.CreatedBy = top.CreatedBy
}
if top.Inherit != nil {
out.Inherit = top.Inherit
}
if top.DefaultTool != "" {
out.DefaultTool = top.DefaultTool
}
if top.AutoOwn != nil {
out.AutoOwn = top.AutoOwn
}
if top.AutoOwnFenced != nil {
out.AutoOwnFenced = top.AutoOwnFenced
}
if top.DropTarget != nil {
out.DropTarget = top.DropTarget
}
// Worm: presence (non-nil, even empty) marks the WORM zone.
// Concat-dedupe across levels (a deeper .zddc adds controllers);
// preserve a non-nil empty slice so `worm: []` survives the
// overlay.
if top.Worm != nil {
out.Worm = mergeStringSlicePreserveEmpty(out.Worm, top.Worm)
}
if top.Virtual != nil {
out.Virtual = top.Virtual
}
out.AvailableTools = mergeStringSlice(out.AvailableTools, top.AvailableTools)
out.Admins = mergeStringSlice(out.Admins, top.Admins)
out.ACL.Allow = mergeStringSlice(out.ACL.Allow, top.ACL.Allow)
out.ACL.Deny = mergeStringSlice(out.ACL.Deny, top.ACL.Deny)
if top.ACL.Inherit != nil {
out.ACL.Inherit = top.ACL.Inherit
}
out.ACL.Permissions = mergeStringMap(out.ACL.Permissions, top.ACL.Permissions)
out.Apps = mergeStringMap(out.Apps, top.Apps)
out.Tables = mergeStringMap(out.Tables, top.Tables)
out.Display = mergeStringMap(out.Display, top.Display)
// Roles: per-name merge (top wins on name clash). This combines
// the on-disk .zddc at a level with any virtual contributions
// from ancestor paths: at the same level. Cross-LEVEL role
// membership union (and the reset flag) is handled at lookup
// time by lookupRoleMembers, not here.
if len(top.Roles) > 0 {
if out.Roles == nil {
out.Roles = make(map[string]Role, len(top.Roles))
} else {
merged := make(map[string]Role, len(out.Roles)+len(top.Roles))
for k, v := range out.Roles {
merged[k] = v
}
out.Roles = merged
}
for k, v := range top.Roles {
out.Roles[k] = v
}
}
// Paths: top entirely replaces base if set. Recursive descent of
// the walker is what threads ancestor Paths through to the right
// level — merging Paths maps themselves at this layer would
// double-apply.
if len(top.Paths) > 0 {
out.Paths = top.Paths
}
return out
}
func mergeStringMap(base, top map[string]string) map[string]string {
if len(top) == 0 {
return base
}
if len(base) == 0 {
out := make(map[string]string, len(top))
for k, v := range top {
out[k] = v
}
return out
}
out := make(map[string]string, len(base)+len(top))
for k, v := range base {
out[k] = v
}
for k, v := range top {
out[k] = v
}
return out
}
// mergeStringSlicePreserveEmpty is mergeStringSlice but always returns
// a non-nil result when top is non-nil — so an empty `worm: []` in a
// .zddc still marks the WORM zone after the overlay. Caller is
// expected to only invoke this when top != nil.
func mergeStringSlicePreserveEmpty(base, top []string) []string {
seen := make(map[string]struct{}, len(base)+len(top))
out := make([]string, 0, len(base)+len(top))
for _, v := range base {
if _, ok := seen[v]; ok {
continue
}
seen[v] = struct{}{}
out = append(out, v)
}
for _, v := range top {
if _, ok := seen[v]; ok {
continue
}
seen[v] = struct{}{}
out = append(out, v)
}
return out
}
func mergeStringSlice(base, top []string) []string {
if len(top) == 0 {
return base
}
if len(base) == 0 {
out := make([]string, len(top))
copy(out, top)
return out
}
// Concatenate with dedupe (preserve order: base first, then
// top entries that weren't already in base).
seen := make(map[string]struct{}, len(base)+len(top))
out := make([]string, 0, len(base)+len(top))
for _, v := range base {
if _, ok := seen[v]; ok {
continue
}
seen[v] = struct{}{}
out = append(out, v)
}
for _, v := range top {
if _, ok := seen[v]; ok {
continue
}
seen[v] = struct{}{}
out = append(out, v)
}
return out
}