Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: dynamic oidc redirect url based on url origin (#1094)
Kyle Mendelle5e04e0536c6
diff --git a/backend/internal/huma/handlers/oidc.go b/backend/internal/huma/handlers/oidc.goindex 8121bb854..94a44c30f 100644--- a/backend/internal/huma/handlers/oidc.go+++ b/backend/internal/huma/handlers/oidc.go@@ -7,8 +7,10 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/internal/common"+ "github.com/getarcaneapp/arcane/backend/internal/config""github.com/getarcaneapp/arcane/backend/internal/services""github.com/getarcaneapp/arcane/backend/internal/utils/cookie"+ httputils "github.com/getarcaneapp/arcane/backend/internal/utils/http""go.getarcane.app/types/auth""go.getarcane.app/types/user")@@ -17,12 +19,20 @@ import (type OidcHandler struct {authService *services.AuthServiceoidcService *services.OidcService+ config *config.Config}// ============================================================================// Input/Output Types// ============================================================================+type OidcHeaders struct {+ Origin string `header:"Origin"`+ XForwardedHost string `header:"X-Forwarded-Host"`+ XForwardedProto string `header:"X-Forwarded-Proto"`+ Host string `header:"Host"`+}+type GetOidcStatusInput struct{}type GetOidcStatusOutput struct {@@ -30,6 +40,7 @@ type GetOidcStatusOutput struct {}type GetOidcAuthUrlInput struct {+ OidcHeadersBody auth.OidcAuthUrlRequest}@@ -39,6 +50,7 @@ type GetOidcAuthUrlOutput struct {}type HandleOidcCallbackInput struct {+ OidcHeadersOidcStateCookie string `cookie:"oidc_state" doc:"OIDC state cookie from auth URL request"`Body auth.OidcCallbackRequest}@@ -48,7 +60,9 @@ type HandleOidcCallbackOutput struct {Body auth.OidcCallbackResponse}-type GetOidcConfigInput struct{}+type GetOidcConfigInput struct {+ OidcHeaders+}type GetOidcConfigOutput struct {Body auth.OidcConfigResponse@@ -59,8 +73,8 @@ type GetOidcConfigOutput struct {// ============================================================================// RegisterOidc registers all OIDC authentication endpoints using Huma.-func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *services.OidcService) {- h := &OidcHandler{authService: authService, oidcService: oidcService}+func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *services.OidcService, cfg *config.Config) {+ h := &OidcHandler{authService: authService, oidcService: oidcService, config: cfg}huma.Register(api, huma.Operation{OperationID: "get-oidc-status",@@ -120,7 +134,7 @@ func (h *OidcHandler) GetOidcStatus(ctx context.Context, _ *GetOidcStatusInput)}// GetOidcConfig returns the OIDC client configuration.-func (h *OidcHandler) GetOidcConfig(ctx context.Context, _ *GetOidcConfigInput) (*GetOidcConfigOutput, error) {+func (h *OidcHandler) GetOidcConfig(ctx context.Context, input *GetOidcConfigInput) (*GetOidcConfigOutput, error) {if h.authService == nil || h.oidcService == nil {return nil, huma.Error500InternalServerError("service not available")}@@ -130,10 +144,16 @@ func (h *OidcHandler) GetOidcConfig(ctx context.Context, _ *GetOidcConfigInput)return nil, huma.Error500InternalServerError((&common.OidcConfigError{}).Error())}+ appUrl := ""+ if h.config != nil {+ appUrl = h.config.AppUrl+ }+ origin := httputils.GetClientBaseURL(input.Origin, input.XForwardedHost, input.XForwardedProto, input.Host, appUrl)+return &GetOidcConfigOutput{Body: auth.OidcConfigResponse{ClientID: config.ClientID,- RedirectUri: h.oidcService.GetOidcRedirectURL(),+ RedirectUri: h.oidcService.GetOidcRedirectURL(origin),IssuerUrl: config.IssuerURL,AuthorizationEndpoint: config.AuthorizationEndpoint,TokenEndpoint: config.TokenEndpoint,@@ -157,7 +177,12 @@ func (h *OidcHandler) GetOidcAuthUrl(ctx context.Context, input *GetOidcAuthUrlIreturn nil, huma.Error400BadRequest((&common.OidcDisabledError{}).Error())}- authUrl, stateCookieValue, err := h.oidcService.GenerateAuthURL(ctx, input.Body.RedirectUri)+ appUrl := ""+ if h.config != nil {+ appUrl = h.config.AppUrl+ }+ origin := httputils.GetClientBaseURL(input.Origin, input.XForwardedHost, input.XForwardedProto, input.Host, appUrl)+ authUrl, stateCookieValue, err := h.oidcService.GenerateAuthURL(ctx, input.Body.RedirectUri, origin)if err != nil {return nil, huma.Error500InternalServerError((&common.OidcAuthUrlGenerationError{Err: err}).Error())}@@ -184,8 +209,14 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcCreturn nil, huma.Error400BadRequest((&common.OidcStateCookieError{}).Error())}+ appUrl := ""+ if h.config != nil {+ appUrl = h.config.AppUrl+ }+ origin := httputils.GetClientBaseURL(input.Origin, input.XForwardedHost, input.XForwardedProto, input.Host, appUrl)+// Process OIDC callback- userInfo, tokenResp, err := h.oidcService.HandleCallback(ctx, input.Body.Code, input.Body.State, input.OidcStateCookie)+ userInfo, tokenResp, err := h.oidcService.HandleCallback(ctx, input.Body.Code, input.Body.State, input.OidcStateCookie, origin)if err != nil {return nil, huma.Error400BadRequest((&common.OidcCallbackError{Err: err}).Error())}diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.goindex 644cad235..a29f38485 100644--- a/backend/internal/huma/huma.go+++ b/backend/internal/huma/huma.go@@ -331,7 +331,7 @@ func registerHandlers(api huma.API, svc *Services) {handlers.RegisterUsers(api, userSvc)handlers.RegisterVersion(api, versionSvc)handlers.RegisterEvents(api, eventSvc)- handlers.RegisterOidc(api, authSvc, oidcSvc)+ handlers.RegisterOidc(api, authSvc, oidcSvc, cfg)handlers.RegisterEnvironments(api, environmentSvc, settingsSvc, cfg)handlers.RegisterContainerRegistries(api, containerRegistrySvc)handlers.RegisterTemplates(api, templateSvc)diff --git a/backend/internal/services/oidc_service.go b/backend/internal/services/oidc_service.goindex 6ca19eef8..772f288bb 100644--- a/backend/internal/services/oidc_service.go+++ b/backend/internal/services/oidc_service.go@@ -83,7 +83,7 @@ func (s *OidcService) ensureOpenIDScope(scopes []string) []string {return scopes}-func (s *OidcService) getOauth2Config(cfg *models.OidcConfig, provider *oidc.Provider) oauth2.Config {+func (s *OidcService) getOauth2Config(cfg *models.OidcConfig, provider *oidc.Provider, origin string) oauth2.Config {scopes := strings.Fields(cfg.Scopes)if len(scopes) == 0 {scopes = []string{"email", "profile"}@@ -94,12 +94,12 @@ func (s *OidcService) getOauth2Config(cfg *models.OidcConfig, provider *oidc.ProClientID: cfg.ClientID,ClientSecret: cfg.ClientSecret,Endpoint: provider.Endpoint(),- RedirectURL: s.GetOidcRedirectURL(),+ RedirectURL: s.GetOidcRedirectURL(origin),Scopes: scopes,}}-func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string) (string, string, error) {+func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string, origin string) (string, string, error) {config, err := s.getEffectiveConfig(ctx)if err != nil {slog.Error("GenerateAuthURL: failed to get OIDC config", "error", err)@@ -116,7 +116,7 @@ func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string) (snonce := utils.GenerateRandomString(32)codeVerifier := utils.GenerateRandomString(128)- oauth2Config := s.getOauth2Config(config, provider)+ oauth2Config := s.getOauth2Config(config, provider, origin)authURL := oauth2Config.AuthCodeURL(state,oauth2.SetAuthURLParam("nonce", nonce),@@ -142,8 +142,11 @@ func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string) (sreturn authURL, encodedState, nil}-func (s *OidcService) GetOidcRedirectURL() string {- baseUrl := strings.TrimSuffix(s.config.AppUrl, "/")+func (s *OidcService) GetOidcRedirectURL(origin string) string {+ baseUrl := origin+ if baseUrl == "" {+ baseUrl = strings.TrimSuffix(s.config.AppUrl, "/")+ }return baseUrl + "/auth/oidc/callback"}@@ -198,8 +201,8 @@ func (s *OidcService) getOrDiscoverProvider(ctx context.Context, issuer string)return v.(*oidc.Provider), nil}-func (s *OidcService) exchangeToken(ctx context.Context, cfg *models.OidcConfig, provider *oidc.Provider, code string, verifier string) (*oauth2.Token, error) {- oauth2Config := s.getOauth2Config(cfg, provider)+func (s *OidcService) exchangeToken(ctx context.Context, cfg *models.OidcConfig, provider *oidc.Provider, code string, verifier string, origin string) (*oauth2.Token, error) {+ oauth2Config := s.getOauth2Config(cfg, provider, origin)providerCtx := oidc.ClientContext(ctx, s.httpClient)token, err := oauth2Config.Exchange(providerCtx, code, oauth2.VerifierOption(verifier))@@ -256,7 +259,7 @@ func (s *OidcService) fetchClaims(ctx context.Context, provider *oidc.Provider,return claims, nil}-func (s *OidcService) HandleCallback(ctx context.Context, code, state, storedState string) (*auth.OidcUserInfo, *auth.OidcTokenResponse, error) {+func (s *OidcService) HandleCallback(ctx context.Context, code, state, storedState, origin string) (*auth.OidcUserInfo, *auth.OidcTokenResponse, error) {slog.Debug("HandleCallback: processing callback", "code_present", code != "", "state_present", state != "")stateData, err := s.validateState(state, storedState)@@ -275,7 +278,7 @@ func (s *OidcService) HandleCallback(ctx context.Context, code, state, storedStareturn nil, nil, err}- token, err := s.exchangeToken(ctx, cfg, provider, code, stateData.CodeVerifier)+ token, err := s.exchangeToken(ctx, cfg, provider, code, stateData.CodeVerifier, origin)if err != nil {return nil, nil, err}diff --git a/backend/internal/utils/http/request.go b/backend/internal/utils/http/request.goindex 220a42182..7804dbe3e 100644--- a/backend/internal/utils/http/request.go+++ b/backend/internal/utils/http/request.go@@ -90,3 +90,36 @@ func GetIntQueryParam(c *gin.Context, name string, required bool) (int, error) {}return n, nil}++// GetClientBaseURL determines the client's base URL from request headers.+// It checks Origin, X-Forwarded-Host/Proto, and Host headers.+// If none provide a valid URL, it falls back to the configured appURL.+func GetClientBaseURL(origin, forwardedHost, forwardedProto, host, appURL string) string {+ // 1. Trust Origin if present+ if origin != "" {+ return strings.TrimSuffix(origin, "/")+ }++ scheme := "http"+ // Try to get scheme from AppURL as default+ if u, err := url.Parse(appURL); err == nil && u.Scheme != "" {+ scheme = u.Scheme+ }++ if forwardedProto != "" {+ scheme = forwardedProto+ }++ // 2. Check X-Forwarded-Host+ if forwardedHost != "" {+ return fmt.Sprintf("%s://%s", scheme, forwardedHost)+ }++ // 3. Check Host+ if host != "" {+ return fmt.Sprintf("%s://%s", scheme, host)+ }++ // 4. Fallback+ return strings.TrimSuffix(appURL, "/")+}