Documentation
ΒΆ
Overview ΒΆ
Package auth provides authentication and authorization utilities for AI providers. It includes API key management, OAuth flows, security helpers, and credential storage.
Package auth provides authentication and authorization utilities for AI providers. It includes API key management, OAuth flows, security helpers, and credential storage.
Index ΒΆ
- Constants
- func AuthConfigToProviderConfig(authConfig types.AuthConfig, providerType types.ProviderType) types.ProviderConfig
- func ProviderConfigToAuthConfig(providerConfig types.ProviderConfig) types.AuthConfig
- type APIKeyAuthenticator
- type APIKeyAuthenticatorImpl
- func (a *APIKeyAuthenticatorImpl) Authenticate(ctx context.Context, config types.AuthConfig) error
- func (a *APIKeyAuthenticatorImpl) GetAuthMethod() types.AuthMethod
- func (a *APIKeyAuthenticatorImpl) GetKeyManager() APIKeyManager
- func (a *APIKeyAuthenticatorImpl) GetToken() (string, error)
- func (a *APIKeyAuthenticatorImpl) IsAuthenticated() bool
- func (a *APIKeyAuthenticatorImpl) Logout(ctx context.Context) error
- func (a *APIKeyAuthenticatorImpl) RefreshToken(ctx context.Context) error
- func (a *APIKeyAuthenticatorImpl) ReportKeyFailure(key string, err error) error
- func (a *APIKeyAuthenticatorImpl) ReportKeySuccess(key string) error
- func (a *APIKeyAuthenticatorImpl) RotateKey() error
- type APIKeyConfig
- type APIKeyManager
- type APIKeyManagerImpl
- func (m *APIKeyManagerImpl) AddKey(key string) error
- func (m *APIKeyManagerImpl) ExecuteWithFailover(ctx context.Context, ...) (string, *types.Usage, error)
- func (m *APIKeyManagerImpl) ExecuteWithFailoverMessage(ctx context.Context, ...) (types.ChatMessage, *types.Usage, error)
- func (m *APIKeyManagerImpl) GetCurrentKey() string
- func (m *APIKeyManagerImpl) GetKeys() []string
- func (m *APIKeyManagerImpl) GetNextKey() (string, error)
- func (m *APIKeyManagerImpl) GetStatus() map[string]interface{}
- func (m *APIKeyManagerImpl) IsHealthy() bool
- func (m *APIKeyManagerImpl) RemoveKey(key string) error
- func (m *APIKeyManagerImpl) ReportFailure(key string, err error)
- func (m *APIKeyManagerImpl) ReportSuccess(key string)
- type AuthError
- type AuthFeatureFlags
- type AuthManager
- type AuthManagerBuilder
- func (b *AuthManagerBuilder) Build() (*AuthManagerImpl, error)
- func (b *AuthManagerBuilder) WithAuthenticator(provider string, authenticator Authenticator) *AuthManagerBuilder
- func (b *AuthManagerBuilder) WithConfig(config *Config) *AuthManagerBuilder
- func (b *AuthManagerBuilder) WithLogger(logger Logger) *AuthManagerBuilder
- func (b *AuthManagerBuilder) WithStorage(storage TokenStorage) *AuthManagerBuilder
- type AuthManagerImpl
- func (am *AuthManagerImpl) Authenticate(ctx context.Context, provider string, config types.AuthConfig) error
- func (am *AuthManagerImpl) CleanupExpired() error
- func (am *AuthManagerImpl) Close() error
- func (am *AuthManagerImpl) ForEachAuthenticated(ctx context.Context, ...) error
- func (am *AuthManagerImpl) GetAuthStatus() map[string]*AuthState
- func (am *AuthManagerImpl) GetAuthenticatedProviders() []string
- func (am *AuthManagerImpl) GetAuthenticator(provider string) (Authenticator, error)
- func (am *AuthManagerImpl) GetConfig() *Config
- func (am *AuthManagerImpl) GetProviders() []string
- func (am *AuthManagerImpl) GetStorage() TokenStorage
- func (am *AuthManagerImpl) GetTokenInfo(provider string) (*TokenInfo, error)
- func (am *AuthManagerImpl) HandleOAuthCallback(ctx context.Context, provider string, code, state string) error
- func (am *AuthManagerImpl) IsAuthenticated(provider string) bool
- func (am *AuthManagerImpl) Logout(ctx context.Context, provider string) error
- func (am *AuthManagerImpl) RefreshAllTokens(ctx context.Context) error
- func (am *AuthManagerImpl) RegisterAuthenticator(provider string, authenticator Authenticator) error
- func (am *AuthManagerImpl) RemoveAuthenticator(provider string) error
- func (am *AuthManagerImpl) SetLogger(logger Logger)
- func (am *AuthManagerImpl) StartOAuthFlow(ctx context.Context, provider string, scopes []string) (string, error)
- type AuthState
- type Authenticator
- type AuthenticatorFactory
- type BackoffConfig
- type BackupConfig
- type BearerTokenAuthenticatorImpl
- func (b *BearerTokenAuthenticatorImpl) Authenticate(ctx context.Context, config types.AuthConfig) error
- func (b *BearerTokenAuthenticatorImpl) GetAuthMethod() types.AuthMethod
- func (b *BearerTokenAuthenticatorImpl) GetToken() (string, error)
- func (b *BearerTokenAuthenticatorImpl) IsAuthenticated() bool
- func (b *BearerTokenAuthenticatorImpl) Logout(ctx context.Context) error
- func (b *BearerTokenAuthenticatorImpl) RefreshToken(ctx context.Context) error
- type CircuitBreakerConfig
- type Config
- type DefaultLogger
- type EncryptionConfig
- type FailoverConfig
- type FileStorageConfig
- type FileTokenStorage
- func (fts *FileTokenStorage) CleanupExpired() error
- func (fts *FileTokenStorage) Close() error
- func (fts *FileTokenStorage) DeleteToken(key string) error
- func (fts *FileTokenStorage) GetTokenInfo(key string) (*TokenMetadata, error)
- func (fts *FileTokenStorage) IsTokenValid(key string) bool
- func (fts *FileTokenStorage) ListTokens() ([]string, error)
- func (fts *FileTokenStorage) RetrieveToken(key string) (*types.OAuthConfig, error)
- func (fts *FileTokenStorage) StoreToken(key string, token *types.OAuthConfig) error
- type HTTPConfig
- type HealthConfig
- type KeyDerivationConfig
- type Logger
- type MemoryStorageConfig
- type MemoryTokenStorage
- func (mts *MemoryTokenStorage) CleanupExpired() error
- func (mts *MemoryTokenStorage) Close() error
- func (mts *MemoryTokenStorage) DeleteToken(key string) error
- func (mts *MemoryTokenStorage) GetTokenInfo(key string) (*TokenMetadata, error)
- func (mts *MemoryTokenStorage) IsTokenValid(key string) bool
- func (mts *MemoryTokenStorage) ListTokens() ([]string, error)
- func (mts *MemoryTokenStorage) RetrieveToken(key string) (*types.OAuthConfig, error)
- func (mts *MemoryTokenStorage) StoreToken(key string, token *types.OAuthConfig) error
- type OAuthAuthenticator
- type OAuthAuthenticatorImpl
- func (a *OAuthAuthenticatorImpl) Authenticate(ctx context.Context, config types.AuthConfig) error
- func (a *OAuthAuthenticatorImpl) GetAuthMethod() types.AuthMethod
- func (a *OAuthAuthenticatorImpl) GetToken() (string, error)
- func (a *OAuthAuthenticatorImpl) GetTokenInfo() (*TokenInfo, error)
- func (a *OAuthAuthenticatorImpl) HandleCallback(ctx context.Context, code, state string) error
- func (a *OAuthAuthenticatorImpl) IsAuthenticated() bool
- func (a *OAuthAuthenticatorImpl) IsOAuthEnabled() bool
- func (a *OAuthAuthenticatorImpl) Logout(ctx context.Context) error
- func (a *OAuthAuthenticatorImpl) RefreshToken(ctx context.Context) error
- func (a *OAuthAuthenticatorImpl) SetOAuthConfig(config *types.OAuthConfig)
- func (a *OAuthAuthenticatorImpl) StartOAuthFlow(ctx context.Context, scopes []string) (string, error)
- type OAuthConfig
- type OAuthHelper
- func (h *OAuthHelper) BuildAuthURL(authURL, clientID, redirectURI, state string, scopes []string, ...) (string, error)
- func (h *OAuthHelper) ExchangeCodeForToken(ctx context.Context, ...) (*OAuthTokenResponse, error)
- func (h *OAuthHelper) ValidateCallback(state, expectedState, code, errorParam string) error
- type OAuthTokenResponse
- type PKCEConfig
- type ProviderAuthConfig
- type ProviderAuthRegistry
- func (r *ProviderAuthRegistry) GetProvider(provider string) (*ProviderAuthConfig, bool)
- func (r *ProviderAuthRegistry) GetProvidersByMethod(method types.AuthMethod) []string
- func (r *ProviderAuthRegistry) ListProviders() []string
- func (r *ProviderAuthRegistry) RegisterProvider(config *ProviderAuthConfig)
- type ProxyAuthConfig
- type ProxyConfig
- type RateLimitConfig
- type RateLimiter
- type RefreshConfig
- type RetryConfig
- type RotationConfig
- type SecurityAuditor
- func (sa *SecurityAuditor) LogAuthAttempt(provider, method string, success bool, ip string)
- func (sa *SecurityAuditor) LogSecurityEvent(event, provider, details string)
- func (sa *SecurityAuditor) LogTokenOperation(operation, provider string, success bool)
- func (sa *SecurityAuditor) ValidateConfiguration() error
- type SecurityConfig
- type SecurityUtils
- func (su *SecurityUtils) DecryptSensitiveData(encryptedData, key []byte) ([]byte, error)
- func (su *SecurityUtils) DeriveKey(password, salt []byte, iterations, keyLength int) []byte
- func (su *SecurityUtils) EncryptSensitiveData(data, key []byte) ([]byte, error)
- func (su *SecurityUtils) GenerateSecureToken(length int) (string, error)
- func (su *SecurityUtils) MaskToken(token string) string
- func (su *SecurityUtils) SanitizeLogMessage(message string) string
- func (su *SecurityUtils) ValidateAPIKeyFormat(key string, format string) error
- func (su *SecurityUtils) ValidateOAuthState(state, expectedState string) error
- func (su *SecurityUtils) ValidateRedirectURI(uri, expectedURI string) error
- func (su *SecurityUtils) ValidateTokenExpiration(expiresAt time.Time, buffer time.Duration) error
- type StateConfig
- type TLSConfig
- type TimeoutConfig
- type TokenInfo
- type TokenMaskingConfig
- type TokenMetadata
- type TokenStorage
- type TokenStorageConfig
Examples ΒΆ
Constants ΒΆ
const ( //nolint:gosec // This is an error code string, not a hardcoded credential ErrCodeInvalidCredentials = "invalid_credentials" ErrCodeTokenExpired = "token_expired" ErrCodeRefreshFailed = "refresh_failed" ErrCodeOAuthFlowFailed = "oauth_flow_failed" ErrCodeInvalidConfig = "invalid_config" ErrCodeNetworkError = "network_error" ErrCodeScopeInsufficient = "scope_insufficient" ErrCodeKeyRotationFailed = "key_rotation_failed" ErrCodeAllKeysExhausted = "all_keys_exhausted" ErrCodeStorageError = "storage_error" ErrCodeEncryptionError = "encryption_error" )
Common error codes
Variables ΒΆ
This section is empty.
Functions ΒΆ
func AuthConfigToProviderConfig ΒΆ
func AuthConfigToProviderConfig(authConfig types.AuthConfig, providerType types.ProviderType) types.ProviderConfig
AuthConfigToProviderConfig converts an AuthConfig to ProviderConfig
func ProviderConfigToAuthConfig ΒΆ
func ProviderConfigToAuthConfig(providerConfig types.ProviderConfig) types.AuthConfig
ProviderConfigToAuthConfig converts a ProviderConfig to AuthConfig
Types ΒΆ
type APIKeyAuthenticator ΒΆ
type APIKeyAuthenticator interface {
Authenticator
// GetKeyManager returns the API key manager for multi-key operations
GetKeyManager() APIKeyManager
// RotateKey rotates to the next available API key
RotateKey() error
// ReportKeySuccess reports successful API key usage
ReportKeySuccess(key string) error
// ReportKeyFailure reports failed API key usage
ReportKeyFailure(key string, err error) error
}
APIKeyAuthenticator extends Authenticator for API key-specific functionality
type APIKeyAuthenticatorImpl ΒΆ
type APIKeyAuthenticatorImpl struct {
// contains filtered or unexported fields
}
APIKeyAuthenticatorImpl implements APIKeyAuthenticator
func (*APIKeyAuthenticatorImpl) Authenticate ΒΆ
func (a *APIKeyAuthenticatorImpl) Authenticate(ctx context.Context, config types.AuthConfig) error
Authenticate performs authentication with the given config
func (*APIKeyAuthenticatorImpl) GetAuthMethod ΒΆ
func (a *APIKeyAuthenticatorImpl) GetAuthMethod() types.AuthMethod
GetAuthMethod returns the authentication method type
func (*APIKeyAuthenticatorImpl) GetKeyManager ΒΆ
func (a *APIKeyAuthenticatorImpl) GetKeyManager() APIKeyManager
GetKeyManager returns the API key manager
func (*APIKeyAuthenticatorImpl) GetToken ΒΆ
func (a *APIKeyAuthenticatorImpl) GetToken() (string, error)
GetToken returns the current authentication token
func (*APIKeyAuthenticatorImpl) IsAuthenticated ΒΆ
func (a *APIKeyAuthenticatorImpl) IsAuthenticated() bool
IsAuthenticated checks if currently authenticated
func (*APIKeyAuthenticatorImpl) Logout ΒΆ
func (a *APIKeyAuthenticatorImpl) Logout(ctx context.Context) error
Logout clears authentication state
func (*APIKeyAuthenticatorImpl) RefreshToken ΒΆ
func (a *APIKeyAuthenticatorImpl) RefreshToken(ctx context.Context) error
RefreshToken refreshes the authentication token (no-op for API keys)
func (*APIKeyAuthenticatorImpl) ReportKeyFailure ΒΆ
func (a *APIKeyAuthenticatorImpl) ReportKeyFailure(key string, err error) error
ReportKeyFailure reports failed API key usage
func (*APIKeyAuthenticatorImpl) ReportKeySuccess ΒΆ
func (a *APIKeyAuthenticatorImpl) ReportKeySuccess(key string) error
ReportKeySuccess reports successful API key usage
func (*APIKeyAuthenticatorImpl) RotateKey ΒΆ
func (a *APIKeyAuthenticatorImpl) RotateKey() error
RotateKey rotates to the next available API key
type APIKeyConfig ΒΆ
type APIKeyConfig struct {
// Load balancing strategy
Strategy string `json:"strategy"`
// Health check configuration
Health HealthConfig `json:"health"`
// Failover configuration
Failover FailoverConfig `json:"failover"`
// Rotation configuration
Rotation RotationConfig `json:"rotation"`
}
APIKeyConfig represents configuration for API key management
type APIKeyManager ΒΆ
type APIKeyManager interface {
// GetCurrentKey returns the first available API key without advancing the round-robin counter
GetCurrentKey() string
// GetNextKey returns the next available API key using round-robin load balancing
GetNextKey() (string, error)
// ReportSuccess reports that an API call succeeded with this key
ReportSuccess(key string)
// ReportFailure reports that an API call failed with this key
ReportFailure(key string, err error)
// ExecuteWithFailover attempts an operation with automatic failover to next key on failure
ExecuteWithFailover(ctx context.Context, operation func(context.Context, string) (string, *types.Usage, error)) (string, *types.Usage, error)
// ExecuteWithFailoverMessage attempts an operation with automatic failover (message variant)
ExecuteWithFailoverMessage(ctx context.Context, operation func(context.Context, string) (types.ChatMessage, *types.Usage, error)) (types.ChatMessage, *types.Usage, error)
// GetStatus returns the current health status of all keys
GetStatus() map[string]interface{}
// GetKeys returns a copy of the keys slice
GetKeys() []string
// AddKey adds a new API key to the manager
AddKey(key string) error
// RemoveKey removes an API key from the manager
RemoveKey(key string) error
// IsHealthy returns true if at least one key is healthy
IsHealthy() bool
}
APIKeyManager manages multiple API keys with load balancing and failover
Example ΒΆ
ExampleAPIKeyManager shows how to use the API key manager with multi-key support
config := &APIKeyConfig{
Strategy: "round_robin",
Health: HealthConfig{
Enabled: true,
FailureThreshold: 3,
Backoff: BackoffConfig{
Initial: 1 * time.Second,
Maximum: 60 * time.Second,
Multiplier: 2.0,
Jitter: true,
},
},
Failover: FailoverConfig{
Enabled: true,
MaxAttempts: 3,
},
}
keys := []string{
"sk-1234567890abcdef",
"sk-abcdef1234567890",
"sk-7890abcdef123456",
}
manager, err := NewAPIKeyManager("openai", keys, config)
if err != nil {
panic(err)
}
// Execute with failover
result, usage, err := manager.ExecuteWithFailover(context.Background(), func(ctx context.Context, apiKey string) (string, *types.Usage, error) {
// Simulate API call
println("Using API key:", apiKey[:8]+"...")
return "API response", &types.Usage{TotalTokens: 100}, nil
})
if err != nil {
panic(err)
}
println("Result:", result)
println("Usage:", usage.TotalTokens, "tokens")
// Get status
status := manager.GetStatus()
println("Healthy keys:", status["healthy_keys"])
type APIKeyManagerImpl ΒΆ
type APIKeyManagerImpl struct {
// contains filtered or unexported fields
}
APIKeyManagerImpl implements APIKeyManager with load balancing and failover
func NewAPIKeyManager ΒΆ
func NewAPIKeyManager(providerName string, keys []string, config *APIKeyConfig) (*APIKeyManagerImpl, error)
NewAPIKeyManager creates a new API key manager
func (*APIKeyManagerImpl) AddKey ΒΆ
func (m *APIKeyManagerImpl) AddKey(key string) error
AddKey adds a new API key to the manager
func (*APIKeyManagerImpl) ExecuteWithFailover ΒΆ
func (m *APIKeyManagerImpl) ExecuteWithFailover(ctx context.Context, operation func(context.Context, string) (string, *types.Usage, error)) (string, *types.Usage, error)
ExecuteWithFailover attempts an operation with automatic failover to next key on failure
func (*APIKeyManagerImpl) ExecuteWithFailoverMessage ΒΆ added in v1.0.39
func (m *APIKeyManagerImpl) ExecuteWithFailoverMessage(ctx context.Context, operation func(context.Context, string) (types.ChatMessage, *types.Usage, error)) (types.ChatMessage, *types.Usage, error)
ExecuteWithFailoverMessage attempts an operation with automatic failover (message variant) This is used for operations that return ChatMessage to preserve tool calls and structured content
func (*APIKeyManagerImpl) GetCurrentKey ΒΆ
func (m *APIKeyManagerImpl) GetCurrentKey() string
GetCurrentKey returns the first available API key without advancing the round-robin counter
func (*APIKeyManagerImpl) GetKeys ΒΆ
func (m *APIKeyManagerImpl) GetKeys() []string
GetKeys returns a copy of the keys slice
func (*APIKeyManagerImpl) GetNextKey ΒΆ
func (m *APIKeyManagerImpl) GetNextKey() (string, error)
GetNextKey returns the next available API key using round-robin load balancing
func (*APIKeyManagerImpl) GetStatus ΒΆ
func (m *APIKeyManagerImpl) GetStatus() map[string]interface{}
GetStatus returns the current health status of all keys
func (*APIKeyManagerImpl) IsHealthy ΒΆ
func (m *APIKeyManagerImpl) IsHealthy() bool
IsHealthy returns true if at least one key is healthy
func (*APIKeyManagerImpl) RemoveKey ΒΆ
func (m *APIKeyManagerImpl) RemoveKey(key string) error
RemoveKey removes an API key from the manager
func (*APIKeyManagerImpl) ReportFailure ΒΆ
func (m *APIKeyManagerImpl) ReportFailure(key string, err error)
ReportFailure reports that an API call failed with this key
func (*APIKeyManagerImpl) ReportSuccess ΒΆ
func (m *APIKeyManagerImpl) ReportSuccess(key string)
ReportSuccess reports that an API call succeeded with this key
type AuthError ΒΆ
type AuthError struct {
Provider string `json:"provider"`
Code string `json:"code"`
Message string `json:"message"`
Details string `json:"details,omitempty"`
Retry bool `json:"retry,omitempty"`
}
AuthError represents authentication-related errors
func (*AuthError) IsRetryable ΒΆ
IsRetryable returns true if the error is retryable
type AuthFeatureFlags ΒΆ
type AuthFeatureFlags struct {
SupportsOAuth bool `json:"supports_oauth"`
SupportsAPIKey bool `json:"supports_api_key"`
SupportsMultiKey bool `json:"supports_multi_key"`
RequiresPKCE bool `json:"requires_pkce"`
TokenRefresh bool `json:"token_refresh"`
}
AuthFeatureFlags represents authentication feature flags for a provider
type AuthManager ΒΆ
type AuthManager interface {
// RegisterAuthenticator registers an authenticator for a provider
RegisterAuthenticator(provider string, authenticator Authenticator) error
// GetAuthenticator returns the authenticator for a provider
GetAuthenticator(provider string) (Authenticator, error)
// Authenticate authenticates a provider
Authenticate(ctx context.Context, provider string, config types.AuthConfig) error
// IsAuthenticated checks if a provider is authenticated
IsAuthenticated(provider string) bool
// Logout logs out a provider
Logout(ctx context.Context, provider string) error
// RefreshAllTokens refreshes all tokens that need it
RefreshAllTokens(ctx context.Context) error
// GetAuthenticatedProviders returns a list of authenticated providers
GetAuthenticatedProviders() []string
// GetAuthStatus returns the authentication status for all providers
GetAuthStatus() map[string]*AuthState
// CleanupExpired removes expired tokens and cleans up authenticators
CleanupExpired() error
// ForEachAuthenticated executes a function for each authenticated provider
ForEachAuthenticated(ctx context.Context, fn func(provider string, authenticator Authenticator) error) error
// GetTokenInfo returns token information for a specific provider
GetTokenInfo(provider string) (*TokenInfo, error)
// StartOAuthFlow starts OAuth flow for a provider
StartOAuthFlow(ctx context.Context, provider string, scopes []string) (string, error)
// HandleOAuthCallback handles OAuth callback for a provider
HandleOAuthCallback(ctx context.Context, provider string, code, state string) error
}
AuthManager manages authentication for multiple providers
type AuthManagerBuilder ΒΆ
type AuthManagerBuilder struct {
// contains filtered or unexported fields
}
AuthManagerBuilder provides a builder pattern for creating AuthManager instances
func NewAuthManagerBuilder ΒΆ
func NewAuthManagerBuilder() *AuthManagerBuilder
NewAuthManagerBuilder creates a new auth manager builder
func (*AuthManagerBuilder) Build ΒΆ
func (b *AuthManagerBuilder) Build() (*AuthManagerImpl, error)
Build creates the auth manager
func (*AuthManagerBuilder) WithAuthenticator ΒΆ
func (b *AuthManagerBuilder) WithAuthenticator(provider string, authenticator Authenticator) *AuthManagerBuilder
WithAuthenticator adds an authenticator
func (*AuthManagerBuilder) WithConfig ΒΆ
func (b *AuthManagerBuilder) WithConfig(config *Config) *AuthManagerBuilder
WithConfig sets the configuration
func (*AuthManagerBuilder) WithLogger ΒΆ
func (b *AuthManagerBuilder) WithLogger(logger Logger) *AuthManagerBuilder
WithLogger sets the logger
func (*AuthManagerBuilder) WithStorage ΒΆ
func (b *AuthManagerBuilder) WithStorage(storage TokenStorage) *AuthManagerBuilder
WithStorage sets the token storage
type AuthManagerImpl ΒΆ
type AuthManagerImpl struct {
// contains filtered or unexported fields
}
AuthManagerImpl manages authentication for multiple providers
func NewAuthManager ΒΆ
func NewAuthManager(storage TokenStorage, config *Config) *AuthManagerImpl
NewAuthManager creates a new authentication manager
Example ΒΆ
ExampleNewAuthManager shows how to create a new auth manager
// Create default configuration with encryption disabled for testing
config := DefaultConfig()
config.TokenStorage.Encryption.Enabled = false
// Create memory-based token storage for testing
storage := NewMemoryTokenStorage(&config.TokenStorage.Memory)
// Create auth manager
authManager := NewAuthManager(storage, config)
// Register OAuth authenticator for Anthropic
authenticator := NewOAuthAuthenticator("anthropic", storage, &config.OAuth)
if err := authManager.RegisterAuthenticator("anthropic", authenticator); err != nil {
// In real usage, you'd handle this error properly
println("Warning: failed to register authenticator:", err.Error())
}
// Check auth status
status := authManager.GetAuthStatus()
for provider, state := range status {
println("Provider:", provider, "Authenticated:", state.Authenticated)
}
func (*AuthManagerImpl) Authenticate ΒΆ
func (am *AuthManagerImpl) Authenticate(ctx context.Context, provider string, config types.AuthConfig) error
Authenticate authenticates a provider
func (*AuthManagerImpl) CleanupExpired ΒΆ
func (am *AuthManagerImpl) CleanupExpired() error
CleanupExpired removes expired tokens and cleans up authenticators
func (*AuthManagerImpl) Close ΒΆ
func (am *AuthManagerImpl) Close() error
Close closes the auth manager and cleans up resources
func (*AuthManagerImpl) ForEachAuthenticated ΒΆ
func (am *AuthManagerImpl) ForEachAuthenticated(ctx context.Context, fn func(provider string, authenticator Authenticator) error) error
ForEachAuthenticated executes a function for each authenticated provider
func (*AuthManagerImpl) GetAuthStatus ΒΆ
func (am *AuthManagerImpl) GetAuthStatus() map[string]*AuthState
GetAuthStatus returns the authentication status for all providers
func (*AuthManagerImpl) GetAuthenticatedProviders ΒΆ
func (am *AuthManagerImpl) GetAuthenticatedProviders() []string
GetAuthenticatedProviders returns a list of authenticated providers
func (*AuthManagerImpl) GetAuthenticator ΒΆ
func (am *AuthManagerImpl) GetAuthenticator(provider string) (Authenticator, error)
GetAuthenticator returns the authenticator for a provider
func (*AuthManagerImpl) GetConfig ΒΆ
func (am *AuthManagerImpl) GetConfig() *Config
GetConfig returns the auth manager configuration
func (*AuthManagerImpl) GetProviders ΒΆ
func (am *AuthManagerImpl) GetProviders() []string
GetProviders returns a list of all registered providers
func (*AuthManagerImpl) GetStorage ΒΆ
func (am *AuthManagerImpl) GetStorage() TokenStorage
GetStorage returns the token storage instance
func (*AuthManagerImpl) GetTokenInfo ΒΆ
func (am *AuthManagerImpl) GetTokenInfo(provider string) (*TokenInfo, error)
GetTokenInfo returns token information for a specific provider
func (*AuthManagerImpl) HandleOAuthCallback ΒΆ
func (am *AuthManagerImpl) HandleOAuthCallback(ctx context.Context, provider string, code, state string) error
HandleOAuthCallback handles OAuth callback for a provider
func (*AuthManagerImpl) IsAuthenticated ΒΆ
func (am *AuthManagerImpl) IsAuthenticated(provider string) bool
IsAuthenticated checks if a provider is authenticated
func (*AuthManagerImpl) Logout ΒΆ
func (am *AuthManagerImpl) Logout(ctx context.Context, provider string) error
Logout logs out a provider
func (*AuthManagerImpl) RefreshAllTokens ΒΆ
func (am *AuthManagerImpl) RefreshAllTokens(ctx context.Context) error
RefreshAllTokens refreshes all tokens that need it
func (*AuthManagerImpl) RegisterAuthenticator ΒΆ
func (am *AuthManagerImpl) RegisterAuthenticator(provider string, authenticator Authenticator) error
RegisterAuthenticator registers an authenticator for a provider
func (*AuthManagerImpl) RemoveAuthenticator ΒΆ
func (am *AuthManagerImpl) RemoveAuthenticator(provider string) error
RemoveAuthenticator removes an authenticator for a provider
func (*AuthManagerImpl) SetLogger ΒΆ
func (am *AuthManagerImpl) SetLogger(logger Logger)
SetLogger sets the logger for the auth manager
func (*AuthManagerImpl) StartOAuthFlow ΒΆ
func (am *AuthManagerImpl) StartOAuthFlow(ctx context.Context, provider string, scopes []string) (string, error)
StartOAuthFlow starts OAuth flow for a provider
type AuthState ΒΆ
type AuthState struct {
Provider string `json:"provider"`
Authenticated bool `json:"authenticated"`
Method types.AuthMethod `json:"method"`
LastAuth time.Time `json:"last_auth"`
ExpiresAt time.Time `json:"expires_at,omitempty"`
CanRefresh bool `json:"can_refresh"`
}
AuthState represents the current authentication state
type Authenticator ΒΆ
type Authenticator interface {
// Authenticate performs authentication with the given config
Authenticate(ctx context.Context, config types.AuthConfig) error
// IsAuthenticated checks if currently authenticated
IsAuthenticated() bool
// GetToken returns the current authentication token
GetToken() (string, error)
// RefreshToken refreshes the authentication token if needed
RefreshToken(ctx context.Context) error
// Logout clears authentication state
Logout(ctx context.Context) error
// GetAuthMethod returns the authentication method type
GetAuthMethod() types.AuthMethod
}
Authenticator defines the interface for authentication methods
type AuthenticatorFactory ΒΆ
type AuthenticatorFactory struct {
// contains filtered or unexported fields
}
AuthenticatorFactory creates authenticators for different providers and methods
func NewAuthenticatorFactory ΒΆ
func NewAuthenticatorFactory(config *Config, storage TokenStorage) *AuthenticatorFactory
NewAuthenticatorFactory creates a new authenticator factory
Example ΒΆ
ExampleNewAuthenticatorFactory shows how to use the authenticator factory
// Create factory
config := DefaultConfig()
storage := NewMemoryTokenStorage(&config.TokenStorage.Memory)
factory := NewAuthenticatorFactory(config, storage)
// Create API key authenticator
apiKeyAuth, err := factory.CreateAuthenticator("openai", types.AuthMethodAPIKey, "sk-1234567890abcdef")
if err != nil {
panic(err)
}
// Create OAuth authenticator (placeholder - OAuth config structure has changed)
oauthAuth, err := factory.CreateAuthenticator("google", types.AuthMethodOAuth, &types.AuthConfig{
Method: types.AuthMethodOAuth,
})
if err != nil {
// OAuth configuration now uses OAuthCredentialSet in provider config
println("OAuth authenticator creation:", err)
}
// Create custom authenticator
customAuth := &CustomAuthenticator{}
wrappedAuth, err := factory.CreateAuthenticator("custom", types.AuthMethodCustom, customAuth)
if err != nil {
panic(err)
}
// Use authenticators
_ = apiKeyAuth
_ = oauthAuth
_ = wrappedAuth
func (*AuthenticatorFactory) CreateAuthenticator ΒΆ
func (f *AuthenticatorFactory) CreateAuthenticator(provider string, method types.AuthMethod, config interface{}) (Authenticator, error)
CreateAuthenticator creates an authenticator for the specified provider and method
func (*AuthenticatorFactory) SetLogger ΒΆ
func (f *AuthenticatorFactory) SetLogger(logger Logger)
SetLogger sets the logger for the factory
type BackoffConfig ΒΆ
type BackoffConfig struct {
// Initial backoff duration
Initial time.Duration `json:"initial"`
// Maximum backoff duration
Maximum time.Duration `json:"maximum"`
// Backoff multiplier
Multiplier float64 `json:"multiplier"`
// Jitter
Jitter bool `json:"jitter"`
}
BackoffConfig represents configuration for exponential backoff
type BackupConfig ΒΆ
type BackupConfig struct {
// Enable backup
Enabled bool `json:"enabled"`
// Backup directory
Directory string `json:"directory"`
// Backup interval
Interval time.Duration `json:"interval"`
// Max backup files to keep
MaxFiles int `json:"max_files"`
}
BackupConfig represents configuration for token backup
type BearerTokenAuthenticatorImpl ΒΆ
type BearerTokenAuthenticatorImpl struct {
// contains filtered or unexported fields
}
BearerTokenAuthenticatorImpl implements simple bearer token authentication
func (*BearerTokenAuthenticatorImpl) Authenticate ΒΆ
func (b *BearerTokenAuthenticatorImpl) Authenticate(ctx context.Context, config types.AuthConfig) error
Authenticate performs authentication with the given config
func (*BearerTokenAuthenticatorImpl) GetAuthMethod ΒΆ
func (b *BearerTokenAuthenticatorImpl) GetAuthMethod() types.AuthMethod
GetAuthMethod returns the authentication method type
func (*BearerTokenAuthenticatorImpl) GetToken ΒΆ
func (b *BearerTokenAuthenticatorImpl) GetToken() (string, error)
GetToken returns the current authentication token
func (*BearerTokenAuthenticatorImpl) IsAuthenticated ΒΆ
func (b *BearerTokenAuthenticatorImpl) IsAuthenticated() bool
IsAuthenticated checks if currently authenticated
func (*BearerTokenAuthenticatorImpl) Logout ΒΆ
func (b *BearerTokenAuthenticatorImpl) Logout(ctx context.Context) error
Logout clears authentication state
func (*BearerTokenAuthenticatorImpl) RefreshToken ΒΆ
func (b *BearerTokenAuthenticatorImpl) RefreshToken(ctx context.Context) error
RefreshToken refreshes the authentication token (no-op for bearer tokens)
type CircuitBreakerConfig ΒΆ
type CircuitBreakerConfig struct {
// Enable circuit breaker
Enabled bool `json:"enabled"`
// Failure threshold
FailureThreshold int `json:"failure_threshold"`
// Recovery timeout
RecoveryTimeout time.Duration `json:"recovery_timeout"`
// Half-open max requests
HalfOpenMaxRequests int `json:"half_open_max_requests"`
}
CircuitBreakerConfig represents configuration for circuit breaker
type Config ΒΆ
type Config struct {
// Token storage configuration
TokenStorage TokenStorageConfig `json:"token_storage"`
// OAuth configuration
OAuth OAuthConfig `json:"oauth"`
// API key management configuration
APIKey APIKeyConfig `json:"api_key"`
// Security configuration
Security SecurityConfig `json:"security"`
// Retry configuration
Retry RetryConfig `json:"retry"`
// Default timeouts
Timeouts TimeoutConfig `json:"timeouts"`
}
Config represents the configuration for the authentication system
type DefaultLogger ΒΆ
type DefaultLogger struct{}
DefaultLogger provides a simple no-op logger
func (*DefaultLogger) Debug ΒΆ
func (l *DefaultLogger) Debug(msg string, fields ...interface{})
func (*DefaultLogger) Error ΒΆ
func (l *DefaultLogger) Error(msg string, fields ...interface{})
func (*DefaultLogger) Info ΒΆ
func (l *DefaultLogger) Info(msg string, fields ...interface{})
func (*DefaultLogger) Warn ΒΆ
func (l *DefaultLogger) Warn(msg string, fields ...interface{})
type EncryptionConfig ΒΆ
type EncryptionConfig struct {
// Enable encryption
Enabled bool `json:"enabled"`
// Encryption key
Key string `json:"key"`
// Key file path
KeyFile string `json:"key_file"`
// Encryption algorithm
Algorithm string `json:"algorithm"`
// Key derivation configuration
KeyDerivation KeyDerivationConfig `json:"key_derivation"`
}
EncryptionConfig represents configuration for token encryption
type FailoverConfig ΒΆ
type FailoverConfig struct {
// Enable failover
Enabled bool `json:"enabled"`
// Maximum attempts
MaxAttempts int `json:"max_attempts"`
// Failover strategy
Strategy string `json:"strategy"`
// Circuit breaker configuration
CircuitBreaker CircuitBreakerConfig `json:"circuit_breaker"`
}
FailoverConfig represents configuration for API key failover
type FileStorageConfig ΒΆ
type FileStorageConfig struct {
// Directory to store tokens
Directory string `json:"directory"`
// File permissions
FilePermissions string `json:"file_permissions"`
// Directory permissions
DirectoryPermissions string `json:"directory_permissions"`
// Backup configuration
Backup BackupConfig `json:"backup"`
}
FileStorageConfig represents configuration for file-based token storage
type FileTokenStorage ΒΆ
type FileTokenStorage struct {
// contains filtered or unexported fields
}
FileTokenStorage implements TokenStorage using encrypted files
func NewFileTokenStorage ΒΆ
func NewFileTokenStorage(config *FileStorageConfig, encryption *EncryptionConfig) (*FileTokenStorage, error)
NewFileTokenStorage creates a new file-based token storage
Example ΒΆ
ExampleNewFileTokenStorage shows how to use token encryption
config := &EncryptionConfig{
Enabled: false, // Disabled for testing
Key: "my-encryption-key-32-bytes-long!",
Algorithm: "aes-256-gcm",
KeyDerivation: KeyDerivationConfig{
Function: "sha256",
Iterations: 100000,
KeyLength: 32,
},
}
storageConfig := &FileStorageConfig{
Directory: "./test-tokens",
FilePermissions: "0600",
DirectoryPermissions: "0700",
}
storage, err := NewFileTokenStorage(storageConfig, config)
if err != nil {
panic(err)
}
// Store encrypted token
token := &types.OAuthConfig{
AccessToken: "secret-access-token",
RefreshToken: "secret-refresh-token",
ExpiresAt: time.Now().Add(1 * time.Hour),
}
err = storage.StoreToken("test-provider", token)
if err != nil {
panic(err)
}
// Retrieve and decrypt token
retrievedToken, err := storage.RetrieveToken("test-provider")
if err != nil {
panic(err)
}
println("Retrieved token:", retrievedToken.AccessToken)
// Get metadata
metadata, err := storage.GetTokenInfo("test-provider")
if err != nil {
panic(err)
}
println("Token is encrypted:", metadata.IsEncrypted)
println("Created at:", metadata.CreatedAt.Format(time.RFC3339))
func (*FileTokenStorage) CleanupExpired ΒΆ
func (fts *FileTokenStorage) CleanupExpired() error
CleanupExpired removes all expired tokens
func (*FileTokenStorage) Close ΒΆ
func (fts *FileTokenStorage) Close() error
Close stops the cleanup ticker
func (*FileTokenStorage) DeleteToken ΒΆ
func (fts *FileTokenStorage) DeleteToken(key string) error
DeleteToken removes a stored token
func (*FileTokenStorage) GetTokenInfo ΒΆ
func (fts *FileTokenStorage) GetTokenInfo(key string) (*TokenMetadata, error)
GetTokenInfo returns metadata about a stored token
func (*FileTokenStorage) IsTokenValid ΒΆ
func (fts *FileTokenStorage) IsTokenValid(key string) bool
IsTokenValid checks if a token exists and is not expired
func (*FileTokenStorage) ListTokens ΒΆ
func (fts *FileTokenStorage) ListTokens() ([]string, error)
ListTokens returns a list of all stored token keys
func (*FileTokenStorage) RetrieveToken ΒΆ
func (fts *FileTokenStorage) RetrieveToken(key string) (*types.OAuthConfig, error)
RetrieveToken retrieves and decrypts an OAuth token from disk
func (*FileTokenStorage) StoreToken ΒΆ
func (fts *FileTokenStorage) StoreToken(key string, token *types.OAuthConfig) error
StoreToken stores an OAuth token encrypted on disk
type HTTPConfig ΒΆ
type HTTPConfig struct {
// Timeout
Timeout time.Duration `json:"timeout"`
// User agent
UserAgent string `json:"user_agent"`
// TLS configuration
TLS TLSConfig `json:"tls"`
// Proxy configuration
Proxy ProxyConfig `json:"proxy"`
}
HTTPConfig represents configuration for HTTP clients
type HealthConfig ΒΆ
type HealthConfig struct {
// Enable health tracking
Enabled bool `json:"enabled"`
// Failure threshold
FailureThreshold int `json:"failure_threshold"`
// Success threshold
SuccessThreshold int `json:"success_threshold"`
// Backoff configuration
Backoff BackoffConfig `json:"backoff"`
// Health check interval
CheckInterval time.Duration `json:"check_interval"`
}
HealthConfig represents configuration for API key health tracking
type KeyDerivationConfig ΒΆ
type KeyDerivationConfig struct {
// Key derivation function
Function string `json:"function"`
// Salt
Salt string `json:"salt"`
// Number of iterations
Iterations int `json:"iterations"`
// Key length
KeyLength int `json:"key_length"`
}
KeyDerivationConfig represents configuration for key derivation
type Logger ΒΆ
type Logger interface {
Debug(msg string, fields ...interface{})
Info(msg string, fields ...interface{})
Warn(msg string, fields ...interface{})
Error(msg string, fields ...interface{})
}
Logger interface for authentication events
type MemoryStorageConfig ΒΆ
type MemoryStorageConfig struct {
// Maximum number of tokens to store
MaxTokens int `json:"max_tokens"`
// Cleanup interval
CleanupInterval time.Duration `json:"cleanup_interval"`
// Enable persistence to file
EnablePersistence bool `json:"enable_persistence"`
// Persistence file path
PersistenceFile string `json:"persistence_file"`
}
MemoryStorageConfig represents configuration for memory-based token storage
type MemoryTokenStorage ΒΆ
type MemoryTokenStorage struct {
// contains filtered or unexported fields
}
MemoryTokenStorage implements TokenStorage in memory for testing or temporary use
func NewMemoryTokenStorage ΒΆ
func NewMemoryTokenStorage(config *MemoryStorageConfig) *MemoryTokenStorage
NewMemoryTokenStorage creates a new memory-based token storage
func (*MemoryTokenStorage) CleanupExpired ΒΆ
func (mts *MemoryTokenStorage) CleanupExpired() error
CleanupExpired removes all expired tokens
func (*MemoryTokenStorage) Close ΒΆ
func (mts *MemoryTokenStorage) Close() error
Close stops the cleanup routine
func (*MemoryTokenStorage) DeleteToken ΒΆ
func (mts *MemoryTokenStorage) DeleteToken(key string) error
DeleteToken removes a stored token from memory
func (*MemoryTokenStorage) GetTokenInfo ΒΆ
func (mts *MemoryTokenStorage) GetTokenInfo(key string) (*TokenMetadata, error)
GetTokenInfo returns metadata about a stored token
func (*MemoryTokenStorage) IsTokenValid ΒΆ
func (mts *MemoryTokenStorage) IsTokenValid(key string) bool
IsTokenValid checks if a token exists and is not expired in memory
func (*MemoryTokenStorage) ListTokens ΒΆ
func (mts *MemoryTokenStorage) ListTokens() ([]string, error)
ListTokens returns a list of all stored token keys in memory
func (*MemoryTokenStorage) RetrieveToken ΒΆ
func (mts *MemoryTokenStorage) RetrieveToken(key string) (*types.OAuthConfig, error)
RetrieveToken retrieves an OAuth token from memory
func (*MemoryTokenStorage) StoreToken ΒΆ
func (mts *MemoryTokenStorage) StoreToken(key string, token *types.OAuthConfig) error
StoreToken stores an OAuth token in memory
type OAuthAuthenticator ΒΆ
type OAuthAuthenticator interface {
Authenticator
// StartOAuthFlow initiates the OAuth flow and returns the auth URL
StartOAuthFlow(ctx context.Context, scopes []string) (string, error)
// HandleCallback processes the OAuth callback
HandleCallback(ctx context.Context, code, state string) error
// IsOAuthEnabled checks if OAuth is properly configured
IsOAuthEnabled() bool
// GetTokenInfo returns detailed token information
GetTokenInfo() (*TokenInfo, error)
}
OAuthAuthenticator extends Authenticator for OAuth-specific functionality
Example ΒΆ
ExampleOAuthAuthenticator shows how to implement OAuth flow
// Create storage and config
storage := NewMemoryTokenStorage(nil)
oauthConfig := &OAuthConfig{
DefaultScopes: []string{"profile", "email"},
State: StateConfig{
Length: 32,
Expiration: 10 * time.Minute,
EnableValidation: true,
},
PKCE: PKCEConfig{
Enabled: true,
Method: "S256",
VerifierLength: 128,
},
Refresh: RefreshConfig{
Enabled: true,
Buffer: 5 * time.Minute,
MaxRetries: 3,
},
}
// Create OAuth authenticator
authenticator := NewOAuthAuthenticator("google", storage, oauthConfig)
var oauthAuthenticator OAuthAuthenticator = authenticator
ctx := context.Background()
// Configure OAuth
authConfig := types.AuthConfig{
Method: types.AuthMethodOAuth,
APIKey: "", // OAuth uses token storage, not direct API key
}
err := oauthAuthenticator.Authenticate(ctx, authConfig)
if err != nil {
// Need to start OAuth flow
authURL, err := oauthAuthenticator.StartOAuthFlow(ctx, []string{"profile", "email"})
if err != nil {
panic(err)
}
println("Visit this URL to authorize:", authURL)
// After user authorization, handle callback
// err = oauthAuthenticator.HandleCallback(ctx, "authorization_code", "state")
// if err != nil {
// panic(err)
// }
}
// Get token info
if tokenInfo, err := oauthAuthenticator.GetTokenInfo(); err == nil {
println("Token expires at:", tokenInfo.ExpiresAt.Format(time.RFC3339))
println("Token is expired:", tokenInfo.IsExpired)
}
type OAuthAuthenticatorImpl ΒΆ
type OAuthAuthenticatorImpl struct {
// contains filtered or unexported fields
}
OAuthAuthenticatorImpl implements OAuthAuthenticator
func NewOAuthAuthenticator ΒΆ
func NewOAuthAuthenticator(provider string, storage TokenStorage, config *OAuthConfig) *OAuthAuthenticatorImpl
NewOAuthAuthenticator creates a new OAuth authenticator
func (*OAuthAuthenticatorImpl) Authenticate ΒΆ
func (a *OAuthAuthenticatorImpl) Authenticate(ctx context.Context, config types.AuthConfig) error
Authenticate performs authentication with the given config Note: For OAuth authentication via this pkg/auth module, the OAuth config must be set during creation of the authenticator or via SetOAuthConfig. types.AuthConfig no longer supports OAuthConfig field.
func (*OAuthAuthenticatorImpl) GetAuthMethod ΒΆ
func (a *OAuthAuthenticatorImpl) GetAuthMethod() types.AuthMethod
GetAuthMethod returns the authentication method type
func (*OAuthAuthenticatorImpl) GetToken ΒΆ
func (a *OAuthAuthenticatorImpl) GetToken() (string, error)
GetToken returns the current authentication token
func (*OAuthAuthenticatorImpl) GetTokenInfo ΒΆ
func (a *OAuthAuthenticatorImpl) GetTokenInfo() (*TokenInfo, error)
GetTokenInfo returns detailed token information
func (*OAuthAuthenticatorImpl) HandleCallback ΒΆ
func (a *OAuthAuthenticatorImpl) HandleCallback(ctx context.Context, code, state string) error
HandleCallback processes the OAuth callback
func (*OAuthAuthenticatorImpl) IsAuthenticated ΒΆ
func (a *OAuthAuthenticatorImpl) IsAuthenticated() bool
IsAuthenticated checks if currently authenticated
func (*OAuthAuthenticatorImpl) IsOAuthEnabled ΒΆ
func (a *OAuthAuthenticatorImpl) IsOAuthEnabled() bool
IsOAuthEnabled checks if OAuth is properly configured
func (*OAuthAuthenticatorImpl) Logout ΒΆ
func (a *OAuthAuthenticatorImpl) Logout(ctx context.Context) error
Logout clears authentication state
func (*OAuthAuthenticatorImpl) RefreshToken ΒΆ
func (a *OAuthAuthenticatorImpl) RefreshToken(ctx context.Context) error
RefreshToken refreshes the authentication token
func (*OAuthAuthenticatorImpl) SetOAuthConfig ΒΆ
func (a *OAuthAuthenticatorImpl) SetOAuthConfig(config *types.OAuthConfig)
SetOAuthConfig sets the OAuth configuration
func (*OAuthAuthenticatorImpl) StartOAuthFlow ΒΆ
func (a *OAuthAuthenticatorImpl) StartOAuthFlow(ctx context.Context, scopes []string) (string, error)
StartOAuthFlow initiates the OAuth flow and returns the auth URL
type OAuthConfig ΒΆ
type OAuthConfig struct {
// Default scopes
DefaultScopes []string `json:"default_scopes"`
// State management
State StateConfig `json:"state"`
// PKCE configuration
PKCE PKCEConfig `json:"pkce"`
// Token refresh configuration
Refresh RefreshConfig `json:"refresh"`
// HTTP client configuration
HTTP HTTPConfig `json:"http"`
}
OAuthConfig represents configuration for OAuth
type OAuthHelper ΒΆ
type OAuthHelper struct {
// contains filtered or unexported fields
}
OAuthHelper provides utility functions for OAuth flows
func NewOAuthHelper ΒΆ
func NewOAuthHelper(config *OAuthConfig) *OAuthHelper
NewOAuthHelper creates a new OAuth helper
func (*OAuthHelper) BuildAuthURL ΒΆ
func (h *OAuthHelper) BuildAuthURL(authURL, clientID, redirectURI, state string, scopes []string, pkceChallenge string) (string, error)
BuildAuthURL builds an OAuth authorization URL
func (*OAuthHelper) ExchangeCodeForToken ΒΆ
func (h *OAuthHelper) ExchangeCodeForToken(ctx context.Context, tokenURL, clientID, clientSecret, redirectURI, code, codeVerifier string) (*OAuthTokenResponse, error)
ExchangeCodeForToken exchanges an authorization code for an access token
func (*OAuthHelper) ValidateCallback ΒΆ
func (h *OAuthHelper) ValidateCallback(state, expectedState, code, errorParam string) error
ValidateCallback validates an OAuth callback response
type OAuthTokenResponse ΒΆ
type OAuthTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int64 `json:"expires_in"`
RefreshToken string `json:"refresh_token,omitempty"`
Scope string `json:"scope,omitempty"`
Error string `json:"error,omitempty"`
ErrorDescription string `json:"error_description,omitempty"`
}
OAuthTokenResponse represents the token response from OAuth servers
type PKCEConfig ΒΆ
type PKCEConfig struct {
// Enable PKCE
Enabled bool `json:"enabled"`
// Code challenge method
Method string `json:"method"`
// Code verifier length
VerifierLength int `json:"verifier_length"`
}
PKCEConfig represents configuration for PKCE
type ProviderAuthConfig ΒΆ
type ProviderAuthConfig struct {
Provider string `json:"provider"`
AuthMethod types.AuthMethod `json:"auth_method"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
OAuthURL string `json:"oauth_url,omitempty"`
RequiredScopes []string `json:"required_scopes,omitempty"`
OptionalScopes []string `json:"optional_scopes,omitempty"`
Features AuthFeatureFlags `json:"features"`
}
ProviderAuthConfig represents provider-specific authentication configuration
type ProviderAuthRegistry ΒΆ
type ProviderAuthRegistry struct {
// contains filtered or unexported fields
}
ProviderAuthRegistry provides a registry of provider-specific authentication configurations
func CreateStandardRegistry ΒΆ
func CreateStandardRegistry() *ProviderAuthRegistry
CreateStandardRegistry creates a registry with standard provider configurations
func NewProviderAuthRegistry ΒΆ
func NewProviderAuthRegistry() *ProviderAuthRegistry
NewProviderAuthRegistry creates a new provider auth registry
func (*ProviderAuthRegistry) GetProvider ΒΆ
func (r *ProviderAuthRegistry) GetProvider(provider string) (*ProviderAuthConfig, bool)
GetProvider returns a provider's authentication configuration
func (*ProviderAuthRegistry) GetProvidersByMethod ΒΆ
func (r *ProviderAuthRegistry) GetProvidersByMethod(method types.AuthMethod) []string
GetProvidersByMethod returns providers that support the specified authentication method
func (*ProviderAuthRegistry) ListProviders ΒΆ
func (r *ProviderAuthRegistry) ListProviders() []string
ListProviders returns a list of all registered providers
func (*ProviderAuthRegistry) RegisterProvider ΒΆ
func (r *ProviderAuthRegistry) RegisterProvider(config *ProviderAuthConfig)
RegisterProvider registers a provider's authentication configuration
type ProxyAuthConfig ΒΆ
type ProxyAuthConfig struct {
// Username
Username string `json:"username"`
// Password
Password string `json:"password"`
}
ProxyAuthConfig represents configuration for proxy authentication
type ProxyConfig ΒΆ
type ProxyConfig struct {
// Enable proxy
Enabled bool `json:"enabled"`
// Proxy URL
URL string `json:"url"`
// Proxy authentication
Auth ProxyAuthConfig `json:"auth"`
}
ProxyConfig represents configuration for HTTP proxy
type RateLimitConfig ΒΆ
type RateLimitConfig struct {
// Enable rate limiting
Enabled bool `json:"enabled"`
// Requests per minute
RequestsPerMinute int `json:"requests_per_minute"`
// Burst size
Burst int `json:"burst"`
}
RateLimitConfig represents configuration for rate limiting
type RateLimiter ΒΆ
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter provides simple rate limiting functionality
func NewRateLimiter ΒΆ
func NewRateLimiter(limit int, window time.Duration) *RateLimiter
NewRateLimiter creates a new rate limiter
func (*RateLimiter) Allow ΒΆ
func (rl *RateLimiter) Allow(identifier string) bool
Allow checks if a request is allowed for the given identifier
type RefreshConfig ΒΆ
type RefreshConfig struct {
// Enable automatic refresh
Enabled bool `json:"enabled"`
// Refresh buffer (refresh token before it expires)
Buffer time.Duration `json:"buffer"`
// Max retry attempts
MaxRetries int `json:"max_retries"`
// Enable refresh on failure
RefreshOnFailure bool `json:"refresh_on_failure"`
}
RefreshConfig represents configuration for token refresh
type RetryConfig ΒΆ
type RetryConfig struct {
// Enable retry
Enabled bool `json:"enabled"`
// Maximum attempts
MaxAttempts int `json:"max_attempts"`
// Initial delay
InitialDelay time.Duration `json:"initial_delay"`
// Maximum delay
MaxDelay time.Duration `json:"max_delay"`
// Backoff multiplier
Multiplier float64 `json:"multiplier"`
// Jitter
Jitter bool `json:"jitter"`
}
RetryConfig represents configuration for retry operations
type RotationConfig ΒΆ
type RotationConfig struct {
// Enable rotation
Enabled bool `json:"enabled"`
// Rotation interval
Interval time.Duration `json:"interval"`
// Rotation strategy
Strategy string `json:"strategy"`
}
RotationConfig represents configuration for API key rotation
type SecurityAuditor ΒΆ
type SecurityAuditor struct {
// contains filtered or unexported fields
}
SecurityAuditor provides security auditing capabilities
func NewSecurityAuditor ΒΆ
func NewSecurityAuditor(logger Logger, config *SecurityConfig) *SecurityAuditor
NewSecurityAuditor creates a new security auditor
func (*SecurityAuditor) LogAuthAttempt ΒΆ
func (sa *SecurityAuditor) LogAuthAttempt(provider, method string, success bool, ip string)
LogAuthAttempt logs an authentication attempt
func (*SecurityAuditor) LogSecurityEvent ΒΆ
func (sa *SecurityAuditor) LogSecurityEvent(event, provider, details string)
LogSecurityEvent logs a security event
func (*SecurityAuditor) LogTokenOperation ΒΆ
func (sa *SecurityAuditor) LogTokenOperation(operation, provider string, success bool)
LogTokenOperation logs a token operation
func (*SecurityAuditor) ValidateConfiguration ΒΆ
func (sa *SecurityAuditor) ValidateConfiguration() error
ValidateConfiguration validates security configuration
type SecurityConfig ΒΆ
type SecurityConfig struct {
// Enable audit logging
AuditLogging bool `json:"audit_logging"`
// Token masking
TokenMasking TokenMaskingConfig `json:"token_masking"`
// Rate limiting
RateLimiting RateLimitConfig `json:"rate_limiting"`
}
SecurityConfig represents security configuration
type SecurityUtils ΒΆ
type SecurityUtils struct {
// contains filtered or unexported fields
}
SecurityUtils provides security utilities for authentication
func NewSecurityUtils ΒΆ
func NewSecurityUtils(config *SecurityConfig) *SecurityUtils
NewSecurityUtils creates a new security utilities instance
func (*SecurityUtils) DecryptSensitiveData ΒΆ
func (su *SecurityUtils) DecryptSensitiveData(encryptedData, key []byte) ([]byte, error)
DecryptSensitiveData decrypts sensitive data using AES-GCM
func (*SecurityUtils) DeriveKey ΒΆ
func (su *SecurityUtils) DeriveKey(password, salt []byte, iterations, keyLength int) []byte
DeriveKey derives a cryptographic key from a password
func (*SecurityUtils) EncryptSensitiveData ΒΆ
func (su *SecurityUtils) EncryptSensitiveData(data, key []byte) ([]byte, error)
EncryptSensitiveData encrypts sensitive data using AES-GCM
func (*SecurityUtils) GenerateSecureToken ΒΆ
func (su *SecurityUtils) GenerateSecureToken(length int) (string, error)
GenerateSecureToken generates a cryptographically secure random token
func (*SecurityUtils) MaskToken ΒΆ
func (su *SecurityUtils) MaskToken(token string) string
MaskToken masks a token for secure display
func (*SecurityUtils) SanitizeLogMessage ΒΆ
func (su *SecurityUtils) SanitizeLogMessage(message string) string
SanitizeLogMessage sanitizes sensitive information from log messages
func (*SecurityUtils) ValidateAPIKeyFormat ΒΆ
func (su *SecurityUtils) ValidateAPIKeyFormat(key string, format string) error
ValidateAPIKeyFormat validates an API key format
func (*SecurityUtils) ValidateOAuthState ΒΆ
func (su *SecurityUtils) ValidateOAuthState(state, expectedState string) error
ValidateOAuthState validates OAuth state parameter
func (*SecurityUtils) ValidateRedirectURI ΒΆ
func (su *SecurityUtils) ValidateRedirectURI(uri, expectedURI string) error
ValidateRedirectURI validates OAuth redirect URI
func (*SecurityUtils) ValidateTokenExpiration ΒΆ
ValidateTokenExpiration checks if a token is expired or nearing expiration
type StateConfig ΒΆ
type StateConfig struct {
// State length
Length int `json:"length"`
// State expiration
Expiration time.Duration `json:"expiration"`
// Enable state validation
EnableValidation bool `json:"enable_validation"`
}
StateConfig represents configuration for OAuth state management
type TLSConfig ΒΆ
type TLSConfig struct {
// Insecure skip verify
InsecureSkipVerify bool `json:"insecure_skip_verify"`
// CA certificate file
CAFile string `json:"ca_file"`
// Certificate file
CertFile string `json:"cert_file"`
// Key file
KeyFile string `json:"key_file"`
}
TLSConfig represents configuration for TLS
type TimeoutConfig ΒΆ
type TimeoutConfig struct {
// Authentication timeout
Auth time.Duration `json:"auth"`
// Token refresh timeout
TokenRefresh time.Duration `json:"token_refresh"`
// OAuth flow timeout
OAuthFlow time.Duration `json:"oauth_flow"`
// Storage operation timeout
Storage time.Duration `json:"storage"`
}
TimeoutConfig represents timeout configuration
type TokenInfo ΒΆ
type TokenInfo struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token,omitempty"`
TokenType string `json:"token_type"`
ExpiresAt time.Time `json:"expires_at"`
Scopes []string `json:"scopes"`
IsExpired bool `json:"is_expired"`
ExpiresIn int64 `json:"expires_in"`
}
TokenInfo represents information about an authentication token
type TokenMaskingConfig ΒΆ
type TokenMaskingConfig struct {
// Enable masking
Enabled bool `json:"enabled"`
// Prefix length to show
PrefixLength int `json:"prefix_length"`
// Suffix length to show
SuffixLength int `json:"suffix_length"`
// Mask character
MaskChar string `json:"mask_char"`
}
TokenMaskingConfig represents configuration for token masking
type TokenMetadata ΒΆ
type TokenMetadata struct {
Provider string `json:"provider"`
CreatedAt time.Time `json:"created_at"`
LastAccessed time.Time `json:"last_accessed"`
ExpiresAt time.Time `json:"expires_at"`
IsEncrypted bool `json:"is_encrypted"`
}
TokenMetadata represents metadata about a stored token
type TokenStorage ΒΆ
type TokenStorage interface {
types.TokenStorage
// IsTokenValid checks if a token exists and is not expired
IsTokenValid(key string) bool
// CleanupExpired removes all expired tokens
CleanupExpired() error
// GetTokenInfo returns metadata about a stored token
GetTokenInfo(key string) (*TokenMetadata, error)
}
TokenStorage defines the interface for token persistence Extends the kit version with additional functionality
type TokenStorageConfig ΒΆ
type TokenStorageConfig struct {
// Storage backend type (file, memory, custom)
Type string `json:"type"`
// File storage configuration
File FileStorageConfig `json:"file"`
// Memory storage configuration
Memory MemoryStorageConfig `json:"memory"`
// Encryption configuration
Encryption EncryptionConfig `json:"encryption"`
}
TokenStorageConfig represents configuration for token storage