ZDDC/zddc/internal/handler/authcheck_test.go
ZDDC 2d114fcb96 refactor: unified listing protocol + form-editor retirement + admin elevation
Three coordinated changes that share the same files. Common theme:
convention beats exception. Where the codebase had a bespoke wire shape
or a special-case route, replace it with the generic shape every other
client already speaks.

== Listing protocol ==

GET / Accept: application/json used to dispatch to a bespoke
ServeProjectList handler returning {name, url, title} per project — a
shape that diverged from every other directory's listing.FileInfo
response. Now:

- listing.FileInfo gains an optional `title` field (read from each
  directory's own .zddc title:). Generic clients (landing, browse)
  read the same shape from every URL.
- appfs.ListDirectory emits a virtual `.zddc` entry (is_dir:false,
  virtual:true) when no on-disk file exists at that path and the
  caller asked for ?hidden=1. Opens an editable view of the cascade
  defaults; PUT-saving its bytes materialises a real file.
- The bespoke GET / JSON branch in cmd/zddc-server/main.go is gone.
  The bare-root landing serve is Accept-gated: HTML requests get the
  landing tool (project picker), JSON requests fall through to
  ServeDirectory and get the generic listing.
- landing's fetchProjects filters the new generic shape (is_dir,
  strip trailing slash) — same pattern fetchParties already used at
  /<project>/archive/.

== Form editor retirement ==

`<dir>/.zddc.html` was a server-rendered form for editing per-directory
.zddc files (~900 LOC across zddceditor.go, zddchandler.go, zddc_assets.go).
Browse's YAML/CodeMirror editor (with .zddc-schema lint) already edits
the same files via the generic file-API. Two ways to edit the same data
is exception, not convention.

- Delete zddceditor.go, zddchandler.go, zddc_assets.go and tests.
- `/<dir>/.zddc.html` → 302 redirect to `/<dir>/?file=.zddc` (browse
  opens the .zddc in its editor pane).
- /.profile/zddc/* namespace deleted (REST API + assets sub-route).
- Profile page's "Editable .zddc files" list links to browse.
- ServeZddcFile's 405 message + virtual-body comment point at the
  browse URL instead of the dead form.

== Admin elevation (Principal model) ==

Sudo-style: admins are treated as normal users by default; opting into
admin powers is per-request and gated by a `zddc-elevate=1` cookie.

- zddc.Principal{Email, Elevated} replaces bare-email arguments on
  IsAdmin / IsSubtreeAdmin / CanEditZddc. The signature change makes
  the elevation gate compiler-enforced at every admin call site —
  audit-fragility is gone. The empty-email short-circuit is no longer
  load-bearing for elevation; Principal.gate() is the explicit check.
- handler.ACLMiddleware derives Elevated per request: bearer tokens
  are implicitly elevated (CLI clients can't toggle a cookie); browser
  sessions elevate only when zddc-elevate=1 is set. PrincipalFromContext(r)
  is the one-call-per-site bundling helper.
- Every admin-check call site updated to pass a Principal.
- /.auth/admin (forward_auth target for the dev-shell IDE) explicitly
  bypasses elevation with a synthetic-elevated Principal — different
  cookie scope than zddc-server origin, documented inline.
- AccessView gains CanElevate (elevation-independent "does this email
  have admin authority anywhere?") so the header toggle can render
  itself for an un-elevated admin who hasn't opted in yet.
- ServeProjectList is removed; ProjectInfo + EnumerateProjects stay
  for the profile page's server-rendered project list.
- MatchAppHTML stays — still used by main.go to route <dir>/<tool>.html
  URLs to the apps subsystem when no real file exists.
- Test helpers carry Elevated=true by default (matches the
  pre-elevation default; tests for the un-elevated gate use the
  explicit form).

Go tests pass across all 14 internal packages. Browse + every other
tool rebuilds clean.

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

64 lines
2.1 KiB
Go

package handler
import (
"net/http"
"net/http/httptest"
"testing"
)
// TestServeAuthAdmin pins the contract of the forward_auth endpoint
// used by upstream proxies (Caddy in the dev-shell pod) to gate
// admin-only routes:
//
// 200 → caller is in the root .zddc admins: list
// 403 → anonymous, OR not in admins:, OR no admins configured
//
// Reuses the profileTestRoot fixture which materializes a temp .zddc
// with the supplied admins, and the requestWithEmail helper that
// injects the email into request context the same way ACLMiddleware
// would in production.
func TestServeAuthAdmin(t *testing.T) {
cfg, _ := profileTestRoot(t, []string{"alice@example.com"})
cases := []struct {
name string
email string
wantStatus int
}{
{"empty email is denied", "", http.StatusForbidden},
{"non-admin is denied", "bob@example.com", http.StatusForbidden},
{"admin is allowed", "alice@example.com", http.StatusOK},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
req := requestAsAdmin(http.MethodGet, AuthPathPrefix+"/admin", tc.email)
rec := httptest.NewRecorder()
ServeAuthAdmin(cfg, rec, req)
if rec.Code != tc.wantStatus {
t.Errorf("status = %d, want %d (body: %q)",
rec.Code, tc.wantStatus, rec.Body.String())
}
})
}
}
// TestServeAuthAdmin_NoZddcRootDeniesEverything covers the bootstrap-
// state behaviour: when no /srv/.zddc exists, IsAdmin returns false for
// everyone, which means /.auth/admin returns 403 universally. This is
// the desired safe-default before an operator drops a root .zddc onto
// the share.
func TestServeAuthAdmin_NoZddcRootDeniesEverything(t *testing.T) {
// profileTestRoot with nil admins skips writing the file entirely.
cfg, _ := profileTestRoot(t, nil)
for _, email := range []string{"", "alice@example.com", "anyone@example.com"} {
req := requestAsAdmin(http.MethodGet, AuthPathPrefix+"/admin", email)
rec := httptest.NewRecorder()
ServeAuthAdmin(cfg, rec, req)
if rec.Code != http.StatusForbidden {
t.Errorf("email %q without .zddc: status %d, want 403",
email, rec.Code)
}
}
}