ZDDC/zddc/internal/handler/fileapi_test.go
ZDDC 3115e388fc feat(server): authenticated CRUD + verb-based RBAC with WORM archive folders
Replaces the binary acl.allow/deny model with five permission verbs
(r/w/c/d/a) and first-class roles, and adds an authenticated file API
(PUT/DELETE/POST move/mkdir) so the HTML tools can edit-in-place over
HTTP. Closes the AC-3(7) and AC-6 federal-readiness gaps.

File API (zddc/internal/handler/fileapi.go)
  - PUT <new>      → action c
  - PUT <existing> → action w
  - PUT <.zddc>    → action a (CanEditZddc strict-ancestor rule)
  - DELETE         → action d
  - POST mkdir     → action c (auto-writes creator-owned .zddc when the
                     parent is Incoming/Working/Staging)
  - POST move      → action w on src + c on dst, atomic via os.Rename
  - Optional If-Match for optimistic concurrency, --max-write-bytes cap,
    audit log emits a structured file_write event per operation.

Permission model (zddc/internal/zddc/{acl,file,roles,cascade_mode}.go)
  - acl.permissions: { principal → verb-set } map; principals are email
    patterns or role names. Empty verb set is an explicit deny.
  - roles: { name → members } definitions, available at the level they
    declare and all descendants. Closer-to-leaf shadows ancestor.
  - Legacy acl.allow/deny still work; they fold into permissions at
    parse time (allow → "rwcd", deny → "").
  - Cascade walks leaf→root; first level with any matching entry wins;
    the union of matching verb sets at that level decides.
  - --cascade-mode=strict adds a root→leaf ancestor-deny pre-pass so an
    ancestor explicit-deny is absolute (NIST AC-6). Default delegated
    preserves the existing commercial behavior.

Special folders (zddc/internal/zddc/special.go)
  - Incoming / Working / Staging: mkdir auto-writes a .zddc into the new
    subdir granting created_by + that email rwcda directly. Same form
    operators write by hand; creator can edit it later to add others.
  - Issued / Received: server-enforced WORM split. Cascade grants
    inherited from above the WORM folder are masked to r only; grants
    placed at-or-below the WORM folder retain r,c. Operators grant
    write-once (cr) to the doc controller via an explicit .zddc at the
    Issued/Received folder. Admins exempt — only escape hatch.

Browser polyfill (shared/zddc-source.js)
  - HttpDirectoryHandle + HttpFileHandle implement the FS Access API
    surface (values, getFileHandle, createWritable, removeEntry,
    queryPermission/requestPermission) over zddc-server's listing JSON
    and file API. Existing tools written against showDirectoryPicker
    work unchanged.
  - detectServerRoot() returns { handle, status }: tools auto-load on
    HTTP, surface a clear "no permission to list" message on 403, and
    fall back to the welcome screen on 0.
  - classifier renames take the atomic POST move path on HTTP-backed
    handles; mdedit and transmittal route reads/writes through the
    polyfill so prior FS-API code paths cover both modes.

Tests
  - zddc/internal/zddc/{cascade_mode,roles,special,acl}_test.go cover
    delegated vs strict, role membership / shadowing / legacy fallback,
    WORM split semantics, verb-set parser round-trip.
  - zddc/internal/handler/fileapi_test.go now also covers role-based
    vendor scenarios, WORM blocking vendor & doc controller writes,
    explicit Issued .zddc unlocking the cr drop-box, admin bypass,
    auto-ownership on mkdir, and strict-mode lockouts.

Docs
  - ARCHITECTURE.md + zddc/README.md document the verb model, role
    syntax, special-folder behaviors, cascade-mode flag, and full file
    API surface. Federal-readiness gap analysis strikes AC-3(7) and
    AC-6.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 15:58:04 -05:00

666 lines
23 KiB
Go

package handler
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"codeberg.org/VARASYS/ZDDC/zddc/internal/config"
"codeberg.org/VARASYS/ZDDC/zddc/internal/policy"
"codeberg.org/VARASYS/ZDDC/zddc/internal/zddc"
)
// fileAPITestSetup writes a tree of directories and seed files under a
// temp root and returns a do() helper that builds and runs file API
// requests. The root .zddc grants caller@example.com read+write across
// the tree (single ACL allows both — the internal decider doesn't split
// read/write yet).
//
// seed: relative path → bytes (created as a regular file).
// dirs: relative paths to mkdir.
func fileAPITestSetup(t *testing.T, dirs []string, seed map[string]string) (cfg config.Config, do func(method, target, email string, body []byte, headers map[string]string) *httptest.ResponseRecorder, root string) {
t.Helper()
root = t.TempDir()
// Root .zddc grants writer access to *@example.com.
if err := os.WriteFile(filepath.Join(root, ".zddc"),
[]byte("acl:\n allow:\n - \"*@example.com\"\n deny: []\n"), 0o644); err != nil {
t.Fatalf("write root .zddc: %v", err)
}
for _, d := range dirs {
if err := os.MkdirAll(filepath.Join(root, d), 0o755); err != nil {
t.Fatalf("mkdir %s: %v", d, err)
}
}
for rel, body := range seed {
full := filepath.Join(root, rel)
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
t.Fatalf("mkdir parent of %s: %v", rel, err)
}
if err := os.WriteFile(full, []byte(body), 0o644); err != nil {
t.Fatalf("seed %s: %v", rel, err)
}
}
zddc.InvalidateCache(root)
cfg = config.Config{
Root: root,
EmailHeader: "X-Auth-Request-Email",
MaxWriteBytes: 1024 * 1024,
}
do = func(method, target, email string, body []byte, headers map[string]string) *httptest.ResponseRecorder {
var req *http.Request
if body != nil {
req = httptest.NewRequest(method, target, bytes.NewReader(body))
} else {
req = httptest.NewRequest(method, target, nil)
}
for k, v := range headers {
req.Header.Set(k, v)
}
ctx := context.WithValue(req.Context(), EmailKey, email)
req = req.WithContext(ctx)
rec := httptest.NewRecorder()
ServeFileAPI(cfg, rec, req)
return rec
}
return cfg, do, root
}
func sha32(data []byte) string {
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:])[:32]
}
func TestFileAPI_PutCreatesFile(t *testing.T) {
_, do, root := fileAPITestSetup(t, []string{"Incoming"}, nil)
body := []byte("hello world")
rec := do(http.MethodPut, "/Incoming/note.txt", "alice@example.com", body, nil)
if rec.Code != http.StatusCreated {
t.Fatalf("want 201, got %d: %s", rec.Code, rec.Body.String())
}
got, err := os.ReadFile(filepath.Join(root, "Incoming/note.txt"))
if err != nil {
t.Fatalf("read back: %v", err)
}
if string(got) != "hello world" {
t.Fatalf("body mismatch: %q", got)
}
wantTag := `"` + sha32(body) + `"`
if got := rec.Header().Get("ETag"); got != wantTag {
t.Fatalf("ETag: want %s, got %s", wantTag, got)
}
}
func TestFileAPI_PutOverwritesExisting(t *testing.T) {
_, do, root := fileAPITestSetup(t, nil, map[string]string{
"Incoming/old.txt": "first",
})
body := []byte("second")
rec := do(http.MethodPut, "/Incoming/old.txt", "alice@example.com", body, nil)
if rec.Code != http.StatusOK {
t.Fatalf("want 200 (overwrite), got %d: %s", rec.Code, rec.Body.String())
}
got, _ := os.ReadFile(filepath.Join(root, "Incoming/old.txt"))
if string(got) != "second" {
t.Fatalf("body: %q", got)
}
}
func TestFileAPI_PutAutoCreatesParents(t *testing.T) {
_, do, root := fileAPITestSetup(t, nil, nil)
rec := do(http.MethodPut, "/Incoming/sub/deep/x.bin", "alice@example.com", []byte("data"), nil)
if rec.Code != http.StatusCreated {
t.Fatalf("want 201, got %d: %s", rec.Code, rec.Body.String())
}
if _, err := os.Stat(filepath.Join(root, "Incoming/sub/deep/x.bin")); err != nil {
t.Fatalf("stat: %v", err)
}
}
func TestFileAPI_PutDenyForbidden(t *testing.T) {
cfg, do, _ := fileAPITestSetup(t, []string{"Working"}, nil)
// Tighten ACL to a different domain — alice@example.com no longer
// matches and writes must be 403.
if err := os.WriteFile(filepath.Join(cfg.Root, ".zddc"),
[]byte("acl:\n allow:\n - \"*@allowed.com\"\n deny: []\n"), 0o644); err != nil {
t.Fatalf("rewrite .zddc: %v", err)
}
zddc.InvalidateCache(cfg.Root)
rec := do(http.MethodPut, "/Working/note.md", "alice@example.com", []byte("nope"), nil)
if rec.Code != http.StatusForbidden {
t.Fatalf("want 403, got %d: %s", rec.Code, rec.Body.String())
}
}
func TestFileAPI_PutHiddenSegmentRejected(t *testing.T) {
_, do, _ := fileAPITestSetup(t, nil, nil)
for _, p := range []string{"/.zddc", "/foo/.hidden", "/_app/spoof.html", "/_template/x"} {
rec := do(http.MethodPut, p, "alice@example.com", []byte("x"), nil)
if rec.Code != http.StatusNotFound {
t.Fatalf("want 404 for %s, got %d", p, rec.Code)
}
}
}
func TestFileAPI_PutOversizeRejected(t *testing.T) {
cfg, _, _ := fileAPITestSetup(t, []string{"Incoming"}, nil)
cfg.MaxWriteBytes = 16
body := bytes.Repeat([]byte("A"), 32)
req := httptest.NewRequest(http.MethodPut, "/Incoming/big.bin", bytes.NewReader(body))
ctx := context.WithValue(req.Context(), EmailKey, "alice@example.com")
req = req.WithContext(ctx)
rec := httptest.NewRecorder()
ServeFileAPI(cfg, rec, req)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("want 413, got %d: %s", rec.Code, rec.Body.String())
}
}
func TestFileAPI_PutTrailingSlashRejected(t *testing.T) {
_, do, _ := fileAPITestSetup(t, nil, nil)
rec := do(http.MethodPut, "/Incoming/", "alice@example.com", []byte("x"), nil)
if rec.Code != http.StatusBadRequest {
t.Fatalf("want 400, got %d", rec.Code)
}
}
func TestFileAPI_DeleteRemovesFile(t *testing.T) {
_, do, root := fileAPITestSetup(t, nil, map[string]string{
"Incoming/old.txt": "garbage",
})
rec := do(http.MethodDelete, "/Incoming/old.txt", "alice@example.com", nil, nil)
if rec.Code != http.StatusNoContent {
t.Fatalf("want 204, got %d: %s", rec.Code, rec.Body.String())
}
if _, err := os.Stat(filepath.Join(root, "Incoming/old.txt")); !os.IsNotExist(err) {
t.Fatalf("file should be gone, err=%v", err)
}
}
func TestFileAPI_DeleteMissing404(t *testing.T) {
_, do, _ := fileAPITestSetup(t, nil, nil)
rec := do(http.MethodDelete, "/Incoming/never-existed.txt", "alice@example.com", nil, nil)
if rec.Code != http.StatusNotFound {
t.Fatalf("want 404, got %d", rec.Code)
}
}
func TestFileAPI_DeleteDirectoryConflict(t *testing.T) {
_, do, _ := fileAPITestSetup(t, []string{"Incoming/sub"}, nil)
rec := do(http.MethodDelete, "/Incoming/sub", "alice@example.com", nil, nil)
if rec.Code != http.StatusConflict {
t.Fatalf("want 409, got %d: %s", rec.Code, rec.Body.String())
}
}
func TestFileAPI_MoveRenames(t *testing.T) {
_, do, root := fileAPITestSetup(t, nil, map[string]string{
"Incoming/old.pdf": "PDF body",
})
rec := do(http.MethodPost, "/Incoming/old.pdf", "alice@example.com", nil, map[string]string{
"X-ZDDC-Op": "move",
"X-ZDDC-Destination": "/Incoming/new.pdf",
})
if rec.Code != http.StatusOK {
t.Fatalf("want 200, got %d: %s", rec.Code, rec.Body.String())
}
if _, err := os.Stat(filepath.Join(root, "Incoming/old.pdf")); !os.IsNotExist(err) {
t.Fatalf("source still exists")
}
got, err := os.ReadFile(filepath.Join(root, "Incoming/new.pdf"))
if err != nil {
t.Fatalf("read dest: %v", err)
}
if string(got) != "PDF body" {
t.Fatalf("dest bytes: %q", got)
}
if dst := rec.Header().Get("X-ZDDC-Destination"); dst != "/Incoming/new.pdf" {
t.Fatalf("destination header: %s", dst)
}
}
func TestFileAPI_MoveDestinationExistsConflict(t *testing.T) {
_, do, _ := fileAPITestSetup(t, nil, map[string]string{
"Incoming/a.txt": "a",
"Incoming/b.txt": "b",
})
rec := do(http.MethodPost, "/Incoming/a.txt", "alice@example.com", nil, map[string]string{
"X-ZDDC-Op": "move",
"X-ZDDC-Destination": "/Incoming/b.txt",
})
if rec.Code != http.StatusConflict {
t.Fatalf("want 409, got %d: %s", rec.Code, rec.Body.String())
}
}
func TestFileAPI_MoveMissingDestinationHeader(t *testing.T) {
_, do, _ := fileAPITestSetup(t, nil, map[string]string{
"Incoming/a.txt": "a",
})
rec := do(http.MethodPost, "/Incoming/a.txt", "alice@example.com", nil, map[string]string{
"X-ZDDC-Op": "move",
})
if rec.Code != http.StatusBadRequest {
t.Fatalf("want 400, got %d: %s", rec.Code, rec.Body.String())
}
}
func TestFileAPI_MoveCreatesParentDirs(t *testing.T) {
_, do, root := fileAPITestSetup(t, nil, map[string]string{
"Incoming/a.txt": "hi",
})
rec := do(http.MethodPost, "/Incoming/a.txt", "alice@example.com", nil, map[string]string{
"X-ZDDC-Op": "move",
"X-ZDDC-Destination": "/Working/sub/a.txt",
})
if rec.Code != http.StatusOK {
t.Fatalf("want 200, got %d: %s", rec.Code, rec.Body.String())
}
if _, err := os.Stat(filepath.Join(root, "Working/sub/a.txt")); err != nil {
t.Fatalf("dest not present: %v", err)
}
}
func TestFileAPI_PostUnknownOp(t *testing.T) {
_, do, _ := fileAPITestSetup(t, []string{"Incoming"}, nil)
rec := do(http.MethodPost, "/Incoming/x.txt", "alice@example.com", nil, map[string]string{
"X-ZDDC-Op": "weld",
})
if rec.Code != http.StatusBadRequest {
t.Fatalf("want 400, got %d", rec.Code)
}
}
func TestFileAPI_PostMissingOp(t *testing.T) {
_, do, _ := fileAPITestSetup(t, []string{"Incoming"}, nil)
rec := do(http.MethodPost, "/Incoming/x.txt", "alice@example.com", nil, nil)
if rec.Code != http.StatusBadRequest {
t.Fatalf("want 400, got %d", rec.Code)
}
}
func TestFileAPI_MkdirCreates(t *testing.T) {
_, do, root := fileAPITestSetup(t, nil, nil)
rec := do(http.MethodPost, "/Incoming/newfolder/", "alice@example.com", nil, map[string]string{
"X-ZDDC-Op": "mkdir",
})
if rec.Code != http.StatusCreated {
t.Fatalf("want 201, got %d: %s", rec.Code, rec.Body.String())
}
info, err := os.Stat(filepath.Join(root, "Incoming/newfolder"))
if err != nil {
t.Fatalf("stat: %v", err)
}
if !info.IsDir() {
t.Fatalf("not a dir")
}
}
func TestFileAPI_MkdirIdempotent(t *testing.T) {
_, do, _ := fileAPITestSetup(t, []string{"Incoming/exists"}, nil)
rec := do(http.MethodPost, "/Incoming/exists/", "alice@example.com", nil, map[string]string{
"X-ZDDC-Op": "mkdir",
})
if rec.Code != http.StatusOK {
t.Fatalf("want 200, got %d", rec.Code)
}
}
func TestFileAPI_IfMatchEnforced(t *testing.T) {
_, do, _ := fileAPITestSetup(t, nil, map[string]string{
"Incoming/x.txt": "v1",
})
// Wrong ETag → 412.
rec := do(http.MethodPut, "/Incoming/x.txt", "alice@example.com", []byte("v2"), map[string]string{
"If-Match": `"` + strings.Repeat("0", 32) + `"`,
})
if rec.Code != http.StatusPreconditionFailed {
t.Fatalf("want 412, got %d", rec.Code)
}
// Correct ETag → 200.
correctTag := sha32([]byte("v1"))
rec = do(http.MethodPut, "/Incoming/x.txt", "alice@example.com", []byte("v2"), map[string]string{
"If-Match": `"` + correctTag + `"`,
})
if rec.Code != http.StatusOK {
t.Fatalf("want 200, got %d: %s", rec.Code, rec.Body.String())
}
}
func TestFileAPI_IfMatchWildcardOnMissing(t *testing.T) {
_, do, _ := fileAPITestSetup(t, []string{"Incoming"}, nil)
rec := do(http.MethodPut, "/Incoming/new.txt", "alice@example.com", []byte("data"), map[string]string{
"If-Match": `*`,
})
if rec.Code != http.StatusPreconditionFailed {
t.Fatalf("want 412 (wildcard expects existing), got %d", rec.Code)
}
}
func TestFileAPI_PathTraversalBlocked(t *testing.T) {
_, do, _ := fileAPITestSetup(t, nil, nil)
rec := do(http.MethodPut, "/../escaped.txt", "alice@example.com", []byte("x"), nil)
if rec.Code != http.StatusNotFound && rec.Code != http.StatusBadRequest {
t.Fatalf("traversal not blocked: %d", rec.Code)
}
}
func TestFileAPI_AnonymousDenied(t *testing.T) {
_, do, _ := fileAPITestSetup(t, []string{"Incoming"}, nil)
rec := do(http.MethodPut, "/Incoming/note.txt", "", []byte("x"), nil)
if rec.Code != http.StatusForbidden {
t.Fatalf("want 403 for anon, got %d", rec.Code)
}
}
// rolePermissionsTestSetup creates a vendor-exchange shape:
//
// root .zddc: _company:r, _doc_controller:rwcda
// Vendor/.zddc: vendor_acme:rwcd, _doc_controller:rwcda, _company:""
// roles defined at root.
//
// Returns the same do() helper as fileAPITestSetup.
func rolePermissionsTestSetup(t *testing.T) (cfg config.Config, do func(method, target, email string, body []byte, headers map[string]string) *httptest.ResponseRecorder, root string) {
t.Helper()
root = t.TempDir()
// Root .zddc — company gets r, doc_controller gets rwcda. Roles
// defined here so the vendor subtree's permissions can reference
// them by name.
rootZ := []byte(`roles:
_company:
members: ["*@mycompany.com"]
_doc_controller:
members: [dc@mycompany.com]
vendor_acme:
members: ["*@acme.com"]
acl:
permissions:
_company: r
_doc_controller: rwcda
`)
if err := os.WriteFile(filepath.Join(root, ".zddc"), rootZ, 0o644); err != nil {
t.Fatalf("root .zddc: %v", err)
}
// Vendor subtree: narrow scope.
vendorDir := filepath.Join(root, "Vendor")
if err := os.MkdirAll(filepath.Join(vendorDir, "Incoming"), 0o755); err != nil {
t.Fatalf("mkdir Vendor/Incoming: %v", err)
}
if err := os.MkdirAll(filepath.Join(vendorDir, "Issued"), 0o755); err != nil {
t.Fatalf("mkdir Vendor/Issued: %v", err)
}
if err := os.MkdirAll(filepath.Join(vendorDir, "Received"), 0o755); err != nil {
t.Fatalf("mkdir Vendor/Received: %v", err)
}
vendorZ := []byte(`acl:
permissions:
vendor_acme: rwcd
_doc_controller: rwcda
_company: ""
`)
if err := os.WriteFile(filepath.Join(vendorDir, ".zddc"), vendorZ, 0o644); err != nil {
t.Fatalf("vendor .zddc: %v", err)
}
zddc.InvalidateCache(root)
cfg = config.Config{
Root: root,
EmailHeader: "X-Auth-Request-Email",
MaxWriteBytes: 1024 * 1024,
CascadeMode: "delegated",
}
decider := &policy.InternalDecider{}
do = func(method, target, email string, body []byte, headers map[string]string) *httptest.ResponseRecorder {
var req *http.Request
if body != nil {
req = httptest.NewRequest(method, target, bytes.NewReader(body))
} else {
req = httptest.NewRequest(method, target, nil)
}
for k, v := range headers {
req.Header.Set(k, v)
}
ctx := context.WithValue(req.Context(), EmailKey, email)
ctx = context.WithValue(ctx, DeciderKey, decider)
req = req.WithContext(ctx)
rec := httptest.NewRecorder()
ServeFileAPI(cfg, rec, req)
return rec
}
return cfg, do, root
}
func TestFileAPI_RoleBasedVendorIncoming(t *testing.T) {
_, do, _ := rolePermissionsTestSetup(t)
// Vendor PUTs into their Incoming → 201.
rec := do(http.MethodPut, "/Vendor/Incoming/submission.pdf", "rep@acme.com", []byte("data"), nil)
if rec.Code != http.StatusCreated {
t.Fatalf("PUT vendor → Incoming: want 201, got %d: %s", rec.Code, rec.Body.String())
}
// Vendor overwrites the same file → 200 (rwcd has w).
rec = do(http.MethodPut, "/Vendor/Incoming/submission.pdf", "rep@acme.com", []byte("data2"), nil)
if rec.Code != http.StatusOK {
t.Fatalf("PUT vendor → Incoming overwrite: want 200, got %d", rec.Code)
}
}
func TestFileAPI_WORM_VendorReadOnlyInIssued(t *testing.T) {
_, do, root := rolePermissionsTestSetup(t)
// Seed an existing Issued file.
if err := os.WriteFile(filepath.Join(root, "Vendor/Issued/spec.pdf"), []byte("FILED"), 0o644); err != nil {
t.Fatalf("seed: %v", err)
}
// Vendor cannot overwrite — ancestor grant masked to r in Issued.
rec := do(http.MethodPut, "/Vendor/Issued/spec.pdf", "rep@acme.com", []byte("tamper"), nil)
if rec.Code != http.StatusForbidden {
t.Fatalf("PUT vendor → Issued (overwrite): want 403, got %d: %s", rec.Code, rec.Body.String())
}
// Vendor cannot delete.
rec = do(http.MethodDelete, "/Vendor/Issued/spec.pdf", "rep@acme.com", nil, nil)
if rec.Code != http.StatusForbidden {
t.Fatalf("DELETE vendor → Issued: want 403, got %d", rec.Code)
}
// Vendor cannot create new files — they have no explicit .zddc grant
// at the Issued folder, so the WORM split reduces their inherited
// rwcd to r-only.
rec = do(http.MethodPut, "/Vendor/Issued/new.pdf", "rep@acme.com", []byte("x"), nil)
if rec.Code != http.StatusForbidden {
t.Fatalf("PUT vendor → Issued (create): want 403 (no explicit grant at Issued), got %d", rec.Code)
}
}
func TestFileAPI_WORM_DocControllerNeedsExplicitGrant(t *testing.T) {
_, do, root := rolePermissionsTestSetup(t)
// Without a .zddc at Vendor/Issued/ explicitly granting cr, the dc's
// inherited rwcda is masked to r. They cannot create.
rec := do(http.MethodPut, "/Vendor/Issued/no-grant.pdf", "dc@mycompany.com", []byte("x"), nil)
if rec.Code != http.StatusForbidden {
t.Fatalf("dc without explicit grant → Issued: want 403, got %d: %s", rec.Code, rec.Body.String())
}
// Operator places an explicit grant at Vendor/Issued/.zddc. Now dc
// has cr at-or-below the WORM folder, which survives the mask.
issuedZ := []byte(`acl:
permissions:
_doc_controller: cr
`)
if err := os.WriteFile(filepath.Join(root, "Vendor/Issued/.zddc"), issuedZ, 0o644); err != nil {
t.Fatalf("write Issued .zddc: %v", err)
}
zddc.InvalidateCache(root)
rec = do(http.MethodPut, "/Vendor/Issued/2026-Q2-spec.pdf", "dc@mycompany.com", []byte("CONTROLLED"), nil)
if rec.Code != http.StatusCreated {
t.Fatalf("dc with explicit grant → Issued: want 201, got %d: %s", rec.Code, rec.Body.String())
}
got, _ := os.ReadFile(filepath.Join(root, "Vendor/Issued/2026-Q2-spec.pdf"))
if string(got) != "CONTROLLED" {
t.Fatalf("body: %q", got)
}
// dc still cannot overwrite — explicit grant is cr, no w.
rec = do(http.MethodPut, "/Vendor/Issued/2026-Q2-spec.pdf", "dc@mycompany.com", []byte("REVISION"), nil)
if rec.Code != http.StatusForbidden {
t.Fatalf("dc PUT overwrite → Issued: want 403, got %d", rec.Code)
}
// dc still cannot delete.
rec = do(http.MethodDelete, "/Vendor/Issued/2026-Q2-spec.pdf", "dc@mycompany.com", nil, nil)
if rec.Code != http.StatusForbidden {
t.Fatalf("dc DELETE → Issued: want 403, got %d", rec.Code)
}
}
func TestFileAPI_WORM_AdminBypass(t *testing.T) {
cfg, do, root := rolePermissionsTestSetup(t)
// Promote root@example.com to root admin.
rootZ, _ := os.ReadFile(filepath.Join(cfg.Root, ".zddc"))
updated := string(rootZ) + "\nadmins:\n - root@example.com\n"
if err := os.WriteFile(filepath.Join(cfg.Root, ".zddc"), []byte(updated), 0o644); err != nil {
t.Fatalf("rewrite root .zddc: %v", err)
}
zddc.InvalidateCache(cfg.Root)
// Seed an Issued file and have root@ delete it (escape hatch).
if err := os.WriteFile(filepath.Join(root, "Vendor/Issued/mistake.pdf"), []byte("oops"), 0o644); err != nil {
t.Fatalf("seed: %v", err)
}
rec := do(http.MethodDelete, "/Vendor/Issued/mistake.pdf", "root@example.com", nil, nil)
if rec.Code != http.StatusNoContent {
t.Fatalf("admin DELETE → Issued: want 204, got %d: %s", rec.Code, rec.Body.String())
}
}
func TestFileAPI_AutoMkdirOwnership(t *testing.T) {
_, do, root := rolePermissionsTestSetup(t)
// Vendor creates a folder under their Incoming. Server should
// auto-write a .zddc granting them rwcda on the new subtree.
rec := do(http.MethodPost, "/Vendor/Incoming/2026-05-15-issue/", "rep@acme.com", nil, map[string]string{
"X-ZDDC-Op": "mkdir",
})
if rec.Code != http.StatusCreated {
t.Fatalf("mkdir: want 201, got %d: %s", rec.Code, rec.Body.String())
}
autoZ := filepath.Join(root, "Vendor/Incoming/2026-05-15-issue/.zddc")
data, err := os.ReadFile(autoZ)
if err != nil {
t.Fatalf("auto .zddc not written: %v", err)
}
body := string(data)
if !strings.Contains(body, "created_by: rep@acme.com") {
t.Errorf("auto .zddc missing created_by: %s", body)
}
if !strings.Contains(body, "rep@acme.com: rwcda") {
t.Errorf("auto .zddc missing email→rwcda grant: %s", body)
}
// Now the cascade caches are stale because we didn't go through
// WriteFile here; the server's writeAutoOwnZddc DID call WriteFile
// (via zddc.WriteFile → InvalidateCache). Confirm the vendor can
// now PUT a brand-new file inside their owned folder where they
// otherwise wouldn't have ACL admin rights.
zddc.InvalidateCache(root)
rec = do(http.MethodPut, "/Vendor/Incoming/2026-05-15-issue/note.txt", "rep@acme.com", []byte("x"), nil)
if rec.Code != http.StatusCreated {
t.Fatalf("vendor PUT in own subtree: want 201, got %d: %s", rec.Code, rec.Body.String())
}
}
func TestFileAPI_AutoMkdirNotInIssued(t *testing.T) {
_, do, root := rolePermissionsTestSetup(t)
// Place an explicit grant so dc has cr at the Issued level.
issuedZ := []byte("acl:\n permissions:\n _doc_controller: cr\n")
if err := os.WriteFile(filepath.Join(root, "Vendor/Issued/.zddc"), issuedZ, 0o644); err != nil {
t.Fatalf("seed Issued .zddc: %v", err)
}
zddc.InvalidateCache(root)
// Doc controller mkdir under Issued — should succeed (cr survives mask)
// but should NOT auto-write an ownership .zddc (Issued is excluded
// from auto-own).
rec := do(http.MethodPost, "/Vendor/Issued/2026-Q2/", "dc@mycompany.com", nil, map[string]string{
"X-ZDDC-Op": "mkdir",
})
if rec.Code != http.StatusCreated {
t.Fatalf("mkdir: want 201, got %d: %s", rec.Code, rec.Body.String())
}
autoZ := filepath.Join(root, "Vendor/Issued/2026-Q2/.zddc")
if _, err := os.Stat(autoZ); !os.IsNotExist(err) {
t.Errorf("auto .zddc should NOT be written under Issued; got err=%v", err)
}
}
func TestFileAPI_StrictMode_AncestorDenyAbsolute(t *testing.T) {
cfg, _, root := rolePermissionsTestSetup(t)
cfg.CascadeMode = "strict"
// Add a strict-mode lockout at root: deny vendor_acme everywhere.
rootZ, _ := os.ReadFile(filepath.Join(root, ".zddc"))
updated := strings.Replace(string(rootZ), "_doc_controller: rwcda\n",
"_doc_controller: rwcda\n vendor_acme: \"\"\n", 1)
if err := os.WriteFile(filepath.Join(root, ".zddc"), []byte(updated), 0o644); err != nil {
t.Fatalf("rewrite root: %v", err)
}
zddc.InvalidateCache(root)
// Build a strict-mode decider so the file API uses the new mode.
decider := &policy.InternalDecider{Mode: zddc.ModeStrict}
doStrict := func(method, target, email string, body []byte) *httptest.ResponseRecorder {
var req *http.Request
if body != nil {
req = httptest.NewRequest(method, target, bytes.NewReader(body))
} else {
req = httptest.NewRequest(method, target, nil)
}
ctx := context.WithValue(req.Context(), EmailKey, email)
ctx = context.WithValue(ctx, DeciderKey, decider)
req = req.WithContext(ctx)
rec := httptest.NewRecorder()
ServeFileAPI(cfg, rec, req)
return rec
}
// Vendor's leaf rwcd grant in Vendor/.zddc is overridden by the
// root deny under strict mode.
rec := doStrict(http.MethodPut, "/Vendor/Incoming/blocked.pdf", "rep@acme.com", []byte("nope"))
if rec.Code != http.StatusForbidden {
t.Fatalf("strict mode: vendor should be denied by root explicit-deny, got %d: %s", rec.Code, rec.Body.String())
}
}