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

54 lines
2.4 KiB
Go

package handler
import (
"net/http"
"codeberg.org/VARASYS/ZDDC/zddc/internal/config"
"codeberg.org/VARASYS/ZDDC/zddc/internal/zddc"
)
// AuthPathPrefix is the URL prefix at which machine-only auth-check
// endpoints live. Mirrors ProfilePathPrefix's dot-prefix convention so
// the dispatch's reserved-prefix guard sees it as an internal namespace
// rather than user content.
const AuthPathPrefix = "/.auth"
// ServeAuthAdmin is a forward_auth target for upstream proxies (e.g. the
// dev-shell pod's Caddy in front of code-server). It returns:
//
// - 200 OK — caller's resolved email is in the root .zddc's
// admins: list, per zddc.IsAdmin.
// - 403 Forbidden — anonymous, or email not in the admins: list, or
// no root .zddc exists. Also covers the case where
// the admins: field is empty/missing.
//
// The endpoint produces no body and does not redirect — it's a pure
// authorization decision intended to be polled by Caddy's forward_auth
// directive (or any equivalent in nginx, Traefik, oauth2-proxy, etc.).
//
// Performance: zddc.IsAdmin is a single map lookup against a cached
// PolicyChain; the .zddc file is parsed once and re-read only when the
// fsnotify watcher fires. Suitable to call on every request without
// noticeable overhead.
//
// Scope: gates ON ROOT-ADMIN STATUS ONLY. This is intentionally
// stricter than the regular acl.allow / acl.deny chain — admin-only
// endpoints (the dev-shell IDE, future maintenance routes) shouldn't
// fall through to subtree-level allowances. For per-route ACL, callers
// continue using the existing handlers (archive, profile, etc.) which
// consult AllowedWithChain.
func ServeAuthAdmin(cfg config.Config, w http.ResponseWriter, r *http.Request) {
email := EmailFromContext(r)
// Elevation-independent gate. Upstream proxies (Caddy forward_auth
// for the dev-shell IDE) call this from a different cookie scope
// than the zddc-server origin, so the elevation cookie can't reach
// here even when the user has it set. This is a coarse "is this
// email a root admin?" check, not a per-action authority decision —
// construct a synthetically-elevated Principal so the underlying
// admin check evaluates the admins: list as usual.
if email == "" || !zddc.IsAdmin(cfg.Root, zddc.Principal{Email: email, Elevated: true}) {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
w.WriteHeader(http.StatusOK)
}