ZDDC/zddc/internal/handler/directory_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

239 lines
8.6 KiB
Go

package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"codeberg.org/VARASYS/ZDDC/zddc/internal/config"
"codeberg.org/VARASYS/ZDDC/zddc/internal/zddc"
)
// TestServeDirectoryRootIsPublic asserts that the landing page (the root
// directory listing) is reachable by anyone, including anonymous callers
// whose email is empty AND whose access would be denied by a restrictive
// root .zddc. Per-project filtering inside fs.ListDirectory still hides
// directories the caller can't reach (separately verified below).
//
// The behavior was changed when "Everyone needs to have access to the
// landing page" became the explicit requirement; this test is the
// regression guard.
func TestServeDirectoryRootIsPublic(t *testing.T) {
root := t.TempDir()
// Restrictive root .zddc — only admin@example.com is allowed by ACL,
// nothing else. A user without that email would have been 403'd before
// the bypass.
if err := os.WriteFile(filepath.Join(root, ".zddc"),
[]byte("admins:\n - admin@example.com\nacl:\n permissions:\n admin@example.com: rwcd\n"),
0o644); err != nil {
t.Fatalf("write root .zddc: %v", err)
}
// One project visible to everyone, one only to admin.
for _, name := range []string{"PublicProj", "PrivateProj"} {
if err := os.MkdirAll(filepath.Join(root, name), 0o755); err != nil {
t.Fatalf("mkdir %s: %v", name, err)
}
}
if err := os.WriteFile(filepath.Join(root, "PublicProj", ".zddc"),
[]byte("acl:\n permissions:\n \"*\": rwcd\n"), 0o644); err != nil {
t.Fatalf("write PublicProj .zddc: %v", err)
}
if err := os.WriteFile(filepath.Join(root, "PrivateProj", ".zddc"),
[]byte("acl:\n permissions:\n admin@example.com: rwcd\n"), 0o644); err != nil {
t.Fatalf("write PrivateProj .zddc: %v", err)
}
cfg := config.Config{Root: root, EmailHeader: "X-Auth-Request-Email"}
t.Run("anonymous JSON GET / does not 403", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("Accept", "application/json")
// Anonymous: empty email in context.
req = req.WithContext(context.WithValue(req.Context(), EmailKey, ""))
rec := httptest.NewRecorder()
ServeDirectory(cfg, nil, rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (root is public); body = %s",
rec.Code, rec.Body.String())
}
})
t.Run("anonymous JSON GET / hides private projects", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("Accept", "application/json")
req = req.WithContext(context.WithValue(req.Context(), EmailKey, ""))
rec := httptest.NewRecorder()
ServeDirectory(cfg, nil, rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", rec.Code, rec.Body.String())
}
var entries []map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &entries); err != nil {
t.Fatalf("invalid JSON: %v\n%s", err, rec.Body.String())
}
names := map[string]bool{}
for _, e := range entries {
if n, ok := e["name"].(string); ok {
names[n] = true
}
}
if !names["PublicProj/"] {
t.Errorf("PublicProj missing from anonymous listing: %v", names)
}
if names["PrivateProj/"] {
t.Errorf("PrivateProj leaked to anonymous listing: %v", names)
}
})
t.Run("admin JSON GET / sees both projects", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("Accept", "application/json")
req = req.WithContext(context.WithValue(req.Context(), EmailKey, "admin@example.com"))
rec := httptest.NewRecorder()
ServeDirectory(cfg, nil, rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("admin status = %d, want 200", rec.Code)
}
var entries []map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &entries); err != nil {
t.Fatalf("invalid JSON: %v", err)
}
if len(entries) != 2 {
t.Errorf("admin should see both projects; got %d", len(entries))
}
})
t.Run("anonymous still gets 403 on private subdirectory", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/PrivateProj/", nil)
req.Header.Set("Accept", "application/json")
req = req.WithContext(context.WithValue(req.Context(), EmailKey, ""))
rec := httptest.NewRecorder()
ServeDirectory(cfg, nil, rec, req)
if rec.Code != http.StatusForbidden {
t.Errorf("private subdir for anonymous: status = %d, want 403", rec.Code)
}
})
}
// TestServeDirectoryRedirectsTableRowsDir asserts that an HTML GET on a
// directory containing a table.yaml bounces to that dir's table.html URL
// (in-dir convention: /<dir>/table.html serves the table view, the row
// YAMLs are siblings of table.yaml). JSON GETs fall through to the
// listing so the table client can still enumerate row files.
func TestServeDirectoryRedirectsTableRowsDir(t *testing.T) {
root := t.TempDir()
mdlDir := filepath.Join(root, "Working", "MDL")
if err := os.MkdirAll(mdlDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(mdlDir, "table.yaml"),
[]byte(sampleTableSpec), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(mdlDir, "form.yaml"),
[]byte(sampleRowFormSpec), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, "Working", ".zddc"), []byte(`acl:
permissions:
"*@example.com": rwcda
`), 0o644); err != nil {
t.Fatal(err)
}
zddc.InvalidateCache(root)
cfg := config.Config{Root: root, EmailHeader: "X-Auth-Request-Email"}
t.Run("HTML GET on dir with table.yaml redirects to table.html", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/Working/MDL/", nil)
req.Header.Set("Accept", "text/html")
req = req.WithContext(context.WithValue(req.Context(), EmailKey, "casey@example.com"))
rec := httptest.NewRecorder()
ServeDirectory(cfg, nil, rec, req)
if rec.Code != http.StatusFound {
t.Fatalf("status = %d, want 302; body = %s", rec.Code, rec.Body.String())
}
if got, want := rec.Header().Get("Location"), "/Working/MDL/table.html"; got != want {
t.Errorf("Location = %q, want %q", got, want)
}
})
t.Run("JSON GET on dir with table.yaml falls through to listing", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/Working/MDL/", nil)
req.Header.Set("Accept", "application/json")
req = req.WithContext(context.WithValue(req.Context(), EmailKey, "casey@example.com"))
rec := httptest.NewRecorder()
ServeDirectory(cfg, nil, rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", rec.Code, rec.Body.String())
}
if ct := rec.Header().Get("Content-Type"); ct != "application/json" {
t.Errorf("Content-Type = %q, want application/json", ct)
}
})
t.Run("HTML GET on plain dir is not redirected", func(t *testing.T) {
// Sibling dir without a table.yaml — no redirect.
if err := os.MkdirAll(filepath.Join(root, "Working", "Other"), 0o755); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodGet, "/Working/Other/", nil)
req.Header.Set("Accept", "text/html")
req = req.WithContext(context.WithValue(req.Context(), EmailKey, "casey@example.com"))
rec := httptest.NewRecorder()
ServeDirectory(cfg, nil, rec, req)
if rec.Code == http.StatusFound {
t.Fatalf("got 302 to %q for non-table dir", rec.Header().Get("Location"))
}
})
}
// TestServeDirectoryDefaultMdlNoRedirect covers the default-MDL case:
// when no on-disk table.yaml exists, archive/<party>/mdl/ (slash form)
// no longer redirects to mdl/table.html. Per the slash/no-slash
// convention, the slash form is the browse view; the no-slash form
// /Project/archive/Acme/mdl serves the tables app via the dispatcher.
// User-declared tables with a real table.yaml on disk DO still
// redirect (see TestServeDirectoryRedirectsRealTable).
func TestServeDirectoryDefaultMdlNoRedirect(t *testing.T) {
root := t.TempDir()
if err := os.WriteFile(filepath.Join(root, ".zddc"),
[]byte("acl:\n permissions:\n \"*@example.com\": rwcda\n"), 0o644); err != nil {
t.Fatal(err)
}
mdlDir := filepath.Join(root, "Project", "archive", "Acme", "mdl")
if err := os.MkdirAll(mdlDir, 0o755); err != nil {
t.Fatal(err)
}
zddc.InvalidateCache(root)
cfg := config.Config{Root: root, EmailHeader: "X-Auth-Request-Email"}
req := httptest.NewRequest(http.MethodGet, "/Project/archive/Acme/mdl/", nil)
req.Header.Set("Accept", "text/html")
req = req.WithContext(context.WithValue(req.Context(), EmailKey, "casey@example.com"))
rec := httptest.NewRecorder()
ServeDirectory(cfg, nil, rec, req)
// Should NOT redirect to /table.html — slash form is browse, not tables.
if rec.Code == http.StatusFound {
t.Fatalf("got 302 redirect to %q, want browse view (200)",
rec.Header().Get("Location"))
}
}