mirror of
https://github.com/idanoo/autobrr
synced 2025-07-23 00:39:13 +00:00
feat(auth): implement auth proxy support with OpenID Connect (#1853)
* feat(auth): implement oidc * refactor(auth): centralize OIDC state cookie handling * fix(web): resolve unused error variables in route handlers * docs(readme): add OIDC authentication feature to list * fix(auth): improve OIDC cookie handling for reverse proxy setups The OIDC state cookie's Secure flag is now properly set when running behind a reverse proxy by checking both direct TLS and X-Forwarded-Proto header. This fixes authentication issues in common setups where: - autobrr runs behind a reverse proxy that terminates HTTPS - local development environments without TLS - mixed protocol environments (internal HTTP, external HTTPS) * fix: use crypt/random if argon2id fails * feat(auth): show both login options when user exists in db if user doesn't exist, e.g. canOnboard=true then we only show the OIDC button, since regular login makes no sense in that case If user does not exist in db and the user wants to create a local user, OIDC needs to be disabled first * feat(auth): improve OIDC provider initialization with discovery logging * revert(issuer): do not remove trailing slash * feat(auth): improve OIDC username resolution with additional claims * fix(auth): handle OIDC issuer URLs with and without trailing slashes When initializing the OIDC provider, automatically retry with/without trailing slash if the first attempt fails. - First attempts with original issuer URL - If fails with trailing slash, retries without - If fails without trailing slash, retries with * feat(oidc): add gorilla sessions store for secure state management Add gorilla sessions store to handle encrypted state cookies in OIDC flow, while removing redundant session validation checks Co-authored-by: Kyle Sanderson <kyle.leet@gmail.com> * fix(auth): prevent duplicate OIDC state cookies for authenticated sessions Modify OIDC config handler to check for existing authenticated sessions before setting state cookie. Still returns OIDC enabled status to maintain UI state, but prevents unnecessary cookie creation for authenticated users. * feat(oidc): use random secret for temporary state cookies Co-authored-by: Kyle Sanderson <kyle.leet@gmail.com> * feat(auth): add rate limiting to OIDC endpoints Co-authored-by: Kyle Sanderson <kyle.leet@gmail.com> * fix(auth): validate OIDC authorization code presence in callback Co-authored-by: Kyle Sanderson <kyle.leet@gmail.com> * fix(auth): properly handle OIDC session errors Improve error handling in OIDC login flow by properly handling cookie store session errors. Return HTTP 500 if session cannot be retrieved instead of silently continuing with potentially invalid state. Co-authored-by: Kyle Sanderson <kyle.leet@gmail.com> * feat(auth): track and display authentication method for oidc and password logins * fix: tests * docs(readme): add environment variable section * go mod tidy * chore: log style and errors --------- Co-authored-by: Kyle Sanderson <kyle.leet@gmail.com> Co-authored-by: ze0s <ze0s@riseup.net>
This commit is contained in:
parent
80423d6273
commit
43c28fc0c6
19 changed files with 893 additions and 130 deletions
|
@ -6,13 +6,16 @@ package http
|
|||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/autobrr/autobrr/internal/auth"
|
||||
"github.com/autobrr/autobrr/internal/domain"
|
||||
"github.com/autobrr/autobrr/pkg/errors"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
@ -25,16 +28,21 @@ type authService interface {
|
|||
}
|
||||
|
||||
type authHandler struct {
|
||||
log zerolog.Logger
|
||||
encoder encoder
|
||||
config *domain.Config
|
||||
service authService
|
||||
server Server
|
||||
|
||||
log zerolog.Logger
|
||||
encoder encoder
|
||||
config *domain.Config
|
||||
service authService
|
||||
server Server
|
||||
cookieStore *sessions.CookieStore
|
||||
oidcHandler *auth.OIDCHandler
|
||||
}
|
||||
|
||||
func newAuthHandler(encoder encoder, log zerolog.Logger, server Server, config *domain.Config, cookieStore *sessions.CookieStore, service authService) *authHandler {
|
||||
oidcHandler, err := auth.NewOIDCHandler(config, log)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("failed to initialize OIDC handler")
|
||||
}
|
||||
|
||||
return &authHandler{
|
||||
log: log,
|
||||
encoder: encoder,
|
||||
|
@ -42,6 +50,7 @@ func newAuthHandler(encoder encoder, log zerolog.Logger, server Server, config *
|
|||
service: service,
|
||||
cookieStore: cookieStore,
|
||||
server: server,
|
||||
oidcHandler: oidcHandler,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -50,6 +59,12 @@ func (h authHandler) Routes(r chi.Router) {
|
|||
r.Post("/onboard", h.onboard)
|
||||
r.Get("/onboard", h.canOnboard)
|
||||
|
||||
r.Route("/oidc", func(r chi.Router) {
|
||||
r.Use(middleware.ThrottleBacklog(1, 1, time.Second))
|
||||
r.Get("/config", h.getOIDCConfig)
|
||||
r.Get("/callback", h.handleOIDCCallback)
|
||||
})
|
||||
|
||||
// Group for authenticated routes
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(h.server.IsAuthenticated)
|
||||
|
@ -84,6 +99,7 @@ func (h authHandler) login(w http.ResponseWriter, r *http.Request) {
|
|||
// Set user as authenticated
|
||||
session.Values["authenticated"] = true
|
||||
session.Values["created"] = time.Now().Unix()
|
||||
session.Values["auth_method"] = "password"
|
||||
|
||||
// Set cookie options
|
||||
session.Options.HttpOnly = true
|
||||
|
@ -187,9 +203,16 @@ func (h authHandler) onboardEligible(ctx context.Context) (int, error) {
|
|||
// If there is a valid session return OK, otherwise the middleware returns early with a 401
|
||||
func (h authHandler) validate(w http.ResponseWriter, r *http.Request) {
|
||||
session := r.Context().Value("session").(*sessions.Session)
|
||||
if session != nil {
|
||||
if session != nil && session.Values["username"] != nil {
|
||||
h.log.Debug().Msgf("found user session: %+v", session)
|
||||
// Return username if available in session
|
||||
response := map[string]interface{}{
|
||||
"username": session.Values["username"],
|
||||
"auth_method": session.Values["auth_method"],
|
||||
}
|
||||
|
||||
h.encoder.StatusResponse(w, http.StatusOK, response)
|
||||
return
|
||||
}
|
||||
// send empty response as ok
|
||||
h.encoder.NoContent(w)
|
||||
|
@ -212,3 +235,93 @@ func (h authHandler) updateUser(w http.ResponseWriter, r *http.Request) {
|
|||
// send response as ok
|
||||
h.encoder.StatusResponseMessage(w, http.StatusOK, "user successfully updated")
|
||||
}
|
||||
|
||||
func (h authHandler) getOIDCConfig(w http.ResponseWriter, r *http.Request) {
|
||||
h.log.Debug().Msg("getting OIDC config")
|
||||
|
||||
if h.oidcHandler == nil {
|
||||
h.log.Debug().Msg("OIDC handler is nil, returning disabled config")
|
||||
h.encoder.StatusResponse(w, http.StatusOK, auth.GetConfigResponse{
|
||||
Enabled: false,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Get the config first
|
||||
config := h.oidcHandler.GetConfigResponse()
|
||||
|
||||
// Check for existing session
|
||||
session, err := h.cookieStore.Get(r, "user_session")
|
||||
if err == nil && session.Values["authenticated"] == true {
|
||||
h.log.Debug().Msg("user already has valid session, skipping OIDC state cookie")
|
||||
// Still return enabled=true, just don't set the cookie
|
||||
h.encoder.StatusResponse(w, http.StatusOK, config)
|
||||
return
|
||||
}
|
||||
|
||||
h.log.Debug().Bool("enabled", config.Enabled).Str("authorization_url", config.AuthorizationURL).Str("state", config.State).Msg("returning OIDC config")
|
||||
|
||||
// Only set state cookie if user is not already authenticated
|
||||
h.oidcHandler.SetStateCookie(w, r, config.State)
|
||||
|
||||
h.encoder.StatusResponse(w, http.StatusOK, config)
|
||||
}
|
||||
|
||||
func (h authHandler) handleOIDCCallback(w http.ResponseWriter, r *http.Request) {
|
||||
if h.oidcHandler == nil {
|
||||
h.encoder.StatusError(w, http.StatusServiceUnavailable, errors.New("OIDC not configured"))
|
||||
return
|
||||
}
|
||||
|
||||
username, err := h.oidcHandler.HandleCallback(w, r)
|
||||
if err != nil {
|
||||
h.encoder.StatusError(w, http.StatusUnauthorized, errors.Wrap(err, "OIDC authentication failed"))
|
||||
return
|
||||
}
|
||||
|
||||
// Create new session
|
||||
session, err := h.cookieStore.Get(r, "user_session")
|
||||
if err != nil {
|
||||
h.log.Error().Err(err).Msgf("Auth: Failed to create cookies with attempt username: [%s] ip: %s", username, r.RemoteAddr)
|
||||
h.encoder.StatusError(w, http.StatusInternalServerError, errors.New("could not create cookies"))
|
||||
return
|
||||
}
|
||||
|
||||
// Set user as authenticated
|
||||
session.Values["authenticated"] = true
|
||||
session.Values["created"] = time.Now().Unix()
|
||||
session.Values["username"] = username
|
||||
session.Values["auth_method"] = "oidc"
|
||||
|
||||
// Set cookie options
|
||||
session.Options.HttpOnly = true
|
||||
session.Options.SameSite = http.SameSiteLaxMode
|
||||
session.Options.Path = h.config.BaseURL
|
||||
|
||||
// If forwarded protocol is https then set cookie secure
|
||||
if r.Header.Get("X-Forwarded-Proto") == "https" {
|
||||
session.Options.Secure = true
|
||||
session.Options.SameSite = http.SameSiteStrictMode
|
||||
}
|
||||
|
||||
if err := session.Save(r, w); err != nil {
|
||||
h.encoder.StatusError(w, http.StatusInternalServerError, errors.Wrap(err, "could not save session"))
|
||||
return
|
||||
}
|
||||
|
||||
// Redirect to the frontend
|
||||
frontendURL := h.config.BaseURL
|
||||
if frontendURL == "/" {
|
||||
if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
|
||||
host := r.Header.Get("X-Forwarded-Host")
|
||||
if host == "" {
|
||||
host = r.Host
|
||||
}
|
||||
frontendURL = fmt.Sprintf("%s://%s", proto, host)
|
||||
}
|
||||
}
|
||||
|
||||
h.log.Debug().Str("redirect_url", frontendURL).Str("x_forwarded_proto", r.Header.Get("X-Forwarded-Proto")).Str("x_forwarded_host", r.Header.Get("X-Forwarded-Host")).Str("host", r.Host).Msg("redirecting to frontend after OIDC callback")
|
||||
|
||||
http.Redirect(w, r, frontendURL, http.StatusFound)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue