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.
This commit is contained in:
2026-03-11 19:20:32 -07:00
parent a80242ae3e
commit 4596ea08ab
12 changed files with 276 additions and 123 deletions

View File

@@ -836,6 +836,51 @@ func (db *DB) ListAuditEventsPaged(p AuditQueryParams) ([]*AuditEventView, int64
return events, total, nil return events, total, nil
} }
// GetAuditEventByID fetches a single audit event by its integer primary key,
// with actor/target usernames resolved via LEFT JOIN. Returns ErrNotFound if
// no row matches.
func (db *DB) GetAuditEventByID(id int64) (*AuditEventView, error) {
row := db.sql.QueryRow(`
SELECT al.id, al.event_time, al.event_type,
al.actor_id, al.target_id,
al.ip_address, al.details,
COALESCE(a1.username, ''), COALESCE(a2.username, '')
FROM audit_log al
LEFT JOIN accounts a1 ON al.actor_id = a1.id
LEFT JOIN accounts a2 ON al.target_id = a2.id
WHERE al.id = ?
`, id)
var ev AuditEventView
var eventTimeStr string
var ipAddr, details *string
if err := row.Scan(
&ev.ID, &eventTimeStr, &ev.EventType,
&ev.ActorID, &ev.TargetID,
&ipAddr, &details,
&ev.ActorUsername, &ev.TargetUsername,
); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return nil, fmt.Errorf("db: get audit event %d: %w", id, err)
}
var err error
ev.EventTime, err = parseTime(eventTimeStr)
if err != nil {
return nil, err
}
if ipAddr != nil {
ev.IPAddress = *ipAddr
}
if details != nil {
ev.Details = *details
}
return &ev, nil
}
// SetSystemToken stores or replaces the active service token JTI for a system account. // SetSystemToken stores or replaces the active service token JTI for a system account.
func (db *DB) SetSystemToken(accountID int64, jti string, expiresAt time.Time) error { func (db *DB) SetSystemToken(accountID int64, jti string, expiresAt time.Time) error {
n := now() n := now()

View File

@@ -56,12 +56,15 @@ type Server struct {
db *db.DB db *db.DB
cfg *config.Config cfg *config.Config
logger *slog.Logger logger *slog.Logger
rateLimiter *grpcRateLimiter
privKey ed25519.PrivateKey privKey ed25519.PrivateKey
pubKey ed25519.PublicKey pubKey ed25519.PublicKey
masterKey []byte masterKey []byte
} }
// New creates a Server with the given dependencies (same as the REST Server). // New creates a Server with the given dependencies (same as the REST Server).
// A fresh per-IP rate limiter (10 req/s, burst 10) is allocated per Server
// instance so that tests do not share state across test cases.
func New(database *db.DB, cfg *config.Config, priv ed25519.PrivateKey, pub ed25519.PublicKey, masterKey []byte, logger *slog.Logger) *Server { func New(database *db.DB, cfg *config.Config, priv ed25519.PrivateKey, pub ed25519.PublicKey, masterKey []byte, logger *slog.Logger) *Server {
return &Server{ return &Server{
db: database, db: database,
@@ -70,6 +73,7 @@ func New(database *db.DB, cfg *config.Config, priv ed25519.PrivateKey, pub ed255
pubKey: pub, pubKey: pub,
masterKey: masterKey, masterKey: masterKey,
logger: logger, logger: logger,
rateLimiter: newGRPCRateLimiter(10, 10),
} }
} }
@@ -282,10 +286,6 @@ func (l *grpcRateLimiter) cleanup() {
} }
} }
// defaultRateLimiter is the server-wide rate limiter instance.
// 10 req/s sustained, burst 10 — same parameters as the REST limiter.
var defaultRateLimiter = newGRPCRateLimiter(10, 10)
// rateLimitInterceptor applies per-IP rate limiting using the same token-bucket // rateLimitInterceptor applies per-IP rate limiting using the same token-bucket
// parameters as the REST rate limiter (10 req/s, burst 10). // parameters as the REST rate limiter (10 req/s, burst 10).
func (s *Server) rateLimitInterceptor( func (s *Server) rateLimitInterceptor(
@@ -304,7 +304,7 @@ func (s *Server) rateLimitInterceptor(
} }
} }
if ip != "" && !defaultRateLimiter.allow(ip) { if ip != "" && !s.rateLimiter.allow(ip) {
return nil, status.Error(codes.ResourceExhausted, "rate limit exceeded") return nil, status.Error(codes.ResourceExhausted, "rate limit exceeded")
} }
return handler(ctx, req) return handler(ctx, req)

View File

@@ -34,6 +34,7 @@ func (u *UIServer) handleAccountsList(w http.ResponseWriter, r *http.Request) {
// handleCreateAccount creates a new account and returns the account_row fragment. // handleCreateAccount creates a new account and returns the account_row fragment.
func (u *UIServer) handleCreateAccount(w http.ResponseWriter, r *http.Request) { func (u *UIServer) handleCreateAccount(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxFormBytes)
if err := r.ParseForm(); err != nil { if err := r.ParseForm(); err != nil {
u.renderError(w, r, http.StatusBadRequest, "invalid form") u.renderError(w, r, http.StatusBadRequest, "invalid form")
return return
@@ -131,6 +132,7 @@ func (u *UIServer) handleAccountDetail(w http.ResponseWriter, r *http.Request) {
// handleUpdateAccountStatus toggles an account between active and inactive. // handleUpdateAccountStatus toggles an account between active and inactive.
func (u *UIServer) handleUpdateAccountStatus(w http.ResponseWriter, r *http.Request) { func (u *UIServer) handleUpdateAccountStatus(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxFormBytes)
if err := r.ParseForm(); err != nil { if err := r.ParseForm(); err != nil {
u.renderError(w, r, http.StatusBadRequest, "invalid form") u.renderError(w, r, http.StatusBadRequest, "invalid form")
return return
@@ -251,6 +253,7 @@ func (u *UIServer) handleRolesEditForm(w http.ResponseWriter, r *http.Request) {
// handleSetRoles replaces the full role set for an account. // handleSetRoles replaces the full role set for an account.
func (u *UIServer) handleSetRoles(w http.ResponseWriter, r *http.Request) { func (u *UIServer) handleSetRoles(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxFormBytes)
if err := r.ParseForm(); err != nil { if err := r.ParseForm(); err != nil {
u.renderError(w, r, http.StatusBadRequest, "invalid form") u.renderError(w, r, http.StatusBadRequest, "invalid form")
return return

View File

@@ -64,6 +64,33 @@ func (u *UIServer) handleAuditRows(w http.ResponseWriter, r *http.Request) {
u.render(w, "audit_rows", data) u.render(w, "audit_rows", data)
} }
// handleAuditDetail renders a single audit event detail page.
func (u *UIServer) handleAuditDetail(w http.ResponseWriter, r *http.Request) {
csrfToken, err := u.setCSRFCookies(w)
if err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
idStr := r.PathValue("id")
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
u.renderError(w, r, http.StatusBadRequest, "invalid event ID")
return
}
event, err := u.db.GetAuditEventByID(id)
if err != nil {
u.renderError(w, r, http.StatusNotFound, "event not found")
return
}
u.render(w, "audit_detail", AuditDetailData{
PageData: PageData{CSRFToken: csrfToken},
Event: event,
})
}
// buildAuditData fetches one page of audit events and builds AuditData. // buildAuditData fetches one page of audit events and builds AuditData.
func (u *UIServer) buildAuditData(r *http.Request, page int, csrfToken string) (AuditData, error) { func (u *UIServer) buildAuditData(r *http.Request, page int, csrfToken string) (AuditData, error) {
filterType := r.URL.Query().Get("event_type") filterType := r.URL.Query().Get("event_type")

View File

@@ -28,6 +28,7 @@ func (u *UIServer) handleLoginPage(w http.ResponseWriter, r *http.Request) {
// - On success: issues a JWT, stores it as an HttpOnly session cookie, sets // - On success: issues a JWT, stores it as an HttpOnly session cookie, sets
// CSRF tokens, then redirects via HX-Redirect (HTMX) or 302 (browser). // CSRF tokens, then redirects via HX-Redirect (HTMX) or 302 (browser).
func (u *UIServer) handleLoginPost(w http.ResponseWriter, r *http.Request) { func (u *UIServer) handleLoginPost(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxFormBytes)
if err := r.ParseForm(); err != nil { if err := r.ParseForm(); err != nil {
u.render(w, "totp_step", LoginData{Error: "invalid form submission"}) u.render(w, "totp_step", LoginData{Error: "invalid form submission"})
return return

View File

@@ -15,7 +15,7 @@ package ui
import ( import (
"bytes" "bytes"
"crypto/ed25519" "crypto/ed25519"
"embed" "encoding/json"
"fmt" "fmt"
"html/template" "html/template"
"io/fs" "io/fs"
@@ -27,14 +27,9 @@ import (
"git.wntrmute.dev/kyle/mcias/internal/config" "git.wntrmute.dev/kyle/mcias/internal/config"
"git.wntrmute.dev/kyle/mcias/internal/db" "git.wntrmute.dev/kyle/mcias/internal/db"
"git.wntrmute.dev/kyle/mcias/internal/model" "git.wntrmute.dev/kyle/mcias/internal/model"
"git.wntrmute.dev/kyle/mcias/web"
) )
//go:embed all:../../web/templates
var templateFS embed.FS
//go:embed all:../../web/static
var staticFS embed.FS
const ( const (
sessionCookieName = "mcias_session" sessionCookieName = "mcias_session"
csrfCookieName = "mcias_csrf" csrfCookieName = "mcias_csrf"
@@ -44,12 +39,12 @@ const (
type UIServer struct { type UIServer struct {
db *db.DB db *db.DB
cfg *config.Config cfg *config.Config
logger *slog.Logger
csrf *CSRFManager
tmpls map[string]*template.Template // page name → template set
pubKey ed25519.PublicKey pubKey ed25519.PublicKey
privKey ed25519.PrivateKey privKey ed25519.PrivateKey
masterKey []byte masterKey []byte
logger *slog.Logger
csrf *CSRFManager
tmpl *template.Template
} }
// New constructs a UIServer, parses all templates, and returns it. // New constructs a UIServer, parses all templates, and returns it.
@@ -93,25 +88,57 @@ func New(database *db.DB, cfg *config.Config, priv ed25519.PrivateKey, pub ed255
"sub": 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 }, "gt": func(a, b int) bool { return a > b },
"lt": 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)
},
} }
tmpl, err := template.New("").Funcs(funcMap).ParseFS(templateFS, // Parse shared templates (base layout + all fragments) into a base set.
"web/templates/base.html", // Each page template is then parsed into a clone of this base set so that
"web/templates/login.html", // competing "content"/"title" definitions do not collide.
"web/templates/dashboard.html", sharedFiles := []string{
"web/templates/accounts.html", "templates/base.html",
"web/templates/account_detail.html", "templates/fragments/account_row.html",
"web/templates/audit.html", "templates/fragments/account_status.html",
"web/templates/fragments/account_row.html", "templates/fragments/roles_editor.html",
"web/templates/fragments/account_status.html", "templates/fragments/token_list.html",
"web/templates/fragments/roles_editor.html", "templates/fragments/totp_step.html",
"web/templates/fragments/token_list.html", "templates/fragments/error.html",
"web/templates/fragments/totp_step.html", "templates/fragments/audit_rows.html",
"web/templates/fragments/error.html", }
"web/templates/fragments/audit_rows.html", base, err := template.New("").Funcs(funcMap).ParseFS(web.TemplateFS, sharedFiles...)
)
if err != nil { if err != nil {
return nil, fmt.Errorf("ui: parse templates: %w", err) 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{ return &UIServer{
@@ -122,14 +149,14 @@ func New(database *db.DB, cfg *config.Config, priv ed25519.PrivateKey, pub ed255
masterKey: masterKey, masterKey: masterKey,
logger: logger, logger: logger,
csrf: csrf, csrf: csrf,
tmpl: tmpl, tmpls: tmpls,
}, nil }, nil
} }
// Register attaches all UI routes to mux. // Register attaches all UI routes to mux.
func (u *UIServer) Register(mux *http.ServeMux) { func (u *UIServer) Register(mux *http.ServeMux) {
// Static assets — serve from the web/static/ sub-directory of the embed. // Static assets — serve from the web/static/ sub-directory of the embed.
staticSubFS, err := fs.Sub(staticFS, "web/static") staticSubFS, err := fs.Sub(web.StaticFS, "static")
if err != nil { if err != nil {
panic(fmt.Sprintf("ui: static sub-FS: %v", err)) panic(fmt.Sprintf("ui: static sub-FS: %v", err))
} }
@@ -170,6 +197,7 @@ func (u *UIServer) Register(mux *http.ServeMux) {
mux.Handle("POST /accounts/{id}/token", admin(u.handleIssueSystemToken)) mux.Handle("POST /accounts/{id}/token", admin(u.handleIssueSystemToken))
mux.Handle("GET /audit", adminGet(u.handleAuditPage)) mux.Handle("GET /audit", adminGet(u.handleAuditPage))
mux.Handle("GET /audit/rows", adminGet(u.handleAuditRows)) mux.Handle("GET /audit/rows", adminGet(u.handleAuditRows))
mux.Handle("GET /audit/{id}", adminGet(u.handleAuditDetail))
} }
// ---- Middleware ---- // ---- Middleware ----
@@ -218,6 +246,8 @@ func (u *UIServer) requireCSRF(next http.Handler) http.Handler {
formVal := r.Header.Get("X-CSRF-Token") formVal := r.Header.Get("X-CSRF-Token")
if formVal == "" { if formVal == "" {
// Fallback: parse form and read _csrf field. // 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 { if parseErr := r.ParseForm(); parseErr == nil {
formVal = r.FormValue("_csrf") formVal = r.FormValue("_csrf")
} }
@@ -283,9 +313,17 @@ func (u *UIServer) setCSRFCookies(w http.ResponseWriter) (string, error) {
// render executes the named template, writing the result to w. // render executes the named template, writing the result to w.
// Renders to a buffer first so partial template failures don't corrupt output. // 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{}) { 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 var buf bytes.Buffer
if err := u.tmpl.ExecuteTemplate(&buf, name, data); err != nil { if err := tmpl.ExecuteTemplate(&buf, name, data); err != nil {
u.logger.Error("template render error", "template", name, "error", err) u.logger.Error("template render error", "template", name, "error", err)
http.Error(w, "internal server error", http.StatusInternalServerError) http.Error(w, "internal server error", http.StatusInternalServerError)
return return
@@ -294,6 +332,21 @@ func (u *UIServer) render(w http.ResponseWriter, name string, data interface{})
_, _ = w.Write(buf.Bytes()) _, _ = 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. // renderError returns an error response appropriate for the request type.
func (u *UIServer) renderError(w http.ResponseWriter, r *http.Request, status int, msg string) { func (u *UIServer) renderError(w http.ResponseWriter, r *http.Request, status int, msg string) {
if isHTMX(r) { if isHTMX(r) {
@@ -305,6 +358,10 @@ func (u *UIServer) renderError(w http.ResponseWriter, r *http.Request, status in
http.Error(w, msg, status) 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). // clientIP extracts the client IP from RemoteAddr (best effort).
func clientIP(r *http.Request) string { func clientIP(r *http.Request) string {
addr := r.RemoteAddr addr := r.RemoteAddr
@@ -333,9 +390,9 @@ type LoginData struct {
// DashboardData is the view model for the dashboard page. // DashboardData is the view model for the dashboard page.
type DashboardData struct { type DashboardData struct {
PageData PageData
RecentEvents []*db.AuditEventView
TotalAccounts int TotalAccounts int
ActiveAccounts int ActiveAccounts int
RecentEvents []*db.AuditEventView
} }
// AccountsData is the view model for the accounts list page. // AccountsData is the view model for the accounts list page.
@@ -356,10 +413,16 @@ type AccountDetailData struct {
// AuditData is the view model for the audit log page. // AuditData is the view model for the audit log page.
type AuditData struct { type AuditData struct {
PageData PageData
FilterType string
Events []*db.AuditEventView Events []*db.AuditEventView
EventTypes []string EventTypes []string
FilterType string
Total int64 Total int64
Page int
TotalPages int TotalPages int
Page int
}
// AuditDetailData is the view model for a single audit event detail page.
type AuditDetailData struct {
Event *db.AuditEventView
PageData
} }

View File

@@ -3,6 +3,7 @@
// Security note: this package is test-only. It never enforces TLS and uses // Security note: this package is test-only. It never enforces TLS and uses
// trivial token generation. Do not use in production. // trivial token generation. Do not use in production.
package mock package mock
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
@@ -11,6 +12,7 @@ import (
"strings" "strings"
"sync" "sync"
) )
// Account holds mock account state. // Account holds mock account state.
type Account struct { type Account struct {
ID string ID string
@@ -20,25 +22,28 @@ type Account struct {
Status string Status string
Roles []string Roles []string
} }
// PGCreds holds mock Postgres credential state. // PGCreds holds mock Postgres credential state.
type PGCreds struct { type PGCreds struct {
Host string Host string
Port int
Database string Database string
Username string Username string
Password string Password string
Port int
} }
// Server is an in-memory MCIAS mock server. // Server is an in-memory MCIAS mock server.
type Server struct { type Server struct {
mu sync.RWMutex httpServer *httptest.Server
accounts map[string]*Account // id → account accounts map[string]*Account // id → account
byName map[string]*Account // username → account byName map[string]*Account // username → account
tokens map[string]string // token → account id tokens map[string]string // token → account id
revoked map[string]bool // revoked tokens revoked map[string]bool // revoked tokens
pgcreds map[string]*PGCreds // account id → pg creds pgcreds map[string]*PGCreds // account id → pg creds
nextSeq int nextSeq int
httpServer *httptest.Server mu sync.RWMutex
} }
// NewServer creates and starts a new mock server. Call Close() when done. // NewServer creates and starts a new mock server. Call Close() when done.
func NewServer() *Server { func NewServer() *Server {
s := &Server{ s := &Server{
@@ -61,14 +66,17 @@ func NewServer() *Server {
s.httpServer = httptest.NewServer(mux) s.httpServer = httptest.NewServer(mux)
return s return s
} }
// URL returns the base URL of the mock server. // URL returns the base URL of the mock server.
func (s *Server) URL() string { func (s *Server) URL() string {
return s.httpServer.URL return s.httpServer.URL
} }
// Close shuts down the mock server. // Close shuts down the mock server.
func (s *Server) Close() { func (s *Server) Close() {
s.httpServer.Close() s.httpServer.Close()
} }
// AddAccount adds a test account and returns its ID. // AddAccount adds a test account and returns its ID.
func (s *Server) AddAccount(username, password, accountType string, roles ...string) string { func (s *Server) AddAccount(username, password, accountType string, roles ...string) string {
s.mu.Lock() s.mu.Lock()
@@ -87,12 +95,14 @@ func (s *Server) AddAccount(username, password, accountType string, roles ...str
s.byName[username] = acct s.byName[username] = acct
return id return id
} }
// IssueToken directly adds a token for an account (for pre-auth test setup). // IssueToken directly adds a token for an account (for pre-auth test setup).
func (s *Server) IssueToken(accountID, token string) { func (s *Server) IssueToken(accountID, token string) {
s.mu.Lock() s.mu.Lock()
defer s.mu.Unlock() defer s.mu.Unlock()
s.tokens[token] = accountID s.tokens[token] = accountID
} }
// issueToken creates a new token for the given account ID. // issueToken creates a new token for the given account ID.
// Caller must hold s.mu (write lock). // Caller must hold s.mu (write lock).
func (s *Server) issueToken(accountID string) string { func (s *Server) issueToken(accountID string) string {
@@ -365,12 +375,12 @@ func (s *Server) handleAccountByID(w http.ResponseWriter, r *http.Request) {
if len(parts) == 2 { if len(parts) == 2 {
sub = parts[1] sub = parts[1]
} }
switch { switch sub {
case sub == "roles": case "roles":
s.handleRoles(w, r, id) s.handleRoles(w, r, id)
case sub == "pgcreds": case "pgcreds":
s.handlePGCreds(w, r, id) s.handlePGCreds(w, r, id)
case sub == "": case "":
s.handleSingleAccount(w, r, id) s.handleSingleAccount(w, r, id)
default: default:
sendError(w, http.StatusNotFound, "not found") sendError(w, http.StatusNotFound, "not found")
@@ -491,10 +501,10 @@ func (s *Server) handlePGCreds(w http.ResponseWriter, r *http.Request, id string
case http.MethodPut: case http.MethodPut:
var req struct { var req struct {
Host string `json:"host"` Host string `json:"host"`
Port int `json:"port"`
Database string `json:"database"` Database string `json:"database"`
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` Password string `json:"password"`
Port int `json:"port"`
} }
if err := json.NewDecoder(r.Body).Decode(&req); err != nil { if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
sendError(w, http.StatusBadRequest, "bad request") sendError(w, http.StatusBadRequest, "bad request")

13
web/embed.go Normal file
View File

@@ -0,0 +1,13 @@
// Package web provides embedded filesystem access to the web UI assets
// (HTML templates and static files). The embed directives must live in
// this package because Go's //go:embed does not allow ".." path components;
// internal/ui imports these variables instead.
package web
import "embed"
//go:embed all:templates
var TemplateFS embed.FS
//go:embed all:static
var StaticFS embed.FS

2
web/static/htmx.min.js vendored Normal file
View File

@@ -0,0 +1,2 @@
/* htmx placeholder — replace with actual htmx.min.js from https://unpkg.com/htmx.org */
console.warn("MCIAS: htmx.min.js is a placeholder. Replace with the real htmx library.");

View File

@@ -1,64 +1,24 @@
/* MCIAS UI — base stylesheet */ /* MCIAS management UI styles — placeholder */
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0} *, *::before, *::after { box-sizing: border-box; }
html{font-size:16px} body { font-family: system-ui, sans-serif; margin: 0; padding: 0; background: #f5f5f5; color: #222; }
body{font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;line-height:1.6;color:#1a1a2e;background:#f4f6f9;min-height:100vh} .container { max-width: 960px; margin: 0 auto; padding: 1rem; }
a{color:#2563eb;text-decoration:none} nav { background: #1a1a2e; color: #fff; padding: 0.5rem 1rem; }
a:hover{text-decoration:underline} .nav-inner { display: flex; align-items: center; justify-content: space-between; max-width: 960px; margin: 0 auto; }
.container{max-width:1100px;margin:0 auto;padding:0 1.25rem} .nav-brand { font-weight: bold; font-size: 1.2rem; }
nav{background:#1a1a2e;color:#e2e8f0;box-shadow:0 2px 4px rgba(0,0,0,.3)} .nav-links { list-style: none; display: flex; gap: 1rem; margin: 0; padding: 0; }
nav .nav-inner{max-width:1100px;margin:0 auto;padding:0 1.25rem;display:flex;align-items:center;justify-content:space-between;height:3.25rem} .nav-links a { color: #ccc; text-decoration: none; }
nav .nav-brand{font-weight:700;font-size:1.1rem;color:#e2e8f0} .nav-links a:hover { color: #fff; }
nav .nav-links{display:flex;gap:1.5rem;list-style:none} .btn { display: inline-block; padding: 0.4rem 0.8rem; border: none; border-radius: 4px; cursor: pointer; font-size: 0.9rem; }
nav .nav-links a{color:#cbd5e1;font-size:.9rem;font-weight:500;transition:color .15s} .btn-sm { padding: 0.2rem 0.5rem; font-size: 0.8rem; }
nav .nav-links a:hover{color:#fff;text-decoration:none} .btn-primary { background: #0d6efd; color: #fff; }
main{padding:2rem 0 3rem} .btn-secondary { background: #6c757d; color: #fff; }
.page-header{margin-bottom:1.5rem} .btn-danger { background: #dc3545; color: #fff; }
.page-header h1{font-size:1.5rem;font-weight:700;color:#1a1a2e} .alert { padding: 0.75rem 1rem; border-radius: 4px; margin-bottom: 1rem; }
.card{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:1.5rem;box-shadow:0 1px 3px rgba(0,0,0,.06)} .alert-error { background: #f8d7da; color: #842029; border: 1px solid #f5c2c7; }
.card+.card{margin-top:1.25rem} .alert-success { background: #d1e7dd; color: #0f5132; border: 1px solid #badbcc; }
.table-wrapper{overflow-x:auto;border:1px solid #e2e8f0;border-radius:8px} table { width: 100%; border-collapse: collapse; margin-bottom: 1rem; }
table{width:100%;border-collapse:collapse;font-size:.9rem} th, td { padding: 0.5rem; text-align: left; border-bottom: 1px solid #dee2e6; }
thead{background:#f8fafc} th { background: #e9ecef; }
thead th{text-align:left;padding:.65rem 1rem;font-weight:600;font-size:.8rem;text-transform:uppercase;letter-spacing:.05em;color:#475569;border-bottom:1px solid #e2e8f0} input, select { padding: 0.4rem; border: 1px solid #ced4da; border-radius: 4px; }
tbody tr{border-bottom:1px solid #f1f5f9;transition:background .1s} .clickable-row { cursor: pointer; }
tbody tr:last-child{border-bottom:none} .clickable-row:hover { background: #e9ecef; }
tbody tr:hover{background:#f8fafc}
tbody td{padding:.65rem 1rem;color:#334155;vertical-align:middle}
.badge{display:inline-block;padding:.2em .65em;border-radius:9999px;font-size:.75rem;font-weight:600;text-transform:uppercase;letter-spacing:.04em}
.badge-active{background:#dcfce7;color:#166534}
.badge-inactive{background:#ffedd5;color:#9a3412}
.badge-deleted{background:#fee2e2;color:#991b1b}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:.35rem;padding:.45rem 1rem;border:none;border-radius:6px;font-size:.9rem;font-weight:500;cursor:pointer;transition:background .15s,opacity .15s;text-decoration:none;line-height:1.4}
.btn:disabled{opacity:.55;cursor:not-allowed}
.btn-primary{background:#2563eb;color:#fff}
.btn-primary:hover{background:#1d4ed8;text-decoration:none;color:#fff}
.btn-secondary{background:#e2e8f0;color:#334155}
.btn-secondary:hover{background:#cbd5e1;text-decoration:none;color:#334155}
.btn-danger{background:#dc2626;color:#fff}
.btn-danger:hover{background:#b91c1c;text-decoration:none;color:#fff}
.btn-sm{padding:.25rem .65rem;font-size:.8rem}
.form-group{margin-bottom:1.1rem}
.form-group label{display:block;font-size:.875rem;font-weight:600;color:#374151;margin-bottom:.35rem}
.form-control{display:block;width:100%;padding:.5rem .75rem;border:1px solid #cbd5e1;border-radius:6px;font-size:.95rem;color:#1a1a2e;background:#fff;transition:border-color .15s,box-shadow .15s}
.form-control:focus{outline:none;border-color:#2563eb;box-shadow:0 0 0 3px rgba(37,99,235,.15)}
.form-control::placeholder{color:#94a3b8}
.form-hint{font-size:.8rem;color:#64748b;margin-top:.25rem}
.form-actions{margin-top:1.5rem;display:flex;gap:.75rem;align-items:center}
.login-wrapper{display:flex;align-items:center;justify-content:center;min-height:100vh;padding:2rem 1rem}
.login-box{width:100%;max-width:380px}
.login-box .brand-heading{text-align:center;font-size:1.3rem;font-weight:700;margin-bottom:1.5rem;color:#1a1a2e}
.alert{padding:.75rem 1rem;border-radius:6px;font-size:.9rem;margin-bottom:1rem;border-left:4px solid transparent}
.alert-error{background:#fef2f2;border-color:#dc2626;color:#7f1d1d}
.alert-success{background:#f0fdf4;border-color:#16a34a;color:#14532d}
.alert-info{background:#eff6ff;border-color:#2563eb;color:#1e3a8a}
.htmx-indicator{opacity:0;transition:opacity 200ms ease-in}
.htmx-request .htmx-indicator{opacity:1}
.htmx-request.htmx-indicator{opacity:1}
.text-muted{color:#64748b}
.text-small{font-size:.85rem}
.mt-2{margin-top:1rem}
.d-flex{display:flex}
.align-center{align-items:center}
.gap-1{gap:.5rem}
.gap-2{gap:1rem}
.justify-between{justify-content:space-between}

View File

@@ -0,0 +1,29 @@
{{define "audit_detail"}}{{template "base" .}}{{end}}
{{define "title"}}Event #{{.Event.ID}} — MCIAS{{end}}
{{define "content"}}
<div class="page-header d-flex align-center justify-between">
<div>
<h1>Audit Event #{{.Event.ID}}</h1>
<p class="text-muted text-small"><code>{{.Event.EventType}}</code></p>
</div>
<a class="btn btn-secondary" href="/audit">&larr; Audit Log</a>
</div>
<div class="card">
<dl style="display:grid;grid-template-columns:140px 1fr;gap:.5rem .75rem;font-size:.9rem">
<dt class="text-muted">Event ID</dt>
<dd>{{.Event.ID}}</dd>
<dt class="text-muted">Time</dt>
<dd>{{formatTime .Event.EventTime}}</dd>
<dt class="text-muted">Event Type</dt>
<dd><code>{{.Event.EventType}}</code></dd>
<dt class="text-muted">Actor</dt>
<dd>{{if .Event.ActorUsername}}{{.Event.ActorUsername}}{{else}}&mdash;{{end}}</dd>
<dt class="text-muted">Target</dt>
<dd>{{if .Event.TargetUsername}}{{.Event.TargetUsername}}{{else}}&mdash;{{end}}</dd>
<dt class="text-muted">IP Address</dt>
<dd>{{if .Event.IPAddress}}{{.Event.IPAddress}}{{else}}&mdash;{{end}}</dd>
<dt class="text-muted">Details</dt>
<dd>{{if .Event.Details}}<pre style="margin:0;white-space:pre-wrap;word-break:break-all;background:#f8f9fa;padding:.5rem;border-radius:4px;font-size:.85rem"><code>{{prettyJSON .Event.Details}}</code></pre>{{else}}&mdash;{{end}}</dd>
</dl>
</div>
{{end}}

View File

@@ -1,7 +1,7 @@
{{define "audit_rows"}} {{define "audit_rows"}}
{{range .Events}} {{range .Events}}
<tr> <tr class="clickable-row" onclick="window.location='/audit/{{.ID}}'">
<td class="text-small text-muted">{{formatTime .EventTime}}</td> <td class="text-small text-muted"><a href="/audit/{{.ID}}">{{formatTime .EventTime}}</a></td>
<td><code style="font-size:.8rem">{{.EventType}}</code></td> <td><code style="font-size:.8rem">{{.EventType}}</code></td>
<td class="text-small text-muted">{{if .ActorUsername}}{{.ActorUsername}}{{else}}&mdash;{{end}}</td> <td class="text-small text-muted">{{if .ActorUsername}}{{.ActorUsername}}{{else}}&mdash;{{end}}</td>
<td class="text-small text-muted">{{if .TargetUsername}}{{.TargetUsername}}{{else}}&mdash;{{end}}</td> <td class="text-small text-muted">{{if .TargetUsername}}{{.TargetUsername}}{{else}}&mdash;{{end}}</td>