// 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 // Enforces HS256 via WithValidMethods to prevent algorithm confusion attacks. 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. Enforces HS256 via WithValidMethods // to prevent algorithm confusion attacks. 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 (belt AND suspenders with WithValidMethods) if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, jwt.ErrSignatureInvalid } return signingKey, nil }, jwt.WithValidMethods([]string{"HS256"})) 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 } // OperatorIDFromCtx extracts the operator ID from a context directly. func OperatorIDFromCtx(ctx context.Context) string { id, _ := ctx.Value(OperatorIDKey).(string) return id } // OperatorRoleFromCtx extracts the operator role from a context directly. func OperatorRoleFromCtx(ctx context.Context) string { role, _ := ctx.Value(OperatorRoleKey).(string) return role }