felt/internal/server/middleware/auth.go
Mikkel Georgsen 16caa12d64 feat(01-01): implement core infrastructure — NATS, LibSQL, WebSocket hub, HTTP server
- Embedded NATS server with JetStream (sync_interval=always per Jepsen 2025)
- AUDIT and STATE JetStream streams for tournament event durability
- NATS publisher with UUID validation to prevent subject injection
- WebSocket hub with JWT auth (query param), tournament-scoped broadcasting
- Origin validation and slow-consumer message dropping
- chi HTTP router with middleware (logger, recoverer, request ID, CORS, body limits)
- Server timeouts: ReadHeader 10s, Read 30s, Write 60s, Idle 120s, MaxHeader 1MB
- MaxBytesReader middleware for request body limits (1MB default)
- JWT auth middleware with HMAC-SHA256 validation
- Role-based access control (admin > floor > viewer)
- Health endpoint reporting all subsystem status (DB, NATS, WebSocket)
- SvelteKit SPA served via go:embed with fallback routing
- Signal-driven graceful shutdown in reverse startup order
- 9 integration tests covering all verification criteria

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 03:42:42 +01:00

96 lines
2.8 KiB
Go

// Package middleware provides HTTP middleware for the Felt tournament engine.
package middleware
import (
"context"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v5"
)
// contextKey is a private type for context keys to avoid collisions.
type contextKey string
const (
// OperatorIDKey is the context key for the authenticated operator ID.
OperatorIDKey contextKey = "operator_id"
// OperatorRoleKey is the context key for the authenticated operator role.
OperatorRoleKey contextKey = "operator_role"
)
// JWTAuth returns middleware that validates JWT tokens from the Authorization header.
// Tokens must be in the format: Bearer <token>
func JWTAuth(signingKey []byte) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, `{"error":"missing authorization header"}`, http.StatusUnauthorized)
return
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "bearer") {
http.Error(w, `{"error":"invalid authorization format"}`, http.StatusUnauthorized)
return
}
tokenStr := parts[1]
operatorID, role, err := ValidateJWT(tokenStr, signingKey)
if err != nil {
http.Error(w, `{"error":"invalid or expired token"}`, http.StatusUnauthorized)
return
}
// Add operator info to request context
ctx := context.WithValue(r.Context(), OperatorIDKey, operatorID)
ctx = context.WithValue(ctx, OperatorRoleKey, role)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// ValidateJWT parses and validates a JWT token string, returning the
// operator ID and role from claims.
func ValidateJWT(tokenStr string, signingKey []byte) (operatorID string, role string, err error) {
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
// Verify signing method is HMAC
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return signingKey, nil
})
if err != nil {
return "", "", err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok || !token.Valid {
return "", "", jwt.ErrSignatureInvalid
}
operatorID, _ = claims["sub"].(string)
role, _ = claims["role"].(string)
if operatorID == "" {
return "", "", jwt.ErrSignatureInvalid
}
if role == "" {
role = "viewer" // Default role
}
return operatorID, role, nil
}
// OperatorID extracts the operator ID from the request context.
func OperatorID(r *http.Request) string {
id, _ := r.Context().Value(OperatorIDKey).(string)
return id
}
// OperatorRole extracts the operator role from the request context.
func OperatorRole(r *http.Request) string {
role, _ := r.Context().Value(OperatorRoleKey).(string)
return role
}