auth

package
v1.0.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2025 License: MIT Imports: 21 Imported by: 0

README ΒΆ

Authentication Package

The auth package provides a comprehensive authentication system for AI providers, supporting multiple authentication methods including OAuth 2.0, API keys, and bearer tokens with features like token encryption, multi-key management, and automatic failover.

Features

πŸ” Multiple Authentication Methods
  • OAuth 2.0: Complete OAuth flow implementation with PKCE support
  • API Keys: Single and multi-key management with load balancing
  • Bearer Tokens: Simple token-based authentication
  • Custom: Extensible for provider-specific authentication
πŸ›‘οΈ Security & Encryption
  • AES-GCM token encryption with key derivation
  • Secure token storage with automatic expiration
  • PKCE (Proof Key for Code Exchange) support
  • Token masking for secure logging
πŸ”„ Advanced Features
  • Multi-key load balancing with round-robin, random, and weighted strategies
  • Circuit breaker pattern for fault tolerance
  • Automatic token refresh with configurable buffers
  • Health tracking with exponential backoff
  • Comprehensive error handling with retry logic
πŸ“Š Monitoring & Observability
  • Detailed health status reporting
  • Request metrics and success rates
  • Token metadata and expiration tracking
  • Migration reporting and validation

Quick Start

Basic Setup
package main

import (
    "context"
    "log"
    "time"

    "github.com/cecil-the-coder/ai-provider-kit/pkg/auth"
    "github.com/cecil-the-coder/ai-provider-kit/pkg/types"
)

func main() {
    // Create default configuration
    config := auth.DefaultConfig()

    // Create file-based token storage with encryption
    storage, err := auth.NewFileTokenStorage(
        &config.TokenStorage.File,
        &config.TokenStorage.Encryption,
    )
    if err != nil {
        log.Fatal(err)
    }

    // Create auth manager
    authManager := auth.NewAuthManager(storage, config)

    // Register authenticator
    authenticator := auth.NewOAuthAuthenticator("anthropic", storage, &config.OAuth)
    err = authManager.RegisterAuthenticator("anthropic", authenticator)
    if err != nil {
        log.Fatal(err)
    }

    // Use authentication
    ctx := context.Background()
    err = authManager.Authenticate(ctx, "anthropic", types.AuthConfig{
        Method: types.AuthMethodOAuth,
        OAuthConfig: &types.OAuthConfig{
            ClientID:     "your-client-id",
            ClientSecret: "your-client-secret",
            AuthURL:      "https://auth.anthropic.com/oauth/authorize",
            TokenURL:     "https://auth.anthropic.com/oauth/token",
            RedirectURL:  "http://localhost:8080/callback",
        },
    })
    if err != nil {
        log.Fatal(err)
    }
}
API Key Management
// Configure API key manager
apiKeyConfig := &auth.APIKeyConfig{
    Strategy: "round_robin",
    Health: auth.HealthConfig{
        Enabled:          true,
        FailureThreshold: 3,
        Backoff: auth.BackoffConfig{
            Initial:   1 * time.Second,
            Maximum:   60 * time.Second,
            Multiplier: 2.0,
            Jitter:    true,
        },
    },
}

// Create manager with multiple keys
manager, err := auth.NewAPIKeyManager("openai", []string{
    "sk-key1...",
    "sk-key2...",
    "sk-key3...",
}, apiKeyConfig)

// Execute with automatic failover
result, err := manager.ExecuteWithFailover(func(apiKey string) (string, error) {
    // Make API call with key
    return callAPI(apiKey)
})

// Report success/failure
manager.ReportSuccess(apiKey)
manager.ReportFailure(apiKey, err)

// Get health status
status := manager.GetStatus()
OAuth Flow Implementation
// Start OAuth flow
authenticator := auth.NewOAuthAuthenticator("google", storage, &oauthConfig)

authURL, err := authenticator.StartOAuthFlow(ctx, []string{"profile", "email"})
if err != nil {
    log.Fatal(err)
}

// Redirect user to authURL
// After authorization, handle callback
err = authenticator.HandleCallback(ctx, authorizationCode, state)
if err != nil {
    log.Fatal(err)
}

// Get token information
tokenInfo, err := authenticator.GetTokenInfo()
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Token expires at: %v\n", tokenInfo.ExpiresAt)

Configuration

Complete Configuration
config := &auth.Config{
    TokenStorage: auth.TokenStorageConfig{
        Type: "file",
        File: auth.FileStorageConfig{
            Directory:           "./tokens",
            FilePermissions:     "0600",
            DirectoryPermissions: "0700",
            Backup: auth.BackupConfig{
                Enabled: true,
                Interval: 24 * time.Hour,
                MaxFiles: 10,
            },
        },
        Encryption: auth.EncryptionConfig{
            Enabled:  true,
            Key:      "your-encryption-key-32-bytes!",
            Algorithm: "aes-256-gcm",
            KeyDerivation: auth.KeyDerivationConfig{
                Function:  "pbkdf2",
                Iterations: 100000,
                KeyLength: 32,
            },
        },
    },
    OAuth: auth.OAuthConfig{
        DefaultScopes: []string{},
        State: auth.StateConfig{
            Length:          32,
            Expiration:      10 * time.Minute,
            EnableValidation: true,
        },
        PKCE: auth.PKCEConfig{
            Enabled:       true,
            Method:        "S256",
            VerifierLength: 128,
        },
        Refresh: auth.RefreshConfig{
            Enabled:         true,
            Buffer:          5 * time.Minute,
            MaxRetries:      3,
            RefreshOnFailure: true,
        },
    },
    APIKey: auth.APIKeyConfig{
        Strategy: "round_robin",
        Health: auth.HealthConfig{
            Enabled:          true,
            FailureThreshold: 3,
            Backoff: auth.BackoffConfig{
                Initial:   1 * time.Second,
                Maximum:   60 * time.Second,
                Multiplier: 2.0,
                Jitter:    true,
            },
        },
        Failover: auth.FailoverConfig{
            Enabled:     true,
            MaxAttempts: 3,
        },
    },
}
Environment Variables

The authentication system supports configuration through environment variables:

# Token Storage
AUTH_STORAGE_TYPE=file
AUTH_STORAGE_DIRECTORY=./tokens
AUTH_ENCRYPTION_ENABLED=true
AUTH_ENCRYPTION_KEY=your-encryption-key

# OAuth
AUTH_OAUTH_STATE_LENGTH=32
AUTH_OAUTH_PKCE_ENABLED=true
AUTH_OAUTH_REFRESH_BUFFER=5m

# API Keys
AUTH_APIKEY_STRATEGY=round_robin
AUTH_APIKEY_FAILURE_THRESHOLD=3
AUTH_APIKEY_MAX_ATTEMPTS=3

Migration from provider-library

The package includes a migration helper to transition from the old authentication system:

// Create migration helper
helper := auth.NewMigrationHelper(auth.DefaultConfig())

// Define providers to migrate
configs := []auth.ProviderMigrationConfig{
    {
        Provider:      "anthropic",
        AuthMethod:    types.AuthMethodAPIKey,
        OldConfig:     "sk-ant-api03-...",
        MigrateTokens: false,
    },
    {
        Provider:      "gemini",
        AuthMethod:    types.AuthMethodOAuth,
        OldConfig: &types.AuthConfig{
            OAuthConfig: &types.OAuthConfig{
                AccessToken: "ya29.a0AfH6SMB...",
                ExpiresAt:   time.Now().Add(1 * time.Hour),
            },
        },
        MigrateTokens: true,
    },
}

// Migrate all providers
authenticators, err := helper.MigrateAllProviders(ctx, configs)
if err != nil {
    log.Fatal(err)
}

// Create auth manager with migrated providers
authManager, err := helper.CreateAuthManager()
if err != nil {
    log.Fatal(err)
}

// Register migrated authenticators
for provider, authenticator := range authenticators {
    authManager.RegisterAuthenticator(provider, authenticator)
}

// Generate migration report
report := helper.GetMigrationReport(ctx, authenticators)
fmt.Printf("Migration completed: %d/%d providers\n",
    report.SuccessfulMigrations, report.TotalProviders)

API Reference

Core Interfaces
Authenticator
type Authenticator interface {
    Authenticate(ctx context.Context, config types.AuthConfig) error
    IsAuthenticated() bool
    GetToken() (string, error)
    RefreshToken(ctx context.Context) error
    Logout(ctx context.Context) error
    GetAuthMethod() types.AuthMethod
}
OAuthAuthenticator
type OAuthAuthenticator interface {
    Authenticator
    StartOAuthFlow(ctx context.Context, scopes []string) (string, error)
    HandleCallback(ctx context.Context, code, state string) error
    IsOAuthEnabled() bool
    GetTokenInfo() (*TokenInfo, error)
}
APIKeyAuthenticator
type APIKeyAuthenticator interface {
    Authenticator
    GetKeyManager() APIKeyManager
    RotateKey() error
    ReportKeySuccess(key string) error
    ReportKeyFailure(key string, err error) error
}
AuthManager
type AuthManager interface {
    RegisterAuthenticator(provider string, authenticator Authenticator) error
    GetAuthenticator(provider string) (Authenticator, error)
    Authenticate(ctx context.Context, provider string, config types.AuthConfig) error
    IsAuthenticated(provider string) bool
    Logout(ctx context.Context, provider string) error
    RefreshAllTokens(ctx context.Context) error
    GetAuthenticatedProviders() []string
    GetAuthStatus() map[string]*AuthState
    StartOAuthFlow(ctx context.Context, provider string, scopes []string) (string, error)
    HandleOAuthCallback(ctx context.Context, provider string, code, state string) error
}
Storage Interfaces
TokenStorage
type TokenStorage interface {
    StoreToken(key string, token *types.OAuthConfig) error
    RetrieveToken(key string) (*types.OAuthConfig, error)
    DeleteToken(key string) error
    ListTokens() ([]string, error)
    IsTokenValid(key string) bool
    CleanupExpired() error
    GetTokenInfo(key string) (*TokenMetadata, error)
}

Error Handling

The authentication system provides detailed error information:

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"`
}

// Error codes
const (
    ErrCodeInvalidCredentials  = "invalid_credentials"
    ErrCodeTokenExpired        = "token_expired"
    ErrCodeRefreshFailed       = "refresh_failed"
    ErrCodeOAuthFlowFailed     = "oauth_flow_failed"
    ErrCodeNetworkError        = "network_error"
    ErrCodeStorageError        = "storage_error"
    ErrCodeEncryptionError     = "encryption_error"
)

Best Practices

Security
  1. Always enable encryption for token storage
  2. Use strong encryption keys (32 bytes minimum)
  3. Implement proper key rotation for long-lived tokens
  4. Validate OAuth state to prevent CSRF attacks
  5. Use PKCE for public OAuth clients
Performance
  1. Use memory storage for short-lived tokens
  2. Configure appropriate backoff for retry logic
  3. Implement circuit breakers for external services
  4. Monitor health metrics for proactive issue detection
Reliability
  1. Configure multiple API keys for redundancy
  2. Implement proper error handling with retry logic
  3. Set appropriate timeouts for network operations
  4. Monitor token expiration and refresh proactively

Examples

See the example_test.go file for comprehensive examples of:

  • OAuth flow implementation
  • API key management with failover
  • Token encryption and storage
  • Migration from old auth systems
  • Custom authenticator implementation

Testing

Run the test suite:

go test ./pkg/auth/...

Run examples:

go test -run Example ./pkg/auth/...

Contributing

  1. Follow Go coding standards
  2. Add comprehensive tests for new features
  3. Update documentation for API changes
  4. Ensure backward compatibility where possible

License

This package is part of the ai-provider-kit project and follows the same license terms.

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 ΒΆ

Examples ΒΆ

Constants ΒΆ

View Source
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"
	ErrCodeProviderUnavailable = "provider_unavailable"
	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 ΒΆ

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(operation func(apiKey string) (string, error)) (string, error)

	// GetStatus returns the current health status of all keys
	GetStatus() map[string]interface{}

	// GetKeys returns all configured keys (masked for security)
	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, err := manager.ExecuteWithFailover(func(apiKey string) (string, error) {
	// Simulate API call
	println("Using API key:", apiKey[:8]+"...")
	return "API response", nil
})

if err != nil {
	panic(err)
}

println("Result:", result)

// 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(operation func(apiKey string) (string, error)) (string, error)

ExecuteWithFailover attempts an operation with automatic failover to next key on failure

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 all configured keys (masked for security)

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) Error ΒΆ

func (e *AuthError) Error() string

func (*AuthError) IsRetryable ΒΆ

func (e *AuthError) IsRetryable() bool

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 ΒΆ

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

func DefaultConfig ΒΆ

func DefaultConfig() *Config

DefaultConfig returns the default configuration

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 ΒΆ

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 ΒΆ

func (su *SecurityUtils) ValidateTokenExpiration(expiresAt time.Time, buffer time.Duration) error

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL