fixup! Further pursue of perfection.

This commit is contained in:
2025-09-04 22:43:39 +01:00
parent 29ec26cbaa
commit f291dcca26
43 changed files with 3995 additions and 2916 deletions
-12
View File
@@ -51,46 +51,35 @@ func (a *Adapter) BuildAuthURL(redirectURL, state, nonce, codeChallenge string)
scopes := a.legacySettings.GetScopes()
// When overrideScopes is true, use exactly the scopes provided without modification
if a.legacySettings.IsOverrideScopes() {
// Use scopes as-is, don't let provider add anything
finalParams := params
finalParams.Set("scope", strings.Join(scopes, " "))
// For provider-specific parameters, we still need to check the provider type
switch a.provider.GetType() {
case ProviderTypeGoogle:
// Google-specific parameters
finalParams.Set("access_type", "offline")
finalParams.Set("prompt", "consent")
case ProviderTypeAzure:
// Azure-specific parameters
finalParams.Set("response_mode", "query")
}
return a.buildURLWithParams(a.legacySettings.GetAuthURL(), finalParams)
}
// When overrideScopes is false, let the provider add necessary scopes
authParams, err := a.provider.BuildAuthParams(params, scopes)
if err != nil {
// Log the error appropriately
return ""
}
finalParams := authParams.URLValues
finalParams.Set("scope", strings.Join(authParams.Scopes, " "))
// Build the full URL with params
return a.buildURLWithParams(a.legacySettings.GetAuthURL(), finalParams)
}
// buildURLWithParams takes a base URL and query parameters and constructs a full URL string.
// If the baseURL is relative (doesn't start with http/https), it prepends the scheme and host
// from the configured issuerURL.
func (a *Adapter) buildURLWithParams(baseURL string, params url.Values) string {
if !strings.HasPrefix(baseURL, "http://") && !strings.HasPrefix(baseURL, "https://") {
// Relative URL - resolve against issuer URL
issuerURLParsed, err := url.Parse(a.legacySettings.GetIssuerURL())
if err != nil {
return ""
@@ -106,7 +95,6 @@ func (a *Adapter) buildURLWithParams(baseURL string, params url.Values) string {
return resolvedURL.String()
}
// Absolute URL
u, err := url.Parse(baseURL)
if err != nil {
return ""
+1 -6
View File
@@ -28,7 +28,7 @@ func (p *AzureProvider) GetCapabilities() ProviderCapabilities {
return ProviderCapabilities{
SupportsRefreshTokens: true,
RequiresOfflineAccessScope: true,
PreferredTokenValidation: "access", // Azure AD prefers access token validation
PreferredTokenValidation: "access",
}
}
@@ -36,7 +36,6 @@ func (p *AzureProvider) GetCapabilities() ProviderCapabilities {
func (p *AzureProvider) BuildAuthParams(baseParams url.Values, scopes []string) (*AuthParams, error) {
baseParams.Set("response_mode", "query")
// Ensure "offline_access" scope is present for refresh tokens
hasOfflineAccess := false
for _, scope := range scopes {
if scope == "offline_access" {
@@ -54,7 +53,6 @@ func (p *AzureProvider) BuildAuthParams(baseParams url.Values, scopes []string)
}, nil
}
// ValidateTokens overrides the default token validation to implement Azure-specific logic.
// Azure may use access tokens for validation, and this method ensures that behavior is preserved.
func (p *AzureProvider) ValidateTokens(session Session, verifier TokenVerifier, tokenCache TokenCache, refreshGracePeriod time.Duration) (*ValidationResult, error) {
if !session.GetAuthenticated() {
@@ -102,10 +100,7 @@ func (p *AzureProvider) ValidateTokens(session Session, verifier TokenVerifier,
return &ValidationResult{IsExpired: true}, nil
}
// ValidateConfig validates Azure-specific configuration requirements.
// Azure requires specific tenant configuration and scope handling.
func (p *AzureProvider) ValidateConfig() error {
// Azure provider validation - ensure we have the necessary configuration
// In a real implementation, this might check for tenant ID, proper issuer URL format, etc.
return p.BaseProvider.ValidateConfig()
}
+13 -14
View File
@@ -6,19 +6,19 @@ import (
"time"
)
// BaseProvider provides a common foundation for OIDC provider implementations.
// BaseProvider provides common functionality for all OIDC provider implementations.
// It defines default behaviors that can be overridden by specific providers.
// It can be embedded in specific provider structs to share common logic.
type BaseProvider struct {
// Common configuration or dependencies can be added here.
}
// GetType returns the default provider type, which is Generic.
// GetType returns the default provider type (generic).
// This should be overridden by specific provider implementations.
func (p *BaseProvider) GetType() ProviderType {
return ProviderTypeGeneric
}
// GetCapabilities returns a default set of capabilities for a generic OIDC provider.
// GetCapabilities returns default provider capabilities.
// This can be overridden by specific providers to declare their unique features.
func (p *BaseProvider) GetCapabilities() ProviderCapabilities {
return ProviderCapabilities{
@@ -28,7 +28,8 @@ func (p *BaseProvider) GetCapabilities() ProviderCapabilities {
}
}
// ValidateTokens provides a default token validation implementation.
// ValidateTokens performs basic token validation logic common to all providers.
// It checks authentication state, token presence, and determines if refresh is needed.
// This method can be extended or replaced by specific providers.
func (p *BaseProvider) ValidateTokens(session Session, verifier TokenVerifier, tokenCache TokenCache, refreshGracePeriod time.Duration) (*ValidationResult, error) {
if !session.GetAuthenticated() {
@@ -70,7 +71,7 @@ func (p *BaseProvider) ValidateTokens(session Session, verifier TokenVerifier, t
return p.ValidateTokenExpiry(session, idToken, tokenCache, refreshGracePeriod)
}
// ValidateTokenExpiry provides common token expiry validation logic that can be used by all providers.
// ValidateTokenExpiry checks if a token is expired or needs refresh based on cached claims.
// This method is now exported so provider implementations can reuse this logic without duplication.
func (p *BaseProvider) ValidateTokenExpiry(session Session, token string, tokenCache TokenCache, refreshGracePeriod time.Duration) (*ValidationResult, error) {
cachedClaims, found := tokenCache.Get(token)
@@ -100,10 +101,9 @@ func (p *BaseProvider) ValidateTokenExpiry(session Session, token string, tokenC
return &ValidationResult{Authenticated: true}, nil
}
// BuildAuthParams provides a default implementation for building authorization parameters.
// It includes the "offline_access" scope by default.
// BuildAuthParams constructs authorization parameters for the provider.
// It includes the "offline_access" scope by default for refresh token support.
func (p *BaseProvider) BuildAuthParams(baseParams url.Values, scopes []string) (*AuthParams, error) {
// Ensure offline_access is included if not already present
hasOfflineAccess := false
for _, scope := range scopes {
if scope == "offline_access" {
@@ -121,21 +121,20 @@ func (p *BaseProvider) BuildAuthParams(baseParams url.Values, scopes []string) (
}, nil
}
// HandleTokenRefresh provides a default implementation for token refresh handling.
// HandleTokenRefresh processes provider-specific token refresh logic.
// By default, it does nothing and assumes the standard token response is sufficient.
func (p *BaseProvider) HandleTokenRefresh(tokenData *TokenResult) error {
// No provider-specific refresh handling by default.
return nil
}
// ValidateConfig provides a default implementation for configuration validation.
// ValidateConfig checks provider-specific configuration requirements.
// By default, it assumes the configuration is valid.
func (p *BaseProvider) ValidateConfig() error {
// No provider-specific config validation by default.
return nil
}
// NewBaseProvider creates a new BaseProvider.
// NewBaseProvider creates a new BaseProvider instance.
// This can be used when a generic OIDC provider is sufficient.
func NewBaseProvider() *BaseProvider {
return &BaseProvider{}
}
+4 -7
View File
@@ -15,7 +15,6 @@ type ProviderFactory struct {
func NewProviderFactory() *ProviderFactory {
registry := NewProviderRegistry()
// Register all available providers
registry.RegisterProvider(NewGenericProvider())
registry.RegisterProvider(NewGoogleProvider())
registry.RegisterProvider(NewAzureProvider())
@@ -25,14 +24,13 @@ func NewProviderFactory() *ProviderFactory {
}
}
// CreateProvider creates and returns the appropriate provider for the given issuer URL.
// CreateProvider creates an OIDC provider based on the issuer URL.
// It automatically detects the provider type and returns a configured instance.
func (f *ProviderFactory) CreateProvider(issuerURL string) (OIDCProvider, error) {
if issuerURL == "" {
return nil, fmt.Errorf("issuer URL cannot be empty")
}
// Validate URL format
if _, err := url.Parse(issuerURL); err != nil {
return nil, fmt.Errorf("invalid issuer URL format: %w", err)
}
@@ -42,7 +40,6 @@ func (f *ProviderFactory) CreateProvider(issuerURL string) (OIDCProvider, error)
return nil, fmt.Errorf("unable to detect provider for issuer URL: %s", issuerURL)
}
// Validate the provider configuration if it implements config validation
if err := provider.ValidateConfig(); err != nil {
return nil, fmt.Errorf("provider configuration validation failed: %w", err)
}
@@ -50,7 +47,7 @@ func (f *ProviderFactory) CreateProvider(issuerURL string) (OIDCProvider, error)
return provider, nil
}
// CreateProviderByType creates a provider instance for a specific provider type.
// CreateProviderByType creates a provider instance of the specified type.
// This is useful when you want to force a specific provider type regardless of URL.
func (f *ProviderFactory) CreateProviderByType(providerType ProviderType) (OIDCProvider, error) {
var provider OIDCProvider
@@ -76,13 +73,13 @@ func (f *ProviderFactory) CreateProviderByType(providerType ProviderType) (OIDCP
// GetSupportedProviders returns a list of all supported provider types and their detection patterns.
func (f *ProviderFactory) GetSupportedProviders() map[ProviderType][]string {
return map[ProviderType][]string{
ProviderTypeGeneric: {"*"}, // Generic supports any issuer
ProviderTypeGeneric: {"*"},
ProviderTypeGoogle: {"accounts.google.com"},
ProviderTypeAzure: {"login.microsoftonline.com", "sts.windows.net"},
}
}
// DetectProviderType returns the provider type that would be used for a given issuer URL.
// DetectProviderType determines the provider type for a given issuer URL.
// This is useful for diagnostic purposes or UI display.
func (f *ProviderFactory) DetectProviderType(issuerURL string) (ProviderType, error) {
provider, err := f.CreateProvider(issuerURL)
+1 -4
View File
@@ -25,7 +25,7 @@ func (p *GoogleProvider) GetType() ProviderType {
func (p *GoogleProvider) GetCapabilities() ProviderCapabilities {
return ProviderCapabilities{
SupportsRefreshTokens: true,
RequiresOfflineAccessScope: false, // Google uses access_type=offline instead
RequiresOfflineAccessScope: false,
RequiresPromptConsent: true,
PreferredTokenValidation: "id",
}
@@ -50,10 +50,7 @@ func (p *GoogleProvider) BuildAuthParams(baseParams url.Values, scopes []string)
}, nil
}
// ValidateConfig validates Google-specific configuration requirements.
// Google requires specific scopes and client configuration for proper operation.
func (p *GoogleProvider) ValidateConfig() error {
// Google provider doesn't require additional validation beyond the base implementation
// All Google-specific requirements are handled in BuildAuthParams
return p.BaseProvider.ValidateConfig()
}
+8 -34
View File
@@ -22,80 +22,54 @@ type TokenCache interface {
type ProviderType int
const (
// ProviderTypeGeneric represents a standard, compliant OIDC provider.
ProviderTypeGeneric ProviderType = iota
// ProviderTypeGoogle represents Google as the OIDC provider.
ProviderTypeGoogle
// ProviderTypeAzure represents Microsoft Azure AD as the OIDC provider.
ProviderTypeAzure
)
// ProviderCapabilities defines the specific features and behaviors of an OIDC provider.
type ProviderCapabilities struct {
// SupportsRefreshTokens indicates if the provider issues refresh tokens.
SupportsRefreshTokens bool
// RequiresOfflineAccessScope indicates if the "offline_access" scope is needed for refresh tokens.
PreferredTokenValidation string
SupportsRefreshTokens bool
RequiresOfflineAccessScope bool
// RequiresPromptConsent indicates if "prompt=consent" is needed to ensure a refresh token is issued.
RequiresPromptConsent bool
// PreferredTokenValidation specifies the recommended token type to validate (e.g., "access" or "id").
PreferredTokenValidation string
RequiresPromptConsent bool
}
// ValidationResult holds the outcome of a token validation check.
type ValidationResult struct {
// Authenticated is true if the token is valid and the user is authenticated.
Authenticated bool
// NeedsRefresh is true if the token is approaching its expiry and should be refreshed.
NeedsRefresh bool
// IsExpired is true if the token has expired or is invalid.
IsExpired bool
NeedsRefresh bool
IsExpired bool
}
// AuthParams contains the provider-specific parameters for building the authorization URL.
type AuthParams struct {
// URLValues are the query parameters to be added to the authorization URL.
URLValues url.Values
// Scopes is the list of scopes to be requested.
Scopes []string
Scopes []string
}
// TokenResult holds the tokens returned by the provider.
type TokenResult struct {
// IDToken is the OIDC ID token.
IDToken string
// AccessToken is the OAuth2 access token.
AccessToken string
// RefreshToken is the OAuth2 refresh token.
IDToken string
AccessToken string
RefreshToken string
}
// OIDCProvider defines the interface for an OIDC provider implementation.
// This abstraction allows for provider-specific logic to be encapsulated.
type OIDCProvider interface {
// GetType returns the type of the provider (e.g., Google, Azure, Generic).
GetType() ProviderType
// GetCapabilities returns the feature set of the provider.
GetCapabilities() ProviderCapabilities
// ValidateTokens performs token validation according to the provider's specific rules.
// It should check the validity of the access and/or ID tokens from the session.
ValidateTokens(session Session, verifier TokenVerifier, tokenCache TokenCache, refreshGracePeriod time.Duration) (*ValidationResult, error)
// BuildAuthParams modifies the authorization URL parameters for the provider.
// This can be used to add provider-specific parameters like "access_type" for Google.
BuildAuthParams(baseParams url.Values, scopes []string) (*AuthParams, error)
// HandleTokenRefresh manages the token refresh process for the provider.
// It can modify the token request or handle the response as needed.
HandleTokenRefresh(tokenData *TokenResult) error
// ValidateConfig checks if the user's configuration is valid for this provider.
ValidateConfig() error
}
// Session represents the session data required by providers for validation.
// This interface decouples the providers from the main session management implementation.
type Session interface {
GetIDToken() string
+6 -17
View File
@@ -6,13 +6,13 @@ import (
"sync"
)
// ProviderRegistry holds and manages the available OIDC provider implementations.
// ProviderRegistry manages a collection of OIDC provider implementations.
// It provides thread-safe access to provider instances and caches detection results.
type ProviderRegistry struct {
mu sync.RWMutex
providers []OIDCProvider
cache map[string]OIDCProvider
typeMap map[ProviderType]OIDCProvider // Maps provider type to instance
typeMap map[ProviderType]OIDCProvider
providers []OIDCProvider
mu sync.RWMutex
}
// NewProviderRegistry creates and initializes a new ProviderRegistry.
@@ -33,7 +33,7 @@ func (r *ProviderRegistry) RegisterProvider(provider OIDCProvider) {
r.typeMap[provider.GetType()] = provider
}
// GetProviderByType returns a provider instance for the specified type.
// GetProviderByType retrieves a provider instance by its type.
// Returns nil if the provider type is not registered.
func (r *ProviderRegistry) GetProviderByType(providerType ProviderType) OIDCProvider {
r.mu.RLock()
@@ -61,12 +61,9 @@ func (r *ProviderRegistry) ClearCache() {
r.cache = make(map[string]OIDCProvider)
}
// DetectProvider determines the most appropriate provider for a given issuer URL.
// It iterates through the registered providers and returns the first one that matches.
// Detection is based on URL patterns and other provider-specific criteria.
// DetectProvider identifies the appropriate OIDC provider for an issuer URL.
// Uses double-checked locking pattern to avoid race conditions while caching results.
func (r *ProviderRegistry) DetectProvider(issuerURL string) OIDCProvider {
// First check: read lock for cache lookup
r.mu.RLock()
if provider, found := r.cache[issuerURL]; found {
r.mu.RUnlock()
@@ -74,19 +71,15 @@ func (r *ProviderRegistry) DetectProvider(issuerURL string) OIDCProvider {
}
r.mu.RUnlock()
// Cache miss - acquire write lock for detection and caching
r.mu.Lock()
defer r.mu.Unlock()
// Second check: another goroutine might have cached the result while we waited for write lock
if provider, found := r.cache[issuerURL]; found {
return provider
}
// Perform detection under write lock
detectedProvider := r.detectProviderUnsafe(issuerURL)
// Cache the result (even if nil to avoid repeated expensive operations)
r.cache[issuerURL] = detectedProvider
return detectedProvider
@@ -95,15 +88,12 @@ func (r *ProviderRegistry) DetectProvider(issuerURL string) OIDCProvider {
// detectProviderUnsafe performs the actual provider detection logic.
// This method assumes the caller holds the appropriate lock and should not be called directly.
func (r *ProviderRegistry) detectProviderUnsafe(issuerURL string) OIDCProvider {
// Normalize issuer URL for consistent matching
normalizedURL, err := url.Parse(issuerURL)
if err != nil {
// Log error or handle it appropriately
return nil
}
host := normalizedURL.Host
// Iterate through registered providers to find a match
for _, p := range r.providers {
switch p.GetType() {
case ProviderTypeGoogle:
@@ -117,7 +107,6 @@ func (r *ProviderRegistry) detectProviderUnsafe(issuerURL string) OIDCProvider {
}
}
// Fallback to the generic provider if no specific provider is detected
for _, p := range r.providers {
if p.GetType() == ProviderTypeGeneric {
return p
-6
View File
@@ -59,7 +59,6 @@ func (v *ConfigValidator) ValidateScopes(scopes []string) error {
return fmt.Errorf("at least one scope must be provided")
}
// Check for required OIDC scope
hasOpenIDScope := false
for _, scope := range scopes {
if strings.TrimSpace(scope) == "openid" {
@@ -109,7 +108,6 @@ func (v *ConfigValidator) ValidateProviderSpecificConfig(provider OIDCProvider,
// validateGoogleConfig validates Google-specific configuration.
func (v *ConfigValidator) validateGoogleConfig(config map[string]interface{}) error {
// Google-specific validation logic
if issuerURL, ok := config["issuer_url"].(string); ok {
if !strings.Contains(issuerURL, "accounts.google.com") {
return fmt.Errorf("google provider requires issuer URL to contain accounts.google.com")
@@ -121,21 +119,18 @@ func (v *ConfigValidator) validateGoogleConfig(config map[string]interface{}) er
// validateAzureConfig validates Azure-specific configuration.
func (v *ConfigValidator) validateAzureConfig(config map[string]interface{}) error {
// Azure-specific validation logic
if issuerURL, ok := config["issuer_url"].(string); ok {
if !strings.Contains(issuerURL, "login.microsoftonline.com") && !strings.Contains(issuerURL, "sts.windows.net") {
return fmt.Errorf("azure provider requires issuer URL to contain login.microsoftonline.com or sts.windows.net")
}
}
// Check for tenant ID in the URL
if issuerURL, ok := config["issuer_url"].(string); ok {
parsedURL, err := url.Parse(issuerURL)
if err == nil {
pathParts := strings.Split(parsedURL.Path, "/")
hasTenantID := false
for _, part := range pathParts {
// Simple check for GUID-like structure (tenant ID)
if len(part) == 36 && strings.Count(part, "-") == 4 {
hasTenantID = true
break
@@ -152,6 +147,5 @@ func (v *ConfigValidator) validateAzureConfig(config map[string]interface{}) err
// validateGenericConfig validates generic OIDC provider configuration.
func (v *ConfigValidator) validateGenericConfig(config map[string]interface{}) error {
// Generic provider validation - basic checks only
return nil
}