Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(auth): improve OIDC authentication reliability #67

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 50 additions & 11 deletions internal/api/handlers/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,11 @@ func (h *AuthHandler) Callback(c *gin.Context) {
code := c.Query("code")
state := c.Query("state")

log.Debug().
Bool("has_code", code != "").
Str("state", state).
Msg("received callback")

if code == "" {
log.Error().Msg("no code in callback")
c.Redirect(http.StatusTemporaryRedirect, "/login?error=no_code")
Expand All @@ -235,7 +240,9 @@ func (h *AuthHandler) Callback(c *gin.Context) {
return
}
if err == cache.ErrKeyNotFound {
log.Debug().Msg("state not found or expired")
log.Debug().
Str("state_key", stateKey).
Msg("state not found or expired")
} else {
log.Error().Err(err).Msg("failed to get state from cache")
}
Expand All @@ -256,37 +263,64 @@ func (h *AuthHandler) Callback(c *gin.Context) {
}
}

// Exchange code for token using context
log.Debug().Msg("exchanging code for token")

token, err := h.oauth2Config.Exchange(ctx, code)
if err != nil {
if ctx.Err() != nil {
log.Error().Err(ctx.Err()).Msg("Context canceled during token exchange")
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/login?error=timeout", frontendUrl))
return
}
log.Error().Err(err).Msg("code exchange failed")
log.Error().
Err(err).
Str("token_url", h.oauth2Config.Endpoint.TokenURL).
Msg("code exchange failed")
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/login?error=exchange_failed", frontendUrl))
return
}

log.Debug().
Bool("token_received", token.AccessToken != "").
Msg("token exchange completed")

rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
log.Error().Msg("no id_token in token response")
log.Error().
Interface("extras", token.Extra("")).
Msg("no id_token in token response")
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/login?error=no_id_token", frontendUrl))
return
}

// Set a default expiry if none provided
expiryTime := token.Expiry
if expiryTime.IsZero() {
expiryTime = time.Now().Add(24 * time.Hour)
log.Debug().
Time("assigned_expiry", expiryTime).
Msg("token had no expiry, assigned default 24 hours")
}

sessionData := types.SessionData{
AccessToken: token.AccessToken,
TokenType: token.TokenType,
RefreshToken: token.RefreshToken,
IDToken: rawIDToken,
ExpiresAt: token.Expiry,
ExpiresAt: expiryTime,
AuthType: "oidc",
}

sessionKey := fmt.Sprintf("oidc:session:%s", token.AccessToken)
if err := h.cache.Set(ctx, sessionKey, sessionData, time.Until(token.Expiry)); err != nil {
// Generate a random session ID instead of using the access token
sessionID, err := generateSecureRandomString(32)
if err != nil {
log.Error().Err(err).Msg("failed to generate session ID")
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/login?error=session_failed", frontendUrl))
return
}

sessionKey := fmt.Sprintf("oidc:session:%s", sessionID)
if err := h.cache.Set(ctx, sessionKey, sessionData, time.Until(expiryTime)); err != nil {
if ctx.Err() != nil {
log.Error().Err(ctx.Err()).Msg("Context canceled while storing session")
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/login?error=timeout", frontendUrl))
Expand All @@ -299,21 +333,26 @@ func (h *AuthHandler) Callback(c *gin.Context) {

var isSecure = c.GetHeader("X-Forwarded-Proto") == "https"

// Set the random session ID in the cookie instead of the access token
c.SetCookie(
"session",
token.AccessToken,
int(time.Until(token.Expiry).Seconds()),
sessionID,
int(time.Until(expiryTime).Seconds()),
"/",
"",
isSecure,
true,
)

c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s?access_token=%s&id_token=%s",
redirectURL := fmt.Sprintf("%s?access_token=%s&id_token=%s",
frontendUrl,
token.AccessToken,
rawIDToken,
))
)

//log.Debug().Msg("redirecting to frontend")

c.Redirect(http.StatusTemporaryRedirect, redirectURL)
}

func (h *AuthHandler) Logout(c *gin.Context) {
Expand Down
14 changes: 12 additions & 2 deletions internal/api/middleware/cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,19 @@ func SetupCORS() gin.HandlerFunc {
"Content-Type",
"Accept",
"X-Requested-With",
"X-CSRF-Token",
"Access-Control-Allow-Origin",
"Access-Control-Allow-Headers",
"Access-Control-Allow-Methods",
"Access-Control-Allow-Credentials",
},
ExposeHeaders: []string{"Content-Length", "Content-Type"},
MaxAge: 12 * time.Hour,
AllowCredentials: true, // Important for OAuth flows
ExposeHeaders: []string{
"Content-Length",
"Content-Type",
"X-CSRF-Token",
},
MaxAge: 12 * time.Hour,
}

return cors.New(config)
Expand Down
2 changes: 1 addition & 1 deletion internal/api/middleware/csrf.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func DefaultCSRFConfig() *CSRFConfig {
HttpOnly: true,
MaxAge: int(csrfTokenDuration.Seconds()),
ExemptMethods: []string{"GET", "HEAD", "OPTIONS"},
ExemptPaths: []string{},
ExemptPaths: []string{"/api/auth/callback"},
}
}

Expand Down
8 changes: 6 additions & 2 deletions internal/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,14 @@ func (s *Server) Handler() http.Handler {
}

r.Use(middleware.SetupCORS())
// TODO: Enable secure headers and CSRF?
//r.Use(middleware.Secure(nil))
//r.Use(middleware.CSRF(nil))

// Create rate limiters with different configurations
apiRateLimiter := middleware.NewRateLimiter(s.cache, time.Minute, 60, "api:") // 60 requests per minute for API
healthRateLimiter := middleware.NewRateLimiter(s.cache, time.Minute, 30, "health:") // 30 health checks per minute
authRateLimiter := middleware.NewRateLimiter(s.cache, time.Minute, 30, "auth:") // 30 auth requests per minute
authRateLimiter := middleware.NewRateLimiter(s.cache, time.Second, 1, "auth:") // 1 auth request per second

// Special rate limiter for Tailscale services
tailscaleRateLimiter := middleware.NewRateLimiter(s.cache, 2*time.Minute, 20, "tailscale:") // 20 requests per 2 minutes
Expand Down Expand Up @@ -145,13 +148,14 @@ func (s *Server) Handler() http.Handler {

// OIDC auth endpoints (only if OIDC is configured)
if oidcAuthHandler != nil {
public.GET("/api/auth/callback", oidcAuthHandler.Callback)
oidcAuth := public.Group("/api/auth/oidc")
oidcAuth.Use(authRateLimiter.RateLimit())
{
oidcAuth.GET("/login", oidcAuthHandler.Login)
oidcAuth.POST("/logout", oidcAuthHandler.Logout)
}

public.GET("/api/auth/callback", authRateLimiter.RateLimit(), oidcAuthHandler.Callback)
}

// Built-in auth endpoints
Expand Down
Loading