mirror of
https://github.com/IS1DI/x0gp.git
synced 2026-07-19 22:07:03 +00:00
Add Supabase JWT authorization middleware, config parsing, and WebSocket token verification
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
// Package auth handles Supabase JWT validation and HTTP middleware.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type contextKey int
|
||||
|
||||
const (
|
||||
driverIDKey contextKey = iota
|
||||
emailKey
|
||||
)
|
||||
|
||||
// Claims represents the parsed Supabase JWT claims we care about.
|
||||
type Claims struct {
|
||||
DriverID string
|
||||
Email string
|
||||
}
|
||||
|
||||
// ValidateJWT parses and validates a Supabase HMAC-SHA256 JWT using the secret.
|
||||
func ValidateJWT(tokenStr string, secret string) (Claims, error) {
|
||||
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
return []byte(secret), nil
|
||||
})
|
||||
if err != nil {
|
||||
return Claims{}, err
|
||||
}
|
||||
|
||||
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||
sub, _ := claims["sub"].(string)
|
||||
email, _ := claims["email"].(string)
|
||||
if sub == "" {
|
||||
return Claims{}, errors.New("missing sub claim")
|
||||
}
|
||||
return Claims{
|
||||
DriverID: sub,
|
||||
Email: email,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return Claims{}, errors.New("invalid token")
|
||||
}
|
||||
|
||||
// Middleware returns an HTTP middleware that extracts and validates the Bearer token.
|
||||
// When devMode is enabled, authentication is bypassed entirely.
|
||||
func Middleware(secret string, devMode bool) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if devMode {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"error":"unauthorized","message":"missing authorization header"}`))
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.Split(authHeader, " ")
|
||||
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"error":"unauthorized","message":"invalid authorization format"}`))
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := ValidateJWT(parts[1], secret)
|
||||
if err != nil {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(fmt.Sprintf(`{"error":"unauthorized","message":%q}`, err.Error())))
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), driverIDKey, claims.DriverID)
|
||||
ctx = context.WithValue(ctx, emailKey, claims.Email)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// DriverIDFromContext retrieves the driver ID from the context.
|
||||
func DriverIDFromContext(ctx context.Context) (string, bool) {
|
||||
id, ok := ctx.Value(driverIDKey).(string)
|
||||
return id, ok
|
||||
}
|
||||
|
||||
// EmailFromContext retrieves the email from the context.
|
||||
func EmailFromContext(ctx context.Context) (string, bool) {
|
||||
email, ok := ctx.Value(emailKey).(string)
|
||||
return email, ok
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
const testSecret = "my-super-secret-supabase-jwt-key"
|
||||
|
||||
func generateTestToken(sub string, email string, expiresAt time.Time, secret string) (string, error) {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"sub": sub,
|
||||
"email": email,
|
||||
"exp": expiresAt.Unix(),
|
||||
})
|
||||
return token.SignedString([]byte(secret))
|
||||
}
|
||||
|
||||
func TestValidateJWT(t *testing.T) {
|
||||
// 1. Valid token
|
||||
validToken, err := generateTestToken("driver-uuid-123", "driver@test.com", time.Now().Add(time.Hour), testSecret)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate valid token: %v", err)
|
||||
}
|
||||
|
||||
claims, err := ValidateJWT(validToken, testSecret)
|
||||
if err != nil {
|
||||
t.Errorf("expected no error, got: %v", err)
|
||||
}
|
||||
if claims.DriverID != "driver-uuid-123" || claims.Email != "driver@test.com" {
|
||||
t.Errorf("unexpected claims: %+v", claims)
|
||||
}
|
||||
|
||||
// 2. Expired token
|
||||
expiredToken, err := generateTestToken("driver-uuid-123", "driver@test.com", time.Now().Add(-time.Hour), testSecret)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate expired token: %v", err)
|
||||
}
|
||||
|
||||
_, err = ValidateJWT(expiredToken, testSecret)
|
||||
if err == nil {
|
||||
t.Error("expected error for expired token, got nil")
|
||||
}
|
||||
|
||||
// 3. Invalid signature
|
||||
_, err = ValidateJWT(validToken, "wrong-secret-key")
|
||||
if err == nil {
|
||||
t.Error("expected error for wrong signature, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthMiddleware(t *testing.T) {
|
||||
nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
driverID, ok := DriverIDFromContext(r.Context())
|
||||
if ok {
|
||||
w.Header().Set("X-Driver-ID", driverID)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
// 1. DevMode = true: bypass authentication
|
||||
mwDev := Middleware(testSecret, true)(nextHandler)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/races", nil)
|
||||
w := httptest.NewRecorder()
|
||||
mwDev.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200 OK in DevMode, got %d", w.Code)
|
||||
}
|
||||
|
||||
// 2. DevMode = false: missing Authorization header
|
||||
mwProd := Middleware(testSecret, false)(nextHandler)
|
||||
w = httptest.NewRecorder()
|
||||
mwProd.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401 Unauthorized for missing auth header, got %d", w.Code)
|
||||
}
|
||||
|
||||
// 3. DevMode = false: invalid Authorization format
|
||||
reqFormat := httptest.NewRequest(http.MethodGet, "/api/races", nil)
|
||||
reqFormat.Header.Set("Authorization", "InvalidFormat token123")
|
||||
w = httptest.NewRecorder()
|
||||
mwProd.ServeHTTP(w, reqFormat)
|
||||
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401 Unauthorized for invalid format, got %d", w.Code)
|
||||
}
|
||||
|
||||
// 4. DevMode = false: valid token
|
||||
validToken, err := generateTestToken("driver-uuid-123", "driver@test.com", time.Now().Add(time.Hour), testSecret)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to generate valid token: %v", err)
|
||||
}
|
||||
|
||||
reqValid := httptest.NewRequest(http.MethodGet, "/api/races", nil)
|
||||
reqValid.Header.Set("Authorization", "Bearer "+validToken)
|
||||
w = httptest.NewRecorder()
|
||||
mwProd.ServeHTTP(w, reqValid)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("expected 200 OK for valid token, got %d", w.Code)
|
||||
}
|
||||
if w.Header().Get("X-Driver-ID") != "driver-uuid-123" {
|
||||
t.Errorf("expected X-Driver-ID header to be set in context, got %q", w.Header().Get("X-Driver-ID"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextHelpers(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
if _, ok := DriverIDFromContext(ctx); ok {
|
||||
t.Error("expected ok=false for empty context")
|
||||
}
|
||||
|
||||
ctx = context.WithValue(ctx, driverIDKey, "test-driver")
|
||||
id, ok := DriverIDFromContext(ctx)
|
||||
if !ok || id != "test-driver" {
|
||||
t.Errorf("expected test-driver, got %s (ok=%t)", id, ok)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user