Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: use oidc well-known to discover urls (#351)
Kyle Mendell4801b0029bf2
diff --git a/.env.example b/.env.exampleindex 73a07c5d2..c5f1fe573 100644--- a/.env.example+++ b/.env.example@@ -14,8 +14,5 @@ JWT_SECRET=your-super-secret-jwt-key-change-this-in-productionOIDC_ENABLED=trueOIDC_CLIENT_ID=""OIDC_CLIENT_SECRET=""-OIDC_REDIRECT_URI="http://localhost:8080/auth/oidc/callback"-OIDC_AUTHORIZATION_ENDPOINT="https://example.com/authorize"-OIDC_TOKEN_ENDPOINT="https://example.com/api/oidc/token"-OIDC_USERINFO_ENDPOINT="https://example.com/api/oidc/userinfo"-OIDC_SCOPES="openid email profile" # Space separated list of scopes\ No newline at end of file+OIDC_ISSUER_URL="https://id.example.com"+OIDC_SCOPES="openid email profile"\ No newline at end of filediff --git a/backend/internal/api/oidc_handler.go b/backend/internal/api/oidc_handler.goindex a873286ef..437d91fe6 100644--- a/backend/internal/api/oidc_handler.go+++ b/backend/internal/api/oidc_handler.go@@ -50,6 +50,7 @@ func (h *OidcHandler) GetOidcStatus(c *gin.Context) {func (h *OidcHandler) GetOidcAuthUrl(c *gin.Context) {var req OidcAuthUrlRequest+if err := c.ShouldBindJSON(&req); err != nil {c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "Invalid request format"})return@@ -74,7 +75,7 @@ func (h *OidcHandler) GetOidcAuthUrl(c *gin.Context) {c.SetCookie("oidc_state",stateCookieValue,- 600,+ 600, // 10 minutes"/","",c.Request.TLS != nil,@@ -151,7 +152,8 @@ func (h *OidcHandler) GetOidcConfig(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"clientId": config.ClientID,- "redirectUri": config.RedirectURI,+ "redirectUri": h.appConfig.GetOidcRedirectURI(),+ "issuerUrl": config.IssuerURL,"authorizationEndpoint": config.AuthorizationEndpoint,"tokenEndpoint": config.TokenEndpoint,"userinfoEndpoint": config.UserinfoEndpoint,diff --git a/backend/internal/api/routes.go b/backend/internal/api/routes.goindex a66113423..ef2fdd46e 100644--- a/backend/internal/api/routes.go+++ b/backend/internal/api/routes.go@@ -30,7 +30,8 @@ type Services struct {func SetupRoutes(r *gin.Engine, services *Services, appConfig *config.Config) {api := r.Group("/api")- setupAuthRoutes(api, services, appConfig)+ setupAuthRoutes(api, services)+ setupOidcRoutes(api, services, appConfig)setupUserRoutes(api, services)setupStackRoutes(api, services)setupEnvironmentRoutes(api, services)@@ -76,7 +77,18 @@ func setupImageUpdateRoutes(api *gin.RouterGroup, services *Services) {imageUpdates.POST("/compare", imageUpdateHandler.CompareVersions)}-func setupAuthRoutes(api *gin.RouterGroup, services *Services, appConfig *config.Config) {+func setupOidcRoutes(api *gin.RouterGroup, services *Services, appConfig *config.Config) {+ oidcHandler := NewOidcHandler(services.Auth, services.Oidc, appConfig)+ oidc := api.Group("/oidc")+ {+ oidc.POST("/url", oidcHandler.GetOidcAuthUrl)+ oidc.POST("/callback", oidcHandler.HandleOidcCallback)+ oidc.GET("/config", oidcHandler.GetOidcConfig)+ oidc.GET("/status", oidcHandler.GetOidcStatus)+ }+}++func setupAuthRoutes(api *gin.RouterGroup, services *Services) {auth := api.Group("/auth")authHandler := NewAuthHandler(services.User, services.Auth, services.Oidc)@@ -88,14 +100,6 @@ func setupAuthRoutes(api *gin.RouterGroup, services *Services, appConfig *configauth.POST("/refresh", authHandler.RefreshToken)auth.POST("/password", middleware.AuthMiddleware(services.Auth), authHandler.ChangePassword)- oidcHandler := NewOidcHandler(services.Auth, services.Oidc, appConfig)- oidc := auth.Group("/oidc")- {- oidc.POST("/url", oidcHandler.GetOidcAuthUrl)- oidc.POST("/callback", oidcHandler.HandleOidcCallback)- oidc.GET("/config", oidcHandler.GetOidcConfig)- oidc.GET("/status", oidcHandler.GetOidcStatus)- }}func setupUserRoutes(api *gin.RouterGroup, services *Services) {diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.goindex ba059f092..3a1767faa 100644--- a/backend/internal/bootstrap/services_bootstrap.go+++ b/backend/internal/bootstrap/services_bootstrap.go@@ -25,7 +25,7 @@ func initializeServices(db *database.DB, cfg *config.Config) (*api.Services, *senetworkService := services.NewNetworkService(db, dockerClientService)templateService := services.NewTemplateService(db)authService := services.NewAuthService(userService, settingsService, cfg.JWTSecret, cfg)- oidcService := services.NewOidcService(authService)+ oidcService := services.NewOidcService(authService, cfg)autoUpdate := services.NewAutoUpdateService(db, dockerClientService, settingsService, containerService, stackService, imageService, containerRegistry)systemService := services.NewSystemService(db, dockerClientService, containerService, imageService, volumeService, networkService, settingsService)diff --git a/backend/internal/config/config.go b/backend/internal/config/config.goindex c4494f9df..785fa5690 100644--- a/backend/internal/config/config.go+++ b/backend/internal/config/config.go@@ -3,6 +3,7 @@ package configimport ("os""strconv"+ "strings")const (@@ -16,20 +17,17 @@ type Config struct {Environment stringJWTSecret string- OidcEnabled bool- OidcClientID string- OidcClientSecret string- OidcRedirectURI string- OidcAuthorizationEndpoint string- OidcTokenEndpoint string- OidcUserinfoEndpoint string- OidcScopes string+ OidcEnabled bool+ OidcClientID string+ OidcClientSecret string+ OidcIssuerURL string+ OidcScopes stringEncryptionKey string}func Load() *Config {- publicOidcEnabled, _ := strconv.ParseBool(os.Getenv("OIDC_ENABLED"))+ oidcEnabled, _ := strconv.ParseBool(os.Getenv("OIDC_ENABLED"))return &Config{AppUrl: getEnvOrDefault("APP_URL", "http://localhost:8080"),@@ -39,17 +37,19 @@ func Load() *Config {JWTSecret: getEnvOrDefault("JWT_SECRET", "default-jwt-secret-change-me"),EncryptionKey: getEnvOrDefault("ENCRYPTION_KEY", "arcane-dev-key-32-characters!!!"),- OidcEnabled: publicOidcEnabled,- OidcClientID: os.Getenv("OIDC_CLIENT_ID"),- OidcClientSecret: os.Getenv("OIDC_CLIENT_SECRET"),- OidcRedirectURI: os.Getenv("OIDC_REDIRECT_URI"),- OidcAuthorizationEndpoint: os.Getenv("OIDC_AUTHORIZATION_ENDPOINT"),- OidcTokenEndpoint: os.Getenv("OIDC_TOKEN_ENDPOINT"),- OidcUserinfoEndpoint: os.Getenv("OIDC_USERINFO_ENDPOINT"),- OidcScopes: getEnvOrDefault("OIDC_SCOPES", "openid email profile"),+ OidcEnabled: oidcEnabled,+ OidcClientID: os.Getenv("OIDC_CLIENT_ID"),+ OidcClientSecret: os.Getenv("OIDC_CLIENT_SECRET"),+ OidcIssuerURL: os.Getenv("OIDC_ISSUER_URL"),+ OidcScopes: getEnvOrDefault("OIDC_SCOPES", "openid email profile"),}}+func (c *Config) GetOidcRedirectURI() string {+ baseUrl := strings.TrimSuffix(c.AppUrl, "/")+ return baseUrl + "/auth/oidc/callback"+}+func getEnvOrDefault(key, defaultValue string) string {if value := os.Getenv(key); value != "" {return valuediff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.goindex 0a4bada4f..0389da0bd 100644--- a/backend/internal/models/settings.go+++ b/backend/internal/models/settings.go@@ -10,13 +10,16 @@ type AuthSettings struct {}type OidcConfig struct {- ClientID string `json:"clientId"`- ClientSecret string `json:"clientSecret"`- RedirectURI string `json:"redirectUri"`- AuthorizationEndpoint string `json:"authorizationEndpoint"`- TokenEndpoint string `json:"tokenEndpoint"`- UserinfoEndpoint string `json:"userinfoEndpoint"`- Scopes string `json:"scopes"`+ ClientID string `json:"clientId"`+ ClientSecret string `json:"clientSecret"`+ IssuerURL string `json:"issuerUrl"`+ Scopes string `json:"scopes"`++ // These will be auto-discovered and cached+ AuthorizationEndpoint string `json:"authorizationEndpoint,omitempty"`+ TokenEndpoint string `json:"tokenEndpoint,omitempty"`+ UserinfoEndpoint string `json:"userinfoEndpoint,omitempty"`+ JwksURI string `json:"jwksUri,omitempty"`}type RegistryCredential struct {diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.goindex f379aaaf1..42cf54f88 100644--- a/backend/internal/services/auth_service.go+++ b/backend/internal/services/auth_service.go@@ -123,13 +123,10 @@ func (s *AuthService) SyncOidcEnvToDatabase(ctx context.Context) error {}envOidcConfig := models.OidcConfig{- ClientID: s.config.OidcClientID,- ClientSecret: s.config.OidcClientSecret,- RedirectURI: s.config.OidcRedirectURI,- AuthorizationEndpoint: s.config.OidcAuthorizationEndpoint,- TokenEndpoint: s.config.OidcTokenEndpoint,- UserinfoEndpoint: s.config.OidcUserinfoEndpoint,- Scopes: s.config.OidcScopes,+ ClientID: s.config.OidcClientID,+ ClientSecret: s.config.OidcClientSecret,+ IssuerURL: s.config.OidcIssuerURL,+ Scopes: s.config.OidcScopes,}oidcConfigBytes, err := json.Marshal(envOidcConfig)@@ -152,10 +149,6 @@ func (s *AuthService) SyncOidcEnvToDatabase(ctx context.Context) error {return fmt.Errorf("failed to update settings in DB with OIDC env config: %w", err)}- if s.config.OidcClientID == "" || s.config.OidcRedirectURI == "" || s.config.OidcAuthorizationEndpoint == "" || s.config.OidcTokenEndpoint == "" {- log.Println("⚠️ Warning: Synced OIDC settings from environment, but one or more critical OIDC environment variables (ClientID, RedirectURI, AuthEndpoint, TokenEndpoint) were empty. OIDC may not function correctly.")- }-return nil}@@ -197,30 +190,23 @@ func (s *AuthService) GetOidcConfigurationStatus(ctx context.Context) (*OidcStatstatus := &OidcStatusInfo{}status.EnvForced = s.config.OidcEnabled- if status.EnvForced {- // This reflects if the env vars themselves were complete at load time- status.EnvConfigured = s.config.OidcClientID != "" &&- // s.config.OidcClientSecret != "" && // ClientSecret might be optional for "configured" status display- s.config.OidcRedirectURI != "" &&- s.config.OidcAuthorizationEndpoint != "" &&- s.config.OidcTokenEndpoint != "" &&- s.config.OidcUserinfoEndpoint != ""++ if s.config.OidcEnabled {+ status.EnvConfigured = s.config.OidcClientID != "" && s.config.OidcIssuerURL != ""}- // Get effective settings which are now purely from the databaseeffectiveAuthSettings, err := s.getAuthSettings(ctx)if err != nil {- // If we can't get settings, we can't determine DB/effective statusreturn status, fmt.Errorf("failed to get effective auth settings for OIDC status: %w", err)}status.DbEnabled = effectiveAuthSettings.OidcEnabledif effectiveAuthSettings.Oidc != nil {status.DbConfigured = effectiveAuthSettings.Oidc.ClientID != "" &&- effectiveAuthSettings.Oidc.RedirectURI != "" &&- effectiveAuthSettings.Oidc.AuthorizationEndpoint != "" &&- effectiveAuthSettings.Oidc.TokenEndpoint != "" &&- effectiveAuthSettings.Oidc.UserinfoEndpoint != ""+ (effectiveAuthSettings.Oidc.IssuerURL != "" ||+ (effectiveAuthSettings.Oidc.AuthorizationEndpoint != "" &&+ effectiveAuthSettings.Oidc.TokenEndpoint != "" &&+ effectiveAuthSettings.Oidc.UserinfoEndpoint != ""))}status.EffectivelyEnabled = status.DbEnabled@@ -229,14 +215,12 @@ func (s *AuthService) GetOidcConfigurationStatus(ctx context.Context) (*OidcStatreturn status, nil}-// updateAuthSettings updates the auth settings in the databasefunc (s *AuthService) updateAuthSettings(ctx context.Context, authSettings *AuthSettings) error {settings, err := s.settingsService.GetSettings(ctx)if err != nil {return err}- // Convert AuthSettings struct to map[string]interface{}authBytes, err := json.Marshal(authSettings)if err != nil {return fmt.Errorf("failed to marshal auth settings: %w", err)@@ -266,7 +250,6 @@ func (s *AuthService) GetSessionTimeout(ctx context.Context) (int, error) {return authSettings.SessionTimeout, nil}-// UpdateSessionTimeout updates the session timeout in the auth settingsfunc (s *AuthService) UpdateSessionTimeout(ctx context.Context, minutes int) error {if minutes <= 0 {return errors.New("session timeout must be positive")diff --git a/backend/internal/services/oidc_service.go b/backend/internal/services/oidc_service.goindex 5141efb3d..85bc91d07 100644--- a/backend/internal/services/oidc_service.go+++ b/backend/internal/services/oidc_service.go@@ -12,18 +12,33 @@ import ("net/http""net/url""strings"+ "sync""time"+ "github.com/ofkm/arcane-backend/internal/config""github.com/ofkm/arcane-backend/internal/models")-// OidcService handles OIDC authentication flows+type OidcDiscoveryDocument struct {+ Issuer string `json:"issuer"`+ AuthorizationEndpoint string `json:"authorization_endpoint"`+ TokenEndpoint string `json:"token_endpoint"`+ UserinfoEndpoint string `json:"userinfo_endpoint"`+ JwksURI string `json:"jwks_uri"`+ ScopesSupported []string `json:"scopes_supported"`+ ResponseTypesSupported []string `json:"response_types_supported"`+ CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`+}+type OidcService struct {- authService *AuthService- httpClient *http.Client+ authService *AuthService+ config *config.Config+ httpClient *http.Client+ discoveryCache map[string]*OidcDiscoveryDocument+ cacheMutex sync.RWMutex+ cacheExpiry map[string]time.Time}-// OidcState represents the OIDC state parameter with additional metadatatype OidcState struct {State string `json:"state"`CodeVerifier string `json:"code_verifier"`@@ -31,7 +46,6 @@ type OidcState struct {CreatedAt time.Time `json:"created_at"`}-// TokenResponse represents the response from the OIDC token endpointtype TokenResponse struct {AccessToken string `json:"access_token"`TokenType string `json:"token_type"`@@ -40,20 +54,115 @@ type TokenResponse struct {IDToken string `json:"id_token,omitempty"`}-// NewOidcService creates a new OIDC service instance-func NewOidcService(authService *AuthService) *OidcService {+func NewOidcService(authService *AuthService, cfg *config.Config) *OidcService {return &OidcService{authService: authService,+ config: cfg,httpClient: &http.Client{Timeout: 30 * time.Second,},+ discoveryCache: make(map[string]*OidcDiscoveryDocument),+ cacheExpiry: make(map[string]time.Time),}}-// GenerateAuthURL creates an OIDC authorization URL with PKCE-func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string) (string, string, error) {- // Get OIDC configuration+func (s *OidcService) discoverOidcEndpoints(ctx context.Context, issuerURL string) (*OidcDiscoveryDocument, error) {+ s.cacheMutex.RLock()+ if cached, exists := s.discoveryCache[issuerURL]; exists {+ if expiry, hasExpiry := s.cacheExpiry[issuerURL]; hasExpiry && time.Now().Before(expiry) {+ s.cacheMutex.RUnlock()+ return cached, nil+ }+ }+ s.cacheMutex.RUnlock()++ // Construct well-known URL+ wellKnownURL := strings.TrimSuffix(issuerURL, "/") + "/.well-known/openid-configuration"++ req, err := http.NewRequestWithContext(ctx, http.MethodGet, wellKnownURL, nil)+ if err != nil {+ return nil, fmt.Errorf("failed to create discovery request: %w", err)+ }++ req.Header.Set("Accept", "application/json")+ req.Header.Set("User-Agent", "Arcane-OIDC-Client/1.0")++ resp, err := s.httpClient.Do(req)+ if err != nil {+ return nil, fmt.Errorf("failed to fetch OIDC discovery document from %s: %w", wellKnownURL, err)+ }+ defer resp.Body.Close()++ // Read the response body for better error reporting+ bodyBytes, err := io.ReadAll(resp.Body)+ if err != nil {+ return nil, fmt.Errorf("failed to read discovery response body: %w", err)+ }++ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("OIDC discovery endpoint %s returned %d: %s",+ wellKnownURL, resp.StatusCode, string(bodyBytes))+ }++ contentType := resp.Header.Get("Content-Type")+ if !strings.Contains(contentType, "application/json") {+ return nil, fmt.Errorf("OIDC discovery endpoint returned non-JSON content-type: %s, body: %s",+ contentType, string(bodyBytes[:min(500, len(bodyBytes))]))+ }++ var discovery OidcDiscoveryDocument+ if err := json.Unmarshal(bodyBytes, &discovery); err != nil {+ return nil, fmt.Errorf("failed to decode discovery document from %s: %w. Response body: %s",+ wellKnownURL, err, string(bodyBytes[:min(500, len(bodyBytes))]))+ }++ if discovery.AuthorizationEndpoint == "" || discovery.TokenEndpoint == "" {+ return nil, fmt.Errorf("discovery document missing required endpoints. Auth: %s, Token: %s",+ discovery.AuthorizationEndpoint, discovery.TokenEndpoint)+ }++ s.cacheMutex.Lock()+ s.discoveryCache[issuerURL] = &discovery+ s.cacheExpiry[issuerURL] = time.Now().Add(1 * time.Hour)+ s.cacheMutex.Unlock()++ return &discovery, nil+}++func (s *OidcService) getEffectiveConfig(ctx context.Context) (*models.OidcConfig, error) {config, err := s.authService.GetOidcConfig(ctx)+ if err != nil {+ return nil, err+ }++ // If we already have endpoints configured (legacy), use them+ if config.AuthorizationEndpoint != "" && config.TokenEndpoint != "" {+ return config, nil+ }++ // Otherwise, discover endpoints+ if config.IssuerURL == "" {+ return nil, errors.New("either issuerUrl or explicit endpoints must be configured")+ }++ discovery, err := s.discoverOidcEndpoints(ctx, config.IssuerURL)+ if err != nil {+ return nil, fmt.Errorf("failed to discover OIDC endpoints: %w", err)+ }++ // Create effective config with discovered endpoints+ effectiveConfig := *config+ effectiveConfig.AuthorizationEndpoint = discovery.AuthorizationEndpoint+ effectiveConfig.TokenEndpoint = discovery.TokenEndpoint+ effectiveConfig.UserinfoEndpoint = discovery.UserinfoEndpoint+ effectiveConfig.JwksURI = discovery.JwksURI++ return &effectiveConfig, nil+}++func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string) (string, string, error) {+ // Get effective OIDC configuration with discovered endpoints+ config, err := s.getEffectiveConfig(ctx)if err != nil {return "", "", err}@@ -75,18 +184,20 @@ func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string) (sreturn "", "", fmt.Errorf("invalid authorization endpoint: %w", err)}+ // Get auto-generated redirect URI from config+ redirectURI := s.config.GetOidcRedirectURI()+query := authURL.Query()query.Set("response_type", "code")query.Set("client_id", config.ClientID)- query.Set("redirect_uri", config.RedirectURI)+ query.Set("redirect_uri", redirectURI)query.Set("scope", strings.Join(scopes, " "))query.Set("state", state)query.Set("code_challenge", codeChallenge)query.Set("code_challenge_method", "S256")authURL.RawQuery = query.Encode()- // Store state with code verifier (in production, use Redis or database)- // For now, we'll return both and expect the caller to manage state+ // Store state with code verifierstateData := OidcState{State: state,CodeVerifier: codeVerifier,@@ -104,7 +215,6 @@ func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string) (sreturn authURL.String(), encodedState, nil}-// HandleCallback processes the OIDC callback and exchanges code for tokensfunc (s *OidcService) HandleCallback(ctx context.Context, code, state, storedState string) (*OidcUserInfo, error) {// Decode stored state to get the original state value and code verifierstateData, err := s.decodeState(storedState)@@ -122,8 +232,8 @@ func (s *OidcService) HandleCallback(ctx context.Context, code, state, storedStareturn nil, errors.New("state has expired")}- // Get OIDC configuration- config, err := s.authService.GetOidcConfig(ctx)+ // Get effective OIDC configuration with discovered endpoints+ config, err := s.getEffectiveConfig(ctx)if err != nil {return nil, err}@@ -143,12 +253,13 @@ func (s *OidcService) HandleCallback(ctx context.Context, code, state, storedStareturn userInfo, nil}-// exchangeCodeForTokens exchanges the authorization code for access tokensfunc (s *OidcService) exchangeCodeForTokens(ctx context.Context, config *models.OidcConfig, code, codeVerifier string) (*TokenResponse, error) {+ redirectURI := s.config.GetOidcRedirectURI()+data := url.Values{}data.Set("grant_type", "authorization_code")data.Set("code", code)- data.Set("redirect_uri", config.RedirectURI)+ data.Set("redirect_uri", redirectURI)data.Set("client_id", config.ClientID)data.Set("client_secret", config.ClientSecret)data.Set("code_verifier", codeVerifier)@@ -180,7 +291,6 @@ func (s *OidcService) exchangeCodeForTokens(ctx context.Context, config *models.return &tokenResponse, nil}-// getUserInfo retrieves user information from the userinfo endpointfunc (s *OidcService) getUserInfo(ctx context.Context, config *models.OidcConfig, accessToken string) (*OidcUserInfo, error) {req, err := http.NewRequestWithContext(ctx, http.MethodGet, config.UserinfoEndpoint, nil)if err != nil {@@ -213,7 +323,6 @@ func (s *OidcService) getUserInfo(ctx context.Context, config *models.OidcConfigreturn &userInfo, nil}-// decodeState decodes the base64-encoded state datafunc (s *OidcService) decodeState(encodedState string) (*OidcState, error) {stateJSON, err := base64.URLEncoding.DecodeString(encodedState)if err != nil {@@ -230,7 +339,6 @@ func (s *OidcService) decodeState(encodedState string) (*OidcState, error) {// Helper functions-// generateRandomString generates a cryptographically secure random stringfunc generateRandomString(length int) string {bytes := make([]byte, length)if _, err := rand.Read(bytes); err != nil {@@ -239,7 +347,6 @@ func generateRandomString(length int) string {return base64.URLEncoding.EncodeToString(bytes)[:length]}-// generateCodeChallenge generates a PKCE code challenge from a verifierfunc generateCodeChallenge(verifier string) string {hash := sha256.Sum256([]byte(verifier))return base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(hash[:])diff --git a/frontend/src/lib/components/dialogs/oidc-config-dialog.svelte b/frontend/src/lib/components/dialogs/oidc-config-dialog.sveltenew file mode 100644index 000000000..b84aaa786--- /dev/null+++ b/frontend/src/lib/components/dialogs/oidc-config-dialog.svelte@@ -0,0 +1,237 @@+<script lang="ts">+ import { Button } from '$lib/components/ui/button/index.js';+ import { Input } from '$lib/components/ui/input/index.js';+ import { Key, AlertTriangle, Info, ChevronDown, Copy } from '@lucide/svelte';+ import * as Dialog from '$lib/components/ui/dialog/index.js';+ import * as Collapsible from '$lib/components/ui/collapsible/index.js';+ import { Label } from '$lib/components/ui/label/index.js';+ import { toast } from 'svelte-sonner';+ import type { Settings } from '$lib/types/settings.type';++ interface OidcStatus {+ envForced: boolean;+ envConfigured: boolean;+ effectivelyEnabled: boolean;+ effectivelyConfigured: boolean;+ dbConfigured: boolean;+ }++ interface OidcForm {+ clientId: string;+ clientSecret: string;+ issuerUrl: string;+ scopes: string;+ }++ let {+ open = $bindable(),+ currentSettings,+ oidcStatus,+ oidcForm = $bindable(),+ onSave+ }: {+ open: boolean;+ currentSettings: Settings;+ oidcStatus: OidcStatus;+ oidcForm: OidcForm;+ onSave: () => void;+ } = $props();++ let isOidcViewMode = $derived(oidcStatus.envForced && oidcStatus.envConfigured);+ let advancedSettingsOpen = $state(false);+ let redirectUri = $derived(`${window.location.origin}/auth/oidc/callback`);++ async function copyToClipboard(text: string) {+ try {+ await navigator.clipboard.writeText(text);+ toast.success('Copied to clipboard');+ } catch (err) {+ toast.error('Failed to copy to clipboard');+ }+ }+</script>++<Dialog.Root bind:open>+ <Dialog.Content class="sm:max-w-[700px] max-h-[90vh] flex flex-col">+ <Dialog.Header class="space-y-3 flex-shrink-0">+ <Dialog.Title class="flex items-center gap-2">+ <Key class="size-5" />+ {#if isOidcViewMode}+ OIDC Server Configuration Status+ {:else if oidcStatus.envForced && !oidcStatus.envConfigured}+ Configure OIDC (Server Override Warning)+ {:else}+ Configure OIDC Provider+ {/if}+ </Dialog.Title>+ <Dialog.Description class="text-sm leading-relaxed">+ {#if isOidcViewMode}+ OIDC authentication is configured and forced ON by server-side environment variables.+ These settings are read-only.+ {:else if oidcStatus.envForced && !oidcStatus.envConfigured}+ OIDC usage is forced ON by the server environment (<code+ class="bg-muted px-1 py-0.5 rounded text-xs">OIDC_ENABLED=true</code+ >), but critical server-side OIDC environment variables appear to be missing or+ incomplete.+ {:else}+ Configure the OIDC settings for your application. These settings will be saved to the+ database and used for OIDC authentication.+ {/if}+ </Dialog.Description>+ </Dialog.Header>++ <div class="flex-1 overflow-y-auto min-h-0 py-4">+ {#if isOidcViewMode}+ <!-- Read-only view for server-configured OIDC -->+ <div class="space-y-6">+ <div class="space-y-4">+ <h3 class="text-base font-semibold">Server Environment Configuration</h3>+ <p class="text-sm text-muted-foreground">+ The following OIDC settings are loaded from the server environment:+ </p>++ {#if currentSettings.auth?.oidc}+ <div class="space-y-3">+ <div class="flex justify-between items-center py-2 border-b border-border/50">+ <span class="font-medium text-sm">Client ID</span>+ <code class="bg-muted px-2 py-1 rounded text-xs">+ {currentSettings.auth.oidc.clientId}+ </code>+ </div>+ <div class="flex justify-between items-center py-2 border-b border-border/50">+ <span class="font-medium text-sm">Client Secret</span>+ <span class="text-muted-foreground italic text-xs">+ (Sensitive - Not Displayed)+ </span>+ </div>+ <div class="flex justify-between items-center py-2">+ <span class="font-medium text-sm">Scopes</span>+ <code class="bg-muted px-2 py-1 rounded text-xs">+ {currentSettings.auth.oidc.scopes}+ </code>+ </div>+ </div>+ {:else}+ <div class="text-center py-4">+ <AlertTriangle class="size-8 text-destructive mx-auto mb-2" />+ <p class="text-destructive text-sm font-medium">+ OIDC configuration details not found in effective settings.+ </p>+ </div>+ {/if}++ <div class="p-3 bg-muted/50 rounded-md">+ <p class="text-muted-foreground text-xs">+ Changes to these settings must be made in your server's environment configuration.+ </p>+ </div>+ </div>+ </div>+ {:else}+ <!-- Editable form for database-configured OIDC -->+ <div class="space-y-6">+ <!-- Basic Configuration -->+ <div class="space-y-4">+ <h3 class="text-base font-semibold">Basic Configuration</h3>+ <p class="text-sm text-muted-foreground">Essential OIDC provider settings</p>++ <div class="space-y-4">+ <div class="space-y-2">+ <Label for="oidcClientId" class="text-sm font-medium">Client ID</Label>+ <Input+ id="oidcClientId"+ bind:value={oidcForm.clientId}+ placeholder="Provided by your OIDC Provider"+ class="font-mono text-sm"+ />+ </div>+ <div class="space-y-2">+ <Label for="oidcClientSecret" class="text-sm font-medium">Client Secret</Label>+ <Input+ id="oidcClientSecret"+ type="password"+ bind:value={oidcForm.clientSecret}+ placeholder="Provided by your OIDC Provider (leave blank to keep existing)"+ class="font-mono text-sm"+ />+ </div>+ <div class="space-y-2">+ <Label for="oidcIssuerUrl" class="text-sm font-medium">Issuer URL</Label>+ <Input+ id="oidcIssuerUrl"+ bind:value={oidcForm.issuerUrl}+ placeholder="https://id.example.com"+ class="font-mono text-sm"+ />+ <p class="text-muted-foreground text-xs">+ The issuer URL will be used to auto-discover OIDC endpoints. This is the+ recommended approach.+ </p>+ </div>+ <div class="space-y-2">+ <Label for="oidcScopes" class="text-sm font-medium">Scopes</Label>+ <Input+ id="oidcScopes"+ bind:value={oidcForm.scopes}+ placeholder="openid email profile"+ class="font-mono text-sm"+ />+ </div>+ </div>+ </div>++ <!-- Warning for server override -->+ {#if oidcStatus.envForced && !oidcStatus.envConfigured}+ <div class="border border-destructive/50 bg-destructive/5 p-4 rounded-md">+ <div class="flex items-center gap-2 mb-2">+ <AlertTriangle class="size-4 text-destructive" />+ <h3 class="text-base font-semibold text-destructive">Server Override Warning</h3>+ </div>+ <p class="text-sm text-destructive/80">+ While you can save these settings to the application database, it's strongly+ recommended to configure the OIDC settings directly in your server's environment for+ them to take full effect as intended by the server override.+ </p>+ </div>+ {/if}+ </div>+ {/if}++ <!-- Redirect URI Information - Always shown -->+ <div class="border-t pt-6 mt-6">+ <div class="flex items-center gap-2 mb-3">+ <Info class="size-4 text-blue-600" />+ <h3 class="text-base font-semibold">Redirect URI Configuration</h3>+ </div>+ <p class="text-sm text-muted-foreground mb-3">+ Configure this redirect URI in your OIDC provider:+ </p>+ <div class="flex items-center gap-2">+ <code class="flex-1 bg-muted p-2 rounded text-xs break-all font-mono">+ {redirectUri}+ </code>+ <Button+ size="sm"+ variant="outline"+ onclick={() => copyToClipboard(redirectUri)}+ class="flex-shrink-0"+ >+ <Copy class="size-3" />+ </Button>+ </div>+ </div>+ </div>++ <Dialog.Footer class="flex gap-3 pt-4 border-t flex-shrink-0">+ <Button variant="outline" onclick={() => (open = false)} class="flex-1 sm:flex-none">+ Close+ </Button>+ {#if !isOidcViewMode}+ <Button onclick={onSave} class="flex-1 sm:flex-none">+ <Key class="size-4 mr-2" />+ Configure OIDC+ </Button>+ {/if}+ </Dialog.Footer>+ </Dialog.Content>+</Dialog.Root>diff --git a/frontend/src/lib/services/api/oidc-api-service.ts b/frontend/src/lib/services/api/oidc-api-service.tsindex 1ed0c7431..f014126cb 100644--- a/frontend/src/lib/services/api/oidc-api-service.ts+++ b/frontend/src/lib/services/api/oidc-api-service.ts@@ -4,18 +4,27 @@ import type { OidcConfig } from '$lib/types/settings.type';export interface OidcUserInfo {sub: string;email: string;- name: string;- preferred_username?: string;+ name?: string;displayName?: string;+ preferred_username?: string;given_name?: string;family_name?: string;picture?: string;groups?: string[];}+export interface OidcStatus {+ envForced: boolean;+ envConfigured: boolean;+ dbEnabled: boolean;+ dbConfigured: boolean;+}+export default class OidcAPIService extends BaseAPIService {async getAuthUrl(redirectUri: string): Promise<string> {- const response = (await this.handleResponse(this.api.post('/auth/oidc/url', { redirectUri }))) as { authUrl: string };+ const response = (await this.handleResponse(this.api.post('/oidc/url', { redirectUri }))) as {+ authUrl: string;+ };return response.authUrl;}@@ -28,39 +37,19 @@ export default class OidcAPIService extends BaseAPIService {user?: OidcUserInfo;error?: string;}> {- return this.handleResponse(this.api.post('/auth/oidc/callback', { code, state }));+ return this.handleResponse(this.api.post('/oidc/callback', { code, state }));}- async getUserInfo(): Promise<OidcUserInfo> {- return this.handleResponse(this.api.get('/auth/oidc/userinfo'));+ async getStatus(): Promise<OidcStatus> {+ return this.handleResponse(this.api.get('/oidc/status'));}- async refreshToken(): Promise<{ token: string }> {- return this.handleResponse(this.api.post('/auth/oidc/refresh'));- }-- async logout(): Promise<void> {- return this.handleResponse(this.api.post('/auth/oidc/logout'));- }-- async getConfig(): Promise<OidcConfig> {- return this.handleResponse(this.api.get('/auth/oidc/config'));+ async getConfig(): Promise<OidcConfig & { redirectUri: string }> {+ return this.handleResponse(this.api.get('/oidc/config'));}async updateConfig(config: Partial<OidcConfig>): Promise<OidcConfig> {- return this.handleResponse(this.api.put('/auth/oidc/config', config));- }-- async testConfig(): Promise<{ success: boolean; message: string }> {- return this.handleResponse(this.api.post('/auth/oidc/test'));- }-- async getStatus(): Promise<{- enabled: boolean;- configured: boolean;- envConfigured: boolean;- settingsConfigured: boolean;- }> {- return this.handleResponse(this.api.get('/auth/oidc/status'));+ const { ...updatePayload } = config;+ return this.handleResponse(this.api.put('/oidc/config', updatePayload));}}diff --git a/frontend/src/lib/services/api/settings-api-service.ts b/frontend/src/lib/services/api/settings-api-service.tsindex e1e8010a6..3b74bc25d 100644--- a/frontend/src/lib/services/api/settings-api-service.ts+++ b/frontend/src/lib/services/api/settings-api-service.ts@@ -47,6 +47,6 @@ export default class SettingsAPIService extends BaseAPIService {}async getOidcStatus(): Promise<OidcStatusInfo> {- return this.handleResponse(this.api.get('/auth/oidc/status'));+ return this.handleResponse(this.api.get('/oidc/status'));}}diff --git a/frontend/src/lib/types/settings.type.ts b/frontend/src/lib/types/settings.type.tsindex d05a81a87..26b205dd3 100644--- a/frontend/src/lib/types/settings.type.ts+++ b/frontend/src/lib/types/settings.type.ts@@ -9,11 +9,8 @@ export interface AuthSettings {export interface OidcConfig {clientId: string;- clientSecret: string;- redirectUri: string;- authorizationEndpoint: string;- tokenEndpoint: string;- userinfoEndpoint: string;+ clientSecret?: string;+ issuerUrl: string;scopes: string;}diff --git a/frontend/src/routes/auth/oidc/callback/+page.svelte b/frontend/src/routes/auth/oidc/callback/+page.svelteindex d583fd1c8..aaa610e35 100644--- a/frontend/src/routes/auth/oidc/callback/+page.svelte+++ b/frontend/src/routes/auth/oidc/callback/+page.svelte@@ -14,11 +14,29 @@try {const code = page.url.searchParams.get('code');const stateFromUrl = page.url.searchParams.get('state');- const finalRedirectTo = localStorage.getItem('oidc_redirect') || '/';+ const errorParam = page.url.searchParams.get('error');+ const errorDescription = page.url.searchParams.get('error_description');++ const finalRedirectTo = localStorage.getItem('oidc_redirect') || '/dashboard';localStorage.removeItem('oidc_redirect');+ // Handle OIDC provider errors+ if (errorParam) {+ let userMessage = 'Authentication was cancelled or failed.';+ if (errorParam === 'access_denied') {+ userMessage = 'Access was denied. You may have cancelled the login or lack permission.';+ } else if (errorParam === 'invalid_request') {+ userMessage = 'Invalid authentication request. Please try again.';+ }++ error = errorDescription || userMessage;+ setTimeout(() => goto('/auth/login?error=oidc_provider_error'), 3000);+ isProcessing = false;+ return;+ }+if (!code || !stateFromUrl) {- error = 'Invalid OIDC response (missing parameters). Please try logging in again.';+ error = 'Invalid authentication response. Missing required parameters.';setTimeout(() => goto('/auth/login?error=oidc_invalid_response'), 3000);isProcessing = false;return;@@ -27,10 +45,15 @@const authResult = await oidcAPI.handleCallback(code, stateFromUrl);if (!authResult.success) {- error = authResult.error || 'Authentication failed. Please try again.';- const errorCode =- authResult.error?.toLowerCase().replace(/\s+/g, '_') || 'oidc_auth_failed';- setTimeout(() => goto(`/auth/login?error=${errorCode}`), 3000);+ let userMessage = 'Authentication failed. Please try again.';+ if (authResult.error?.includes('state')) {+ userMessage = 'Security validation failed. Please try logging in again.';+ } else if (authResult.error?.includes('expired')) {+ userMessage = 'Authentication session expired. Please try again.';+ }++ error = userMessage;+ setTimeout(() => goto('/auth/login?error=oidc_auth_failed'), 3000);isProcessing = false;return;}@@ -42,38 +65,55 @@email: authResult.user.email,displayName:authResult.user.name ||+ authResult.user.displayName ||authResult.user.given_name ||authResult.user.preferred_username ||authResult.user.email ||'User',- roles: ['user'],+ roles: authResult.user.groups || ['user'],createdAt: new Date().toISOString()};userStore.setUser(user);+ await invalidateAll();+ toast.success('Successfully logged in!');+ goto(finalRedirectTo);+ } else {+ error = 'Authentication succeeded but user information is missing.';+ setTimeout(() => goto('/auth/login?error=oidc_user_info_missing'), 3000);+ isProcessing = false;}-- await invalidateAll();- toast.success('Successfully logged in!');- goto(finalRedirectTo);} catch (err: any) {- error = err.message || 'An error occurred during authentication. Please try again.';- setTimeout(() => goto('/auth/login?error=oidc_generic_error'), 3000);- } finally {+ console.error('OIDC callback error:', err);++ let userMessage = 'An error occurred during authentication. Please try again.';+ if (err.message?.includes('network') || err.message?.includes('timeout')) {+ userMessage =+ 'Network error during authentication. Please check your connection and try again.';+ }++ error = userMessage;+ setTimeout(() => goto('/auth/login?error=oidc_callback_error'), 3000);isProcessing = false;}});</script>+<svelte:head>+ <title>Processing Login... - Arcane</title>+</svelte:head>+<div class="flex min-h-screen items-center justify-center bg-background"><div class="w-full max-w-md space-y-8"><div class="text-center">{#if isProcessing}- <div class="mx-auto h-12 w-12 animate-spin rounded-full border-b-2 border-white-600"></div>- <h2 class="mt-6 text-2xl font-bold">Authenticating...</h2>- <p class="mt-2 text-sm">Please wait while we complete your login.</p>+ <div class="mx-auto h-12 w-12 animate-spin rounded-full border-b-2 border-primary"></div>+ <h2 class="mt-6 text-2xl font-bold">Processing Login...</h2>+ <p class="mt-2 text-sm text-muted-foreground">+ Please wait while we complete your authentication.+ </p>{:else if error}- <div class="text-red-600">+ <div class="text-destructive"><svg class="mx-auto h-12 w-12" fill="none" viewBox="0 0 24 24" stroke="currentColor"><pathstroke-linecap="round"@@ -84,7 +124,7 @@</svg><h2 class="mt-6 text-2xl font-bold">Authentication Error</h2><p class="mt-2 text-sm">{error}</p>- <p class="mt-4 text-xs">Redirecting you back to login...</p>+ <p class="mt-4 text-xs text-muted-foreground">Redirecting you back to login...</p></div>{/if}</div>diff --git a/frontend/src/routes/auth/oidc/login/+page.svelte b/frontend/src/routes/auth/oidc/login/+page.svelteindex 95976f233..a5a01d9fc 100644--- a/frontend/src/routes/auth/oidc/login/+page.svelte+++ b/frontend/src/routes/auth/oidc/login/+page.svelte@@ -9,21 +9,43 @@onMount(async () => {try {- const redirectParam = page.url.searchParams.get('redirect') || '/';+ const redirectParam = page.url.searchParams.get('redirect') || '/dashboard';++ // Check if OIDC is properly configured first+ const status = await oidcAPI.getStatus();+ if (!status.dbEnabled || !status.dbConfigured) {+ error =+ 'OIDC authentication is not properly configured. Please contact your administrator.';+ setTimeout(() => goto('/auth/login?error=oidc_not_configured'), 3000);+ isRedirecting = false;+ return;+ }+const authUrl = await oidcAPI.getAuthUrl(redirectParam);if (!authUrl) {- console.error('OIDC auth URL not available from backend.');- error = 'OIDC is not properly configured or the server could not provide an auth URL.';- setTimeout(() => goto('/auth/login?error=oidc_misconfigured'), 3000);+ error =+ 'Unable to generate authentication URL. Please try again or contact your administrator.';+ setTimeout(() => goto('/auth/login?error=oidc_url_generation_failed'), 3000);isRedirecting = false;return;}+localStorage.setItem('oidc_redirect', redirectParam);window.location.href = authUrl;} catch (err: any) {console.error('OIDC login initiation error:', err);- error = err.message || 'Failed to initiate OIDC login. Please check server logs.';- setTimeout(() => goto('/auth/login?error=oidc_misconfigured'), 3000);++ // Parse the error message to provide better user feedback+ let userMessage = 'Failed to initiate OIDC login. Please try again.';+ if (err.message?.includes('discovery')) {+ userMessage = 'OIDC provider configuration error. Please contact your administrator.';+ } else if (err.message?.includes('network') || err.message?.includes('timeout')) {+ userMessage =+ 'Network error connecting to authentication provider. Please check your connection and try again.';+ }++ error = userMessage;+ setTimeout(() => goto('/auth/login?error=oidc_init_failed'), 3000);isRedirecting = false;}});@@ -37,11 +59,13 @@<div class="w-full max-w-md space-y-8"><div class="text-center">{#if isRedirecting && !error}- <div class="mx-auto h-12 w-12 animate-spin rounded-full border-b-2 border-white"></div>+ <div class="mx-auto h-12 w-12 animate-spin rounded-full border-b-2 border-primary"></div><h2 class="mt-6 text-2xl font-bold">Redirecting to Login...</h2>- <p class="mt-2 text-sm">Please wait while we redirect you to your identity provider.</p>+ <p class="mt-2 text-sm text-muted-foreground">+ Please wait while we redirect you to your identity provider.+ </p>{:else if error}- <div class="text-red-600">+ <div class="text-destructive"><svg class="mx-auto h-12 w-12" fill="none" viewBox="0 0 24 24" stroke="currentColor"><pathstroke-linecap="round"@@ -50,9 +74,11 @@d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.732-.833-2.5 0L3.341 16.5c-.77.833.192 2.5 1.732 2.5z"/></svg>- <h2 class="mt-6 text-2xl font-bold">Login Error</h2>+ <h2 class="mt-6 text-2xl font-bold">Authentication Error</h2><p class="mt-2 text-sm">{error}</p>- <p class="mt-4 text-xs">Redirecting you back to the login page...</p>+ <p class="mt-4 text-xs text-muted-foreground">+ Redirecting you back to the login page...+ </p></div>{/if}</div>diff --git a/frontend/src/routes/settings/security/+page.svelte b/frontend/src/routes/settings/security/+page.svelteindex 5914d86e1..bc701da60 100644--- a/frontend/src/routes/settings/security/+page.svelte+++ b/frontend/src/routes/settings/security/+page.svelte@@ -6,8 +6,7 @@import { Switch } from '$lib/components/ui/switch/index.js';import { Lock, Key, AlertTriangle, Info, Save, RefreshCw } from '@lucide/svelte';import settingsStore from '$lib/stores/config-store';- import * as Dialog from '$lib/components/ui/dialog/index.js';- import { Label } from '$lib/components/ui/label/index.js';+ import OidcConfigDialog from '$lib/components/dialogs/oidc-config-dialog.svelte';import { toast } from 'svelte-sonner';import { invalidateAll } from '$app/navigation';import type { Settings } from '$lib/types/settings.type';@@ -20,10 +19,7 @@let oidcConfigForm = $state({clientId: '',clientSecret: '',- redirectUri: 'http://localhost:3000/auth/oidc/callback',- authorizationEndpoint: '',- tokenEndpoint: '',- userinfoEndpoint: '',+ issuerUrl: '',scopes: 'openid email profile'});@@ -45,10 +41,6 @@passwordPolicy = currentSettings.auth?.passwordPolicy ?? 'strong';oidcConfigForm.clientId = currentSettings.auth?.oidc?.clientId || '';- oidcConfigForm.redirectUri = currentSettings.auth?.oidc?.redirectUri || 'http://localhost:3000/auth/oidc/callback';- oidcConfigForm.authorizationEndpoint = currentSettings.auth?.oidc?.authorizationEndpoint || '';- oidcConfigForm.tokenEndpoint = currentSettings.auth?.oidc?.tokenEndpoint || '';- oidcConfigForm.userinfoEndpoint = currentSettings.auth?.oidc?.userinfoEndpoint || '';oidcConfigForm.scopes = currentSettings.auth?.oidc?.scopes || 'openid email profile';oidcConfigForm.clientSecret = '';});@@ -75,10 +67,7 @@oidc: {clientId: oidcConfigForm.clientId,clientSecret: oidcConfigForm.clientSecret || '',- redirectUri: oidcConfigForm.redirectUri,- authorizationEndpoint: oidcConfigForm.authorizationEndpoint,- tokenEndpoint: oidcConfigForm.tokenEndpoint,- userinfoEndpoint: oidcConfigForm.userinfoEndpoint,+ issuerUrl: oidcConfigForm.issuerUrl,scopes: oidcConfigForm.scopes}}@@ -106,10 +95,7 @@if (!isOidcViewMode) {oidcConfigForm.clientId = currentSettings.auth?.oidc?.clientId || '';oidcConfigForm.clientSecret = '';- oidcConfigForm.redirectUri = currentSettings.auth?.oidc?.redirectUri || 'http://localhost:3000/auth/oidc/callback';- oidcConfigForm.authorizationEndpoint = currentSettings.auth?.oidc?.authorizationEndpoint || '';- oidcConfigForm.tokenEndpoint = currentSettings.auth?.oidc?.tokenEndpoint || '';- oidcConfigForm.userinfoEndpoint = currentSettings.auth?.oidc?.userinfoEndpoint || '';+ oidcConfigForm.issuerUrl = currentSettings.auth?.oidc?.issuerUrl || '';oidcConfigForm.scopes = currentSettings.auth?.oidc?.scopes || 'openid email profile';}showOidcConfigDialog = true;@@ -117,14 +103,35 @@async function handleSaveOidcConfig() {try {+ isLoading.saving = true;oidcEnabled = true;- toast.success('OIDC configuration will be saved with other settings.');++ await updateSettingsConfig({+ auth: {+ ...currentSettings.auth,+ localAuthEnabled: localAuthEnabled,+ oidcEnabled: true,+ sessionTimeout: sessionTimeout,+ passwordPolicy: passwordPolicy,+ oidc: {+ clientId: oidcConfigForm.clientId,+ clientSecret: oidcConfigForm.clientSecret || '',+ issuerUrl: oidcConfigForm.issuerUrl,+ scopes: oidcConfigForm.scopes+ }+ }+ });++ toast.success('OIDC configuration saved successfully.');showOidcConfigDialog = false;+ await invalidateAll();} catch (error) {- console.error('Failed to prepare OIDC configuration:', error);- toast.error('Failed to prepare OIDC configuration.', {+ console.error('Failed to save OIDC configuration:', error);+ toast.error('Failed to save OIDC configuration.', {description: error instanceof Error ? error.message : 'An unknown error occurred.'});+ } finally {+ isLoading.saving = false;}}</script>@@ -133,11 +140,17 @@<div class="settings-header"><div class="settings-header-content"><h1 class="settings-title">Security Settings</h1>- <p class="settings-description">Configure authentication methods, session policies, and security settings</p>+ <p class="settings-description">+ Configure authentication methods, session policies, and security settings+ </p></div><div class="settings-actions">- <Button onclick={() => handleSecuritySettingUpdates()} disabled={isLoading.saving} class="arcane-button-save">+ <Button+ onclick={() => handleSecuritySettingUpdates()}+ disabled={isLoading.saving}+ class="arcane-button-save"+ >{#if isLoading.saving}<RefreshCw class="size-4 animate-spin" />Saving...@@ -158,7 +171,9 @@</div><div><Card.Title class="settings-card-title">Authentication Methods</Card.Title>- <Card.Description class="settings-card-description">Configure how users sign in to Arcane</Card.Description>+ <Card.Description class="settings-card-description"+ >Configure how users sign in to Arcane</Card.Description+ ></div></div></Card.Header>@@ -166,9 +181,15 @@<div class="space-y-4"><div class="bg-muted/30 flex items-center justify-between rounded-lg border p-4"><div class="space-y-0.5">- <label for="localAuthSwitch" class="text-base font-medium">Local Authentication</label>- <p class="text-muted-foreground text-sm">Username and password stored in the system</p>- <p class="text-muted-foreground mt-1 text-xs">This is recommended to be enabled as a fallback option if OIDC authentication is unavailable.</p>+ <label for="localAuthSwitch" class="text-base font-medium">Local Authentication</label+ >+ <p class="text-muted-foreground text-sm">+ Username and password stored in the system+ </p>+ <p class="text-muted-foreground mt-1 text-xs">+ This is recommended to be enabled as a fallback option if OIDC authentication is+ unavailable.+ </p></div><Switchid="localAuthSwitch"@@ -184,129 +205,69 @@<p class="text-muted-foreground text-sm">Use an External OIDC Provider{#if data.oidcStatus.envForced}- <span class="text-muted-foreground text-xs">(Forced ON by server environment)</span>+ <span class="text-muted-foreground text-xs"+ >(Forced ON by server environment)</span+ >{/if}</p>{#if data.oidcStatus.effectivelyEnabled || data.oidcStatus.envForced}{#if data.oidcStatus.envForced && !data.oidcStatus.envConfigured}- <Button variant="link" class="text-destructive h-auto p-0 text-xs hover:underline" onclick={openOidcDialog}>+ <Button+ variant="link"+ class="text-destructive h-auto p-0 text-xs hover:underline"+ onclick={openOidcDialog}+ ><AlertTriangle class="mr-1 size-3" />Server forces OIDC, but env vars missing. Configure app settings or fix server env.</Button>{:else if data.oidcStatus.envForced && data.oidcStatus.envConfigured}- <Button variant="link" class="h-auto p-0 text-xs text-sky-600 hover:underline" onclick={openOidcDialog}>+ <Button+ variant="link"+ class="h-auto p-0 text-xs text-sky-600 hover:underline"+ onclick={openOidcDialog}+ ><Info class="mr-1 size-3" />OIDC configured & forced by server. View Status.</Button>{:else if !data.oidcStatus.envForced && data.oidcStatus.effectivelyEnabled && data.oidcStatus.dbConfigured}- <Button variant="link" class="h-auto p-0 text-xs text-sky-600 hover:underline" onclick={openOidcDialog}>+ <Button+ variant="link"+ class="h-auto p-0 text-xs text-sky-600 hover:underline"+ onclick={openOidcDialog}+ ><Info class="mr-1 size-3" />OIDC configured via application settings. Manage.</Button>{:else if !data.oidcStatus.envForced && data.oidcStatus.effectivelyEnabled && !data.oidcStatus.dbConfigured}- <Button variant="link" class="text-destructive h-auto p-0 text-xs hover:underline" onclick={openOidcDialog}>+ <Button+ variant="link"+ class="text-destructive h-auto p-0 text-xs hover:underline"+ onclick={openOidcDialog}+ ><AlertTriangle class="mr-1 size-3" />OIDC enabled, but app settings incomplete. Configure.</Button>{/if}{/if}</div>- <Switch id="oidcAuthSwitch" checked={oidcEnabled} disabled={data.oidcStatus.envForced} onCheckedChange={handleOidcSwitchChange} />+ <Switch+ id="oidcAuthSwitch"+ checked={oidcEnabled}+ disabled={data.oidcStatus.envForced}+ onCheckedChange={handleOidcSwitchChange}+ /></div></div></Card.Content></Card.Root>- <Dialog.Root bind:open={showOidcConfigDialog}>- <Dialog.Content class="sm:max-w-[600px]">- <Dialog.Header>- <Dialog.Title>- {#if isOidcViewMode}OIDC Server Configuration Status- {:else if data.oidcStatus.envForced && !data.oidcStatus.envConfigured}Configure OIDC (Server Override Warning)- {:else}Configure OIDC Provider{/if}- </Dialog.Title>- <Dialog.Description>- {#if isOidcViewMode}- OIDC authentication is configured and forced ON by server-side environment variables. These settings are read-only.- <p class="mt-2">The following OIDC settings are loaded from the server environment:</p>- {:else if data.oidcStatus.envForced && !data.oidcStatus.envConfigured}- OIDC usage is forced ON by the server environment (<code>PUBLIC_OIDC_ENABLED=true</code>), but critical server-side OIDC environment variables appear to be missing or incomplete. The settings below are from your application database. While you can save them here, it's strongly- recommended to configure the OIDC settings directly in your server's environment for them to take full effect as intended by the server override.- {:else}- Configure the OIDC settings for your application. These settings will be saved to the database and used for OIDC authentication.- {/if}- </Dialog.Description>- </Dialog.Header>-- {#if isOidcViewMode}- <div class="max-h-[50vh] overflow-y-auto py-4 pr-2">- <ul class="mt-1 list-inside list-disc space-y-1 text-sm">- {#if currentSettings.auth?.oidc}- <li><strong>Client ID:</strong> {currentSettings.auth.oidc.clientId}</li>- <li>- <strong>Client Secret:</strong>- <span class="text-muted-foreground italic">(Sensitive - Not Displayed)</span>- </li>- <li><strong>Redirect URI:</strong> {currentSettings.auth.oidc.redirectUri}</li>- <li>- <strong>Authorization Endpoint:</strong>- {currentSettings.auth.oidc.authorizationEndpoint}- </li>- <li><strong>Token Endpoint:</strong> {currentSettings.auth.oidc.tokenEndpoint}</li>- <li>- <strong>User Info Endpoint:</strong>- {currentSettings.auth.oidc.userinfoEndpoint}- </li>- <li><strong>Scopes:</strong> {currentSettings.auth.oidc.scopes}</li>- {:else}- <li>- <span class="text-destructive">OIDC configuration details not found in effective settings.</span>- </li>- {/if}- </ul>- <p class="text-muted-foreground mt-3 text-xs">Changes to these settings must be made in your server's environment configuration.</p>- </div>- {:else}- <div class="grid max-h-[50vh] gap-4 overflow-y-auto py-4 pr-2">- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcClientId" class="col-span-1 text-right">Client ID</Label>- <Input id="oidcClientId" bind:value={oidcConfigForm.clientId} class="col-span-3" placeholder="Provided by your OIDC Provider" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcClientSecret" class="col-span-1 text-right">Client Secret</Label>- <Input id="oidcClientSecret" type="password" bind:value={oidcConfigForm.clientSecret} class="col-span-3" placeholder="Provided by your OIDC Provider (leave blank to keep existing if any)" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcRedirectUri" class="col-span-1 text-right">Redirect URI</Label>- <Input id="oidcRedirectUri" bind:value={oidcConfigForm.redirectUri} placeholder="e.g., http://localhost:3000/auth/oidc/callback" class="col-span-3" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcAuthEndpoint" class="col-span-1 text-right">Authorization URL</Label>- <Input id="oidcAuthEndpoint" bind:value={oidcConfigForm.authorizationEndpoint} class="col-span-3" placeholder="OIDC Provider's Authorization Endpoint" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcTokenEndpoint" class="col-span-1 text-right">Token URL</Label>- <Input id="oidcTokenEndpoint" bind:value={oidcConfigForm.tokenEndpoint} class="col-span-3" placeholder="OIDC Provider's Token Endpoint" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcUserinfoEndpoint" class="col-span-1 text-right">User Info URL</Label>- <Input id="oidcUserinfoEndpoint" bind:value={oidcConfigForm.userinfoEndpoint} class="col-span-3" placeholder="OIDC Provider's UserInfo Endpoint" />- </div>- <div class="grid grid-cols-4 items-center gap-4">- <Label for="oidcScopes" class="col-span-1 text-right">Scopes</Label>- <Input id="oidcScopes" bind:value={oidcConfigForm.scopes} placeholder="e.g., openid email profile" class="col-span-3" />- </div>- </div>- {/if}-- <Dialog.Footer>- <Button variant="outline" onclick={() => (showOidcConfigDialog = false)}>Close</Button>- {#if !isOidcViewMode}- <Button onclick={handleSaveOidcConfig}>Configure OIDC</Button>- {/if}- </Dialog.Footer>- </Dialog.Content>- </Dialog.Root>+ <OidcConfigDialog+ bind:open={showOidcConfigDialog}+ {currentSettings}+ oidcStatus={data.oidcStatus}+ bind:oidcForm={oidcConfigForm}+ onSave={handleSaveOidcConfig}+ /><Card.Root class="settings-card"><Card.Header class="settings-card-header">@@ -316,16 +277,28 @@</div><div><Card.Title class="settings-card-title">Session Settings</Card.Title>- <Card.Description class="settings-card-description">Configure session behavior and password policies</Card.Description>+ <Card.Description class="settings-card-description"+ >Configure session behavior and password policies</Card.Description+ ></div></div></Card.Header><Card.Content><div class="space-y-4"><div class="space-y-2">- <label for="sessionTimeout" class="text-sm font-medium">Session Timeout (minutes)</label>- <Input type="number" id="sessionTimeout" name="sessionTimeout" bind:value={sessionTimeout} min="15" max="1440" />- <p class="text-muted-foreground text-xs">Time until inactive sessions are automatically logged out (15-1440 minutes)</p>+ <label for="sessionTimeout" class="text-sm font-medium">Session Timeout (minutes)</label+ >+ <Input+ type="number"+ id="sessionTimeout"+ name="sessionTimeout"+ bind:value={sessionTimeout}+ min="15"+ max="1440"+ />+ <p class="text-muted-foreground text-xs">+ Time until inactive sessions are automatically logged out (15-1440 minutes)+ </p></div><div class="space-y-2">@@ -333,21 +306,27 @@<div class="grid grid-cols-3 gap-2"><Buttonvariant={passwordPolicy === 'basic' ? 'default' : 'outline'}- class={passwordPolicy === 'basic' ? 'arcane-button-create w-full' : 'arcane-button-restart w-full'}+ class={passwordPolicy === 'basic'+ ? 'arcane-button-create w-full'+ : 'arcane-button-restart w-full'}onclick={() => {passwordPolicy = 'basic';}}>Basic</Button><Buttonvariant={passwordPolicy === 'standard' ? 'default' : 'outline'}- class={passwordPolicy === 'standard' ? 'arcane-button-create w-full' : 'arcane-button-restart w-full'}+ class={passwordPolicy === 'standard'+ ? 'arcane-button-create w-full'+ : 'arcane-button-restart w-full'}onclick={() => {passwordPolicy = 'standard';}}>Standard</Button><Buttonvariant={passwordPolicy === 'strong' ? 'default' : 'outline'}- class={passwordPolicy === 'strong' ? 'arcane-button-create w-full' : 'arcane-button-restart w-full'}+ class={passwordPolicy === 'strong'+ ? 'arcane-button-create w-full'+ : 'arcane-button-restart w-full'}onclick={() => {passwordPolicy = 'strong';}}>Strong</Buttondiff --git a/frontend/src/routes/settings/security/+page.ts b/frontend/src/routes/settings/security/+page.tsindex 0c45298b9..24d37bd0a 100644--- a/frontend/src/routes/settings/security/+page.ts+++ b/frontend/src/routes/settings/security/+page.ts@@ -10,11 +10,11 @@ export const load = async () => {dbConfigured: false,effectivelyEnabled: false,effectivelyConfigured: false- })) // Ensure fallback has all new fields+ }))]);return {settings,- oidcStatus // Pass the full oidcStatus object+ oidcStatus};};