// Package ui provides the HTMX-based management web interface for MCIAS. // // Security design: // - Session tokens are stored as HttpOnly, Secure, SameSite=Strict cookies. // They are never accessible to JavaScript. // - CSRF protection uses the HMAC-signed Double-Submit Cookie pattern. // The mcias_csrf cookie is non-HttpOnly so HTMX can include it in the // X-CSRF-Token header on every mutating request. SameSite=Strict is the // primary browser-level CSRF defence. // - UI handlers call internal Go functions directly — no internal HTTP round-trips. // - All templates are parsed once at startup via embed.FS; no dynamic template // loading from disk at request time. package ui import ( "bytes" "crypto/ed25519" "embed" "fmt" "html/template" "io/fs" "log/slog" "net/http" "strings" "time" "git.wntrmute.dev/kyle/mcias/internal/config" "git.wntrmute.dev/kyle/mcias/internal/db" "git.wntrmute.dev/kyle/mcias/internal/model" ) //go:embed all:../../web/templates var templateFS embed.FS //go:embed all:../../web/static var staticFS embed.FS const ( sessionCookieName = "mcias_session" csrfCookieName = "mcias_csrf" ) // UIServer serves the HTMX-based management UI. type UIServer struct { db *db.DB cfg *config.Config pubKey ed25519.PublicKey privKey ed25519.PrivateKey masterKey []byte logger *slog.Logger csrf *CSRFManager tmpl *template.Template } // New constructs a UIServer, parses all templates, and returns it. // Returns an error if template parsing fails. func New(database *db.DB, cfg *config.Config, priv ed25519.PrivateKey, pub ed25519.PublicKey, masterKey []byte, logger *slog.Logger) (*UIServer, error) { csrf := newCSRFManager(masterKey) funcMap := template.FuncMap{ "formatTime": func(t time.Time) string { if t.IsZero() { return "" } return t.UTC().Format("2006-01-02 15:04:05") }, "truncateJTI": func(jti string) string { if len(jti) > 8 { return jti[:8] } return jti }, "string": func(v interface{}) string { switch s := v.(type) { case model.AccountStatus: return string(s) case model.AccountType: return string(s) default: return fmt.Sprintf("%v", v) } }, "hasRole": func(roles []string, role string) bool { for _, r := range roles { if r == role { return true } } return false }, "not": func(b bool) bool { return !b }, "add": func(a, b int) int { return a + b }, "sub": func(a, b int) int { return a - b }, "gt": func(a, b int) bool { return a > b }, "lt": func(a, b int) bool { return a < b }, } tmpl, err := template.New("").Funcs(funcMap).ParseFS(templateFS, "web/templates/base.html", "web/templates/login.html", "web/templates/dashboard.html", "web/templates/accounts.html", "web/templates/account_detail.html", "web/templates/audit.html", "web/templates/fragments/account_row.html", "web/templates/fragments/account_status.html", "web/templates/fragments/roles_editor.html", "web/templates/fragments/token_list.html", "web/templates/fragments/totp_step.html", "web/templates/fragments/error.html", "web/templates/fragments/audit_rows.html", ) if err != nil { return nil, fmt.Errorf("ui: parse templates: %w", err) } return &UIServer{ db: database, cfg: cfg, pubKey: pub, privKey: priv, masterKey: masterKey, logger: logger, csrf: csrf, tmpl: tmpl, }, nil } // Register attaches all UI routes to mux. func (u *UIServer) Register(mux *http.ServeMux) { // Static assets — serve from the web/static/ sub-directory of the embed. staticSubFS, err := fs.Sub(staticFS, "web/static") if err != nil { panic(fmt.Sprintf("ui: static sub-FS: %v", err)) } mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(staticSubFS))) // Redirect root to login. mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/" { http.Redirect(w, r, "/login", http.StatusFound) return } http.NotFound(w, r) }) // Auth routes (no session required). mux.HandleFunc("GET /login", u.handleLoginPage) mux.HandleFunc("POST /login", u.handleLoginPost) mux.HandleFunc("POST /logout", u.handleLogout) // Protected routes. auth := u.requireCookieAuth admin := func(h http.HandlerFunc) http.Handler { return auth(u.requireCSRF(http.HandlerFunc(h))) } adminGet := func(h http.HandlerFunc) http.Handler { return auth(http.HandlerFunc(h)) } mux.Handle("GET /dashboard", adminGet(u.handleDashboard)) mux.Handle("GET /accounts", adminGet(u.handleAccountsList)) mux.Handle("POST /accounts", admin(u.handleCreateAccount)) mux.Handle("GET /accounts/{id}", adminGet(u.handleAccountDetail)) mux.Handle("PATCH /accounts/{id}/status", admin(u.handleUpdateAccountStatus)) mux.Handle("DELETE /accounts/{id}", admin(u.handleDeleteAccount)) mux.Handle("GET /accounts/{id}/roles/edit", adminGet(u.handleRolesEditForm)) mux.Handle("PUT /accounts/{id}/roles", admin(u.handleSetRoles)) mux.Handle("DELETE /token/{jti}", admin(u.handleRevokeToken)) mux.Handle("POST /accounts/{id}/token", admin(u.handleIssueSystemToken)) mux.Handle("GET /audit", adminGet(u.handleAuditPage)) mux.Handle("GET /audit/rows", adminGet(u.handleAuditRows)) } // ---- Middleware ---- // requireCookieAuth validates the mcias_session cookie and injects claims. // On failure, HTMX requests get HX-Redirect; browser requests get a redirect. func (u *UIServer) requireCookieAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie(sessionCookieName) if err != nil || cookie.Value == "" { u.redirectToLogin(w, r) return } claims, err := validateSessionToken(u.pubKey, cookie.Value, u.cfg.Tokens.Issuer) if err != nil { u.clearSessionCookie(w) u.redirectToLogin(w, r) return } // Check revocation. rec, err := u.db.GetTokenRecord(claims.JTI) if err != nil || rec.IsRevoked() { u.clearSessionCookie(w) u.redirectToLogin(w, r) return } ctx := contextWithClaims(r.Context(), claims) next.ServeHTTP(w, r.WithContext(ctx)) }) } // requireCSRF validates the CSRF token on mutating requests (POST/PUT/PATCH/DELETE). // The token is read from X-CSRF-Token header (HTMX) or _csrf form field (fallback). func (u *UIServer) requireCSRF(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie(csrfCookieName) if err != nil || cookie.Value == "" { http.Error(w, "CSRF cookie missing", http.StatusForbidden) return } // Header takes precedence (HTMX sets it automatically via hx-headers on body). formVal := r.Header.Get("X-CSRF-Token") if formVal == "" { // Fallback: parse form and read _csrf field. if parseErr := r.ParseForm(); parseErr == nil { formVal = r.FormValue("_csrf") } } if !u.csrf.Validate(cookie.Value, formVal) { http.Error(w, "CSRF token invalid", http.StatusForbidden) return } next.ServeHTTP(w, r) }) } // ---- Helpers ---- // isHTMX reports whether the request was initiated by HTMX. func isHTMX(r *http.Request) bool { return r.Header.Get("HX-Request") == "true" } // redirectToLogin redirects to the login page, using HX-Redirect for HTMX. func (u *UIServer) redirectToLogin(w http.ResponseWriter, r *http.Request) { if isHTMX(r) { w.Header().Set("HX-Redirect", "/login") w.WriteHeader(http.StatusUnauthorized) return } http.Redirect(w, r, "/login", http.StatusFound) } // clearSessionCookie expires the session cookie. func (u *UIServer) clearSessionCookie(w http.ResponseWriter) { http.SetCookie(w, &http.Cookie{ Name: sessionCookieName, Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: true, SameSite: http.SameSiteStrictMode, }) } // setCSRFCookies sets the mcias_csrf cookie and returns the header value to // embed in the page/form. func (u *UIServer) setCSRFCookies(w http.ResponseWriter) (string, error) { cookieVal, headerVal, err := u.csrf.NewToken() if err != nil { return "", err } http.SetCookie(w, &http.Cookie{ Name: csrfCookieName, Value: cookieVal, Path: "/", // Security: non-HttpOnly so that HTMX can embed it in hx-headers; // SameSite=Strict is the primary CSRF defence for browser requests. HttpOnly: false, Secure: true, SameSite: http.SameSiteStrictMode, }) return headerVal, nil } // render executes the named template, writing the result to w. // Renders to a buffer first so partial template failures don't corrupt output. func (u *UIServer) render(w http.ResponseWriter, name string, data interface{}) { var buf bytes.Buffer if err := u.tmpl.ExecuteTemplate(&buf, name, data); err != nil { u.logger.Error("template render error", "template", name, "error", err) http.Error(w, "internal server error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = w.Write(buf.Bytes()) } // renderError returns an error response appropriate for the request type. func (u *UIServer) renderError(w http.ResponseWriter, r *http.Request, status int, msg string) { if isHTMX(r) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(status) _, _ = fmt.Fprintf(w, `