ZDDC/zddc/internal/handler/tablehandler.go
ZDDC f196205622 refactor(audit): pre-release cleanup pass
Single audit pass that removes pre-release back-compat, consolidates the
admin-policy decider, and fixes the .zddc write path.

Field removal — acl.allow / acl.deny:
- Drop ACLRules.Allow / Deny struct fields and mergeLegacyACL().
- Remove walker / lookups / validate / decider branches that read them.
- Migrate every test fixture (YAML strings and ACLRules struct literals)
  to acl.permissions: { principal → verb-set }.
- Rewrite both bundled Rego policies (access.rego, access_federal.rego)
  to traverse level.acl.permissions; rewrite parity-test helpers.
- Update create-project form (profile page) to collect permissions
  instead of allow/deny lists.

Admin decider consolidation:
- Delete zddc.CanEditZddc — strict-ancestor rule retired. Subtree admins
  own their own .zddc; the policy decider's IsActiveAdmin short-circuit
  is the single bypass site.
- Migrate tablehandler.ServeTable to AllowActionFromChainP — closes the
  same Forbidden bug already fixed for /browse.html.
- Drop AccessView.EditableParentChoices and treeEntry.CanEdit (always
  true after the retirement). Profile page renders AdminSubtrees
  directly for both lists.
- Drop the excludeLeaf parameter from AdminLevelInChain /
  IsAdminForChain — no production caller passed true.

Dead code removed:
- policy.AllowWriteFromChain (zero production callers, zero tests).
- zddc.AllowedWithChain (zero production callers; tests deleted).

ModeStrict retirement — federal posture is OPA-only:
- Delete cascade_mode.go / cascade_mode_test.go and the ModeStrict
  branches in cascade.go and acl.go.
- Drop --cascade-mode flag, CascadeMode config field, and the
  InternalDecider.Mode field.
- Drop the mode parameter from every cascade helper:
  GrantedVerbsAtLevel, AllowedAction, EffectiveVerbs,
  EffectiveVerbsRange, RoleMembers, MatchesPrincipal,
  MatchingPrincipals, WormZoneGrant, PolicyChain.VisibleStart.
- Strip cascade_mode from /.profile/config and
  /.profile/effective-policy responses.
- Refresh README / ARCHITECTURE.md to describe federal posture as
  "deploy OPA with access_federal.rego" (NIST AC-6); the bundled Rego
  is the parent-deny-is-absolute variant. The in-process Go evaluator
  implements only the commercial cascade.

Legacy redirects + .admin.css fallback:
- Drop /<dir>/.zddc.html → ?file=.zddc redirect and its test.
- Drop ?zip=1 retired comment + legacy test (handled by the
  .zip virtual-URL path; covered by TestServeSubtreeZip).
- Drop .admin.css fallback in profile_assets.go — only .profile.css now.
- Refresh stale "retired" / "back-compat" / "legacy" comment markers.

.zddc write path fix:
- Dispatcher: route only GET/HEAD on .zddc URLs to ServeZddcFile; carve
  .zddc out of the dot-prefix guard so PUT/DELETE/POST reach
  ServeFileAPI. Before this, .zddc writes 405'd at ServeZddcFile and
  the YAML editor's save flow had no live path.
- ServeFileAPI.resolveTargetPath: same .zddc-leaf carve-out so the file
  API accepts the path; intermediate dot dirs (.zddc.d/) stay reserved.
- Listing: compute Writable per-file with ActionAdmin for .zddc
  (matches the file API's gate) instead of ActionWrite for everything.
- Virtual .zddc placeholder: compute Writable via the same
  parentActiveAdmin || ActionAdmin path. Was always false before.
- browse YAML editor canSave: exempt virtual .zddc — the synthetic
  body is designed to materialize on PUT.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 16:28:07 -05:00

288 lines
10 KiB
Go

// Package handler — tablehandler.go: directory-of-YAML table view.
//
// URL convention:
//
// GET /<dir>/<name>.table.html → tables.html, only when <dir>/.zddc
// declares tables: { <name>: <spec-path> }
// AND the spec file exists.
//
// Discovery is .zddc-declarative (no auto-mount on file presence). The
// handler's only jobs are:
//
// 1. Recognize the URL — does <dir>/.zddc declare a table named <name>,
// and does the referenced *.table.yaml spec actually exist? If not,
// fall through to the static-file pipeline.
// 2. Gate on the cascading ACL at the request directory (read action).
// 3. Serve the static tables.html bytes.
//
// All rendering is client-side. The page (built from tables/) detects
// HTTP vs file:// mode, then walks the directory via shared/zddc-source.js
// (HttpDirectoryHandle in HTTP mode, real FileSystemDirectoryHandle in
// file mode), reads .zddc, parses the spec, and renders rows in the
// browser. The server does not pre-parse the spec, list rows, or compute
// per-row "editable" — the client does, and ACL is enforced naturally:
// HTTP-mode reads/writes go through the cascade-aware file API, and
// local-mode reads/writes are bounded by whatever the OS gave the
// FS-Access handle.
package handler
import (
_ "embed"
"log/slog"
"net/http"
"path/filepath"
"strings"
"codeberg.org/VARASYS/ZDDC/zddc/internal/config"
"codeberg.org/VARASYS/ZDDC/zddc/internal/policy"
"codeberg.org/VARASYS/ZDDC/zddc/internal/zddc"
)
//go:embed tables.html
var embeddedTablesHTML []byte
//go:embed default-mdl.table.yaml
var embeddedDefaultMdlTable []byte
//go:embed default-mdl.form.yaml
var embeddedDefaultMdlForm []byte
// DefaultMdlTableYAML returns the embedded default mdl.table.yaml bytes.
// Used by the static-file handler to serve the default spec at
// archive/<party>/mdl.table.yaml when no operator file exists on disk.
func DefaultMdlTableYAML() []byte { return embeddedDefaultMdlTable }
// DefaultMdlFormYAML returns the embedded default mdl.form.yaml bytes.
func DefaultMdlFormYAML() []byte { return embeddedDefaultMdlForm }
// IsDefaultMdlSpec reports whether urlPath is one of the default-MDL
// virtual files served when no operator file exists on disk:
//
// <project>/archive/<party>/mdl/table.yaml
// <project>/archive/<party>/mdl/form.yaml
//
// The MDL files live INSIDE the rows-dir along with row YAMLs so the
// whole directory is self-contained — copying mdl/ moves the spec,
// the form, and all rows together. Returns embedded bytes + true when
// the fallback should fire; nil + false when an operator-supplied
// file exists or the path is not eligible.
func IsDefaultMdlSpec(fsRoot, urlPath string) ([]byte, bool) {
base := strings.ToLower(filepath.Base(urlPath))
var bytes []byte
switch base {
case "table.yaml":
bytes = embeddedDefaultMdlTable
case "form.yaml":
bytes = embeddedDefaultMdlForm
default:
return nil, false
}
if !isAtArchivePartyMdlLevel(fsRoot, urlPath) {
return nil, false
}
// Operator file wins if it exists on disk.
rel := strings.TrimPrefix(filepath.ToSlash(urlPath), "/")
abs := filepath.Join(fsRoot, filepath.FromSlash(rel))
if !strings.HasPrefix(abs, fsRoot+string(filepath.Separator)) && abs != fsRoot {
return nil, false
}
if fileExists(abs) {
return nil, false
}
return bytes, true
}
// IsDefaultMdlSpecAbs is the abs-path-keyed variant of IsDefaultMdlSpec.
// Used by handlers that hold a filesystem path rather than a URL.
// Returns the embedded default bytes + true when absPath is the
// virtual archive/<party>/{mdl.table.yaml, mdl.form.yaml} fallback.
func IsDefaultMdlSpecAbs(fsRoot, absPath string) ([]byte, bool) {
if !strings.HasPrefix(absPath, fsRoot+string(filepath.Separator)) && absPath != fsRoot {
return nil, false
}
rel, err := filepath.Rel(fsRoot, absPath)
if err != nil {
return nil, false
}
urlPath := "/" + filepath.ToSlash(rel)
return IsDefaultMdlSpec(fsRoot, urlPath)
}
// isAtArchivePartyLevel reports whether urlPath refers to a file
// directly under <project>/archive/<party>/ (depth-3 directory). The
// canonical-folder names are case-folded.
func isAtArchivePartyLevel(fsRoot, urlPath string) bool {
rel := strings.Trim(filepath.ToSlash(urlPath), "/")
parts := strings.Split(rel, "/")
// <project>/archive/<party>/<file> = 4 segments
if len(parts) != 4 {
return false
}
return strings.EqualFold(parts[1], "archive")
}
// isAtArchivePartyMdlLevel reports whether urlPath refers to a file
// directly under <project>/archive/<party>/mdl/ (depth-4 directory).
// Used by the default-MDL fallback after the spec/form moved INSIDE
// the rows-dir for self-containment.
func isAtArchivePartyMdlLevel(fsRoot, urlPath string) bool {
rel := strings.Trim(filepath.ToSlash(urlPath), "/")
parts := strings.Split(rel, "/")
// <project>/archive/<party>/mdl/<file> = 5 segments
if len(parts) != 5 {
return false
}
return strings.EqualFold(parts[1], "archive") && strings.EqualFold(parts[3], "mdl")
}
// TableRequest describes a recognized table-system request.
type TableRequest struct {
// Name is the table's URL stem (the key declared in .zddc tables).
Name string
// SpecPath is the absolute filesystem path to the *.table.yaml.
// Validated to exist at recognition time.
SpecPath string
// Dir is the absolute path to the request directory (where the
// .zddc declared the table).
Dir string
}
// tableRowsRedirect reports the canonical /<dir>/table.html URL to
// redirect to when (urlPath) names a directory that contains a
// table.yaml (or matches the default-MDL fallback). Returns "" when
// no redirect should fire.
//
// Recognition reuses RecognizeTableRequest by synthesizing the
// equivalent <urlPath>table.html and asking the recognizer whether
// it's a real (or default-MDL) table. Single source of truth for
// validation.
func tableRowsRedirect(fsRoot, urlPath string) string {
// urlPath is the directory request — e.g. "/proj/archive/Acme/mdl/".
if urlPath == "" || urlPath == "/" {
return ""
}
if !strings.HasSuffix(urlPath, "/") {
urlPath += "/"
}
synthesized := urlPath + "table.html"
tr := RecognizeTableRequest(fsRoot, http.MethodGet, synthesized)
if tr == nil {
return ""
}
// Default-MDL case (no on-disk table.yaml): follow the slash/no-
// slash convention — slash form serves browse, no-slash serves
// tables (handled by the dispatcher). Redirecting here would
// override the convention and force the user into the table view
// from any /<party>/mdl/ click.
if !fileExists(tr.SpecPath) {
return ""
}
return synthesized
}
// RecognizeTableRequest classifies r as a table-system request, or
// returns nil if it falls through to other handlers. Discovery is
// presence-based and self-contained: a /<dir>/table.html URL fires
// when <dir>/table.yaml exists on disk, or when the default-MDL
// fallback at archive/<party>/mdl/ applies.
//
// The spec, the row-edit form, and all rows live together in <dir>.
// Copying <dir> elsewhere copies everything needed to re-host the
// table — that's the whole point of the in-dir layout.
//
// The table's "name" is the directory's basename (so the URL
// /<parent>/mdl/table.html names the "mdl" table, with rows in mdl/).
//
// Methods other than GET return nil — the table is read-only at the
// URL level. Writes go through the file API directly.
func RecognizeTableRequest(fsRoot, method, urlPath string) *TableRequest {
if method != http.MethodGet {
return nil
}
if !strings.HasSuffix(urlPath, "/table.html") && urlPath != "/table.html" {
return nil
}
// Strip /table.html — what remains is the rows-dir.
rel := strings.TrimSuffix(strings.TrimPrefix(urlPath, "/"), "/table.html")
rel = strings.TrimSuffix(rel, "table.html") // handles "/table.html" at root → ""
rel = strings.Trim(rel, "/")
if rel == "" {
// /table.html at root has no rows-dir to name.
return nil
}
dirAbs := filepath.Join(fsRoot, filepath.FromSlash(rel))
if !strings.HasPrefix(dirAbs, fsRoot+string(filepath.Separator)) && dirAbs != fsRoot {
return nil
}
name := filepath.Base(dirAbs)
specAbs := filepath.Join(dirAbs, "table.yaml")
// Presence-based discovery: <dir>/table.yaml on disk.
if fileExists(specAbs) {
return &TableRequest{Name: name, SpecPath: specAbs, Dir: dirAbs}
}
// Default-MDL virtual-spec fallback at archive/<party>/mdl/. The
// spec bytes come from IsDefaultMdlSpec via the static-file
// dispatcher when no on-disk file exists at that path; the rows-dir
// itself doesn't need to exist either (fully virtual archive).
if isAtArchivePartyMdlDir(fsRoot, dirAbs) {
return &TableRequest{Name: "mdl", SpecPath: specAbs, Dir: dirAbs}
}
return nil
}
// isAtArchivePartyMdlDir reports whether dirAbs is exactly
// <fsRoot>/<project>/archive/<party>/mdl. Used by the default-MDL
// fallback to recognize the virtual rows-dir whether or not it
// exists on disk.
func isAtArchivePartyMdlDir(fsRoot, dirAbs string) bool {
rel, err := filepath.Rel(fsRoot, dirAbs)
if err != nil {
return false
}
rel = filepath.ToSlash(rel)
if strings.HasPrefix(rel, "../") || rel == ".." || rel == "." {
return false
}
parts := strings.Split(rel, "/")
if len(parts) != 4 {
return false
}
return strings.EqualFold(parts[1], "archive") && strings.EqualFold(parts[3], "mdl")
}
// isNotExistError reports whether err indicates a missing file. Local
// helper to avoid pulling errors.Is into the handler package.
func isNotExistError(err error) bool {
return err != nil && strings.Contains(err.Error(), "no such file or directory")
}
// ServeTable serves the static tables.html bytes for a recognized
// request. ACL gate is the read action at the request directory; on
// allow, the embedded HTML is written verbatim. The client takes over
// from there — see tables/js/main.js.
func ServeTable(cfg config.Config, req *TableRequest, w http.ResponseWriter, r *http.Request) {
p := PrincipalFromContext(r)
decider := DeciderFromContext(r)
chain, err := zddc.EffectivePolicy(cfg.Root, req.Dir)
if err != nil {
slog.Warn("table: policy error", "path", req.Dir, "err", err)
}
if allowed, _ := policy.AllowActionFromChainP(r.Context(), decider, chain, p, r.URL.Path, policy.ActionRead); !allowed {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
if len(embeddedTablesHTML) == 0 {
http.Error(w, "table renderer not built into this binary", http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(embeddedTablesHTML)
}