Files
metacrypt/internal/server/middleware.go
Kyle Isom 4ddd32b117 Implement Phase 1: core framework, operational tooling, and runbook
Core packages: crypto (Argon2id/AES-256-GCM), config (TOML/viper),
db (SQLite/migrations), barrier (encrypted storage), seal (state machine
with rate-limited unseal), auth (MCIAS integration with token cache),
policy (priority-based ACL engine), engine (interface + registry).

Server: HTTPS with TLS 1.2+, REST API, auth/admin middleware, htmx web UI
(init, unseal, login, dashboard pages).

CLI: cobra/viper subcommands (server, init, status, snapshot) with env
var override support (METACRYPT_ prefix).

Operational tooling: Dockerfile (multi-stage, non-root), docker-compose,
hardened systemd units (service + daily backup timer), install script,
backup script with retention pruning, production config examples.

Runbook covering installation, configuration, daily operations,
backup/restore, monitoring, troubleshooting, and security procedures.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-14 20:43:11 -07:00

110 lines
2.9 KiB
Go

package server
import (
"context"
"net/http"
"strings"
"time"
"git.wntrmute.dev/kyle/metacrypt/internal/auth"
"git.wntrmute.dev/kyle/metacrypt/internal/seal"
)
type contextKey string
const tokenInfoKey contextKey = "tokenInfo"
// TokenInfoFromContext extracts the validated token info from the request context.
func TokenInfoFromContext(ctx context.Context) *auth.TokenInfo {
info, _ := ctx.Value(tokenInfoKey).(*auth.TokenInfo)
return info
}
// loggingMiddleware logs HTTP requests, stripping sensitive headers.
func (s *Server) loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := &statusWriter{ResponseWriter: w, status: 200}
next.ServeHTTP(sw, r)
s.logger.Info("http request",
"method", r.Method,
"path", r.URL.Path,
"status", sw.status,
"duration", time.Since(start),
"remote", r.RemoteAddr,
)
})
}
// requireUnseal rejects requests unless the service is unsealed.
func (s *Server) requireUnseal(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
state := s.seal.State()
switch state {
case seal.StateUninitialized:
http.Error(w, `{"error":"not initialized"}`, http.StatusPreconditionFailed)
return
case seal.StateSealed, seal.StateInitializing:
http.Error(w, `{"error":"sealed"}`, http.StatusServiceUnavailable)
return
}
next(w, r)
}
}
// requireAuth validates the bearer token and injects TokenInfo into context.
func (s *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc {
return s.requireUnseal(func(w http.ResponseWriter, r *http.Request) {
token := extractToken(r)
if token == "" {
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
return
}
info, err := s.auth.ValidateToken(token)
if err != nil {
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), tokenInfoKey, info)
next(w, r.WithContext(ctx))
})
}
// requireAdmin requires the authenticated user to have admin role.
func (s *Server) requireAdmin(next http.HandlerFunc) http.HandlerFunc {
return s.requireAuth(func(w http.ResponseWriter, r *http.Request) {
info := TokenInfoFromContext(r.Context())
if info == nil || !info.IsAdmin {
http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden)
return
}
next(w, r)
})
}
func extractToken(r *http.Request) string {
// Check Authorization header first.
authHeader := r.Header.Get("Authorization")
if strings.HasPrefix(authHeader, "Bearer ") {
return strings.TrimPrefix(authHeader, "Bearer ")
}
// Fall back to cookie.
cookie, err := r.Cookie("metacrypt_token")
if err == nil {
return cookie.Value
}
return ""
}
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(code int) {
w.status = code
w.ResponseWriter.WriteHeader(code)
}