Files
mcias/internal/ui/ui.go
Kyle Isom 4596ea08ab Fix grpcserver rate limiter: move to Server field
The package-level defaultRateLimiter drained its token bucket
across all test cases, causing later tests to hit ResourceExhausted.
Move rateLimiter from a package-level var to a *grpcRateLimiter field
on Server; New() allocates a fresh instance (10 req/s, burst 10) per
server. Each test's newTestEnv() constructs its own Server, so tests
no longer share limiter state.

Production behaviour is unchanged: a single Server is constructed at
startup and lives for the process lifetime.
2026-03-11 19:23:34 -07:00

429 lines
13 KiB
Go

// 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"
"encoding/json"
"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"
"git.wntrmute.dev/kyle/mcias/web"
)
const (
sessionCookieName = "mcias_session"
csrfCookieName = "mcias_csrf"
)
// UIServer serves the HTMX-based management UI.
type UIServer struct {
db *db.DB
cfg *config.Config
logger *slog.Logger
csrf *CSRFManager
tmpls map[string]*template.Template // page name → template set
pubKey ed25519.PublicKey
privKey ed25519.PrivateKey
masterKey []byte
}
// 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 },
"prettyJSON": func(s string) string {
var v json.RawMessage
if json.Unmarshal([]byte(s), &v) != nil {
return s
}
pretty, err := json.MarshalIndent(v, "", " ")
if err != nil {
return s
}
return string(pretty)
},
}
// Parse shared templates (base layout + all fragments) into a base set.
// Each page template is then parsed into a clone of this base set so that
// competing "content"/"title" definitions do not collide.
sharedFiles := []string{
"templates/base.html",
"templates/fragments/account_row.html",
"templates/fragments/account_status.html",
"templates/fragments/roles_editor.html",
"templates/fragments/token_list.html",
"templates/fragments/totp_step.html",
"templates/fragments/error.html",
"templates/fragments/audit_rows.html",
}
base, err := template.New("").Funcs(funcMap).ParseFS(web.TemplateFS, sharedFiles...)
if err != nil {
return nil, fmt.Errorf("ui: parse shared templates: %w", err)
}
// Each page template defines "content" and "title" blocks; parsing them
// into separate clones prevents the last-defined block from winning.
pageFiles := map[string]string{
"login": "templates/login.html",
"dashboard": "templates/dashboard.html",
"accounts": "templates/accounts.html",
"account_detail": "templates/account_detail.html",
"audit": "templates/audit.html",
"audit_detail": "templates/audit_detail.html",
}
tmpls := make(map[string]*template.Template, len(pageFiles))
for name, file := range pageFiles {
clone, cloneErr := base.Clone()
if cloneErr != nil {
return nil, fmt.Errorf("ui: clone base templates for %s: %w", name, cloneErr)
}
if _, parseErr := clone.ParseFS(web.TemplateFS, file); parseErr != nil {
return nil, fmt.Errorf("ui: parse page template %s: %w", name, parseErr)
}
tmpls[name] = clone
}
return &UIServer{
db: database,
cfg: cfg,
pubKey: pub,
privKey: priv,
masterKey: masterKey,
logger: logger,
csrf: csrf,
tmpls: tmpls,
}, 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(web.StaticFS, "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))
mux.Handle("GET /audit/{id}", adminGet(u.handleAuditDetail))
}
// ---- 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.
// Security: limit body size to prevent memory exhaustion (gosec G120).
r.Body = http.MaxBytesReader(w, r.Body, maxFormBytes)
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.
// For page templates (dashboard, accounts, etc.) the page-specific template set
// is used; for fragment templates the name is looked up across all sets.
func (u *UIServer) render(w http.ResponseWriter, name string, data interface{}) {
tmpl := u.templateFor(name)
if tmpl == nil {
u.logger.Error("template not found", "template", name)
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
var buf bytes.Buffer
if err := 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())
}
// templateFor returns the template set that contains the named template.
// Page templates have a dedicated set; fragment templates exist in every set.
func (u *UIServer) templateFor(name string) *template.Template {
if t, ok := u.tmpls[name]; ok {
return t
}
// Fragment — available in any page set; pick the first one.
for _, t := range u.tmpls {
if t.Lookup(name) != nil {
return t
}
}
return nil
}
// 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, `<div class="alert alert-error" role="alert">%s</div>`, template.HTMLEscapeString(msg))
return
}
http.Error(w, msg, status)
}
// maxFormBytes limits the size of UI form submissions (1 MiB).
// Security: prevents memory exhaustion from oversized POST bodies (gosec G120).
const maxFormBytes = 1 << 20
// clientIP extracts the client IP from RemoteAddr (best effort).
func clientIP(r *http.Request) string {
addr := r.RemoteAddr
if idx := strings.LastIndex(addr, ":"); idx != -1 {
return addr[:idx]
}
return addr
}
// ---- Page data types ----
// PageData is embedded in all page-level view structs.
type PageData struct {
CSRFToken string
Flash string
Error string
}
// LoginData is the view model for the login page.
type LoginData struct {
Error string
Username string // pre-filled on TOTP step
Password string // pre-filled on TOTP step (value attr, never logged)
}
// DashboardData is the view model for the dashboard page.
type DashboardData struct {
PageData
RecentEvents []*db.AuditEventView
TotalAccounts int
ActiveAccounts int
}
// AccountsData is the view model for the accounts list page.
type AccountsData struct {
PageData
Accounts []*model.Account
}
// AccountDetailData is the view model for the account detail page.
type AccountDetailData struct {
PageData
Account *model.Account
Roles []string
AllRoles []string
Tokens []*model.TokenRecord
}
// AuditData is the view model for the audit log page.
type AuditData struct {
PageData
FilterType string
Events []*db.AuditEventView
EventTypes []string
Total int64
TotalPages int
Page int
}
// AuditDetailData is the view model for a single audit event detail page.
type AuditDetailData struct {
Event *db.AuditEventView
PageData
}