Add redis support for distributed caching (#83)

* Add redis support for distributed caching

* Move towards the self-provided Redis connection pool and RESP protocol implementation.
Official redis client library won't work with yaegi.

* fixup! Move towards the self-provided Redis connection pool and RESP protocol implementation. Official redis client library won't work with yaegi.

* fixup! fixup! Move towards the self-provided Redis connection pool and RESP protocol implementation. Official redis client library won't work with yaegi.

* fixup! fixup! fixup! Move towards the self-provided Redis connection pool and RESP protocol implementation. Official redis client library won't work with yaegi.

* fixup! fixup! fixup! fixup! Move towards the self-provided Redis connection pool and RESP protocol implementation. Official redis client library won't work with yaegi.

* fixup! fixup! fixup! fixup! fixup! Move towards the self-provided Redis connection pool and RESP protocol implementation. Official redis client library won't work with yaegi.

* ... and another all nighter.

* fixup! ... and another all nighter.

* fixup! fixup! ... and another all nighter.

* fixup! fixup! fixup! ... and another all nighter.

* Resolve issue #85 by adding ability to set custom claims in JWT tokens

* Remove redundant validation in auth middleware ( issue #89 )

* Add ability to set cookie prefix for session cookies ( #87 )

* fixup! Add ability to set cookie prefix for session cookies ( #87 )

* Add ability to set cookie max age - issue #91

* Potential fix for code scanning alert no. 10: Size computation for allocation may overflow

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>

* fixup! Merge main into 0.8.0-redis: resolve conflicts

---------

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
This commit is contained in:
2025-11-30 02:18:46 +00:00
committed by GitHub
co-authored by Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
parent 5fcbd54955
commit e64fc7f730
318 changed files with 100989 additions and 948 deletions
+258
View File
@@ -0,0 +1,258 @@
// Package config provides backward compatibility for legacy configuration
package config
import (
"fmt"
"time"
"github.com/lukaszraczylo/traefikoidc/internal/compat"
"github.com/lukaszraczylo/traefikoidc/internal/features"
)
// LegacyAdapter provides backward compatibility for old Config struct
type LegacyAdapter struct {
unified *UnifiedConfig
adapter *compat.ConfigAdapter
}
// NewLegacyAdapter creates a new legacy adapter from unified config
func NewLegacyAdapter(unified *UnifiedConfig) *LegacyAdapter {
adapter := compat.NewConfigAdapter(unified)
// Register getters for commonly used fields
adapter.RegisterGetter("ProviderURL", func() interface{} {
return unified.Provider.IssuerURL
})
adapter.RegisterGetter("ClientID", func() interface{} {
return unified.Provider.ClientID
})
adapter.RegisterGetter("ClientSecret", func() interface{} {
return unified.Provider.ClientSecret
})
adapter.RegisterGetter("CallbackURL", func() interface{} {
return unified.Provider.RedirectURL
})
adapter.RegisterGetter("LogoutURL", func() interface{} {
return unified.Provider.LogoutURL
})
adapter.RegisterGetter("PostLogoutRedirectURI", func() interface{} {
return unified.Provider.PostLogoutRedirectURI
})
adapter.RegisterGetter("SessionEncryptionKey", func() interface{} {
return unified.Session.EncryptionKey
})
adapter.RegisterGetter("ForceHTTPS", func() interface{} {
return unified.Security.ForceHTTPS
})
adapter.RegisterGetter("LogLevel", func() interface{} {
return unified.Logging.Level
})
adapter.RegisterGetter("Scopes", func() interface{} {
return unified.Provider.Scopes
})
adapter.RegisterGetter("OverrideScopes", func() interface{} {
return unified.Provider.OverrideScopes
})
adapter.RegisterGetter("AllowedUsers", func() interface{} {
return unified.Security.AllowedUsers
})
adapter.RegisterGetter("AllowedUserDomains", func() interface{} {
return unified.Security.AllowedUserDomains
})
adapter.RegisterGetter("AllowedRolesAndGroups", func() interface{} {
return unified.Security.AllowedRolesAndGroups
})
adapter.RegisterGetter("ExcludedURLs", func() interface{} {
return unified.Security.ExcludedURLs
})
adapter.RegisterGetter("EnablePKCE", func() interface{} {
return unified.Security.EnablePKCE
})
adapter.RegisterGetter("RateLimit", func() interface{} {
return unified.RateLimit.RequestsPerSecond
})
adapter.RegisterGetter("RefreshGracePeriodSeconds", func() interface{} {
return int(unified.Token.RefreshGracePeriod.Seconds())
})
adapter.RegisterGetter("CookieDomain", func() interface{} {
return unified.Session.Domain
})
adapter.RegisterGetter("SecurityHeaders", func() interface{} {
return unified.Security.Headers
})
return &LegacyAdapter{
unified: unified,
adapter: adapter,
}
}
// ToOldConfig converts unified config to old Config struct format
func (la *LegacyAdapter) ToOldConfig() *Config {
// Use feature flags to determine behavior
if !features.IsUnifiedConfigEnabled() {
// Return existing Config if unified config not enabled
return CreateConfig()
}
cfg := &Config{
ProviderURL: la.unified.Provider.IssuerURL,
ClientID: la.unified.Provider.ClientID,
ClientSecret: la.unified.Provider.ClientSecret,
CallbackURL: la.unified.Provider.RedirectURL,
LogoutURL: la.unified.Provider.LogoutURL,
PostLogoutRedirectURI: la.unified.Provider.PostLogoutRedirectURI,
SessionEncryptionKey: la.unified.Session.EncryptionKey,
ForceHTTPS: la.unified.Security.ForceHTTPS,
LogLevel: la.unified.Logging.Level,
Scopes: la.unified.Provider.Scopes,
OverrideScopes: la.unified.Provider.OverrideScopes,
AllowedUsers: la.unified.Security.AllowedUsers,
AllowedUserDomains: la.unified.Security.AllowedUserDomains,
AllowedRolesAndGroups: la.unified.Security.AllowedRolesAndGroups,
ExcludedURLs: la.unified.Security.ExcludedURLs,
EnablePKCE: la.unified.Security.EnablePKCE,
RateLimit: la.unified.RateLimit.RequestsPerSecond,
RefreshGracePeriodSeconds: int(la.unified.Token.RefreshGracePeriod.Seconds()),
Headers: la.convertHeaders(),
CookieDomain: la.unified.Session.Domain,
SecurityHeaders: la.unified.Security.Headers,
}
return cfg
}
// convertHeaders converts unified header config to old format
func (la *LegacyAdapter) convertHeaders() []HeaderConfig {
headers := make([]HeaderConfig, 0)
for name, value := range la.unified.Middleware.CustomHeaders {
headers = append(headers, HeaderConfig{
Name: name,
Value: value,
})
}
return headers
}
// FromOldConfig creates unified config from old Config struct
func FromOldConfig(old *Config) *UnifiedConfig {
unified := NewUnifiedConfig()
// Map provider settings
unified.Provider.IssuerURL = old.ProviderURL
unified.Provider.ClientID = old.ClientID
unified.Provider.ClientSecret = old.ClientSecret
unified.Provider.RedirectURL = old.CallbackURL
unified.Provider.LogoutURL = old.LogoutURL
unified.Provider.PostLogoutRedirectURI = old.PostLogoutRedirectURI
unified.Provider.Scopes = old.Scopes
unified.Provider.OverrideScopes = old.OverrideScopes
// Map session settings
unified.Session.EncryptionKey = old.SessionEncryptionKey
unified.Session.Domain = old.CookieDomain
// Map security settings
unified.Security.ForceHTTPS = old.ForceHTTPS
unified.Security.EnablePKCE = old.EnablePKCE
unified.Security.AllowedUsers = old.AllowedUsers
unified.Security.AllowedUserDomains = old.AllowedUserDomains
unified.Security.AllowedRolesAndGroups = old.AllowedRolesAndGroups
unified.Security.ExcludedURLs = old.ExcludedURLs
unified.Security.Headers = old.SecurityHeaders
// Map rate limiting
unified.RateLimit.RequestsPerSecond = old.RateLimit
unified.RateLimit.Enabled = old.RateLimit > 0
// Map token settings
unified.Token.RefreshGracePeriod = timeSecondsToDuration(old.RefreshGracePeriodSeconds)
// Map logging
unified.Logging.Level = old.LogLevel
// Map custom headers
if len(old.Headers) > 0 {
unified.Middleware.CustomHeaders = make(map[string]string)
for _, header := range old.Headers {
unified.Middleware.CustomHeaders[header.Name] = header.Value
}
}
// Store original config in legacy field for reference
unified.Legacy["original"] = old
return unified
}
// timeSecondsToDuration converts seconds to time.Duration
func timeSecondsToDuration(seconds int) time.Duration {
return time.Duration(seconds) * time.Second
}
// GetConfigInterface returns appropriate config based on feature flag
func GetConfigInterface() interface{} {
if features.IsUnifiedConfigEnabled() {
return NewUnifiedConfig()
}
return CreateConfig()
}
// ValidateConfig validates config based on feature flag
func ValidateConfig(cfg interface{}) error {
if features.IsUnifiedConfigEnabled() {
if unified, ok := cfg.(*UnifiedConfig); ok {
return unified.Validate()
}
}
// Fall back to old validation if available
if old, ok := cfg.(*Config); ok {
return old.Validate()
}
return nil
}
// Add Validate method to old Config for compatibility
func (c *Config) Validate() error {
var errors ValidationErrors
// Basic validation for old config
if c.ProviderURL == "" {
errors = append(errors, ValidationError{
Field: "ProviderURL",
Message: "provider URL is required",
})
}
if c.ClientID == "" {
errors = append(errors, ValidationError{
Field: "ClientID",
Message: "client ID is required",
})
}
if c.ClientSecret == "" && !c.EnablePKCE {
errors = append(errors, ValidationError{
Field: "ClientSecret",
Message: "client secret is required (or enable PKCE)",
})
}
if c.SessionEncryptionKey != "" && len(c.SessionEncryptionKey) < minEncryptionKeyLength {
errors = append(errors, ValidationError{
Field: "SessionEncryptionKey",
Message: fmt.Sprintf("encryption key must be at least %d characters", minEncryptionKeyLength),
Value: len(c.SessionEncryptionKey),
})
}
if len(errors) > 0 {
return errors
}
return nil
}
+363
View File
@@ -0,0 +1,363 @@
//go:build !yaegi
package config
import (
"testing"
"github.com/lukaszraczylo/traefikoidc/internal/features"
)
// NewLegacyAdapter Tests
func TestNewLegacyAdapter(t *testing.T) {
unified := NewUnifiedConfig()
unified.Provider.IssuerURL = "https://provider.example.com"
unified.Provider.ClientID = "test-client"
unified.Provider.ClientSecret = "test-secret"
adapter := NewLegacyAdapter(unified)
if adapter == nil {
t.Fatal("Expected NewLegacyAdapter to return non-nil")
}
if adapter.unified != unified {
t.Error("Expected adapter to reference the unified config")
}
if adapter.adapter == nil {
t.Error("Expected internal adapter to be initialized")
}
}
// ToOldConfig Tests
func TestLegacyAdapter_ToOldConfig(t *testing.T) {
unified := NewUnifiedConfig()
unified.Provider.IssuerURL = "https://issuer.example.com"
unified.Provider.ClientID = "client-123"
unified.Provider.ClientSecret = "secret-456"
unified.Provider.RedirectURL = "https://app.example.com/callback"
unified.Provider.LogoutURL = "/logout"
unified.Provider.PostLogoutRedirectURI = "https://app.example.com"
unified.Provider.Scopes = []string{"openid", "profile"}
unified.Provider.OverrideScopes = true
unified.Session.EncryptionKey = "test-encryption-key-32-chars!!"
unified.Session.Domain = "example.com"
unified.Security.ForceHTTPS = true
unified.Security.EnablePKCE = true
unified.Security.AllowedUsers = []string{"[email protected]"}
unified.Security.AllowedUserDomains = []string{"example.com"}
unified.Security.AllowedRolesAndGroups = []string{"admin"}
unified.Security.ExcludedURLs = []string{"/health"}
unified.RateLimit.RequestsPerSecond = 100
unified.Logging.Level = "debug"
unified.Middleware.CustomHeaders = map[string]string{
"X-Header-1": "value1",
"X-Header-2": "value2",
}
adapter := NewLegacyAdapter(unified)
oldConfig := adapter.ToOldConfig()
if oldConfig == nil {
t.Fatal("Expected ToOldConfig to return non-nil")
}
// ToOldConfig behavior depends on feature flag
if !features.IsUnifiedConfigEnabled() {
// When feature is disabled, returns default config
if oldConfig.ProviderURL == "" {
t.Log("Feature flag disabled - ToOldConfig returns default config")
}
return
}
// When feature is enabled, verify all fields were correctly mapped
if oldConfig.ProviderURL != unified.Provider.IssuerURL {
t.Errorf("Expected ProviderURL '%s', got '%s'", unified.Provider.IssuerURL, oldConfig.ProviderURL)
}
if oldConfig.ClientID != unified.Provider.ClientID {
t.Errorf("Expected ClientID '%s', got '%s'", unified.Provider.ClientID, oldConfig.ClientID)
}
if oldConfig.ClientSecret != unified.Provider.ClientSecret {
t.Errorf("Expected ClientSecret '%s', got '%s'", unified.Provider.ClientSecret, oldConfig.ClientSecret)
}
if oldConfig.CallbackURL != unified.Provider.RedirectURL {
t.Error("Expected CallbackURL to match RedirectURL")
}
if oldConfig.LogoutURL != unified.Provider.LogoutURL {
t.Error("Expected LogoutURL to match")
}
if oldConfig.ForceHTTPS != unified.Security.ForceHTTPS {
t.Error("Expected ForceHTTPS to match")
}
if oldConfig.EnablePKCE != unified.Security.EnablePKCE {
t.Error("Expected EnablePKCE to match")
}
if oldConfig.RateLimit != unified.RateLimit.RequestsPerSecond {
t.Errorf("Expected RateLimit %d, got %d", unified.RateLimit.RequestsPerSecond, oldConfig.RateLimit)
}
if len(oldConfig.Headers) != 2 {
t.Errorf("Expected 2 headers, got %d", len(oldConfig.Headers))
}
}
// convertHeaders Tests
func TestLegacyAdapter_convertHeaders(t *testing.T) {
unified := NewUnifiedConfig()
unified.Middleware.CustomHeaders = map[string]string{
"X-Custom-Header-1": "value1",
"X-Custom-Header-2": "value2",
"X-Custom-Header-3": "value3",
}
adapter := NewLegacyAdapter(unified)
headers := adapter.convertHeaders()
if len(headers) != 3 {
t.Errorf("Expected 3 headers, got %d", len(headers))
}
// Check that headers were converted
headerMap := make(map[string]string)
for _, h := range headers {
headerMap[h.Name] = h.Value
}
if headerMap["X-Custom-Header-1"] != "value1" {
t.Error("Expected X-Custom-Header-1 to have value 'value1'")
}
if headerMap["X-Custom-Header-2"] != "value2" {
t.Error("Expected X-Custom-Header-2 to have value 'value2'")
}
}
func TestLegacyAdapter_convertHeaders_Empty(t *testing.T) {
unified := NewUnifiedConfig()
// No custom headers
adapter := NewLegacyAdapter(unified)
headers := adapter.convertHeaders()
if len(headers) != 0 {
t.Errorf("Expected 0 headers, got %d", len(headers))
}
}
// GetConfigInterface Tests
func TestGetConfigInterface(t *testing.T) {
cfg := GetConfigInterface()
if cfg == nil {
t.Fatal("Expected GetConfigInterface to return non-nil")
}
// Should return either UnifiedConfig or Config depending on feature flag
_, isUnified := cfg.(*UnifiedConfig)
_, isOld := cfg.(*Config)
if !isUnified && !isOld {
t.Error("Expected either *UnifiedConfig or *Config")
}
// Verify consistency with feature flag
if features.IsUnifiedConfigEnabled() {
if !isUnified {
t.Error("Expected *UnifiedConfig when unified config is enabled")
}
} else {
if !isOld {
t.Error("Expected *Config when unified config is disabled")
}
}
}
// ValidateConfig Tests
func TestValidateConfig_UnifiedConfig(t *testing.T) {
unified := NewUnifiedConfig()
unified.Provider.IssuerURL = "https://provider.example.com"
unified.Provider.ClientID = "client-id"
unified.Provider.ClientSecret = "client-secret"
unified.Session.EncryptionKey = "encryption-key-32-characters!!"
err := ValidateConfig(unified)
// Should succeed regardless of feature flag since we're passing the right type
if err != nil {
t.Errorf("Expected valid unified config to pass validation, got: %v", err)
}
}
func TestValidateConfig_OldConfig(t *testing.T) {
old := CreateConfig()
old.ProviderURL = "https://provider.example.com"
old.ClientID = "client-id"
old.ClientSecret = "client-secret"
old.SessionEncryptionKey = "encryption-key-32-characters!!"
err := ValidateConfig(old)
if err != nil {
t.Errorf("Expected valid old config to pass validation, got: %v", err)
}
}
func TestValidateConfig_InvalidType(t *testing.T) {
// Pass something that's not a config
err := ValidateConfig("not a config")
if err != nil {
t.Errorf("Expected nil for unknown type, got: %v", err)
}
}
// Config.Validate Tests
func TestConfig_Validate_Valid(t *testing.T) {
cfg := CreateConfig()
cfg.ProviderURL = "https://provider.example.com"
cfg.ClientID = "client-id"
cfg.ClientSecret = "client-secret"
cfg.SessionEncryptionKey = "encryption-key-32-characters!!"
err := cfg.Validate()
if err != nil {
t.Errorf("Expected valid config to pass, got: %v", err)
}
}
func TestConfig_Validate_MissingProviderURL(t *testing.T) {
cfg := CreateConfig()
cfg.ClientID = "client-id"
cfg.ClientSecret = "client-secret"
err := cfg.Validate()
if err == nil {
t.Error("Expected error for missing ProviderURL")
}
// Check if it's a ValidationErrors type
if verrs, ok := err.(ValidationErrors); ok {
found := false
for _, verr := range verrs {
if verr.Field == "ProviderURL" {
found = true
break
}
}
if !found {
t.Error("Expected ProviderURL validation error")
}
}
}
func TestConfig_Validate_MissingClientID(t *testing.T) {
cfg := CreateConfig()
cfg.ProviderURL = "https://provider.example.com"
cfg.ClientSecret = "client-secret"
err := cfg.Validate()
if err == nil {
t.Error("Expected error for missing ClientID")
}
if verrs, ok := err.(ValidationErrors); ok {
found := false
for _, verr := range verrs {
if verr.Field == "ClientID" {
found = true
break
}
}
if !found {
t.Error("Expected ClientID validation error")
}
}
}
func TestConfig_Validate_MissingClientSecret_NoPKCE(t *testing.T) {
cfg := CreateConfig()
cfg.ProviderURL = "https://provider.example.com"
cfg.ClientID = "client-id"
cfg.EnablePKCE = false
err := cfg.Validate()
if err == nil {
t.Error("Expected error for missing ClientSecret without PKCE")
}
if verrs, ok := err.(ValidationErrors); ok {
found := false
for _, verr := range verrs {
if verr.Field == "ClientSecret" {
found = true
break
}
}
if !found {
t.Error("Expected ClientSecret validation error")
}
}
}
func TestConfig_Validate_MissingClientSecret_WithPKCE(t *testing.T) {
cfg := CreateConfig()
cfg.ProviderURL = "https://provider.example.com"
cfg.ClientID = "client-id"
cfg.EnablePKCE = true // PKCE enabled, so ClientSecret not required
err := cfg.Validate()
if err != nil {
t.Errorf("Expected no error with PKCE enabled and no ClientSecret, got: %v", err)
}
}
func TestConfig_Validate_ShortEncryptionKey(t *testing.T) {
cfg := CreateConfig()
cfg.ProviderURL = "https://provider.example.com"
cfg.ClientID = "client-id"
cfg.ClientSecret = "client-secret"
cfg.SessionEncryptionKey = "short" // Too short
err := cfg.Validate()
if err == nil {
t.Error("Expected error for short encryption key")
}
if verrs, ok := err.(ValidationErrors); ok {
found := false
for _, verr := range verrs {
if verr.Field == "SessionEncryptionKey" {
found = true
break
}
}
if !found {
t.Error("Expected SessionEncryptionKey validation error")
}
}
}
func TestConfig_Validate_MultipleErrors(t *testing.T) {
cfg := CreateConfig()
// Missing ProviderURL, ClientID, and ClientSecret
err := cfg.Validate()
if err == nil {
t.Fatal("Expected validation errors")
}
verrs, ok := err.(ValidationErrors)
if !ok {
t.Fatal("Expected ValidationErrors type")
}
if len(verrs) < 2 {
t.Errorf("Expected at least 2 validation errors, got %d", len(verrs))
}
}
+276
View File
@@ -0,0 +1,276 @@
// Package config provides default values and initialization for unified configuration
package config
import (
"time"
)
// NewUnifiedConfig creates a new unified configuration with sensible defaults
func NewUnifiedConfig() *UnifiedConfig {
return &UnifiedConfig{
Provider: DefaultProviderConfig(),
Session: DefaultSessionConfig(),
Token: DefaultTokenConfig(),
Redis: *DefaultRedisConfig(), // Using existing DefaultRedisConfig
Security: DefaultSecurityConfig(),
Middleware: DefaultMiddlewareConfig(),
Cache: DefaultCacheConfig(),
RateLimit: DefaultRateLimitConfig(),
Logging: DefaultLoggingConfig(),
Metrics: DefaultMetricsConfig(),
Health: DefaultHealthConfig(),
Transport: DefaultTransportConfig(),
Pool: DefaultPoolConfig(),
Circuit: DefaultCircuitConfig(),
Legacy: make(map[string]interface{}),
}
}
// DefaultProviderConfig returns default provider configuration
func DefaultProviderConfig() ProviderConfig {
return ProviderConfig{
Scopes: []string{"openid", "profile", "email"},
OverrideScopes: false,
CustomClaims: make(map[string]string),
JWKCachePeriod: 24 * time.Hour,
MetadataCacheTTL: 24 * time.Hour,
Discovery: true,
}
}
// DefaultSessionConfig returns default session configuration
func DefaultSessionConfig() SessionConfig {
return SessionConfig{
Name: "oidc_session",
MaxAge: 86400, // 24 hours
ChunkSize: 4000, // Safe size for cookies
MaxChunks: 5,
Path: "/",
Secure: true,
HttpOnly: true,
SameSite: "Lax",
StorageType: "cookie",
CleanupInterval: 1 * time.Hour,
}
}
// DefaultTokenConfig returns default token configuration
func DefaultTokenConfig() TokenConfig {
return TokenConfig{
AccessTokenTTL: 1 * time.Hour,
RefreshTokenTTL: 24 * time.Hour,
RefreshGracePeriod: 60 * time.Second,
ValidationMode: "jwt",
CacheEnabled: true,
CacheTTL: 5 * time.Minute,
CacheNegativeTTL: 30 * time.Second,
ValidateSignature: true,
ValidateExpiry: true,
ValidateAudience: true,
ValidateIssuer: true,
RequiredClaims: []string{"sub", "iat", "exp"},
ClockSkew: 5 * time.Minute,
}
}
// DefaultSecurityConfig returns default security configuration
func DefaultSecurityConfig() SecurityConfig {
return SecurityConfig{
ForceHTTPS: true,
EnablePKCE: true,
AllowedUsers: []string{},
AllowedUserDomains: []string{},
AllowedRolesAndGroups: []string{},
ExcludedURLs: []string{
"/favicon.ico",
"/robots.txt",
"/health",
"/.well-known/",
"/metrics",
"/ping",
"/static/",
"/assets/",
"/js/",
"/css/",
"/images/",
"/fonts/",
},
Headers: createDefaultSecurityConfig(),
CSRFProtection: true,
CSRFTokenName: "csrf_token",
CSRFTokenTTL: 1 * time.Hour,
MaxLoginAttempts: 5,
LockoutDuration: 15 * time.Minute,
RequireMFA: false,
}
}
// DefaultMiddlewareConfig returns default middleware configuration
func DefaultMiddlewareConfig() MiddlewareConfig {
return MiddlewareConfig{
Priority: 1000,
SkipPaths: []string{},
RequirePaths: []string{},
PassthroughMode: false,
MaxRequestSize: 10 * 1024 * 1024, // 10MB
RequestTimeout: 30 * time.Second,
IdleTimeout: 90 * time.Second,
CustomHeaders: make(map[string]string),
RemoveHeaders: []string{},
}
}
// DefaultCacheConfig returns default cache configuration
func DefaultCacheConfig() CacheConfig {
return CacheConfig{
Enabled: true,
Type: "memory",
DefaultTTL: 5 * time.Minute,
MaxEntries: 10000,
MaxEntrySize: 1024 * 1024, // 1MB
EvictionPolicy: "lru",
CleanupInterval: 10 * time.Minute,
Namespace: "traefikoidc",
Compression: false,
Serialization: "json",
}
}
// DefaultRateLimitConfig returns default rate limiting configuration
func DefaultRateLimitConfig() RateLimitConfig {
return RateLimitConfig{
Enabled: false,
RequestsPerSecond: 10,
Burst: 20,
StorageType: "memory",
WindowDuration: 1 * time.Minute,
KeyType: "ip",
CustomKeyFunc: "",
WhitelistIPs: []string{},
WhitelistUsers: []string{},
}
}
// DefaultLoggingConfig returns default logging configuration
func DefaultLoggingConfig() LoggingConfig {
return LoggingConfig{
Level: "info",
Format: "json",
Output: "stdout",
FilePath: "",
FilterSensitive: true,
MaskFields: []string{
"password",
"secret",
"token",
"key",
"authorization",
"cookie",
},
BufferSize: 8192,
FlushInterval: 5 * time.Second,
AuditEnabled: false,
AuditEvents: []string{
"login",
"logout",
"token_refresh",
"auth_failure",
},
}
}
// DefaultMetricsConfig returns default metrics configuration
func DefaultMetricsConfig() MetricsConfig {
return MetricsConfig{
Enabled: false,
Provider: "prometheus",
Endpoint: "/metrics",
Namespace: "traefikoidc",
Subsystem: "middleware",
CollectInterval: 10 * time.Second,
Histograms: true,
Labels: make(map[string]string),
}
}
// DefaultHealthConfig returns default health check configuration
func DefaultHealthConfig() HealthConfig {
return HealthConfig{
Enabled: true,
Path: "/health",
CheckInterval: 30 * time.Second,
Timeout: 5 * time.Second,
CheckProvider: true,
CheckRedis: true,
CheckCache: true,
MaxLatency: 1 * time.Second,
MinMemory: 100 * 1024 * 1024, // 100MB
}
}
// DefaultTransportConfig returns default HTTP transport configuration
func DefaultTransportConfig() TransportConfig {
return TransportConfig{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
MaxConnsPerHost: 0, // No limit
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
DisableKeepAlives: false,
DisableCompression: false,
TLSInsecureSkipVerify: false,
TLSMinVersion: "TLS1.2",
TLSCipherSuites: []string{},
ProxyURL: "",
NoProxy: []string{},
}
}
// DefaultPoolConfig returns default connection pool configuration
func DefaultPoolConfig() PoolConfig {
return PoolConfig{
Enabled: true,
Size: 10,
MinSize: 2,
MaxSize: 50,
MaxAge: 30 * time.Minute,
IdleTimeout: 5 * time.Minute,
WaitTimeout: 5 * time.Second,
HealthCheckInterval: 30 * time.Second,
MaxRetries: 3,
}
}
// DefaultCircuitConfig returns default circuit breaker configuration
func DefaultCircuitConfig() CircuitConfig {
return CircuitConfig{
Enabled: true,
MaxRequests: 100,
Interval: 10 * time.Second,
Timeout: 60 * time.Second,
ConsecutiveFailures: 5,
FailureRatio: 0.5,
OnOpen: "reject",
OnHalfOpen: "passthrough",
MetricsEnabled: true,
LogStateChanges: true,
}
}
// MergeWithDefaults merges a partial configuration with defaults
func MergeWithDefaults(partial *UnifiedConfig) *UnifiedConfig {
if partial == nil {
return NewUnifiedConfig()
}
// Ensure Legacy field is initialized
if partial.Legacy == nil {
partial.Legacy = make(map[string]interface{})
}
// TODO: Implement deep merge logic with defaults
// For now, just return the partial config
return partial
}
+396
View File
@@ -0,0 +1,396 @@
// Package config provides configuration loading and merging logic
package config
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/lukaszraczylo/traefikoidc/internal/features"
"gopkg.in/yaml.v3"
)
// ConfigLoader handles loading configuration from various sources
type ConfigLoader struct {
migrator *ConfigMigrator
envPrefix string
configPaths []string
}
// NewConfigLoader creates a new configuration loader
func NewConfigLoader() *ConfigLoader {
return &ConfigLoader{
migrator: NewConfigMigrator(),
envPrefix: "TRAEFIKOIDC_",
configPaths: getDefaultConfigPaths(),
}
}
// getDefaultConfigPaths returns default configuration file paths to check
func getDefaultConfigPaths() []string {
return []string{
"traefik-oidc.yaml",
"traefik-oidc.yml",
"traefik-oidc.json",
"config.yaml",
"config.yml",
"config.json",
"/etc/traefik-oidc/config.yaml",
"/etc/traefik-oidc/config.json",
}
}
// Load loads configuration from all available sources
func (l *ConfigLoader) Load() (*UnifiedConfig, error) {
// Start with defaults
config := NewUnifiedConfig()
// Try to load from file
if fileConfig, err := l.LoadFromFile(); err == nil && fileConfig != nil {
config = l.mergeConfigs(config, fileConfig)
}
// Load from environment variables
l.LoadFromEnv(config)
// Validate the final configuration
if err := config.Validate(); err != nil {
return nil, fmt.Errorf("configuration validation failed: %w", err)
}
return config, nil
}
// LoadFromFile loads configuration from a file
func (l *ConfigLoader) LoadFromFile(paths ...string) (*UnifiedConfig, error) {
// Use provided paths or default paths
searchPaths := paths
if len(searchPaths) == 0 {
searchPaths = l.configPaths
}
// Check for config file in environment variable
if envPath := os.Getenv(l.envPrefix + "CONFIG_FILE"); envPath != "" {
searchPaths = append([]string{envPath}, searchPaths...)
}
// Try each path
for _, path := range searchPaths {
if _, err := os.Stat(path); err == nil {
return l.loadFile(path)
}
}
// No config file found, not an error (use defaults)
return nil, nil
}
// loadFile loads a specific configuration file
func (l *ConfigLoader) loadFile(path string) (*UnifiedConfig, error) {
// Clean and validate path to prevent traversal attacks
cleanPath := filepath.Clean(path)
// Check for path traversal attempts
if strings.Contains(cleanPath, "..") {
return nil, fmt.Errorf("invalid config path: potential path traversal detected in %s", path)
}
// Ensure the path is within expected directories (current dir or subdirs)
absPath, err := filepath.Abs(cleanPath)
if err != nil {
return nil, fmt.Errorf("failed to resolve absolute path for %s: %w", path, err)
}
// Read the file with validated path
data, err := os.ReadFile(absPath)
if err != nil {
return nil, fmt.Errorf("failed to read config file %s: %w", absPath, err)
}
// Check if unified config is enabled
if features.IsUnifiedConfigEnabled() {
// Use migrator to handle any version
config, warnings, err := l.migrator.Migrate(data)
if err != nil {
return nil, fmt.Errorf("failed to migrate config from %s: %w", path, err)
}
// Log warnings
for _, warning := range warnings {
// In production, use proper logging
fmt.Printf("Config Warning (%s): %s\n", path, warning)
}
return config, nil
}
// Legacy path: load old config and convert
ext := strings.ToLower(filepath.Ext(path))
var oldConfig Config
switch ext {
case ".json":
if err := json.Unmarshal(data, &oldConfig); err != nil {
return nil, fmt.Errorf("failed to parse JSON config: %w", err)
}
case ".yaml", ".yml":
if err := yaml.Unmarshal(data, &oldConfig); err != nil {
return nil, fmt.Errorf("failed to parse YAML config: %w", err)
}
default:
return nil, fmt.Errorf("unsupported config file extension: %s", ext)
}
return FromOldConfig(&oldConfig), nil
}
// LoadFromEnv loads configuration from environment variables
func (l *ConfigLoader) LoadFromEnv(config *UnifiedConfig) {
// Provider configuration
l.loadEnvString(&config.Provider.IssuerURL, "PROVIDER_ISSUER_URL", "PROVIDER_URL")
l.loadEnvString(&config.Provider.ClientID, "PROVIDER_CLIENT_ID", "CLIENT_ID")
l.loadEnvString(&config.Provider.ClientSecret, "PROVIDER_CLIENT_SECRET", "CLIENT_SECRET")
l.loadEnvString(&config.Provider.RedirectURL, "PROVIDER_REDIRECT_URL", "CALLBACK_URL")
l.loadEnvString(&config.Provider.LogoutURL, "PROVIDER_LOGOUT_URL", "LOGOUT_URL")
l.loadEnvString(&config.Provider.PostLogoutRedirectURI, "PROVIDER_POST_LOGOUT_URI", "POST_LOGOUT_REDIRECT_URI")
l.loadEnvStringSlice(&config.Provider.Scopes, "PROVIDER_SCOPES", "SCOPES")
l.loadEnvBool(&config.Provider.OverrideScopes, "PROVIDER_OVERRIDE_SCOPES", "OVERRIDE_SCOPES")
// Session configuration
l.loadEnvString(&config.Session.Name, "SESSION_NAME")
l.loadEnvInt(&config.Session.MaxAge, "SESSION_MAX_AGE")
l.loadEnvString(&config.Session.Secret, "SESSION_SECRET")
l.loadEnvString(&config.Session.EncryptionKey, "SESSION_ENCRYPTION_KEY")
l.loadEnvString(&config.Session.Domain, "SESSION_DOMAIN", "COOKIE_DOMAIN")
l.loadEnvBool(&config.Session.Secure, "SESSION_SECURE")
l.loadEnvBool(&config.Session.HttpOnly, "SESSION_HTTP_ONLY")
l.loadEnvString(&config.Session.SameSite, "SESSION_SAME_SITE")
// Security configuration
l.loadEnvBool(&config.Security.ForceHTTPS, "SECURITY_FORCE_HTTPS", "FORCE_HTTPS")
l.loadEnvBool(&config.Security.EnablePKCE, "SECURITY_ENABLE_PKCE", "ENABLE_PKCE")
l.loadEnvStringSlice(&config.Security.AllowedUsers, "SECURITY_ALLOWED_USERS", "ALLOWED_USERS")
l.loadEnvStringSlice(&config.Security.AllowedUserDomains, "SECURITY_ALLOWED_DOMAINS", "ALLOWED_USER_DOMAINS")
l.loadEnvStringSlice(&config.Security.AllowedRolesAndGroups, "SECURITY_ALLOWED_ROLES", "ALLOWED_ROLES_AND_GROUPS")
l.loadEnvStringSlice(&config.Security.ExcludedURLs, "SECURITY_EXCLUDED_URLS", "EXCLUDED_URLS")
// Cache configuration
l.loadEnvBool(&config.Cache.Enabled, "CACHE_ENABLED")
l.loadEnvString(&config.Cache.Type, "CACHE_TYPE")
l.loadEnvInt(&config.Cache.MaxEntries, "CACHE_MAX_ENTRIES")
// MaxEntrySize is int64, skip for now
// Rate limiting
l.loadEnvBool(&config.RateLimit.Enabled, "RATELIMIT_ENABLED")
l.loadEnvInt(&config.RateLimit.RequestsPerSecond, "RATELIMIT_RPS", "RATE_LIMIT")
l.loadEnvInt(&config.RateLimit.Burst, "RATELIMIT_BURST")
// Logging
l.loadEnvString(&config.Logging.Level, "LOGGING_LEVEL", "LOG_LEVEL")
l.loadEnvString(&config.Logging.Format, "LOGGING_FORMAT")
l.loadEnvString(&config.Logging.Output, "LOGGING_OUTPUT")
// Redis configuration (already handled by its own LoadFromEnv)
config.Redis.LoadFromEnv()
// Feature flags
features.GetManager().LoadFromEnv()
}
// Helper methods for environment variable loading
func (l *ConfigLoader) loadEnvString(target *string, keys ...string) {
for _, key := range keys {
if value := os.Getenv(l.envPrefix + key); value != "" {
*target = value
return
}
// Try without prefix
if value := os.Getenv(key); value != "" {
*target = value
return
}
}
}
func (l *ConfigLoader) loadEnvBool(target *bool, keys ...string) {
for _, key := range keys {
if value := os.Getenv(l.envPrefix + key); value != "" {
*target = strings.ToLower(value) == "true" || value == "1"
return
}
// Try without prefix
if value := os.Getenv(key); value != "" {
*target = strings.ToLower(value) == "true" || value == "1"
return
}
}
}
func (l *ConfigLoader) loadEnvInt(target *int, keys ...string) {
for _, key := range keys {
if value := os.Getenv(l.envPrefix + key); value != "" {
var i int
if _, err := fmt.Sscanf(value, "%d", &i); err == nil {
*target = i
return
}
}
// Try without prefix
if value := os.Getenv(key); value != "" {
var i int
if _, err := fmt.Sscanf(value, "%d", &i); err == nil {
*target = i
return
}
}
}
}
func (l *ConfigLoader) loadEnvStringSlice(target *[]string, keys ...string) {
for _, key := range keys {
if value := os.Getenv(l.envPrefix + key); value != "" {
*target = splitAndTrim(value)
return
}
// Try without prefix
if value := os.Getenv(key); value != "" {
*target = splitAndTrim(value)
return
}
}
}
func splitAndTrim(s string) []string {
parts := strings.Split(s, ",")
result := make([]string, 0, len(parts))
for _, part := range parts {
if trimmed := strings.TrimSpace(part); trimmed != "" {
result = append(result, trimmed)
}
}
return result
}
// mergeConfigs merges two configurations, with source overriding target
func (l *ConfigLoader) mergeConfigs(target, source *UnifiedConfig) *UnifiedConfig {
if source == nil {
return target
}
if target == nil {
return source
}
// Use reflection for deep merge
l.mergeStructs(reflect.ValueOf(target).Elem(), reflect.ValueOf(source).Elem())
return target
}
// mergeStructs recursively merges two structs
func (l *ConfigLoader) mergeStructs(target, source reflect.Value) {
for i := 0; i < source.NumField(); i++ {
sourceField := source.Field(i)
targetField := target.Field(i)
// Skip if source field is zero value
if isZeroValue(sourceField) {
continue
}
switch sourceField.Kind() {
case reflect.Struct:
// Recursively merge structs
l.mergeStructs(targetField, sourceField)
case reflect.Slice:
// Replace slice if source has values
if sourceField.Len() > 0 {
targetField.Set(sourceField)
}
case reflect.Map:
// Merge maps
if !sourceField.IsNil() {
if targetField.IsNil() {
targetField.Set(reflect.MakeMap(sourceField.Type()))
}
for _, key := range sourceField.MapKeys() {
targetField.SetMapIndex(key, sourceField.MapIndex(key))
}
}
default:
// Replace value
targetField.Set(sourceField)
}
}
}
// isZeroValue checks if a reflect.Value is a zero value
func isZeroValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Ptr, reflect.Interface:
return v.IsNil()
case reflect.Slice, reflect.Map:
return v.IsNil() || v.Len() == 0
case reflect.Struct:
// Check if all fields are zero
for i := 0; i < v.NumField(); i++ {
if !isZeroValue(v.Field(i)) {
return false
}
}
return true
default:
zero := reflect.Zero(v.Type())
return reflect.DeepEqual(v.Interface(), zero.Interface())
}
}
// SaveToFile saves the configuration to a file
func (l *ConfigLoader) SaveToFile(config *UnifiedConfig, path string) error {
// Clean and validate path to prevent traversal attacks
cleanPath := filepath.Clean(path)
// Check for path traversal attempts
if strings.Contains(cleanPath, "..") {
return fmt.Errorf("invalid config path: potential path traversal detected in %s", path)
}
// Ensure the path is within expected directories
absPath, err := filepath.Abs(cleanPath)
if err != nil {
return fmt.Errorf("failed to resolve absolute path for %s: %w", path, err)
}
ext := strings.ToLower(filepath.Ext(absPath))
var data []byte
switch ext {
case ".json":
data, err = json.MarshalIndent(config, "", " ")
case ".yaml", ".yml":
data, err = yaml.Marshal(config)
default:
return fmt.Errorf("unsupported file extension: %s", ext)
}
if err != nil {
return fmt.Errorf("failed to marshal config: %w", err)
}
// Create directory if it doesn't exist with secure permissions
dir := filepath.Dir(absPath)
if err := os.MkdirAll(dir, 0700); err != nil {
return fmt.Errorf("failed to create directory %s: %w", dir, err)
}
// Write file with secure permissions (owner read/write only)
if err := os.WriteFile(absPath, data, 0600); err != nil {
return fmt.Errorf("failed to write config file %s: %w", absPath, err)
}
return nil
}
+832
View File
@@ -0,0 +1,832 @@
//go:build !yaegi
package config
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
)
// TestConfigLoader tests the config loader functionality
func TestConfigLoader(t *testing.T) {
loader := NewConfigLoader()
if loader == nil {
t.Fatal("NewConfigLoader should not return nil")
}
if loader.migrator == nil {
t.Error("ConfigLoader should have a migrator")
}
if loader.envPrefix != "TRAEFIKOIDC_" {
t.Errorf("Expected envPrefix to be 'TRAEFIKOIDC_', got %s", loader.envPrefix)
}
if len(loader.configPaths) == 0 {
t.Error("ConfigLoader should have default config paths")
}
}
// TestLoadFromEnv tests loading configuration from environment variables
func TestLoadFromEnv(t *testing.T) {
// Set up test environment variables
testEnvVars := map[string]string{
"TRAEFIKOIDC_PROVIDER_ISSUER_URL": "https://test.example.com",
"TRAEFIKOIDC_PROVIDER_CLIENT_ID": "test-client-id",
"TRAEFIKOIDC_PROVIDER_CLIENT_SECRET": "test-secret",
"TRAEFIKOIDC_SESSION_ENCRYPTION_KEY": "32-character-encryption-key-12345",
"TRAEFIKOIDC_SESSION_CHUNKED": "true",
"TRAEFIKOIDC_REDIS_ENABLED": "true",
"TRAEFIKOIDC_REDIS_ADDR": "redis.example.com:6379",
"TRAEFIKOIDC_SECURITY_FORCE_HTTPS": "true",
"TRAEFIKOIDC_CACHE_ENABLED": "true",
"TRAEFIKOIDC_CACHE_TYPE": "redis",
"TRAEFIKOIDC_RATELIMIT_ENABLED": "true",
"TRAEFIKOIDC_RATELIMIT_RPS": "100",
}
// Set environment variables
for key, value := range testEnvVars {
os.Setenv(key, value)
defer os.Unsetenv(key)
}
loader := NewConfigLoader()
config := &UnifiedConfig{}
loader.LoadFromEnv(config)
// Verify values were loaded
if config.Provider.IssuerURL != "https://test.example.com" {
t.Errorf("Expected IssuerURL to be 'https://test.example.com', got %s", config.Provider.IssuerURL)
}
if config.Provider.ClientID != "test-client-id" {
t.Errorf("Expected ClientID to be 'test-client-id', got %s", config.Provider.ClientID)
}
if config.Provider.ClientSecret != "test-secret" {
t.Errorf("Expected ClientSecret to be 'test-secret', got %s", config.Provider.ClientSecret)
}
if config.Session.EncryptionKey != "32-character-encryption-key-12345" {
t.Errorf("Expected EncryptionKey to be set, got %s", config.Session.EncryptionKey)
}
if !config.Security.ForceHTTPS {
t.Error("Expected ForceHTTPS to be true")
}
if !config.Cache.Enabled {
t.Error("Expected Cache to be enabled")
}
if config.Cache.Type != "redis" {
t.Errorf("Expected Cache.Type to be 'redis', got %s", config.Cache.Type)
}
if !config.RateLimit.Enabled {
t.Error("Expected RateLimit to be enabled")
}
if config.RateLimit.RequestsPerSecond != 100 {
t.Errorf("Expected RequestsPerSecond to be 100, got %d", config.RateLimit.RequestsPerSecond)
}
}
// TestSaveToFile tests saving configuration to files
func TestSaveToFile(t *testing.T) {
// Create a temporary directory for test files
tmpDir, err := os.MkdirTemp("", "config-test-*")
if err != nil {
t.Fatalf("Failed to create temp directory: %v", err)
}
defer os.RemoveAll(tmpDir)
loader := NewConfigLoader()
config := &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://auth.example.com",
ClientID: "test-client",
ClientSecret: "secret",
},
Session: SessionConfig{
EncryptionKey: "32-character-encryption-key-12345",
},
}
tests := []struct {
name string
filename string
wantErr bool
}{
{
name: "save as JSON",
filename: "config.json",
wantErr: false,
},
{
name: "save as YAML",
filename: "config.yaml",
wantErr: false,
},
{
name: "save as YML",
filename: "config.yml",
wantErr: false,
},
{
name: "unsupported extension",
filename: "config.txt",
wantErr: true,
},
{
name: "path traversal attempt",
filename: "../../../etc/config.json",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
filePath := filepath.Join(tmpDir, tt.filename)
err := loader.SaveToFile(config, filePath)
if tt.wantErr {
if err == nil {
t.Error("Expected error but got none")
}
return
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
return
}
// Verify file was created with correct permissions
info, err := os.Stat(filePath)
if err != nil {
t.Errorf("Failed to stat saved file: %v", err)
return
}
// Check file permissions (should be 0600)
mode := info.Mode().Perm()
if mode != 0600 {
t.Errorf("Expected file permissions 0600, got %o", mode)
}
// Verify content can be read back
data, err := os.ReadFile(filePath)
if err != nil {
t.Errorf("Failed to read saved file: %v", err)
return
}
// Verify secrets are redacted
content := string(data)
if strings.Contains(content, "secret") && !strings.Contains(content, "[REDACTED]") {
t.Error("Secrets should be redacted in saved file")
}
})
}
}
// TestLoadFile tests loading configuration from files
func TestLoadFile(t *testing.T) {
// Create a temporary directory for test files
tmpDir, err := os.MkdirTemp("", "config-test-*")
if err != nil {
t.Fatalf("Failed to create temp directory: %v", err)
}
defer os.RemoveAll(tmpDir)
// Test data - using old config format since unified config is not enabled by default
jsonConfig := `{
"providerURL": "https://auth.example.com",
"clientID": "test-client",
"clientSecret": "secret",
"sessionEncryptionKey": "32-character-encryption-key-12345"
}`
yamlConfig := `
providerurl: https://auth.example.com
clientid: test-client
clientsecret: secret
sessionencryptionkey: 32-character-encryption-key-12345
`
tests := []struct {
name string
filename string
content string
wantErr bool
}{
{
name: "load JSON config",
filename: "config.json",
content: jsonConfig,
wantErr: false,
},
{
name: "load YAML config",
filename: "config.yaml",
content: yamlConfig,
wantErr: false,
},
{
name: "path traversal attempt",
filename: "../../../etc/passwd",
content: "",
wantErr: true,
},
{
name: "non-existent file",
filename: "does-not-exist.json",
content: "",
wantErr: true,
},
}
loader := NewConfigLoader()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var filePath string
if tt.content != "" {
filePath = filepath.Join(tmpDir, tt.filename)
err := os.WriteFile(filePath, []byte(tt.content), 0600)
if err != nil {
t.Fatalf("Failed to write test file: %v", err)
return
}
} else {
filePath = tt.filename
}
config, err := loader.loadFile(filePath)
if tt.wantErr {
if err == nil {
t.Error("Expected error but got none")
}
return
}
if err != nil {
if !os.IsNotExist(err) && !strings.Contains(err.Error(), "no such file") {
t.Errorf("Unexpected error: %v", err)
}
return
}
// Verify loaded config
if config == nil {
t.Error("Expected config to be loaded")
return
}
if config.Provider.IssuerURL != "https://auth.example.com" {
t.Errorf("Expected IssuerURL to be 'https://auth.example.com', got %s", config.Provider.IssuerURL)
}
if config.Provider.ClientID != "test-client" {
t.Errorf("Expected ClientID to be 'test-client', got %s", config.Provider.ClientID)
}
})
}
}
// ====================================================================================
// Tests for untested functions (0% coverage)
// ====================================================================================
// TestConfigLoader_Load tests the full Load pipeline
func TestConfigLoader_Load(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "config-load-test-*")
if err != nil {
t.Fatalf("Failed to create temp directory: %v", err)
}
defer os.RemoveAll(tmpDir)
// Create a test config file
configPath := filepath.Join(tmpDir, "traefik-oidc.json")
configData := `{
"providerURL": "https://auth.example.com",
"clientID": "test-client",
"clientSecret": "test-secret",
"sessionEncryptionKey": "32-character-encryption-key-12345"
}`
err = os.WriteFile(configPath, []byte(configData), 0600)
if err != nil {
t.Fatalf("Failed to write test config file: %v", err)
}
// Change to temp directory so loader can find the config
oldDir, _ := os.Getwd()
os.Chdir(tmpDir)
defer os.Chdir(oldDir)
// Set some environment variables to test merging
os.Setenv("TRAEFIKOIDC_SECURITY_FORCE_HTTPS", "true")
defer os.Unsetenv("TRAEFIKOIDC_SECURITY_FORCE_HTTPS")
loader := NewConfigLoader()
config, err := loader.Load()
if err != nil {
t.Fatalf("Load() failed: %v", err)
}
if config == nil {
t.Fatal("Load() returned nil config")
}
// Verify file was loaded
if config.Provider.IssuerURL != "https://auth.example.com" {
t.Errorf("Expected IssuerURL from file, got %s", config.Provider.IssuerURL)
}
// Verify env vars were loaded
if !config.Security.ForceHTTPS {
t.Error("Expected ForceHTTPS from env var to be true")
}
}
// TestConfigLoader_LoadFromFile tests the LoadFromFile function
func TestConfigLoader_LoadFromFile(t *testing.T) {
t.Run("NoConfigFile", func(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "config-nofile-test-*")
if err != nil {
t.Fatalf("Failed to create temp directory: %v", err)
}
defer os.RemoveAll(tmpDir)
oldDir, _ := os.Getwd()
os.Chdir(tmpDir)
defer os.Chdir(oldDir)
loader := NewConfigLoader()
config, err := loader.LoadFromFile()
// Should not error when no config file found
if err != nil {
t.Errorf("LoadFromFile() should not error when no file found: %v", err)
}
// Should return nil config
if config != nil {
t.Error("LoadFromFile() should return nil config when no file found")
}
})
t.Run("LoadFromEnvPath", func(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "config-envpath-test-*")
if err != nil {
t.Fatalf("Failed to create temp directory: %v", err)
}
defer os.RemoveAll(tmpDir)
// Create config file
configPath := filepath.Join(tmpDir, "custom-config.json")
configData := `{
"providerURL": "https://custom.example.com",
"clientID": "custom-client"
}`
err = os.WriteFile(configPath, []byte(configData), 0600)
if err != nil {
t.Fatalf("Failed to write test config: %v", err)
}
// Set env variable pointing to config
os.Setenv("TRAEFIKOIDC_CONFIG_FILE", configPath)
defer os.Unsetenv("TRAEFIKOIDC_CONFIG_FILE")
loader := NewConfigLoader()
config, err := loader.LoadFromFile()
if err != nil {
t.Fatalf("LoadFromFile() failed: %v", err)
}
if config == nil {
t.Fatal("LoadFromFile() returned nil config")
}
if config.Provider.IssuerURL != "https://custom.example.com" {
t.Errorf("Expected IssuerURL 'https://custom.example.com', got %s", config.Provider.IssuerURL)
}
})
t.Run("LoadWithProvidedPaths", func(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "config-provided-test-*")
if err != nil {
t.Fatalf("Failed to create temp directory: %v", err)
}
defer os.RemoveAll(tmpDir)
// Create config file
configPath := filepath.Join(tmpDir, "specific.json")
configData := `{
"providerURL": "https://specific.example.com",
"clientID": "specific-client"
}`
err = os.WriteFile(configPath, []byte(configData), 0600)
if err != nil {
t.Fatalf("Failed to write test config: %v", err)
}
loader := NewConfigLoader()
config, err := loader.LoadFromFile(configPath)
if err != nil {
t.Fatalf("LoadFromFile() with path failed: %v", err)
}
if config == nil {
t.Fatal("LoadFromFile() returned nil config")
}
if config.Provider.IssuerURL != "https://specific.example.com" {
t.Errorf("Expected IssuerURL 'https://specific.example.com', got %s", config.Provider.IssuerURL)
}
})
}
// TestSplitAndTrim tests the splitAndTrim helper function
func TestSplitAndTrim(t *testing.T) {
tests := []struct {
name string
input string
expected []string
}{
{
name: "Simple comma-separated",
input: "a,b,c",
expected: []string{"a", "b", "c"},
},
{
name: "With spaces",
input: "a, b , c",
expected: []string{"a", "b", "c"},
},
{
name: "Empty strings filtered out",
input: "a,,b, ,c",
expected: []string{"a", "b", "c"},
},
{
name: "Leading and trailing spaces",
input: " a , b , c ",
expected: []string{"a", "b", "c"},
},
{
name: "Single value",
input: "single",
expected: []string{"single"},
},
{
name: "Empty string",
input: "",
expected: []string{},
},
{
name: "Only commas and spaces",
input: " , , , ",
expected: []string{},
},
{
name: "Complex real-world example",
input: "openid, profile, email, groups",
expected: []string{"openid", "profile", "email", "groups"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := splitAndTrim(tt.input)
if len(result) != len(tt.expected) {
t.Errorf("Expected %d items, got %d: %v", len(tt.expected), len(result), result)
return
}
for i, expected := range tt.expected {
if result[i] != expected {
t.Errorf("At index %d: expected %q, got %q", i, expected, result[i])
}
}
})
}
}
// TestConfigLoader_MergeConfigs tests the mergeConfigs function
func TestConfigLoader_MergeConfigs(t *testing.T) {
loader := NewConfigLoader()
t.Run("MergeNilSource", func(t *testing.T) {
target := &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://target.example.com",
},
}
result := loader.mergeConfigs(target, nil)
if result != target {
t.Error("mergeConfigs should return target when source is nil")
}
})
t.Run("MergeNilTarget", func(t *testing.T) {
source := &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://source.example.com",
},
}
result := loader.mergeConfigs(nil, source)
if result != source {
t.Error("mergeConfigs should return source when target is nil")
}
})
t.Run("MergeSimpleFields", func(t *testing.T) {
target := &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://target.example.com",
ClientID: "",
},
}
source := &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://source.example.com",
ClientID: "source-client",
},
}
result := loader.mergeConfigs(target, source)
if result.Provider.IssuerURL != "https://source.example.com" {
t.Errorf("Expected IssuerURL to be overridden, got %s", result.Provider.IssuerURL)
}
if result.Provider.ClientID != "source-client" {
t.Errorf("Expected ClientID to be set, got %s", result.Provider.ClientID)
}
})
t.Run("MergeSlices", func(t *testing.T) {
target := &UnifiedConfig{
Provider: ProviderConfig{
Scopes: []string{"openid", "profile"},
},
}
source := &UnifiedConfig{
Provider: ProviderConfig{
Scopes: []string{"email", "groups"},
},
}
result := loader.mergeConfigs(target, source)
// Source slice should replace target slice
if len(result.Provider.Scopes) != 2 {
t.Errorf("Expected 2 scopes, got %d", len(result.Provider.Scopes))
}
if result.Provider.Scopes[0] != "email" {
t.Errorf("Expected first scope 'email', got %s", result.Provider.Scopes[0])
}
})
t.Run("MergeMaps", func(t *testing.T) {
target := &UnifiedConfig{
Middleware: MiddlewareConfig{
CustomHeaders: map[string]string{
"X-Target-Header": "target-value",
},
},
}
source := &UnifiedConfig{
Middleware: MiddlewareConfig{
CustomHeaders: map[string]string{
"X-Source-Header": "source-value",
"X-Target-Header": "overridden-value",
},
},
}
result := loader.mergeConfigs(target, source)
if len(result.Middleware.CustomHeaders) != 2 {
t.Errorf("Expected 2 headers, got %d", len(result.Middleware.CustomHeaders))
}
if result.Middleware.CustomHeaders["X-Target-Header"] != "overridden-value" {
t.Errorf("Expected X-Target-Header to be overridden")
}
if result.Middleware.CustomHeaders["X-Source-Header"] != "source-value" {
t.Errorf("Expected X-Source-Header to be added")
}
})
}
// TestConfigLoader_MergeStructs tests the mergeStructs function indirectly
func TestConfigLoader_MergeStructs(t *testing.T) {
loader := NewConfigLoader()
t.Run("NestedStructMerge", func(t *testing.T) {
target := &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://target.example.com",
ClientID: "target-client",
},
Session: SessionConfig{
Name: "target-session",
MaxAge: 3600,
},
}
source := &UnifiedConfig{
Provider: ProviderConfig{
ClientID: "source-client",
ClientSecret: "source-secret",
},
Session: SessionConfig{
MaxAge: 7200,
},
}
result := loader.mergeConfigs(target, source)
// Provider.IssuerURL should remain (zero value in source)
if result.Provider.IssuerURL != "https://target.example.com" {
t.Errorf("Expected IssuerURL to remain, got %s", result.Provider.IssuerURL)
}
// Provider.ClientID should be overridden
if result.Provider.ClientID != "source-client" {
t.Errorf("Expected ClientID to be overridden, got %s", result.Provider.ClientID)
}
// Provider.ClientSecret should be added
if result.Provider.ClientSecret != "source-secret" {
t.Errorf("Expected ClientSecret to be added, got %s", result.Provider.ClientSecret)
}
// Session.Name should remain (zero value in source)
if result.Session.Name != "target-session" {
t.Errorf("Expected Session.Name to remain, got %s", result.Session.Name)
}
// Session.MaxAge should be overridden
if result.Session.MaxAge != 7200 {
t.Errorf("Expected Session.MaxAge to be overridden, got %d", result.Session.MaxAge)
}
})
}
// TestIsZeroValue tests the isZeroValue helper function
func TestIsZeroValue(t *testing.T) {
tests := []struct {
name string
value interface{}
expected bool
}{
{
name: "Zero string",
value: "",
expected: true,
},
{
name: "Non-zero string",
value: "hello",
expected: false,
},
{
name: "Zero int",
value: 0,
expected: true,
},
{
name: "Non-zero int",
value: 42,
expected: false,
},
{
name: "Zero bool",
value: false,
expected: true,
},
{
name: "Non-zero bool",
value: true,
expected: false,
},
{
name: "Nil pointer",
value: (*string)(nil),
expected: true,
},
{
name: "Non-nil pointer",
value: stringPtr("test"),
expected: false,
},
{
name: "Nil slice",
value: ([]string)(nil),
expected: true,
},
{
name: "Empty slice",
value: []string{},
expected: true,
},
{
name: "Non-empty slice",
value: []string{"a"},
expected: false,
},
{
name: "Nil map",
value: (map[string]string)(nil),
expected: true,
},
{
name: "Empty map",
value: map[string]string{},
expected: true,
},
{
name: "Non-empty map",
value: map[string]string{"key": "value"},
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
v := reflect.ValueOf(tt.value)
result := isZeroValue(v)
if result != tt.expected {
t.Errorf("Expected isZeroValue to be %v, got %v", tt.expected, result)
}
})
}
}
// TestIsZeroValue_Struct tests isZeroValue with struct types
func TestIsZeroValue_Struct(t *testing.T) {
type TestStruct struct {
Field1 string
Field2 int
}
t.Run("Zero struct", func(t *testing.T) {
s := TestStruct{}
v := reflect.ValueOf(s)
result := isZeroValue(v)
if !result {
t.Error("Expected zero struct to return true")
}
})
t.Run("Non-zero struct - Field1 set", func(t *testing.T) {
s := TestStruct{Field1: "test"}
v := reflect.ValueOf(s)
result := isZeroValue(v)
if result {
t.Error("Expected non-zero struct to return false")
}
})
t.Run("Non-zero struct - Field2 set", func(t *testing.T) {
s := TestStruct{Field2: 42}
v := reflect.ValueOf(s)
result := isZeroValue(v)
if result {
t.Error("Expected non-zero struct to return false")
}
})
t.Run("Non-zero struct - Both fields set", func(t *testing.T) {
s := TestStruct{Field1: "test", Field2: 42}
v := reflect.ValueOf(s)
result := isZeroValue(v)
if result {
t.Error("Expected non-zero struct to return false")
}
})
}
// Helper function for pointer tests
func stringPtr(s string) *string {
return &s
}
+169
View File
@@ -0,0 +1,169 @@
// Package config provides unified configuration management for the OIDC middleware
package config
import (
"encoding/json"
)
// REDACTED is the placeholder value for sensitive information
const REDACTED = "[REDACTED]"
// MarshalJSON implements custom JSON marshalling to redact sensitive fields
func (c UnifiedConfig) MarshalJSON() ([]byte, error) {
// Create an alias to avoid recursion
type Alias UnifiedConfig
// Create a copy with redacted sensitive fields
copy := (Alias)(c)
// Redact provider secrets
if copy.Provider.ClientSecret != "" {
copy.Provider.ClientSecret = REDACTED
}
// Redact session secrets
if copy.Session.Secret != "" {
copy.Session.Secret = REDACTED
}
if copy.Session.EncryptionKey != "" {
copy.Session.EncryptionKey = REDACTED
}
if copy.Session.SigningKey != "" {
copy.Session.SigningKey = REDACTED
}
// Redact Redis passwords
if copy.Redis.Password != "" {
copy.Redis.Password = REDACTED
}
if copy.Redis.SentinelPassword != "" {
copy.Redis.SentinelPassword = REDACTED
}
return json.Marshal(copy)
}
// MarshalJSON for ProviderConfig to redact sensitive fields
func (p ProviderConfig) MarshalJSON() ([]byte, error) {
type Alias ProviderConfig
copy := (Alias)(p)
if copy.ClientSecret != "" {
copy.ClientSecret = REDACTED
}
return json.Marshal(copy)
}
// MarshalJSON for SessionConfig to redact sensitive fields
func (s SessionConfig) MarshalJSON() ([]byte, error) {
type Alias SessionConfig
copy := (Alias)(s)
if copy.Secret != "" {
copy.Secret = REDACTED
}
if copy.EncryptionKey != "" {
copy.EncryptionKey = REDACTED
}
if copy.SigningKey != "" {
copy.SigningKey = REDACTED
}
return json.Marshal(copy)
}
// MarshalJSON for RedisConfig to redact sensitive fields
func (r RedisConfig) MarshalJSON() ([]byte, error) {
type Alias RedisConfig
copy := (Alias)(r)
if copy.Password != "" {
copy.Password = REDACTED
}
if copy.SentinelPassword != "" {
copy.SentinelPassword = REDACTED
}
return json.Marshal(copy)
}
// MarshalYAML implements custom YAML marshalling to redact sensitive fields
func (c UnifiedConfig) MarshalYAML() (interface{}, error) {
// Create an alias to avoid recursion
type Alias UnifiedConfig
// Create a copy with redacted sensitive fields
copy := (Alias)(c)
// Redact provider secrets
if copy.Provider.ClientSecret != "" {
copy.Provider.ClientSecret = REDACTED
}
// Redact session secrets
if copy.Session.Secret != "" {
copy.Session.Secret = REDACTED
}
if copy.Session.EncryptionKey != "" {
copy.Session.EncryptionKey = REDACTED
}
if copy.Session.SigningKey != "" {
copy.Session.SigningKey = REDACTED
}
// Redact Redis passwords
if copy.Redis.Password != "" {
copy.Redis.Password = REDACTED
}
if copy.Redis.SentinelPassword != "" {
copy.Redis.SentinelPassword = REDACTED
}
return copy, nil
}
// MarshalYAML for ProviderConfig to redact sensitive fields
func (p ProviderConfig) MarshalYAML() (interface{}, error) {
type Alias ProviderConfig
copy := (Alias)(p)
if copy.ClientSecret != "" {
copy.ClientSecret = REDACTED
}
return copy, nil
}
// MarshalYAML for SessionConfig to redact sensitive fields
func (s SessionConfig) MarshalYAML() (interface{}, error) {
type Alias SessionConfig
copy := (Alias)(s)
if copy.Secret != "" {
copy.Secret = REDACTED
}
if copy.EncryptionKey != "" {
copy.EncryptionKey = REDACTED
}
if copy.SigningKey != "" {
copy.SigningKey = REDACTED
}
return copy, nil
}
// MarshalYAML for RedisConfig to redact sensitive fields
func (r RedisConfig) MarshalYAML() (interface{}, error) {
type Alias RedisConfig
copy := (Alias)(r)
if copy.Password != "" {
copy.Password = REDACTED
}
if copy.SentinelPassword != "" {
copy.SentinelPassword = REDACTED
}
return copy, nil
}
+407
View File
@@ -0,0 +1,407 @@
// Package config provides configuration migration from old to new format
package config
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/lukaszraczylo/traefikoidc/internal/compat"
"github.com/lukaszraczylo/traefikoidc/internal/features"
"gopkg.in/yaml.v3"
)
// ConfigVersion represents the version of a configuration format
type ConfigVersion string
const (
// VersionLegacy represents the original config format
VersionLegacy ConfigVersion = "legacy"
// VersionUnified represents the new unified config format
VersionUnified ConfigVersion = "unified"
// CurrentVersion is the current config version
CurrentVersion ConfigVersion = VersionUnified
)
// ConfigMigrator handles migration between config versions
type ConfigMigrator struct {
compatLayer *compat.CompatibilityLayer
migrations map[ConfigVersion]MigrationFunc
}
// MigrationFunc defines a function that migrates configuration
type MigrationFunc func(data map[string]interface{}) (*UnifiedConfig, error)
// NewConfigMigrator creates a new configuration migrator
func NewConfigMigrator() *ConfigMigrator {
m := &ConfigMigrator{
compatLayer: compat.GetLayer(),
migrations: make(map[ConfigVersion]MigrationFunc),
}
// Register migration functions
m.migrations[VersionLegacy] = m.migrateLegacyToUnified
return m
}
// DetectVersion detects the version of a configuration
func (m *ConfigMigrator) DetectVersion(data []byte) ConfigVersion {
var testMap map[string]interface{}
// Try JSON first
if err := json.Unmarshal(data, &testMap); err != nil {
// Try YAML
if err := yaml.Unmarshal(data, &testMap); err != nil {
return VersionLegacy // Default to legacy if can't parse
}
}
// Check for unified config markers
if _, hasProvider := testMap["provider"]; hasProvider {
if _, hasSession := testMap["session"]; hasSession {
return VersionUnified
}
}
// Check for legacy config markers
if _, hasProviderURL := testMap["providerUrl"]; hasProviderURL {
return VersionLegacy
}
if _, hasProviderURL := testMap["ProviderURL"]; hasProviderURL {
return VersionLegacy
}
return VersionLegacy
}
// Migrate migrates configuration data to the current version
func (m *ConfigMigrator) Migrate(data []byte) (*UnifiedConfig, []string, error) {
warnings := []string{}
// Detect version
version := m.DetectVersion(data)
// If already current version, just unmarshal
if version == CurrentVersion {
var config UnifiedConfig
if err := json.Unmarshal(data, &config); err != nil {
// Try YAML
if err := yaml.Unmarshal(data, &config); err != nil {
return nil, warnings, fmt.Errorf("failed to unmarshal unified config: %w", err)
}
}
return &config, warnings, nil
}
// Parse to generic map
var configMap map[string]interface{}
if err := json.Unmarshal(data, &configMap); err != nil {
// Try YAML
if err := yaml.Unmarshal(data, &configMap); err != nil {
return nil, warnings, fmt.Errorf("failed to unmarshal config: %w", err)
}
}
// Apply migration
migrationFunc, exists := m.migrations[version]
if !exists {
return nil, warnings, fmt.Errorf("no migration path from version %s", version)
}
config, err := migrationFunc(configMap)
if err != nil {
return nil, warnings, fmt.Errorf("migration failed: %w", err)
}
// Collect any deprecation warnings
for key := range configMap {
if warning, deprecated := m.compatLayer.CheckDeprecation(key); deprecated {
warnings = append(warnings, warning)
}
}
return config, warnings, nil
}
// migrateLegacyToUnified migrates legacy config to unified format
func (m *ConfigMigrator) migrateLegacyToUnified(data map[string]interface{}) (*UnifiedConfig, error) {
config := NewUnifiedConfig()
// Use compatibility layer for field mapping
migratedMap, warnings := m.compatLayer.MigrateMap(data)
// Log warnings
for _, warning := range warnings {
// In production, these would be logged
_ = warning
}
// Map provider configuration
if provider, ok := getNestedMap(migratedMap, "Provider"); ok {
_ = mapToStruct(provider, &config.Provider)
} else {
// Direct field mapping for legacy format
config.Provider.IssuerURL = getStringValue(data, "providerUrl", "ProviderURL")
config.Provider.ClientID = getStringValue(data, "clientId", "ClientID")
config.Provider.ClientSecret = getStringValue(data, "clientSecret", "ClientSecret")
config.Provider.RedirectURL = getStringValue(data, "callbackUrl", "CallbackURL")
config.Provider.LogoutURL = getStringValue(data, "logoutUrl", "LogoutURL")
config.Provider.PostLogoutRedirectURI = getStringValue(data, "postLogoutRedirectUri", "PostLogoutRedirectURI")
if scopes := getArrayValue(data, "scopes", "Scopes"); scopes != nil {
config.Provider.Scopes = scopes
}
config.Provider.OverrideScopes = getBoolValue(data, "overrideScopes", "OverrideScopes")
}
// Map session configuration
if session, ok := getNestedMap(migratedMap, "Session"); ok {
_ = mapToStruct(session, &config.Session)
} else {
config.Session.EncryptionKey = getStringValue(data, "sessionEncryptionKey", "SessionEncryptionKey")
config.Session.Domain = getStringValue(data, "cookieDomain", "CookieDomain")
}
// Map security configuration
if security, ok := getNestedMap(migratedMap, "Security"); ok {
_ = mapToStruct(security, &config.Security)
} else {
config.Security.ForceHTTPS = getBoolValue(data, "forceHttps", "ForceHTTPS")
config.Security.EnablePKCE = getBoolValue(data, "enablePkce", "EnablePKCE")
if users := getArrayValue(data, "allowedUsers", "AllowedUsers"); users != nil {
config.Security.AllowedUsers = users
}
if domains := getArrayValue(data, "allowedUserDomains", "AllowedUserDomains"); domains != nil {
config.Security.AllowedUserDomains = domains
}
if roles := getArrayValue(data, "allowedRolesAndGroups", "AllowedRolesAndGroups"); roles != nil {
config.Security.AllowedRolesAndGroups = roles
}
if excluded := getArrayValue(data, "excludedUrls", "ExcludedURLs"); excluded != nil {
config.Security.ExcludedURLs = excluded
}
// Handle security headers
if headers := data["securityHeaders"]; headers != nil {
// Security headers might be in old format
_ = mapToStruct(headers, &config.Security.Headers)
}
}
// Map rate limiting
if rateLimit := getIntValue(data, "rateLimit", "RateLimit"); rateLimit > 0 {
config.RateLimit.Enabled = true
config.RateLimit.RequestsPerSecond = rateLimit
config.RateLimit.Burst = rateLimit * 2 // Default burst to 2x rate
}
// Map token configuration
if refreshGrace := getIntValue(data, "refreshGracePeriodSeconds", "RefreshGracePeriodSeconds"); refreshGrace > 0 {
config.Token.RefreshGracePeriod = time.Duration(refreshGrace) * time.Second
}
// Map logging
config.Logging.Level = strings.ToLower(getStringValue(data, "logLevel", "LogLevel"))
if config.Logging.Level == "" {
config.Logging.Level = "info"
}
// Map custom headers
if headers := data["headers"]; headers != nil {
if headerList, ok := headers.([]interface{}); ok {
config.Middleware.CustomHeaders = make(map[string]string)
for _, h := range headerList {
if headerMap, ok := h.(map[string]interface{}); ok {
name := getStringFromInterface(headerMap["name"])
value := getStringFromInterface(headerMap["value"])
if name != "" {
config.Middleware.CustomHeaders[name] = value
}
}
}
}
}
// Store original data for reference
config.Legacy = data
return config, nil
}
// MigrateFile migrates a configuration file
func (m *ConfigMigrator) MigrateFile(filePath string) (*UnifiedConfig, error) {
// Clean and validate path to prevent traversal attacks
cleanPath := filepath.Clean(filePath)
// Check for path traversal attempts
if strings.Contains(cleanPath, "..") {
return nil, fmt.Errorf("invalid config path: potential path traversal detected in %s", filePath)
}
// Ensure the path is within expected directories
absPath, err := filepath.Abs(cleanPath)
if err != nil {
return nil, fmt.Errorf("failed to resolve absolute path for %s: %w", filePath, err)
}
// Read the file with validated path
data, err := os.ReadFile(absPath)
if err != nil {
return nil, fmt.Errorf("failed to read config file: %w", err)
}
config, warnings, err := m.Migrate(data)
if err != nil {
return nil, err
}
// Log warnings
for _, warning := range warnings {
fmt.Printf("Migration Warning: %s\n", warning)
}
return config, nil
}
// AutoMigrate automatically migrates config based on feature flags
func AutoMigrate(data interface{}) (*UnifiedConfig, error) {
if !features.IsUnifiedConfigEnabled() {
// Feature not enabled, return nil
return nil, nil
}
migrator := NewConfigMigrator()
// Handle different input types
switch v := data.(type) {
case []byte:
config, _, err := migrator.Migrate(v)
return config, err
case string:
config, _, err := migrator.Migrate([]byte(v))
return config, err
case *Config:
// Convert old config to unified
return FromOldConfig(v), nil
case *UnifiedConfig:
// Already unified
return v, nil
case map[string]interface{}:
// Convert map to JSON then migrate
jsonData, err := json.Marshal(v)
if err != nil {
return nil, err
}
config, _, err := migrator.Migrate(jsonData)
return config, err
default:
return nil, fmt.Errorf("unsupported config type: %T", v)
}
}
// Helper functions
func getNestedMap(m map[string]interface{}, key string) (map[string]interface{}, bool) {
if val, exists := m[key]; exists {
if mapped, ok := val.(map[string]interface{}); ok {
return mapped, true
}
}
return nil, false
}
func getStringValue(m map[string]interface{}, keys ...string) string {
for _, key := range keys {
if val, exists := m[key]; exists {
return getStringFromInterface(val)
}
}
return ""
}
func getStringFromInterface(val interface{}) string {
if val == nil {
return ""
}
switch v := val.(type) {
case string:
return v
case []byte:
return string(v)
default:
return fmt.Sprintf("%v", v)
}
}
func getBoolValue(m map[string]interface{}, keys ...string) bool {
for _, key := range keys {
if val, exists := m[key]; exists {
if b, ok := val.(bool); ok {
return b
}
// Try string conversion
if s, ok := val.(string); ok {
return strings.ToLower(s) == "true"
}
}
}
return false
}
func getIntValue(m map[string]interface{}, keys ...string) int {
for _, key := range keys {
if val, exists := m[key]; exists {
switch v := val.(type) {
case int:
return v
case int64:
return int(v)
case float64:
return int(v)
case string:
// Try to parse
var i int
if _, err := fmt.Sscanf(v, "%d", &i); err != nil {
// If parsing fails, return default
return 0
}
return i
}
}
}
return 0
}
func getArrayValue(m map[string]interface{}, keys ...string) []string {
for _, key := range keys {
if val, exists := m[key]; exists {
if arr, ok := val.([]interface{}); ok {
result := make([]string, 0, len(arr))
for _, item := range arr {
result = append(result, getStringFromInterface(item))
}
return result
}
if strArr, ok := val.([]string); ok {
return strArr
}
}
}
return nil
}
func mapToStruct(m interface{}, target interface{}) error {
// Simple mapping using JSON as intermediate
data, err := json.Marshal(m)
if err != nil {
return err
}
return json.Unmarshal(data, target)
}
File diff suppressed because it is too large Load Diff
+297
View File
@@ -0,0 +1,297 @@
// Package config provides configuration structures for the Traefik OIDC plugin.
package config
import (
"os"
"strconv"
"strings"
"time"
)
// RedisMode represents the Redis deployment mode
type RedisMode string
const (
// RedisModeStandalone represents a single Redis instance
RedisModeStandalone RedisMode = "standalone"
// RedisModeCluster represents Redis cluster mode
RedisModeCluster RedisMode = "cluster"
// RedisModeSentinel represents Redis sentinel mode
RedisModeSentinel RedisMode = "sentinel"
)
// RedisConfig holds Redis cache backend configuration
type RedisConfig struct {
// Enabled indicates if Redis backend should be used
Enabled bool `json:"enabled,omitempty" yaml:"enabled,omitempty"`
// Mode specifies the Redis deployment mode
Mode RedisMode `json:"mode,omitempty" yaml:"mode,omitempty"`
// === Standalone Configuration ===
// Addr is the Redis server address (host:port)
Addr string `json:"addr,omitempty" yaml:"addr,omitempty"`
// Password for Redis authentication
Password string `json:"password,omitempty" yaml:"password,omitempty"`
// DB is the database number (0-15)
DB int `json:"db,omitempty" yaml:"db,omitempty"`
// === Cluster Configuration ===
// ClusterAddrs is the list of cluster node addresses
ClusterAddrs []string `json:"clusterAddrs,omitempty" yaml:"clusterAddrs,omitempty"`
// === Sentinel Configuration ===
// MasterName is the name of the master instance
MasterName string `json:"masterName,omitempty" yaml:"masterName,omitempty"`
// SentinelAddrs is the list of sentinel addresses
SentinelAddrs []string `json:"sentinelAddrs,omitempty" yaml:"sentinelAddrs,omitempty"`
// SentinelPassword is the password for sentinel authentication
SentinelPassword string `json:"sentinelPassword,omitempty" yaml:"sentinelPassword,omitempty"`
// === Connection Pool Settings ===
// PoolSize is the maximum number of socket connections
PoolSize int `json:"poolSize,omitempty" yaml:"poolSize,omitempty"`
// MinIdleConns is the minimum number of idle connections
MinIdleConns int `json:"minIdleConns,omitempty" yaml:"minIdleConns,omitempty"`
// MaxRetries is the maximum number of retries before giving up
MaxRetries int `json:"maxRetries,omitempty" yaml:"maxRetries,omitempty"`
// === Timeouts ===
// DialTimeout is the timeout for establishing new connections
DialTimeout time.Duration `json:"dialTimeout,omitempty" yaml:"dialTimeout,omitempty"`
// ReadTimeout is the timeout for socket reads
ReadTimeout time.Duration `json:"readTimeout,omitempty" yaml:"readTimeout,omitempty"`
// WriteTimeout is the timeout for socket writes
WriteTimeout time.Duration `json:"writeTimeout,omitempty" yaml:"writeTimeout,omitempty"`
// PoolTimeout is the timeout for connection pool
PoolTimeout time.Duration `json:"poolTimeout,omitempty" yaml:"poolTimeout,omitempty"`
// ConnMaxIdleTime is the maximum amount of time a connection may be idle
ConnMaxIdleTime time.Duration `json:"connMaxIdleTime,omitempty" yaml:"connMaxIdleTime,omitempty"`
// ConnMaxLifetime is the maximum lifetime of a connection
ConnMaxLifetime time.Duration `json:"connMaxLifetime,omitempty" yaml:"connMaxLifetime,omitempty"`
// === Key Management ===
// KeyPrefix is the prefix for all Redis keys
KeyPrefix string `json:"keyPrefix,omitempty" yaml:"keyPrefix,omitempty"`
// === TLS Configuration ===
// TLSEnabled enables TLS for Redis connections
TLSEnabled bool `json:"tlsEnabled,omitempty" yaml:"tlsEnabled,omitempty"`
// TLSInsecureSkipVerify skips TLS certificate verification
TLSInsecureSkipVerify bool `json:"tlsInsecureSkipVerify,omitempty" yaml:"tlsInsecureSkipVerify,omitempty"`
// === Resilience Settings ===
// EnableCircuitBreaker enables circuit breaker for Redis operations
EnableCircuitBreaker bool `json:"enableCircuitBreaker,omitempty" yaml:"enableCircuitBreaker,omitempty"`
// CircuitBreakerMaxFailures is the number of failures before opening circuit
CircuitBreakerMaxFailures int `json:"circuitBreakerMaxFailures,omitempty" yaml:"circuitBreakerMaxFailures,omitempty"`
// CircuitBreakerTimeout is how long the circuit stays open
CircuitBreakerTimeout time.Duration `json:"circuitBreakerTimeout,omitempty" yaml:"circuitBreakerTimeout,omitempty"`
// EnableHealthCheck enables periodic health checks
EnableHealthCheck bool `json:"enableHealthCheck,omitempty" yaml:"enableHealthCheck,omitempty"`
// HealthCheckInterval is how often to check Redis health
HealthCheckInterval time.Duration `json:"healthCheckInterval,omitempty" yaml:"healthCheckInterval,omitempty"`
}
// DefaultRedisConfig returns default Redis configuration
func DefaultRedisConfig() *RedisConfig {
return &RedisConfig{
Enabled: false,
Mode: RedisModeStandalone,
Addr: "localhost:6379",
DB: 0,
PoolSize: 10,
MinIdleConns: 2,
MaxRetries: 3,
DialTimeout: 5 * time.Second,
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
PoolTimeout: 4 * time.Second,
ConnMaxIdleTime: 5 * time.Minute,
ConnMaxLifetime: 30 * time.Minute,
KeyPrefix: "traefikoidc:",
TLSEnabled: false,
TLSInsecureSkipVerify: false,
EnableCircuitBreaker: true,
CircuitBreakerMaxFailures: 5,
CircuitBreakerTimeout: 30 * time.Second,
EnableHealthCheck: true,
HealthCheckInterval: 30 * time.Second,
}
}
// LoadFromEnv loads Redis configuration from environment variables
func (c *RedisConfig) LoadFromEnv() {
// Enable Redis if environment variable is set
if enabled := os.Getenv("REDIS_ENABLED"); enabled != "" {
c.Enabled = strings.ToLower(enabled) == "true"
}
// Mode
if mode := os.Getenv("REDIS_MODE"); mode != "" {
c.Mode = RedisMode(strings.ToLower(mode))
}
// Standalone configuration
if addr := os.Getenv("REDIS_ADDR"); addr != "" {
c.Addr = addr
}
if password := os.Getenv("REDIS_PASSWORD"); password != "" {
c.Password = password
}
if db := os.Getenv("REDIS_DB"); db != "" {
if dbNum, err := strconv.Atoi(db); err == nil {
c.DB = dbNum
}
}
// Cluster configuration
if clusterAddrs := os.Getenv("REDIS_CLUSTER_ADDRS"); clusterAddrs != "" {
c.ClusterAddrs = strings.Split(clusterAddrs, ",")
for i := range c.ClusterAddrs {
c.ClusterAddrs[i] = strings.TrimSpace(c.ClusterAddrs[i])
}
}
// Sentinel configuration
if masterName := os.Getenv("REDIS_MASTER_NAME"); masterName != "" {
c.MasterName = masterName
}
if sentinelAddrs := os.Getenv("REDIS_SENTINEL_ADDRS"); sentinelAddrs != "" {
c.SentinelAddrs = strings.Split(sentinelAddrs, ",")
for i := range c.SentinelAddrs {
c.SentinelAddrs[i] = strings.TrimSpace(c.SentinelAddrs[i])
}
}
if sentinelPassword := os.Getenv("REDIS_SENTINEL_PASSWORD"); sentinelPassword != "" {
c.SentinelPassword = sentinelPassword
}
// Connection pool settings
if poolSize := os.Getenv("REDIS_POOL_SIZE"); poolSize != "" {
if size, err := strconv.Atoi(poolSize); err == nil {
c.PoolSize = size
}
}
if minIdleConns := os.Getenv("REDIS_MIN_IDLE_CONNS"); minIdleConns != "" {
if conns, err := strconv.Atoi(minIdleConns); err == nil {
c.MinIdleConns = conns
}
}
if maxRetries := os.Getenv("REDIS_MAX_RETRIES"); maxRetries != "" {
if retries, err := strconv.Atoi(maxRetries); err == nil {
c.MaxRetries = retries
}
}
// Timeouts
if dialTimeout := os.Getenv("REDIS_DIAL_TIMEOUT"); dialTimeout != "" {
if timeout, err := time.ParseDuration(dialTimeout); err == nil {
c.DialTimeout = timeout
}
}
if readTimeout := os.Getenv("REDIS_READ_TIMEOUT"); readTimeout != "" {
if timeout, err := time.ParseDuration(readTimeout); err == nil {
c.ReadTimeout = timeout
}
}
if writeTimeout := os.Getenv("REDIS_WRITE_TIMEOUT"); writeTimeout != "" {
if timeout, err := time.ParseDuration(writeTimeout); err == nil {
c.WriteTimeout = timeout
}
}
// Key prefix
if keyPrefix := os.Getenv("REDIS_KEY_PREFIX"); keyPrefix != "" {
c.KeyPrefix = keyPrefix
}
// TLS settings
if tlsEnabled := os.Getenv("REDIS_TLS_ENABLED"); tlsEnabled != "" {
c.TLSEnabled = strings.ToLower(tlsEnabled) == "true"
}
if tlsInsecure := os.Getenv("REDIS_TLS_INSECURE_SKIP_VERIFY"); tlsInsecure != "" {
c.TLSInsecureSkipVerify = strings.ToLower(tlsInsecure) == "true"
}
// Resilience settings
if enableCB := os.Getenv("REDIS_ENABLE_CIRCUIT_BREAKER"); enableCB != "" {
c.EnableCircuitBreaker = strings.ToLower(enableCB) == "true"
}
if cbMaxFailures := os.Getenv("REDIS_CIRCUIT_BREAKER_MAX_FAILURES"); cbMaxFailures != "" {
if failures, err := strconv.Atoi(cbMaxFailures); err == nil {
c.CircuitBreakerMaxFailures = failures
}
}
if cbTimeout := os.Getenv("REDIS_CIRCUIT_BREAKER_TIMEOUT"); cbTimeout != "" {
if timeout, err := time.ParseDuration(cbTimeout); err == nil {
c.CircuitBreakerTimeout = timeout
}
}
if enableHC := os.Getenv("REDIS_ENABLE_HEALTH_CHECK"); enableHC != "" {
c.EnableHealthCheck = strings.ToLower(enableHC) == "true"
}
if hcInterval := os.Getenv("REDIS_HEALTH_CHECK_INTERVAL"); hcInterval != "" {
if interval, err := time.ParseDuration(hcInterval); err == nil {
c.HealthCheckInterval = interval
}
}
}
// Validate checks if the configuration is valid
func (c *RedisConfig) Validate() error {
if !c.Enabled {
return nil
}
switch c.Mode {
case RedisModeStandalone:
if c.Addr == "" {
return &ConfigError{Field: "addr", Message: "Redis address is required for standalone mode"}
}
case RedisModeCluster:
if len(c.ClusterAddrs) == 0 {
return &ConfigError{Field: "clusterAddrs", Message: "At least one cluster address is required"}
}
case RedisModeSentinel:
if c.MasterName == "" {
return &ConfigError{Field: "masterName", Message: "Master name is required for sentinel mode"}
}
if len(c.SentinelAddrs) == 0 {
return &ConfigError{Field: "sentinelAddrs", Message: "At least one sentinel address is required"}
}
default:
return &ConfigError{Field: "mode", Message: "Invalid Redis mode"}
}
return nil
}
// ConfigError represents a configuration validation error
type ConfigError struct {
Field string
Message string
}
// Error implements the error interface
func (e *ConfigError) Error() string {
return "redis config error: " + e.Field + ": " + e.Message
}
+287
View File
@@ -0,0 +1,287 @@
// Package config provides unified configuration management for the OIDC middleware
package config
import (
"time"
)
// UnifiedConfig is the master configuration structure consolidating all config aspects
// This replaces 45 duplicate config structs across the codebase
type UnifiedConfig struct {
// Core Configuration
Provider ProviderConfig `json:"provider" yaml:"provider"`
Session SessionConfig `json:"session" yaml:"session"`
Token TokenConfig `json:"token" yaml:"token"`
Redis RedisConfig `json:"redis" yaml:"redis"`
Security SecurityConfig `json:"security" yaml:"security"`
// Middleware Configuration
Middleware MiddlewareConfig `json:"middleware" yaml:"middleware"`
Cache CacheConfig `json:"cache" yaml:"cache"`
RateLimit RateLimitConfig `json:"rateLimit" yaml:"rateLimit"`
// Operational Configuration
Logging LoggingConfig `json:"logging" yaml:"logging"`
Metrics MetricsConfig `json:"metrics" yaml:"metrics"`
Health HealthConfig `json:"health" yaml:"health"`
// Advanced Configuration
Transport TransportConfig `json:"transport" yaml:"transport"`
Pool PoolConfig `json:"pool" yaml:"pool"`
Circuit CircuitConfig `json:"circuit" yaml:"circuit"`
// Compatibility field for migration
Legacy map[string]interface{} `json:"-" yaml:"-"`
}
// ProviderConfig contains OIDC provider settings
type ProviderConfig struct {
IssuerURL string `json:"issuerURL" yaml:"issuerURL"`
ClientID string `json:"clientID" yaml:"clientID"`
ClientSecret string `json:"clientSecret" yaml:"clientSecret"`
RedirectURL string `json:"redirectURL" yaml:"redirectURL"`
LogoutURL string `json:"logoutURL" yaml:"logoutURL"`
PostLogoutRedirectURI string `json:"postLogoutRedirectURI" yaml:"postLogoutRedirectURI"`
Scopes []string `json:"scopes" yaml:"scopes"`
OverrideScopes bool `json:"overrideScopes" yaml:"overrideScopes"`
CustomClaims map[string]string `json:"customClaims" yaml:"customClaims"`
JWKCachePeriod time.Duration `json:"jwkCachePeriod" yaml:"jwkCachePeriod"`
MetadataCacheTTL time.Duration `json:"metadataCacheTTL" yaml:"metadataCacheTTL"`
Discovery bool `json:"discovery" yaml:"discovery"`
// Provider-specific endpoints
AuthorizationEndpoint string `json:"authorizationEndpoint,omitempty" yaml:"authorizationEndpoint,omitempty"`
TokenEndpoint string `json:"tokenEndpoint,omitempty" yaml:"tokenEndpoint,omitempty"`
UserInfoEndpoint string `json:"userInfoEndpoint,omitempty" yaml:"userInfoEndpoint,omitempty"`
JWKSEndpoint string `json:"jwksEndpoint,omitempty" yaml:"jwksEndpoint,omitempty"`
IntrospectEndpoint string `json:"introspectEndpoint,omitempty" yaml:"introspectEndpoint,omitempty"`
RevocationEndpoint string `json:"revocationEndpoint,omitempty" yaml:"revocationEndpoint,omitempty"`
}
// SessionConfig contains session management settings
type SessionConfig struct {
Name string `json:"name" yaml:"name"`
MaxAge int `json:"maxAge" yaml:"maxAge"`
Secret string `json:"secret" yaml:"secret"`
EncryptionKey string `json:"encryptionKey" yaml:"encryptionKey"`
SigningKey string `json:"signingKey" yaml:"signingKey"`
ChunkSize int `json:"chunkSize" yaml:"chunkSize"`
MaxChunks int `json:"maxChunks" yaml:"maxChunks"`
// Cookie settings
Domain string `json:"domain" yaml:"domain"`
Path string `json:"path" yaml:"path"`
Secure bool `json:"secure" yaml:"secure"`
HttpOnly bool `json:"httpOnly" yaml:"httpOnly"`
SameSite string `json:"sameSite" yaml:"sameSite"`
CookiePrefix string `json:"cookiePrefix" yaml:"cookiePrefix"` // Prefix for cookie names (e.g., "_oidc_myapp_")
// Storage settings
StorageType string `json:"storageType" yaml:"storageType"` // "memory", "redis", "cookie"
CleanupInterval time.Duration `json:"cleanupInterval" yaml:"cleanupInterval"`
}
// TokenConfig contains token handling settings
type TokenConfig struct {
AccessTokenTTL time.Duration `json:"accessTokenTTL" yaml:"accessTokenTTL"`
RefreshTokenTTL time.Duration `json:"refreshTokenTTL" yaml:"refreshTokenTTL"`
RefreshGracePeriod time.Duration `json:"refreshGracePeriod" yaml:"refreshGracePeriod"`
ValidationMode string `json:"validationMode" yaml:"validationMode"` // "jwt", "introspect", "hybrid"
IntrospectURL string `json:"introspectURL" yaml:"introspectURL"`
// Token caching
CacheEnabled bool `json:"cacheEnabled" yaml:"cacheEnabled"`
CacheTTL time.Duration `json:"cacheTTL" yaml:"cacheTTL"`
CacheNegativeTTL time.Duration `json:"cacheNegativeTTL" yaml:"cacheNegativeTTL"`
// Token validation
ValidateSignature bool `json:"validateSignature" yaml:"validateSignature"`
ValidateExpiry bool `json:"validateExpiry" yaml:"validateExpiry"`
ValidateAudience bool `json:"validateAudience" yaml:"validateAudience"`
ValidateIssuer bool `json:"validateIssuer" yaml:"validateIssuer"`
RequiredClaims []string `json:"requiredClaims" yaml:"requiredClaims"`
ClockSkew time.Duration `json:"clockSkew" yaml:"clockSkew"`
}
// SecurityConfig contains security-related settings
type SecurityConfig struct {
ForceHTTPS bool `json:"forceHTTPS" yaml:"forceHTTPS"`
EnablePKCE bool `json:"enablePKCE" yaml:"enablePKCE"`
AllowedUsers []string `json:"allowedUsers" yaml:"allowedUsers"`
AllowedUserDomains []string `json:"allowedUserDomains" yaml:"allowedUserDomains"`
AllowedRolesAndGroups []string `json:"allowedRolesAndGroups" yaml:"allowedRolesAndGroups"`
ExcludedURLs []string `json:"excludedURLs" yaml:"excludedURLs"`
Headers *SecurityHeadersConfig `json:"headers" yaml:"headers"`
// CSRF protection
CSRFProtection bool `json:"csrfProtection" yaml:"csrfProtection"`
CSRFTokenName string `json:"csrfTokenName" yaml:"csrfTokenName"`
CSRFTokenTTL time.Duration `json:"csrfTokenTTL" yaml:"csrfTokenTTL"`
// Additional security
MaxLoginAttempts int `json:"maxLoginAttempts" yaml:"maxLoginAttempts"`
LockoutDuration time.Duration `json:"lockoutDuration" yaml:"lockoutDuration"`
RequireMFA bool `json:"requireMFA" yaml:"requireMFA"`
}
// MiddlewareConfig contains middleware-specific settings
type MiddlewareConfig struct {
Priority int `json:"priority" yaml:"priority"`
SkipPaths []string `json:"skipPaths" yaml:"skipPaths"`
RequirePaths []string `json:"requirePaths" yaml:"requirePaths"`
PassthroughMode bool `json:"passthroughMode" yaml:"passthroughMode"`
// Request handling
MaxRequestSize int64 `json:"maxRequestSize" yaml:"maxRequestSize"`
RequestTimeout time.Duration `json:"requestTimeout" yaml:"requestTimeout"`
IdleTimeout time.Duration `json:"idleTimeout" yaml:"idleTimeout"`
// Response handling
CustomHeaders map[string]string `json:"customHeaders" yaml:"customHeaders"`
RemoveHeaders []string `json:"removeHeaders" yaml:"removeHeaders"`
}
// CacheConfig contains cache configuration
type CacheConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Type string `json:"type" yaml:"type"` // "memory", "redis", "hybrid"
DefaultTTL time.Duration `json:"defaultTTL" yaml:"defaultTTL"`
MaxEntries int `json:"maxEntries" yaml:"maxEntries"`
MaxEntrySize int64 `json:"maxEntrySize" yaml:"maxEntrySize"`
EvictionPolicy string `json:"evictionPolicy" yaml:"evictionPolicy"` // "lru", "lfu", "fifo"
// Memory cache settings
CleanupInterval time.Duration `json:"cleanupInterval" yaml:"cleanupInterval"`
// Distributed cache settings
Namespace string `json:"namespace" yaml:"namespace"`
Compression bool `json:"compression" yaml:"compression"`
Serialization string `json:"serialization" yaml:"serialization"` // "json", "msgpack", "protobuf"
}
// RateLimitConfig contains rate limiting configuration
type RateLimitConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
RequestsPerSecond int `json:"requestsPerSecond" yaml:"requestsPerSecond"`
Burst int `json:"burst" yaml:"burst"`
// Rate limit storage
StorageType string `json:"storageType" yaml:"storageType"` // "memory", "redis"
WindowDuration time.Duration `json:"windowDuration" yaml:"windowDuration"`
// Rate limit keys
KeyType string `json:"keyType" yaml:"keyType"` // "ip", "user", "token", "custom"
CustomKeyFunc string `json:"customKeyFunc" yaml:"customKeyFunc"`
// Whitelisting
WhitelistIPs []string `json:"whitelistIPs" yaml:"whitelistIPs"`
WhitelistUsers []string `json:"whitelistUsers" yaml:"whitelistUsers"`
}
// LoggingConfig contains logging configuration
type LoggingConfig struct {
Level string `json:"level" yaml:"level"` // "debug", "info", "warn", "error"
Format string `json:"format" yaml:"format"` // "json", "text", "structured"
Output string `json:"output" yaml:"output"` // "stdout", "stderr", "file"
FilePath string `json:"filePath" yaml:"filePath"`
// Log filtering
FilterSensitive bool `json:"filterSensitive" yaml:"filterSensitive"`
MaskFields []string `json:"maskFields" yaml:"maskFields"`
// Performance
BufferSize int `json:"bufferSize" yaml:"bufferSize"`
FlushInterval time.Duration `json:"flushInterval" yaml:"flushInterval"`
// Audit logging
AuditEnabled bool `json:"auditEnabled" yaml:"auditEnabled"`
AuditEvents []string `json:"auditEvents" yaml:"auditEvents"`
}
// MetricsConfig contains metrics collection configuration
type MetricsConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Provider string `json:"provider" yaml:"provider"` // "prometheus", "statsd", "otlp"
Endpoint string `json:"endpoint" yaml:"endpoint"`
Namespace string `json:"namespace" yaml:"namespace"`
Subsystem string `json:"subsystem" yaml:"subsystem"`
// Collection settings
CollectInterval time.Duration `json:"collectInterval" yaml:"collectInterval"`
Histograms bool `json:"histograms" yaml:"histograms"`
// Custom labels
Labels map[string]string `json:"labels" yaml:"labels"`
}
// HealthConfig contains health check configuration
type HealthConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Path string `json:"path" yaml:"path"`
CheckInterval time.Duration `json:"checkInterval" yaml:"checkInterval"`
Timeout time.Duration `json:"timeout" yaml:"timeout"`
// Checks to perform
CheckProvider bool `json:"checkProvider" yaml:"checkProvider"`
CheckRedis bool `json:"checkRedis" yaml:"checkRedis"`
CheckCache bool `json:"checkCache" yaml:"checkCache"`
// Thresholds
MaxLatency time.Duration `json:"maxLatency" yaml:"maxLatency"`
MinMemory int64 `json:"minMemory" yaml:"minMemory"`
}
// TransportConfig contains HTTP transport configuration
type TransportConfig struct {
MaxIdleConns int `json:"maxIdleConns" yaml:"maxIdleConns"`
MaxIdleConnsPerHost int `json:"maxIdleConnsPerHost" yaml:"maxIdleConnsPerHost"`
MaxConnsPerHost int `json:"maxConnsPerHost" yaml:"maxConnsPerHost"`
IdleConnTimeout time.Duration `json:"idleConnTimeout" yaml:"idleConnTimeout"`
TLSHandshakeTimeout time.Duration `json:"tlsHandshakeTimeout" yaml:"tlsHandshakeTimeout"`
ExpectContinueTimeout time.Duration `json:"expectContinueTimeout" yaml:"expectContinueTimeout"`
ResponseHeaderTimeout time.Duration `json:"responseHeaderTimeout" yaml:"responseHeaderTimeout"`
DisableKeepAlives bool `json:"disableKeepAlives" yaml:"disableKeepAlives"`
DisableCompression bool `json:"disableCompression" yaml:"disableCompression"`
// TLS configuration
TLSInsecureSkipVerify bool `json:"tlsInsecureSkipVerify" yaml:"tlsInsecureSkipVerify"`
TLSMinVersion string `json:"tlsMinVersion" yaml:"tlsMinVersion"`
TLSCipherSuites []string `json:"tlsCipherSuites" yaml:"tlsCipherSuites"`
// Proxy settings
ProxyURL string `json:"proxyURL" yaml:"proxyURL"`
NoProxy []string `json:"noProxy" yaml:"noProxy"`
}
// PoolConfig contains connection pool configuration
type PoolConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Size int `json:"size" yaml:"size"`
MinSize int `json:"minSize" yaml:"minSize"`
MaxSize int `json:"maxSize" yaml:"maxSize"`
MaxAge time.Duration `json:"maxAge" yaml:"maxAge"`
IdleTimeout time.Duration `json:"idleTimeout" yaml:"idleTimeout"`
WaitTimeout time.Duration `json:"waitTimeout" yaml:"waitTimeout"`
// Health checking
HealthCheckInterval time.Duration `json:"healthCheckInterval" yaml:"healthCheckInterval"`
MaxRetries int `json:"maxRetries" yaml:"maxRetries"`
}
// CircuitConfig contains circuit breaker configuration
type CircuitConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
MaxRequests uint32 `json:"maxRequests" yaml:"maxRequests"`
Interval time.Duration `json:"interval" yaml:"interval"`
Timeout time.Duration `json:"timeout" yaml:"timeout"`
ConsecutiveFailures uint32 `json:"consecutiveFailures" yaml:"consecutiveFailures"`
FailureRatio float64 `json:"failureRatio" yaml:"failureRatio"`
// Circuit states
OnOpen string `json:"onOpen" yaml:"onOpen"` // "reject", "fallback", "passthrough"
OnHalfOpen string `json:"onHalfOpen" yaml:"onHalfOpen"`
// Monitoring
MetricsEnabled bool `json:"metricsEnabled" yaml:"metricsEnabled"`
LogStateChanges bool `json:"logStateChanges" yaml:"logStateChanges"`
}
+263
View File
@@ -0,0 +1,263 @@
//go:build !yaegi
package config
import (
"encoding/json"
"strings"
"testing"
"gopkg.in/yaml.v3"
)
// TestUnifiedConfigJSONMarshalling tests JSON marshalling with secret redaction
func TestUnifiedConfigJSONMarshalling(t *testing.T) {
config := &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://auth.example.com",
ClientID: "test-client",
ClientSecret: "super-secret-value",
},
Session: SessionConfig{
Secret: "session-secret",
EncryptionKey: "32-character-encryption-key-here",
SigningKey: "signing-key-secret",
},
Redis: RedisConfig{
Password: "redis-password",
SentinelPassword: "sentinel-password",
},
}
// Marshal to JSON
jsonBytes, err := json.Marshal(config)
if err != nil {
t.Fatalf("Failed to marshal config to JSON: %v", err)
}
jsonStr := string(jsonBytes)
// Verify secrets are redacted
if !contains(jsonStr, `"clientSecret":"[REDACTED]"`) {
t.Error("ClientSecret should be redacted in JSON output")
}
if !contains(jsonStr, `"secret":"[REDACTED]"`) {
t.Error("Session.Secret should be redacted in JSON output")
}
if !contains(jsonStr, `"encryptionKey":"[REDACTED]"`) {
t.Error("Session.EncryptionKey should be redacted in JSON output")
}
if !contains(jsonStr, `"signingKey":"[REDACTED]"`) {
t.Error("Session.SigningKey should be redacted in JSON output")
}
if !contains(jsonStr, `"password":"[REDACTED]"`) {
t.Error("Redis.Password should be redacted in JSON output")
}
if !contains(jsonStr, `"sentinelPassword":"[REDACTED]"`) {
t.Error("Redis.SentinelPassword should be redacted in JSON output")
}
// Verify non-secret fields are preserved
if !contains(jsonStr, `"issuerURL":"https://auth.example.com"`) {
t.Error("IssuerURL should be preserved in JSON output")
}
if !contains(jsonStr, `"clientID":"test-client"`) {
t.Error("ClientID should be preserved in JSON output")
}
}
// TestUnifiedConfigYAMLMarshalling tests YAML marshalling with secret redaction
func TestUnifiedConfigYAMLMarshalling(t *testing.T) {
config := &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://auth.example.com",
ClientID: "test-client",
ClientSecret: "super-secret-value",
},
Session: SessionConfig{
Secret: "session-secret",
EncryptionKey: "32-character-encryption-key-here",
SigningKey: "signing-key-secret",
},
Redis: RedisConfig{
Password: "redis-password",
SentinelPassword: "sentinel-password",
},
}
// Marshal to YAML
yamlBytes, err := yaml.Marshal(config)
if err != nil {
t.Fatalf("Failed to marshal config to YAML: %v", err)
}
yamlStr := string(yamlBytes)
// Verify secrets are redacted
if !contains(yamlStr, "clientSecret: '[REDACTED]'") {
t.Error("ClientSecret should be redacted in YAML output")
}
if !contains(yamlStr, "secret: '[REDACTED]'") {
t.Error("Session.Secret should be redacted in YAML output")
}
if !contains(yamlStr, "encryptionKey: '[REDACTED]'") {
t.Error("Session.EncryptionKey should be redacted in YAML output")
}
if !contains(yamlStr, "signingKey: '[REDACTED]'") {
t.Error("Session.SigningKey should be redacted in YAML output")
}
if !contains(yamlStr, "password: '[REDACTED]'") {
t.Error("Redis.Password should be redacted in YAML output")
}
if !contains(yamlStr, "sentinelPassword: '[REDACTED]'") {
t.Error("Redis.SentinelPassword should be redacted in YAML output")
}
// Verify non-secret fields are preserved
if !contains(yamlStr, "issuerURL: https://auth.example.com") {
t.Error("IssuerURL should be preserved in YAML output")
}
if !contains(yamlStr, "clientID: test-client") {
t.Error("ClientID should be preserved in YAML output")
}
}
// TestProviderConfigMarshalling tests individual struct marshalling
func TestProviderConfigMarshalling(t *testing.T) {
provider := ProviderConfig{
IssuerURL: "https://auth.example.com",
ClientID: "test-client",
ClientSecret: "super-secret-value",
}
// Test JSON marshalling
jsonBytes, err := json.Marshal(provider)
if err != nil {
t.Fatalf("Failed to marshal ProviderConfig to JSON: %v", err)
}
jsonStr := string(jsonBytes)
if !contains(jsonStr, `"clientSecret":"[REDACTED]"`) {
t.Error("ClientSecret should be redacted in JSON output")
}
if !contains(jsonStr, `"clientID":"test-client"`) {
t.Error("ClientID should be preserved in JSON output")
}
// Test YAML marshalling
yamlBytes, err := yaml.Marshal(provider)
if err != nil {
t.Fatalf("Failed to marshal ProviderConfig to YAML: %v", err)
}
yamlStr := string(yamlBytes)
if !contains(yamlStr, "clientSecret: '[REDACTED]'") {
t.Error("ClientSecret should be redacted in YAML output")
}
if !contains(yamlStr, "clientID: test-client") {
t.Error("ClientID should be preserved in YAML output")
}
}
// TestSessionConfigMarshalling tests session config marshalling
func TestSessionConfigMarshalling(t *testing.T) {
session := SessionConfig{
Name: "session-cookie",
Secret: "session-secret",
EncryptionKey: "32-character-encryption-key-here",
SigningKey: "signing-key-secret",
Domain: "example.com",
Secure: true,
}
// Test JSON marshalling
jsonBytes, err := json.Marshal(session)
if err != nil {
t.Fatalf("Failed to marshal SessionConfig to JSON: %v", err)
}
jsonStr := string(jsonBytes)
if !contains(jsonStr, `"secret":"[REDACTED]"`) {
t.Error("Secret should be redacted in JSON output")
}
if !contains(jsonStr, `"encryptionKey":"[REDACTED]"`) {
t.Error("EncryptionKey should be redacted in JSON output")
}
if !contains(jsonStr, `"signingKey":"[REDACTED]"`) {
t.Error("SigningKey should be redacted in JSON output")
}
if !contains(jsonStr, `"name":"session-cookie"`) {
t.Error("Name should be preserved in JSON output")
}
if !contains(jsonStr, `"domain":"example.com"`) {
t.Error("Domain should be preserved in JSON output")
}
}
// TestRedisConfigMarshalling tests Redis config marshalling
func TestRedisConfigMarshalling(t *testing.T) {
redis := RedisConfig{
Enabled: true,
Mode: RedisModeCluster,
Password: "redis-password",
SentinelPassword: "sentinel-password",
Addr: "localhost:6379",
DB: 1,
}
// Test JSON marshalling
jsonBytes, err := json.Marshal(redis)
if err != nil {
t.Fatalf("Failed to marshal RedisConfig to JSON: %v", err)
}
jsonStr := string(jsonBytes)
if !contains(jsonStr, `"password":"[REDACTED]"`) {
t.Error("Password should be redacted in JSON output")
}
if !contains(jsonStr, `"sentinelPassword":"[REDACTED]"`) {
t.Error("SentinelPassword should be redacted in JSON output")
}
if !contains(jsonStr, `"addr":"localhost:6379"`) {
t.Error("Addr should be preserved in JSON output")
}
if !contains(jsonStr, `"db":1`) {
t.Error("DB should be preserved in JSON output")
}
}
// TestEmptySecretsNotRedacted tests that empty secrets are not shown as redacted
func TestEmptySecretsNotRedacted(t *testing.T) {
config := &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://auth.example.com",
ClientID: "test-client",
ClientSecret: "", // Empty secret
},
Session: SessionConfig{
Secret: "", // Empty secret
EncryptionKey: "", // Empty secret
},
Redis: RedisConfig{
Password: "", // Empty secret
},
}
// Marshal to JSON
jsonBytes, err := json.Marshal(config)
if err != nil {
t.Fatalf("Failed to marshal config to JSON: %v", err)
}
jsonStr := string(jsonBytes)
// Verify empty secrets are not shown as redacted
if contains(jsonStr, "[REDACTED]") {
t.Error("Empty secrets should not be shown as [REDACTED]")
}
}
// Helper function to check if string contains substring
func contains(s, substr string) bool {
return strings.Contains(s, substr)
}
+652
View File
@@ -0,0 +1,652 @@
// Package config provides validation for unified configuration
package config
import (
"fmt"
"net/url"
"regexp"
"strings"
"time"
)
// ValidationError represents a configuration validation error
type ValidationError struct {
Field string
Message string
Value interface{}
}
// Error implements the error interface
func (e *ValidationError) Error() string {
if e.Value != nil {
return fmt.Sprintf("config validation error: %s: %s (value: %v)", e.Field, e.Message, e.Value)
}
return fmt.Sprintf("config validation error: %s: %s", e.Field, e.Message)
}
// ValidationErrors represents multiple validation errors
type ValidationErrors []ValidationError
// Error implements the error interface
func (e ValidationErrors) Error() string {
if len(e) == 0 {
return ""
}
var messages []string
for _, err := range e {
messages = append(messages, err.Error())
}
return strings.Join(messages, "; ")
}
// Validate performs comprehensive validation on the unified configuration
func (c *UnifiedConfig) Validate() error {
var errors ValidationErrors
// Validate Provider configuration
if err := c.validateProvider(); err != nil {
errors = append(errors, err...)
}
// Validate Session configuration
if err := c.validateSession(); err != nil {
errors = append(errors, err...)
}
// Validate Token configuration
if err := c.validateToken(); err != nil {
errors = append(errors, err...)
}
// Validate Redis configuration (uses existing validation)
if err := c.Redis.Validate(); err != nil {
errors = append(errors, ValidationError{
Field: "Redis",
Message: err.Error(),
})
}
// Validate Security configuration
if err := c.validateSecurity(); err != nil {
errors = append(errors, err...)
}
// Validate Middleware configuration
if err := c.validateMiddleware(); err != nil {
errors = append(errors, err...)
}
// Validate Cache configuration
if err := c.validateCache(); err != nil {
errors = append(errors, err...)
}
// Validate RateLimit configuration
if err := c.validateRateLimit(); err != nil {
errors = append(errors, err...)
}
// Validate Logging configuration
if err := c.validateLogging(); err != nil {
errors = append(errors, err...)
}
// Validate Metrics configuration
if err := c.validateMetrics(); err != nil {
errors = append(errors, err...)
}
// Validate Transport configuration
if err := c.validateTransport(); err != nil {
errors = append(errors, err...)
}
// Validate Circuit configuration
if err := c.validateCircuit(); err != nil {
errors = append(errors, err...)
}
if len(errors) > 0 {
return errors
}
return nil
}
// validateProvider validates provider configuration
func (c *UnifiedConfig) validateProvider() ValidationErrors {
var errors ValidationErrors
// IssuerURL is required and must be a valid URL
if c.Provider.IssuerURL == "" {
errors = append(errors, ValidationError{
Field: "Provider.IssuerURL",
Message: "issuer URL is required",
})
} else if _, err := url.Parse(c.Provider.IssuerURL); err != nil {
errors = append(errors, ValidationError{
Field: "Provider.IssuerURL",
Message: "invalid issuer URL",
Value: c.Provider.IssuerURL,
})
}
// ClientID is required
if c.Provider.ClientID == "" {
errors = append(errors, ValidationError{
Field: "Provider.ClientID",
Message: "client ID is required",
})
}
// ClientSecret is required (except for public clients with PKCE)
if c.Provider.ClientSecret == "" && !c.Security.EnablePKCE {
errors = append(errors, ValidationError{
Field: "Provider.ClientSecret",
Message: "client secret is required (or enable PKCE for public clients)",
})
}
// RedirectURL must be valid if provided
if c.Provider.RedirectURL != "" {
if _, err := url.Parse(c.Provider.RedirectURL); err != nil {
errors = append(errors, ValidationError{
Field: "Provider.RedirectURL",
Message: "invalid redirect URL",
Value: c.Provider.RedirectURL,
})
}
}
// Scopes must include 'openid' for OIDC
hasOpenID := false
for _, scope := range c.Provider.Scopes {
if scope == "openid" {
hasOpenID = true
break
}
}
if !hasOpenID && !c.Provider.OverrideScopes {
errors = append(errors, ValidationError{
Field: "Provider.Scopes",
Message: "scopes must include 'openid' for OIDC",
Value: c.Provider.Scopes,
})
}
// JWK cache period must be positive
if c.Provider.JWKCachePeriod < 0 {
errors = append(errors, ValidationError{
Field: "Provider.JWKCachePeriod",
Message: "JWK cache period must be positive",
Value: c.Provider.JWKCachePeriod,
})
}
return errors
}
// validateSession validates session configuration
func (c *UnifiedConfig) validateSession() ValidationErrors {
var errors ValidationErrors
// Session name must not be empty
if c.Session.Name == "" {
errors = append(errors, ValidationError{
Field: "Session.Name",
Message: "session name is required",
})
}
// Session secret or encryption key is required
if c.Session.Secret == "" && c.Session.EncryptionKey == "" {
errors = append(errors, ValidationError{
Field: "Session",
Message: "either session secret or encryption key is required",
})
}
// Encryption key must be at least 32 bytes for security
if c.Session.EncryptionKey != "" && len(c.Session.EncryptionKey) < 32 {
errors = append(errors, ValidationError{
Field: "Session.EncryptionKey",
Message: "encryption key must be at least 32 characters for proper security",
Value: len(c.Session.EncryptionKey),
})
}
// ChunkSize must be reasonable (between 1KB and 10KB)
if c.Session.ChunkSize < 1000 || c.Session.ChunkSize > 10000 {
errors = append(errors, ValidationError{
Field: "Session.ChunkSize",
Message: "chunk size must be between 1000 and 10000 bytes",
Value: c.Session.ChunkSize,
})
}
// MaxChunks must be reasonable (between 1 and 100)
if c.Session.MaxChunks < 1 || c.Session.MaxChunks > 100 {
errors = append(errors, ValidationError{
Field: "Session.MaxChunks",
Message: "max chunks must be between 1 and 100",
Value: c.Session.MaxChunks,
})
}
// SameSite must be valid
validSameSite := map[string]bool{
"": true,
"Lax": true,
"Strict": true,
"None": true,
}
if !validSameSite[c.Session.SameSite] {
errors = append(errors, ValidationError{
Field: "Session.SameSite",
Message: "invalid SameSite value (must be Lax, Strict, or None)",
Value: c.Session.SameSite,
})
}
// StorageType must be valid
validStorage := map[string]bool{
"memory": true,
"redis": true,
"cookie": true,
}
if !validStorage[c.Session.StorageType] {
errors = append(errors, ValidationError{
Field: "Session.StorageType",
Message: "invalid storage type (must be memory, redis, or cookie)",
Value: c.Session.StorageType,
})
}
return errors
}
// validateToken validates token configuration
func (c *UnifiedConfig) validateToken() ValidationErrors {
var errors ValidationErrors
// Token TTLs must be positive
if c.Token.AccessTokenTTL <= 0 {
errors = append(errors, ValidationError{
Field: "Token.AccessTokenTTL",
Message: "access token TTL must be positive",
Value: c.Token.AccessTokenTTL,
})
}
if c.Token.RefreshTokenTTL <= 0 {
errors = append(errors, ValidationError{
Field: "Token.RefreshTokenTTL",
Message: "refresh token TTL must be positive",
Value: c.Token.RefreshTokenTTL,
})
}
// Validation mode must be valid
validModes := map[string]bool{
"jwt": true,
"introspect": true,
"hybrid": true,
}
if !validModes[c.Token.ValidationMode] {
errors = append(errors, ValidationError{
Field: "Token.ValidationMode",
Message: "invalid validation mode (must be jwt, introspect, or hybrid)",
Value: c.Token.ValidationMode,
})
}
// Introspect URL required for introspect or hybrid mode
if (c.Token.ValidationMode == "introspect" || c.Token.ValidationMode == "hybrid") && c.Token.IntrospectURL == "" {
errors = append(errors, ValidationError{
Field: "Token.IntrospectURL",
Message: "introspect URL is required for introspect or hybrid validation mode",
})
}
// Clock skew must be reasonable (0 to 10 minutes)
if c.Token.ClockSkew < 0 || c.Token.ClockSkew > 10*time.Minute {
errors = append(errors, ValidationError{
Field: "Token.ClockSkew",
Message: "clock skew must be between 0 and 10 minutes",
Value: c.Token.ClockSkew,
})
}
return errors
}
// validateSecurity validates security configuration
func (c *UnifiedConfig) validateSecurity() ValidationErrors {
var errors ValidationErrors
// Validate allowed user domains are valid domains
domainRegex := regexp.MustCompile(`^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.[a-zA-Z]{2,}$`)
for _, domain := range c.Security.AllowedUserDomains {
if !domainRegex.MatchString(domain) {
errors = append(errors, ValidationError{
Field: "Security.AllowedUserDomains",
Message: "invalid domain format",
Value: domain,
})
}
}
// Max login attempts must be reasonable
if c.Security.MaxLoginAttempts < 0 || c.Security.MaxLoginAttempts > 100 {
errors = append(errors, ValidationError{
Field: "Security.MaxLoginAttempts",
Message: "max login attempts must be between 0 and 100",
Value: c.Security.MaxLoginAttempts,
})
}
// Lockout duration must be reasonable
if c.Security.LockoutDuration < 0 || c.Security.LockoutDuration > 24*time.Hour {
errors = append(errors, ValidationError{
Field: "Security.LockoutDuration",
Message: "lockout duration must be between 0 and 24 hours",
Value: c.Security.LockoutDuration,
})
}
return errors
}
// validateMiddleware validates middleware configuration
func (c *UnifiedConfig) validateMiddleware() ValidationErrors {
var errors ValidationErrors
// Max request size must be reasonable (1KB to 100MB)
if c.Middleware.MaxRequestSize < 1024 || c.Middleware.MaxRequestSize > 100*1024*1024 {
errors = append(errors, ValidationError{
Field: "Middleware.MaxRequestSize",
Message: "max request size must be between 1KB and 100MB",
Value: c.Middleware.MaxRequestSize,
})
}
// Request timeout must be reasonable
if c.Middleware.RequestTimeout < time.Second || c.Middleware.RequestTimeout > 5*time.Minute {
errors = append(errors, ValidationError{
Field: "Middleware.RequestTimeout",
Message: "request timeout must be between 1 second and 5 minutes",
Value: c.Middleware.RequestTimeout,
})
}
return errors
}
// validateCache validates cache configuration
func (c *UnifiedConfig) validateCache() ValidationErrors {
var errors ValidationErrors
if !c.Cache.Enabled {
return errors
}
// Cache type must be valid
validTypes := map[string]bool{
"memory": true,
"redis": true,
"hybrid": true,
}
if !validTypes[c.Cache.Type] {
errors = append(errors, ValidationError{
Field: "Cache.Type",
Message: "invalid cache type (must be memory, redis, or hybrid)",
Value: c.Cache.Type,
})
}
// Max entries must be reasonable
if c.Cache.MaxEntries < 10 || c.Cache.MaxEntries > 1000000 {
errors = append(errors, ValidationError{
Field: "Cache.MaxEntries",
Message: "max entries must be between 10 and 1000000",
Value: c.Cache.MaxEntries,
})
}
// Eviction policy must be valid
validEviction := map[string]bool{
"lru": true,
"lfu": true,
"fifo": true,
}
if !validEviction[c.Cache.EvictionPolicy] {
errors = append(errors, ValidationError{
Field: "Cache.EvictionPolicy",
Message: "invalid eviction policy (must be lru, lfu, or fifo)",
Value: c.Cache.EvictionPolicy,
})
}
return errors
}
// validateRateLimit validates rate limiting configuration
func (c *UnifiedConfig) validateRateLimit() ValidationErrors {
var errors ValidationErrors
if !c.RateLimit.Enabled {
return errors
}
// Requests per second must be reasonable
if c.RateLimit.RequestsPerSecond < 1 || c.RateLimit.RequestsPerSecond > 10000 {
errors = append(errors, ValidationError{
Field: "RateLimit.RequestsPerSecond",
Message: "requests per second must be between 1 and 10000",
Value: c.RateLimit.RequestsPerSecond,
})
}
// Burst must be at least as large as requests per second
if c.RateLimit.Burst < c.RateLimit.RequestsPerSecond {
errors = append(errors, ValidationError{
Field: "RateLimit.Burst",
Message: "burst must be at least as large as requests per second",
Value: c.RateLimit.Burst,
})
}
// Key type must be valid
validKeyTypes := map[string]bool{
"ip": true,
"user": true,
"token": true,
"custom": true,
}
if !validKeyTypes[c.RateLimit.KeyType] {
errors = append(errors, ValidationError{
Field: "RateLimit.KeyType",
Message: "invalid key type (must be ip, user, token, or custom)",
Value: c.RateLimit.KeyType,
})
}
return errors
}
// validateLogging validates logging configuration
func (c *UnifiedConfig) validateLogging() ValidationErrors {
var errors ValidationErrors
// Log level must be valid
validLevels := map[string]bool{
"debug": true,
"info": true,
"warn": true,
"error": true,
}
if !validLevels[c.Logging.Level] {
errors = append(errors, ValidationError{
Field: "Logging.Level",
Message: "invalid log level (must be debug, info, warn, or error)",
Value: c.Logging.Level,
})
}
// Format must be valid
validFormats := map[string]bool{
"json": true,
"text": true,
"structured": true,
}
if !validFormats[c.Logging.Format] {
errors = append(errors, ValidationError{
Field: "Logging.Format",
Message: "invalid log format (must be json, text, or structured)",
Value: c.Logging.Format,
})
}
// Output must be valid
validOutputs := map[string]bool{
"stdout": true,
"stderr": true,
"file": true,
}
if !validOutputs[c.Logging.Output] {
errors = append(errors, ValidationError{
Field: "Logging.Output",
Message: "invalid log output (must be stdout, stderr, or file)",
Value: c.Logging.Output,
})
}
// File path required if output is file
if c.Logging.Output == "file" && c.Logging.FilePath == "" {
errors = append(errors, ValidationError{
Field: "Logging.FilePath",
Message: "file path is required when output is 'file'",
})
}
return errors
}
// validateMetrics validates metrics configuration
func (c *UnifiedConfig) validateMetrics() ValidationErrors {
var errors ValidationErrors
if !c.Metrics.Enabled {
return errors
}
// Provider must be valid
validProviders := map[string]bool{
"prometheus": true,
"statsd": true,
"otlp": true,
}
if !validProviders[c.Metrics.Provider] {
errors = append(errors, ValidationError{
Field: "Metrics.Provider",
Message: "invalid metrics provider (must be prometheus, statsd, or otlp)",
Value: c.Metrics.Provider,
})
}
// Endpoint required for some providers
if (c.Metrics.Provider == "statsd" || c.Metrics.Provider == "otlp") && c.Metrics.Endpoint == "" {
errors = append(errors, ValidationError{
Field: "Metrics.Endpoint",
Message: fmt.Sprintf("endpoint is required for %s provider", c.Metrics.Provider),
})
}
return errors
}
// validateTransport validates transport configuration
func (c *UnifiedConfig) validateTransport() ValidationErrors {
var errors ValidationErrors
// Max connections must be reasonable
if c.Transport.MaxIdleConns < 0 || c.Transport.MaxIdleConns > 10000 {
errors = append(errors, ValidationError{
Field: "Transport.MaxIdleConns",
Message: "max idle connections must be between 0 and 10000",
Value: c.Transport.MaxIdleConns,
})
}
// TLS min version must be valid
validTLSVersions := map[string]bool{
"TLS1.0": true,
"TLS1.1": true,
"TLS1.2": true,
"TLS1.3": true,
}
if c.Transport.TLSMinVersion != "" && !validTLSVersions[c.Transport.TLSMinVersion] {
errors = append(errors, ValidationError{
Field: "Transport.TLSMinVersion",
Message: "invalid TLS min version (must be TLS1.0, TLS1.1, TLS1.2, or TLS1.3)",
Value: c.Transport.TLSMinVersion,
})
}
// Proxy URL must be valid if provided
if c.Transport.ProxyURL != "" {
if _, err := url.Parse(c.Transport.ProxyURL); err != nil {
errors = append(errors, ValidationError{
Field: "Transport.ProxyURL",
Message: "invalid proxy URL",
Value: c.Transport.ProxyURL,
})
}
}
return errors
}
// validateCircuit validates circuit breaker configuration
func (c *UnifiedConfig) validateCircuit() ValidationErrors {
var errors ValidationErrors
if !c.Circuit.Enabled {
return errors
}
// Consecutive failures must be reasonable
if c.Circuit.ConsecutiveFailures < 1 || c.Circuit.ConsecutiveFailures > 100 {
errors = append(errors, ValidationError{
Field: "Circuit.ConsecutiveFailures",
Message: "consecutive failures must be between 1 and 100",
Value: c.Circuit.ConsecutiveFailures,
})
}
// Failure ratio must be between 0 and 1
if c.Circuit.FailureRatio < 0 || c.Circuit.FailureRatio > 1 {
errors = append(errors, ValidationError{
Field: "Circuit.FailureRatio",
Message: "failure ratio must be between 0 and 1",
Value: c.Circuit.FailureRatio,
})
}
// OnOpen action must be valid
validActions := map[string]bool{
"reject": true,
"fallback": true,
"passthrough": true,
}
if !validActions[c.Circuit.OnOpen] {
errors = append(errors, ValidationError{
Field: "Circuit.OnOpen",
Message: "invalid OnOpen action (must be reject, fallback, or passthrough)",
Value: c.Circuit.OnOpen,
})
}
return errors
}
+588
View File
@@ -0,0 +1,588 @@
//go:build !yaegi
package config
import (
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestValidateUnifiedConfig tests the validation of UnifiedConfig
func TestValidateUnifiedConfig(t *testing.T) {
tests := []struct {
name string
config *UnifiedConfig
expectError bool
errorField string
}{
{
name: "valid config with minimum requirements",
config: &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://auth.example.com",
ClientID: "test-client",
ClientSecret: "secret",
Scopes: []string{"openid", "profile", "email"},
},
Session: SessionConfig{
Name: "oidc_session",
EncryptionKey: "this-is-a-32-character-key-12345",
ChunkSize: 4000,
MaxChunks: 5,
StorageType: "cookie",
},
Token: TokenConfig{
AccessTokenTTL: time.Hour,
RefreshTokenTTL: 24 * time.Hour,
ValidationMode: "jwt",
},
Middleware: MiddlewareConfig{
MaxRequestSize: 10 * 1024 * 1024,
RequestTimeout: 30 * time.Second,
},
Logging: LoggingConfig{
Level: "info",
Format: "json",
Output: "stdout",
},
},
expectError: false,
},
{
name: "missing provider URL",
config: &UnifiedConfig{
Provider: ProviderConfig{
ClientID: "test-client",
ClientSecret: "secret",
},
Session: SessionConfig{
EncryptionKey: "this-is-a-32-character-key-12345",
},
},
expectError: true,
errorField: "Provider.IssuerURL",
},
{
name: "missing client ID",
config: &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://auth.example.com",
ClientSecret: "secret",
},
Session: SessionConfig{
EncryptionKey: "this-is-a-32-character-key-12345",
},
},
expectError: true,
errorField: "Provider.ClientID",
},
{
name: "encryption key too short",
config: &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://auth.example.com",
ClientID: "test-client",
ClientSecret: "secret",
},
Session: SessionConfig{
EncryptionKey: "too-short",
},
},
expectError: true,
errorField: "Session.EncryptionKey",
},
{
name: "invalid chunk size",
config: &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://auth.example.com",
ClientID: "test-client",
ClientSecret: "secret",
},
Session: SessionConfig{
EncryptionKey: "this-is-a-32-character-key-12345",
ChunkSize: 500, // Too small
},
},
expectError: true,
errorField: "Session.ChunkSize",
},
{
name: "invalid max chunks",
config: &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://auth.example.com",
ClientID: "test-client",
ClientSecret: "secret",
},
Session: SessionConfig{
EncryptionKey: "this-is-a-32-character-key-12345",
ChunkSize: 4000,
MaxChunks: 0, // Too small
},
},
expectError: true,
errorField: "Session.MaxChunks",
},
{
name: "invalid TLS min version",
config: &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://auth.example.com",
ClientID: "test-client",
ClientSecret: "secret",
},
Session: SessionConfig{
EncryptionKey: "this-is-a-32-character-key-12345",
},
Transport: TransportConfig{
TLSMinVersion: "1.0", // Too old
},
},
expectError: true,
errorField: "Transport.TLSMinVersion",
},
{
name: "invalid circuit breaker failure ratio",
config: &UnifiedConfig{
Provider: ProviderConfig{
IssuerURL: "https://auth.example.com",
ClientID: "test-client",
ClientSecret: "secret",
},
Session: SessionConfig{
EncryptionKey: "this-is-a-32-character-key-12345",
},
Circuit: CircuitConfig{
Enabled: true,
FailureRatio: 1.5, // Too high
},
},
expectError: true,
errorField: "Circuit.FailureRatio",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.config.Validate()
if tt.expectError {
if err == nil {
t.Errorf("Expected validation error for field %s, but got none", tt.errorField)
} else if validationErrs, ok := err.(ValidationErrors); ok {
found := false
for _, e := range validationErrs {
if e.Field == tt.errorField {
found = true
break
}
}
if !found {
t.Errorf("Expected validation error for field %s, but got errors for: %v",
tt.errorField, validationErrs)
}
}
} else {
if err != nil {
t.Errorf("Expected no validation error, but got: %v", err)
}
}
})
}
}
// TestValidationErrorMessage tests validation error formatting
func TestValidationErrorMessage(t *testing.T) {
errs := ValidationErrors{
{
Field: "Provider.IssuerURL",
Message: "is required",
Value: nil,
},
{
Field: "Session.EncryptionKey",
Message: "must be at least 32 characters",
Value: 16,
},
}
errMsg := errs.Error()
if !strings.Contains(errMsg, "Provider.IssuerURL") {
t.Error("Error message should contain field name Provider.IssuerURL")
}
if !strings.Contains(errMsg, "is required") {
t.Error("Error message should contain 'is required'")
}
if !strings.Contains(errMsg, "Session.EncryptionKey") {
t.Error("Error message should contain field name Session.EncryptionKey")
}
if !strings.Contains(errMsg, "must be at least 32 characters") {
t.Error("Error message should contain 'must be at least 32 characters'")
}
}
// TestValidateRedisConfig tests Redis configuration validation
func TestValidateRedisConfig(t *testing.T) {
tests := []struct {
name string
config *RedisConfig
expectError bool
errorMsg string
}{
{
name: "valid standalone config",
config: &RedisConfig{
Enabled: true,
Mode: RedisModeStandalone,
Addr: "localhost:6379",
},
expectError: false,
},
{
name: "missing address for standalone",
config: &RedisConfig{
Enabled: true,
Mode: RedisModeStandalone,
Addr: "",
},
expectError: true,
errorMsg: "Redis address is required",
},
{
name: "valid cluster config",
config: &RedisConfig{
Enabled: true,
Mode: RedisModeCluster,
ClusterAddrs: []string{"localhost:7000", "localhost:7001"},
},
expectError: false,
},
{
name: "missing cluster addresses",
config: &RedisConfig{
Enabled: true,
Mode: RedisModeCluster,
ClusterAddrs: []string{},
},
expectError: true,
errorMsg: "cluster address is required",
},
{
name: "valid sentinel config",
config: &RedisConfig{
Enabled: true,
Mode: RedisModeSentinel,
MasterName: "mymaster",
SentinelAddrs: []string{"localhost:26379"},
},
expectError: false,
},
{
name: "missing master name for sentinel",
config: &RedisConfig{
Enabled: true,
Mode: RedisModeSentinel,
MasterName: "",
SentinelAddrs: []string{"localhost:26379"},
},
expectError: true,
errorMsg: "Master name is required",
},
{
name: "missing sentinel addresses",
config: &RedisConfig{
Enabled: true,
Mode: RedisModeSentinel,
MasterName: "mymaster",
SentinelAddrs: []string{},
},
expectError: true,
errorMsg: "sentinel address is required",
},
{
name: "disabled redis needs no validation",
config: &RedisConfig{
Enabled: false,
},
expectError: false,
},
{
name: "invalid redis mode",
config: &RedisConfig{
Enabled: true,
Mode: "invalid-mode",
},
expectError: true,
errorMsg: "Invalid Redis mode",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.config.Validate()
if tt.expectError {
if err == nil {
t.Errorf("Expected validation error containing '%s', but got none", tt.errorMsg)
} else if !strings.Contains(err.Error(), tt.errorMsg) {
t.Errorf("Expected error message to contain '%s', but got: %v", tt.errorMsg, err)
}
} else {
if err != nil {
t.Errorf("Expected no validation error, but got: %v", err)
}
}
})
}
}
// ============================================================================
// validateRateLimit Tests
// ============================================================================
func TestValidateRateLimit_Disabled(t *testing.T) {
config := NewUnifiedConfig()
config.RateLimit.Enabled = false
errors := config.validateRateLimit()
assert.Empty(t, errors, "Should have no errors when rate limiting is disabled")
}
func TestValidateRateLimit_ValidConfig(t *testing.T) {
config := NewUnifiedConfig()
config.RateLimit.Enabled = true
config.RateLimit.RequestsPerSecond = 100
config.RateLimit.Burst = 200
config.RateLimit.KeyType = "ip"
errors := config.validateRateLimit()
assert.Empty(t, errors, "Should have no errors for valid rate limit config")
}
func TestValidateRateLimit_RequestsPerSecondTooLow(t *testing.T) {
config := NewUnifiedConfig()
config.RateLimit.Enabled = true
config.RateLimit.RequestsPerSecond = 0
config.RateLimit.Burst = 100
config.RateLimit.KeyType = "ip"
errors := config.validateRateLimit()
require.Len(t, errors, 1)
assert.Equal(t, "RateLimit.RequestsPerSecond", errors[0].Field)
assert.Contains(t, errors[0].Message, "between 1 and 10000")
}
func TestValidateRateLimit_RequestsPerSecondTooHigh(t *testing.T) {
config := NewUnifiedConfig()
config.RateLimit.Enabled = true
config.RateLimit.RequestsPerSecond = 15000
config.RateLimit.Burst = 20000
config.RateLimit.KeyType = "ip"
errors := config.validateRateLimit()
require.Len(t, errors, 1)
assert.Equal(t, "RateLimit.RequestsPerSecond", errors[0].Field)
assert.Contains(t, errors[0].Message, "between 1 and 10000")
}
func TestValidateRateLimit_BurstTooSmall(t *testing.T) {
config := NewUnifiedConfig()
config.RateLimit.Enabled = true
config.RateLimit.RequestsPerSecond = 100
config.RateLimit.Burst = 50 // Less than RequestsPerSecond
config.RateLimit.KeyType = "ip"
errors := config.validateRateLimit()
require.Len(t, errors, 1)
assert.Equal(t, "RateLimit.Burst", errors[0].Field)
assert.Contains(t, errors[0].Message, "at least as large as requests per second")
}
func TestValidateRateLimit_InvalidKeyType(t *testing.T) {
tests := []struct {
name string
keyType string
}{
{"empty key type", ""},
{"invalid key type", "invalid"},
{"random string", "foobar"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
config := NewUnifiedConfig()
config.RateLimit.Enabled = true
config.RateLimit.RequestsPerSecond = 100
config.RateLimit.Burst = 200
config.RateLimit.KeyType = tt.keyType
errors := config.validateRateLimit()
require.Len(t, errors, 1)
assert.Equal(t, "RateLimit.KeyType", errors[0].Field)
assert.Contains(t, errors[0].Message, "invalid key type")
})
}
}
func TestValidateRateLimit_ValidKeyTypes(t *testing.T) {
validKeyTypes := []string{"ip", "user", "token", "custom"}
for _, keyType := range validKeyTypes {
t.Run(keyType, func(t *testing.T) {
config := NewUnifiedConfig()
config.RateLimit.Enabled = true
config.RateLimit.RequestsPerSecond = 100
config.RateLimit.Burst = 200
config.RateLimit.KeyType = keyType
errors := config.validateRateLimit()
assert.Empty(t, errors, "Should have no errors for valid key type: %s", keyType)
})
}
}
func TestValidateRateLimit_MultipleErrors(t *testing.T) {
config := NewUnifiedConfig()
config.RateLimit.Enabled = true
config.RateLimit.RequestsPerSecond = 0 // Too low
config.RateLimit.Burst = 50 // Will pass (0 < 50)
config.RateLimit.KeyType = "invalid" // Invalid
errors := config.validateRateLimit()
// Should have 2 errors (rps and keyType)
assert.Len(t, errors, 2)
// Check each error is present
fields := make(map[string]bool)
for _, err := range errors {
fields[err.Field] = true
}
assert.True(t, fields["RateLimit.RequestsPerSecond"])
assert.True(t, fields["RateLimit.KeyType"])
}
// ============================================================================
// validateMetrics Tests
// ============================================================================
func TestValidateMetrics_Disabled(t *testing.T) {
config := NewUnifiedConfig()
config.Metrics.Enabled = false
errors := config.validateMetrics()
assert.Empty(t, errors, "Should have no errors when metrics are disabled")
}
func TestValidateMetrics_ValidPrometheus(t *testing.T) {
config := NewUnifiedConfig()
config.Metrics.Enabled = true
config.Metrics.Provider = "prometheus"
config.Metrics.Endpoint = "" // Prometheus doesn't require endpoint
errors := config.validateMetrics()
assert.Empty(t, errors, "Should have no errors for valid prometheus config")
}
func TestValidateMetrics_ValidStatsd(t *testing.T) {
config := NewUnifiedConfig()
config.Metrics.Enabled = true
config.Metrics.Provider = "statsd"
config.Metrics.Endpoint = "localhost:8125"
errors := config.validateMetrics()
assert.Empty(t, errors, "Should have no errors for valid statsd config")
}
func TestValidateMetrics_ValidOTLP(t *testing.T) {
config := NewUnifiedConfig()
config.Metrics.Enabled = true
config.Metrics.Provider = "otlp"
config.Metrics.Endpoint = "localhost:4317"
errors := config.validateMetrics()
assert.Empty(t, errors, "Should have no errors for valid otlp config")
}
func TestValidateMetrics_InvalidProvider(t *testing.T) {
tests := []struct {
name string
provider string
}{
{"empty provider", ""},
{"invalid provider", "invalid"},
{"datadog", "datadog"},
{"influx", "influx"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
config := NewUnifiedConfig()
config.Metrics.Enabled = true
config.Metrics.Provider = tt.provider
config.Metrics.Endpoint = "localhost:8080"
errors := config.validateMetrics()
require.Len(t, errors, 1)
assert.Equal(t, "Metrics.Provider", errors[0].Field)
assert.Contains(t, errors[0].Message, "invalid metrics provider")
})
}
}
func TestValidateMetrics_StatsdMissingEndpoint(t *testing.T) {
config := NewUnifiedConfig()
config.Metrics.Enabled = true
config.Metrics.Provider = "statsd"
config.Metrics.Endpoint = "" // Missing required endpoint
errors := config.validateMetrics()
require.Len(t, errors, 1)
assert.Equal(t, "Metrics.Endpoint", errors[0].Field)
assert.Contains(t, errors[0].Message, "endpoint is required for statsd provider")
}
func TestValidateMetrics_OTLPMissingEndpoint(t *testing.T) {
config := NewUnifiedConfig()
config.Metrics.Enabled = true
config.Metrics.Provider = "otlp"
config.Metrics.Endpoint = "" // Missing required endpoint
errors := config.validateMetrics()
require.Len(t, errors, 1)
assert.Equal(t, "Metrics.Endpoint", errors[0].Field)
assert.Contains(t, errors[0].Message, "endpoint is required for otlp provider")
}
func TestValidateMetrics_MultipleErrors(t *testing.T) {
config := NewUnifiedConfig()
config.Metrics.Enabled = true
config.Metrics.Provider = "invalid" // Invalid provider
config.Metrics.Endpoint = "" // Would be missing if provider was statsd/otlp
errors := config.validateMetrics()
// Should have at least 1 error for invalid provider
assert.NotEmpty(t, errors)
assert.Equal(t, "Metrics.Provider", errors[0].Field)
}