ZDDC/zddc/internal/zddc/writer_test.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

150 lines
4.1 KiB
Go

package zddc
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestWriteFileRoundTrip(t *testing.T) {
root := t.TempDir()
in := ZddcFile{
Title: "Greenfield Substation",
ACL: ACLRules{
Permissions: map[string]string{
"*@varasys.io": "rwcd",
"intern@varasys.io": "",
},
},
Admins: []string{"alice@varasys.io"},
}
if err := WriteFile(root, in); err != nil {
t.Fatalf("WriteFile: %v", err)
}
out, err := ParseFile(filepath.Join(root, ".zddc"))
if err != nil {
t.Fatalf("ParseFile: %v", err)
}
if out.Title != in.Title {
t.Errorf("Title = %q, want %q", out.Title, in.Title)
}
if out.ACL.Permissions["*@varasys.io"] != "rwcd" {
t.Errorf("ACL.Permissions[*@varasys.io] = %q, want %q", out.ACL.Permissions["*@varasys.io"], "rwcd")
}
if v, ok := out.ACL.Permissions["intern@varasys.io"]; !ok || v != "" {
t.Errorf("ACL.Permissions[intern@varasys.io] = (%q, ok=%v), want (\"\", true)", v, ok)
}
if len(out.Admins) != 1 || out.Admins[0] != "alice@varasys.io" {
t.Errorf("Admins = %v, want [alice@varasys.io]", out.Admins)
}
}
func TestWriteFileAtomicNoTempLeftBehind(t *testing.T) {
root := t.TempDir()
if err := WriteFile(root, ZddcFile{Title: "a"}); err != nil {
t.Fatalf("WriteFile: %v", err)
}
entries, err := os.ReadDir(root)
if err != nil {
t.Fatalf("ReadDir: %v", err)
}
for _, e := range entries {
if strings.HasSuffix(e.Name(), ".tmp") {
t.Errorf("temp file left behind: %s", e.Name())
}
}
}
func TestWriteFileInvalidatesCache(t *testing.T) {
root := t.TempDir()
sub := filepath.Join(root, "project")
if err := os.MkdirAll(sub, 0o755); err != nil {
t.Fatalf("mkdir: %v", err)
}
// Prime the cache with an empty chain.
if _, err := EffectivePolicy(root, sub); err != nil {
t.Fatalf("prime cache: %v", err)
}
if err := WriteFile(sub, ZddcFile{
ACL: ACLRules{Permissions: map[string]string{"alice@example.com": "rwcd"}},
}); err != nil {
t.Fatalf("WriteFile: %v", err)
}
// After write the cache must reflect the new content.
chain, err := EffectivePolicy(root, sub)
if err != nil {
t.Fatalf("EffectivePolicy: %v", err)
}
if !chain.HasAnyFile {
t.Fatal("HasAnyFile = false; cache not invalidated")
}
leaf := chain.Levels[len(chain.Levels)-1]
if got := leaf.ACL.Permissions["alice@example.com"]; got != "rwcd" {
t.Errorf("leaf permissions[alice] = %q, want %q", got, "rwcd")
}
}
func TestWriteFileOverwritePreservesOriginalOnFailure(t *testing.T) {
// We can't easily simulate a rename failure portably, but we can at
// least confirm that the happy-path overwrite produces the new
// content (so the rename worked) and that the previous content is
// gone (no merge or append).
root := t.TempDir()
if err := WriteFile(root, ZddcFile{Title: "first"}); err != nil {
t.Fatalf("first write: %v", err)
}
if err := WriteFile(root, ZddcFile{Title: "second"}); err != nil {
t.Fatalf("second write: %v", err)
}
out, err := ParseFile(filepath.Join(root, ".zddc"))
if err != nil {
t.Fatalf("parse: %v", err)
}
if out.Title != "second" {
t.Errorf("Title = %q, want %q", out.Title, "second")
}
}
func TestDeleteFile(t *testing.T) {
root := t.TempDir()
if err := WriteFile(root, ZddcFile{Title: "a"}); err != nil {
t.Fatalf("WriteFile: %v", err)
}
if _, err := os.Stat(filepath.Join(root, ".zddc")); err != nil {
t.Fatalf("file should exist before delete: %v", err)
}
// Prime the cache so we can verify invalidation post-delete.
if _, err := EffectivePolicy(root, root); err != nil {
t.Fatalf("prime: %v", err)
}
if err := DeleteFile(root); err != nil {
t.Fatalf("DeleteFile: %v", err)
}
if _, err := os.Stat(filepath.Join(root, ".zddc")); !os.IsNotExist(err) {
t.Errorf("file should be gone after delete: err=%v", err)
}
chain, err := EffectivePolicy(root, root)
if err != nil {
t.Fatalf("EffectivePolicy: %v", err)
}
if chain.HasAnyFile {
t.Error("HasAnyFile should be false after delete; cache not invalidated")
}
}
func TestDeleteFileMissing(t *testing.T) {
root := t.TempDir()
// No .zddc has been written; delete must be a no-op.
if err := DeleteFile(root); err != nil {
t.Errorf("DeleteFile on missing file = %v, want nil", err)
}
}