test(handler): lock-in invariants for admin/elevation/WORM behavior

Baseline test battery that pins the current auth-decision behavior so
the upcoming consolidation refactor (single bypass site in
InternalDecider.Allow) is validated against a green baseline.

Each test names one invariant; failure messages identify exactly
which property regressed. Coverage:

- Un-elevated admin cannot bypass WORM (PUT to issued/ → 403).
- Un-elevated admin cannot edit .zddc (Principal.gate() blocks).
- Elevated admin bypasses WORM (positive control).
- Elevated subtree admin writes within scope, blocked outside it.
- Strict-ancestor rule: subtree admin cannot edit own subtree's
  .zddc, can edit deeper .zddc.
- Empty email never matches.
- WORM cr survives for un-elevated document_controller (create OK,
  overwrite still stripped).
- project_team has read-only outside their auto-own home.
- Forward-auth /.auth/admin gates strictly on ROOT admins:.

wormbypass_test.go retained as the original repro of the live bitnest
observation (un-elevated user write succeeded under --no-auth=1).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
ZDDC 2026-05-18 09:12:37 -05:00
parent 1d758780fe
commit cfa7732183
2 changed files with 358 additions and 0 deletions

View file

@ -0,0 +1,278 @@
package handler
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"codeberg.org/VARASYS/ZDDC/zddc/internal/config"
"codeberg.org/VARASYS/ZDDC/zddc/internal/zddc"
)
// auth_invariants_test.go — behavioral lock-in for the admin/elevation/
// WORM invariants. These tests must pass against the CURRENT code before
// the consolidation refactor (single bypass site in InternalDecider) so
// the refactor can be validated against a green baseline.
//
// Each test covers one invariant called out in the security audit. The
// names are deliberately verbose — when one fails, the failure message
// alone tells you which property got broken.
// invariantsFixture sets up a synthetic ZDDC root with:
//
// - admin@example.com — root super-admin
// - alice@example.com — subtree admin of Project-1/working (via per-dir
// .zddc admins:) — used to test subtree scope
// - bob@example.com — document_controller role member (gets WORM cr
// on received/ + issued/ via cascade defaults)
// - eve@example.com — non-admin, project_team only (read-only across
// the project per defaults)
//
// Plus one file each in working/, issued/, received/ so we can exercise
// reads + writes across the cascade.
func invariantsFixture(t *testing.T) (config.Config, string) {
t.Helper()
root := t.TempDir()
mustWriteHelper(t, filepath.Join(root, ".zddc"),
"admins:\n - admin@example.com\n"+
"roles:\n"+
" document_controller:\n members: [bob@example.com]\n"+
" project_team:\n members: [\"*@example.com\"]\n")
for _, d := range []string{
"Project-1/working/eve@example.com",
"Project-1/archive/Acme/received/Acme-0042",
"Project-1/archive/Acme/issued/2026-05-15_Acme-0099 (IFR) - Test",
} {
if err := os.MkdirAll(filepath.Join(root, d), 0o755); err != nil {
t.Fatalf("mkdir %s: %v", d, err)
}
}
// Subtree-admin grant: alice administers Project-1/working/.
mustWriteHelper(t,
filepath.Join(root, "Project-1/working/.zddc"),
"admins:\n - alice@example.com\n")
// Files to act on.
mustWriteHelper(t,
filepath.Join(root, "Project-1/working/eve@example.com/draft.md"),
"# eve's draft\n")
mustWriteHelper(t,
filepath.Join(root, "Project-1/archive/Acme/received/Acme-0042/Acme-0042_A (RFI) - Test.pdf"),
"%PDF-A\n")
mustWriteHelper(t,
filepath.Join(root, "Project-1/archive/Acme/issued/2026-05-15_Acme-0099 (IFR) - Test/Acme-0099_0A (IFR) - Test.md"),
"# issued draft\n")
zddc.InvalidateCache(root)
return config.Config{
Root: root,
EmailHeader: "X-Auth-Request-Email",
MaxWriteBytes: 64 * 1024,
}, root
}
// do executes a request with the given email / elevation flag. URL-encoding
// is computed from the path so spaces and parens (real ZDDC filenames)
// round-trip cleanly.
func doReq(cfg config.Config, method, urlPath, email string, elevated bool, body []byte, op string) *httptest.ResponseRecorder {
u := &url.URL{Path: urlPath}
req := httptest.NewRequest(method, u.RequestURI(), bytes.NewReader(body))
if op != "" {
req.Header.Set(headerOp, op)
}
ctx := context.WithValue(req.Context(), EmailKey, email)
ctx = context.WithValue(ctx, ElevatedKey, elevated)
req = req.WithContext(ctx)
rec := httptest.NewRecorder()
ServeFileAPI(cfg, rec, req)
return rec
}
// ── Invariant 1 — Un-elevated admin has no admin authority ────────────────
func TestInvariant_UnelevatedAdminCannotBypassWorm(t *testing.T) {
cfg, _ := invariantsFixture(t)
target := "/Project-1/archive/Acme/issued/2026-05-15_Acme-0099 (IFR) - Test/Acme-0099_0A (IFR) - Test.md"
rec := doReq(cfg, http.MethodPut, target, "admin@example.com", false, []byte("# mutated\n"), "")
if rec.Code != http.StatusForbidden {
t.Fatalf("un-elevated admin write succeeded: status=%d body=%s", rec.Code, rec.Body.String())
}
}
func TestInvariant_UnelevatedAdminCannotEditZddc(t *testing.T) {
// The .zddc edit authority lives in zddc.CanEditZddc, gated on
// Principal.gate() — un-elevated must return false even for a root
// super-admin. Exercised at the helper boundary; the HTTP path
// guards .zddc at resolveTargetPath separately.
cfg, _ := invariantsFixture(t)
p := zddc.Principal{Email: "admin@example.com", Elevated: false}
dir := filepath.Join(cfg.Root, "Project-1/working")
if zddc.CanEditZddc(cfg.Root, dir, p) {
t.Fatalf("un-elevated admin can edit .zddc — gate() bypassed")
}
}
// ── Invariant 2 — Elevated admin can do everything (positive control) ─────
func TestInvariant_ElevatedAdminBypassesWorm(t *testing.T) {
cfg, _ := invariantsFixture(t)
target := "/Project-1/archive/Acme/issued/2026-05-15_Acme-0099 (IFR) - Test/Acme-0099_0A (IFR) - Test.md"
rec := doReq(cfg, http.MethodPut, target, "admin@example.com", true, []byte("# fix-mis-filed\n"), "")
if rec.Code != http.StatusOK && rec.Code != http.StatusCreated {
t.Fatalf("elevated admin write blocked: status=%d body=%s", rec.Code, rec.Body.String())
}
}
// ── Invariant 3 — Subtree admin scope ──────────────────────────────────────
func TestInvariant_ElevatedSubtreeAdminWritesInScope(t *testing.T) {
cfg, _ := invariantsFixture(t)
target := "/Project-1/working/eve@example.com/draft.md"
rec := doReq(cfg, http.MethodPut, target, "alice@example.com", true, []byte("# alice override\n"), "")
// alice is subtree admin of Project-1/working/ — should override eve's
// fenced auto-own and write through.
if rec.Code != http.StatusOK && rec.Code != http.StatusCreated {
t.Fatalf("elevated subtree admin write in scope blocked: status=%d body=%s", rec.Code, rec.Body.String())
}
}
func TestInvariant_ElevatedSubtreeAdminBlockedOutsideScope(t *testing.T) {
cfg, _ := invariantsFixture(t)
// alice is subtree admin of /Project-1/working/, NOT of /Project-1/archive/.
target := "/Project-1/archive/Acme/issued/2026-05-15_Acme-0099 (IFR) - Test/Acme-0099_0A (IFR) - Test.md"
rec := doReq(cfg, http.MethodPut, target, "alice@example.com", true, []byte("# out-of-scope\n"), "")
if rec.Code != http.StatusForbidden {
t.Fatalf("subtree admin escaped scope: status=%d body=%s", rec.Code, rec.Body.String())
}
}
// ── Invariant 4 — .zddc strict-ancestor self-elevation prevention ─────────
func TestInvariant_SubtreeAdminCannotEditOwnSubtreeZddc(t *testing.T) {
// alice's authority comes from /Project-1/working/.zddc. She must
// NOT be able to edit that file — strict-ancestor rule prevents
// her from adding peers, removing the delegator, or otherwise
// self-elevating.
cfg, _ := invariantsFixture(t)
p := zddc.Principal{Email: "alice@example.com", Elevated: true}
dir := filepath.Join(cfg.Root, "Project-1/working")
if zddc.CanEditZddc(cfg.Root, dir, p) {
t.Fatalf("subtree admin can edit own .zddc — strict-ancestor rule bypassed")
}
}
func TestInvariant_SubtreeAdminCanEditDeeperZddc(t *testing.T) {
// alice's authority over Project-1/working/ should let her create
// or edit .zddc files in deeper subtrees (e.g., per-user homes).
cfg, _ := invariantsFixture(t)
p := zddc.Principal{Email: "alice@example.com", Elevated: true}
dir := filepath.Join(cfg.Root, "Project-1/working/eve@example.com")
if !zddc.CanEditZddc(cfg.Root, dir, p) {
t.Fatalf("subtree admin blocked from editing deeper .zddc")
}
}
// ── Invariant 5 — Empty email never matches ────────────────────────────────
func TestInvariant_EmptyEmailHasNoAuthority(t *testing.T) {
cfg, _ := invariantsFixture(t)
target := "/Project-1/working/eve@example.com/draft.md"
rec := doReq(cfg, http.MethodPut, target, "", true, []byte("# anon\n"), "")
if rec.Code != http.StatusForbidden && rec.Code != http.StatusUnauthorized {
t.Fatalf("empty-email write succeeded: status=%d body=%s", rec.Code, rec.Body.String())
}
}
// ── Invariant 6 — WORM cr survives for document_controller (no admin) ─────
func TestInvariant_DocControllerCanCreateInWormZone(t *testing.T) {
cfg, _ := invariantsFixture(t)
// bob is a document_controller (per role membership) but NOT an admin.
// He must be able to CREATE new files in received/<tracking>/ even
// without elevation — the WORM cr grant carries.
target := "/Project-1/archive/Acme/received/Acme-0042/Acme-0042_B (RFI) - Followup.pdf"
rec := doReq(cfg, http.MethodPut, target, "bob@example.com", false, []byte("%PDF-B\n"), "")
if rec.Code != http.StatusOK && rec.Code != http.StatusCreated {
t.Fatalf("doc_controller blocked from WORM create: status=%d body=%s", rec.Code, rec.Body.String())
}
}
func TestInvariant_DocControllerCannotOverwriteInWormZone(t *testing.T) {
cfg, _ := invariantsFixture(t)
// bob can CREATE in WORM but cannot OVERWRITE — the worm strip
// removes w/d for everyone, even WORM-listed principals.
target := "/Project-1/archive/Acme/received/Acme-0042/Acme-0042_A (RFI) - Test.pdf"
rec := doReq(cfg, http.MethodPut, target, "bob@example.com", false, []byte("%PDF-mutated\n"), "")
if rec.Code != http.StatusForbidden {
t.Fatalf("doc_controller bypassed WORM overwrite-strip: status=%d body=%s", rec.Code, rec.Body.String())
}
}
// ── Invariant 7 — project_team has read but no write ──────────────────────
func TestInvariant_ProjectTeamCanReadCannotWrite(t *testing.T) {
cfg, _ := invariantsFixture(t)
// eve is project_team (r at project level) and the file lives under
// her own working/ home — but she is NOT in any admin list and not
// elevated, so writes must be ACL-gated.
//
// In her own home, eve has auto-own rwcda via the working/<email>/
// auto-own pattern; the cascade gives her create+write there. So
// the right test is a write OUTSIDE her home — into a peer's area
// or into archive.
target := "/Project-1/archive/Acme/received/Acme-0042/Acme-0042_A (RFI) - Test.pdf"
rec := doReq(cfg, http.MethodPut, target, "eve@example.com", false, []byte("# eve overwrite\n"), "")
if rec.Code != http.StatusForbidden {
t.Fatalf("project_team escaped WORM strip: status=%d body=%s", rec.Code, rec.Body.String())
}
}
// ── Invariant 8 — Forward-auth endpoint requires admin membership ─────────
func TestInvariant_ForwardAuthEndpointGatesOnAdminsList(t *testing.T) {
cfg, _ := invariantsFixture(t)
for _, tc := range []struct {
email string
want int
why string
}{
{"admin@example.com", http.StatusOK, "root admin"},
{"alice@example.com", http.StatusForbidden, "subtree admin only — /.auth/admin gates on ROOT admins:, not subtree"},
{"eve@example.com", http.StatusForbidden, "non-admin"},
{"", http.StatusForbidden, "anonymous"},
} {
req := httptest.NewRequest(http.MethodGet, "/.auth/admin", nil)
ctx := context.WithValue(req.Context(), EmailKey, tc.email)
req = req.WithContext(ctx)
rec := httptest.NewRecorder()
ServeAuthAdmin(cfg, rec, req)
if rec.Code != tc.want {
t.Errorf("/.auth/admin for %q (%s): got %d, want %d",
tc.email, tc.why, rec.Code, tc.want)
}
}
}
// ── Invariant 9 — Profile admin endpoints 404 (not 403) for non-admins ────
func TestInvariant_ProfileAdminEndpointsHideFromNonAdmins(t *testing.T) {
// These checks lock in the existence-hiding property: non-admins must
// see 404, never 403, so they can't probe which paths exist.
t.Skip("requires the profile handler dispatcher entry point; skip until the refactor confirms ServeProfile signature")
}
// dump prints the rec body when t.Logf would help debugging — used in
// failure messages to avoid silently empty 403 cases.
func dumpBody(rec *httptest.ResponseRecorder) string {
s := rec.Body.String()
return strings.TrimSpace(s)
}

View file

@ -0,0 +1,80 @@
package handler
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"testing"
"codeberg.org/VARASYS/ZDDC/zddc/internal/config"
"codeberg.org/VARASYS/ZDDC/zddc/internal/zddc"
)
// TestPutToIssuedAsUnelevatedNonAdminUserDenied reproduces the bitnest
// observation: an un-elevated user@bitnest.cc was able to PUT a markdown
// file inside archive/<party>/issued/<transmittal>/ even though the
// embedded defaults declare issued/ as WORM and the user is not in the
// document_controller role. Expectation: 403. If this test passes (i.e.
// 403), the bug is somewhere outside this path; if it fails (200 or
// similar), we've reproduced the bypass.
func TestPutToIssuedAsUnelevatedNonAdminUserDenied(t *testing.T) {
root := t.TempDir()
// Mirror bitnest's current root .zddc shape: user@bitnest.cc is in
// admins (potential admin) but un-elevated — should NOT have admin
// authority. Roles populate document_controller and project_team
// (which matches *@bitnest.cc → user@bitnest.cc gets project_team:r
// at project level via the embedded defaults).
mustWriteHelper(t, filepath.Join(root, ".zddc"),
"admins:\n - user@bitnest.cc\n"+
"roles:\n"+
" document_controller:\n members: [alice@example.com, bob@example.com]\n"+
" project_team:\n members: [\"*@example.com\", \"*@bitnest.cc\"]\n")
// Materialise the exact path shape from the bitnest log entry.
issuedDir := filepath.Join(root, "Project-1/archive/PartyA/issued/2025-09-21_A-FAC2-PM-DRW-0377 (RSB) - Test")
if err := os.MkdirAll(issuedDir, 0o755); err != nil {
t.Fatalf("mkdir issued: %v", err)
}
target := filepath.Join(issuedDir, "A-FAC1-EL-SPC-0469_0A (IFR) - Test.md")
if err := os.WriteFile(target, []byte("# original\n"), 0o644); err != nil {
t.Fatalf("seed target: %v", err)
}
zddc.InvalidateCache(root)
cfg := config.Config{
Root: root,
EmailHeader: "X-Auth-Request-Email",
MaxWriteBytes: 64 * 1024,
}
// Construct the PUT exactly as the markdown editor in browse would —
// PUT to the file's URL with the modified body.
u := &url.URL{Path: "/Project-1/archive/PartyA/issued/2025-09-21_A-FAC2-PM-DRW-0377 (RSB) - Test/A-FAC1-EL-SPC-0469_0A (IFR) - Test.md"}
req := httptest.NewRequest(http.MethodPut, u.RequestURI(), bytes.NewReader([]byte("# modified by un-elevated user\n")))
req.Header.Set("Content-Type", "text/markdown")
// Critical: emulate ACLMiddleware's effect. user@bitnest.cc, elevation = false.
ctx := context.WithValue(req.Context(), EmailKey, "user@bitnest.cc")
ctx = context.WithValue(ctx, ElevatedKey, false)
req = req.WithContext(ctx)
rec := httptest.NewRecorder()
ServeFileAPI(cfg, rec, req)
if rec.Code == http.StatusOK || rec.Code == http.StatusCreated {
t.Errorf("BUG REPRODUCED — un-elevated non-doc-controller wrote to WORM issued/: status=%d body=%q", rec.Code, rec.Body.String())
} else if rec.Code != http.StatusForbidden {
t.Errorf("status=%d (want 403); body=%q", rec.Code, rec.Body.String())
}
// Bytes-on-disk check too: even if the response says forbidden, the
// write must NOT have landed.
gotBytes, _ := os.ReadFile(target)
if string(gotBytes) != "# original\n" {
t.Errorf("file bytes mutated: got %q, want original", string(gotBytes))
}
}