Documentation
¶
Overview ¶
Package auth provides authentication and authorization capabilities for the event validation system.
This package implements a flexible authentication framework that can be integrated with the event validation system to provide access control, rate limiting, and audit capabilities.
Overview ¶
The authentication system consists of several key components:
- AuthProvider: Interface for authentication backends (JWT, OAuth, RBAC, etc.)
- AuthHooks: Integration points for the validation system
- AuthContext: Represents an authenticated session
- Credentials: Various credential types (basic, token, API key)
Basic Usage ¶
Create an authenticated validator with basic authentication:
// Create auth provider authProvider := auth.NewBasicAuthProvider(nil) // Add users authProvider.AddUser(&auth.User{ Username: "admin", PasswordHash: auth.HashPassword("admin123"), Roles: []string{"admin"}, Permissions: []string{"*:*"}, Active: true, }) // Create authenticated validator validator := auth.NewAuthenticatedValidator( events.DefaultValidationConfig(), authProvider, auth.DefaultAuthConfig(), ) // Validate with credentials result := validator.ValidateWithBasicAuth(ctx, event, "admin", "admin123")
Authentication Providers ¶
The package includes a basic in-memory authentication provider that can be used for testing or as a foundation for more complex providers. You can implement custom providers by implementing the AuthProvider interface:
type MyCustomProvider struct { // ... provider fields } func (p *MyCustomProvider) Authenticate(ctx context.Context, credentials Credentials) (*AuthContext, error) { // Custom authentication logic } func (p *MyCustomProvider) Authorize(ctx context.Context, authCtx *AuthContext, resource, action string) error { // Custom authorization logic }
Hooks ¶
The authentication system supports pre and post validation hooks:
// Pre-validation hook validator.AddPreValidationHook(func(ctx context.Context, event events.Event, authCtx *AuthContext) error { // Custom pre-validation logic return nil }) // Post-validation hook validator.AddPostValidationHook(func(ctx context.Context, event events.Event, authCtx *AuthContext, result *events.ValidationResult) error { // Custom post-validation logic return nil })
Authorization ¶
The system uses a resource:action permission model:
- event:validate - Permission to validate events
- run:validate - Permission to validate run events
- message:validate - Permission to validate message events
- tool:validate - Permission to validate tool events
- state:validate - Permission to validate state events
- *:* - Wildcard permission for all resources and actions
Rate Limiting ¶
Built-in rate limiting can be configured per user or role:
validator.AddPreValidationHook(auth.RateLimitHook(map[string]int{ "default": 1000, // 1000 requests per minute for authenticated users "admin": 10000, // 10000 requests per minute for admins }))
Security Considerations ¶
- Passwords are hashed using SHA-256 (use bcrypt or similar in production)
- Tokens are generated with secure random values
- Sessions can be revoked and have configurable expiration
- Old sessions and revoked tokens are cleaned up periodically
Future Extensions ¶
This foundation can be extended with:
- JWT token support
- OAuth2/OIDC integration
- RBAC with fine-grained permissions
- External authentication providers (LDAP, SAML)
- Multi-factor authentication
- API key management
- Session management and single sign-on
Example (AuthorizationRoles) ¶
Example_authorizationRoles demonstrates role-based authorization
package main import ( "context" "fmt" "time" "github.com/mattsp1290/ag-ui/go-sdk/pkg/core/events" "github.com/mattsp1290/ag-ui/go-sdk/pkg/core/events/auth" ) func main() { // Create provider with users having different roles provider := auth.NewBasicAuthProvider(nil) // Admin user - use complex password: Admin123! provider.AddUser(&auth.User{ Username: "admin", PasswordHash: hashPassword("Admin123!"), Roles: []string{"admin"}, Permissions: []string{"*:*"}, Active: true, }) provider.SetUserPassword("admin", "Admin123!") // Read-only user - use complex password: Reader123! provider.AddUser(&auth.User{ Username: "reader", PasswordHash: hashPassword("Reader123!"), Roles: []string{"reader"}, Permissions: []string{"event:read", "validation:read"}, Active: true, }) provider.SetUserPassword("reader", "Reader123!") // Create validator authConfig := auth.DefaultAuthConfig() authConfig.RequireAuth = true validator := auth.NewAuthenticatedValidator( events.DefaultValidationConfig(), provider, authConfig, ) // Create event (use RunStartedEvent since it's the first event) event := &events.RunStartedEvent{ BaseEvent: &events.BaseEvent{ EventType: events.EventTypeRunStarted, TimestampMs: timePtr(time.Now().UnixMilli()), }, RunIDValue: "run-123", ThreadIDValue: "thread-456", } ctx := context.Background() // Admin can validate result := validator.ValidateWithBasicAuth(ctx, event, "admin", "Admin123!") fmt.Printf("Admin validation: %v\n", result.IsValid) // Reader cannot validate (no validate permission) result = validator.ValidateWithBasicAuth(ctx, event, "reader", "Reader123!") if !result.IsValid { fmt.Printf("Reader validation failed: %s\n", result.Errors[0].Message) } } // Helper functions func timePtr(t int64) *int64 { return &t } func hashPassword(password string) string { return password }
Output: Admin validation: true Reader validation failed: Authorization failed: insufficient permissions
Example (BasicAuthentication) ¶
Example_basicAuthentication demonstrates basic username/password authentication
package main import ( "context" "fmt" "time" "github.com/mattsp1290/ag-ui/go-sdk/pkg/core/events" "github.com/mattsp1290/ag-ui/go-sdk/pkg/core/events/auth" ) func main() { // Create an auth provider provider := auth.NewBasicAuthProvider(nil) // Add a user - use complex password: Secret123! provider.AddUser(&auth.User{ Username: "alice", PasswordHash: hashPassword("Secret123!"), Roles: []string{"validator"}, Permissions: []string{"event:validate", "event:read", "run:validate", "message:validate", "tool:validate", "state:validate"}, Active: true, }) provider.SetUserPassword("alice", "Secret123!") // Create an authenticated validator validator := auth.NewAuthenticatedValidator( events.DefaultValidationConfig(), provider, auth.DefaultAuthConfig(), ) // Create an event to validate event := &events.RunStartedEvent{ BaseEvent: &events.BaseEvent{ EventType: events.EventTypeRunStarted, TimestampMs: timePtr(time.Now().UnixMilli()), }, RunIDValue: "run-123", ThreadIDValue: "thread-456", } // Validate with authentication ctx := context.Background() result := validator.ValidateWithBasicAuth(ctx, event, "alice", "Secret123!") if result.IsValid { fmt.Println("Validation successful") } } // Helper functions func timePtr(t int64) *int64 { return &t } func hashPassword(password string) string { return password }
Output: Validation successful
Example (CustomHooks) ¶
Example_customHooks demonstrates custom authentication hooks
package main import ( "context" "fmt" "strings" "time" "github.com/mattsp1290/ag-ui/go-sdk/pkg/core/events" "github.com/mattsp1290/ag-ui/go-sdk/pkg/core/events/auth" ) func main() { // Create validator validator := auth.CreateWithBasicAuth() // Add custom pre-validation hook validator.AddPreValidationHook(func(ctx context.Context, event events.Event, authCtx *auth.AuthContext) error { if authCtx != nil { eventType := strings.ToLower(string(event.Type())) fmt.Printf("Pre-validation: User %s is validating %s event\n", authCtx.Username, eventType) } return nil }) // Add custom post-validation hook validator.AddPostValidationHook(func(ctx context.Context, event events.Event, authCtx *auth.AuthContext, result *events.ValidationResult) error { if authCtx != nil && result.IsValid { fmt.Printf("Post-validation: User %s successfully validated event\n", authCtx.Username) } return nil }) // Create and validate event (use RunStartedEvent since it's the first event) event := &events.RunStartedEvent{ BaseEvent: &events.BaseEvent{ EventType: events.EventTypeRunStarted, TimestampMs: timePtr(time.Now().UnixMilli()), }, RunIDValue: "run-123", ThreadIDValue: "thread-456", } ctx := context.Background() result := validator.ValidateWithBasicAuth(ctx, event, "admin", "Admin123!") if result.IsValid { fmt.Println("Validation completed") } } // Helper functions func timePtr(t int64) *int64 { return &t }
Output: Pre-validation: User admin is validating run_started event Post-validation: User admin successfully validated event Validation completed
Example (RequiredAuthentication) ¶
Example_requiredAuthentication demonstrates validation that requires authentication
package main import ( "context" "fmt" "time" "github.com/mattsp1290/ag-ui/go-sdk/pkg/core/events" "github.com/mattsp1290/ag-ui/go-sdk/pkg/core/events/auth" ) func main() { // Create validator with required authentication (but without logging hooks for clean output) validator := auth.CreateWithBasicAuth() // Enable required authentication validator.GetAuthHooks().GetConfig().RequireAuth = true validator.GetAuthHooks().GetConfig().AllowAnonymous = false // Create event (use RunStartedEvent since it's the first event) event := &events.RunStartedEvent{ BaseEvent: &events.BaseEvent{ EventType: events.EventTypeRunStarted, TimestampMs: timePtr(time.Now().UnixMilli()), }, RunIDValue: "run-123", ThreadIDValue: "thread-456", } ctx := context.Background() // Try to validate without authentication (will fail) result := validator.ValidateEvent(ctx, event) if !result.IsValid { fmt.Printf("Validation failed: %s\n", result.Errors[0].Message) } // Validate with authentication (will succeed) result = validator.ValidateWithBasicAuth(ctx, event, "validator", "Validator123!") if result.IsValid { fmt.Println("Authenticated validation successful") } } // Helper functions func timePtr(t int64) *int64 { return &t }
Output: Validation failed: Authentication failed: unauthorized Authenticated validation successful
Example (TokenAuthentication) ¶
Example_tokenAuthentication demonstrates token-based authentication
package main import ( "context" "fmt" "log" "time" "github.com/mattsp1290/ag-ui/go-sdk/pkg/core/events" "github.com/mattsp1290/ag-ui/go-sdk/pkg/core/events/auth" ) func main() { // Create provider and user - use complex password: Password123! provider := auth.NewBasicAuthProvider(nil) provider.AddUser(&auth.User{ Username: "bob", PasswordHash: hashPassword("Password123!"), Roles: []string{"admin"}, Permissions: []string{"*:*"}, Active: true, }) provider.SetUserPassword("bob", "Password123!") // Authenticate to get a token ctx := context.Background() authCtx, err := provider.Authenticate(ctx, &auth.BasicCredentials{ Username: "bob", Password: "Password123!", }) if err != nil { log.Fatal(err) } // Create validator validator := auth.NewAuthenticatedValidator( events.DefaultValidationConfig(), provider, auth.DefaultAuthConfig(), ) // Create event event := &events.RunStartedEvent{ BaseEvent: &events.BaseEvent{ EventType: events.EventTypeRunStarted, TimestampMs: timePtr(time.Now().UnixMilli()), }, RunIDValue: "run-123", ThreadIDValue: "thread-456", } // Validate with token result := validator.ValidateWithToken(ctx, event, authCtx.Token) if result.IsValid { fmt.Println("Token validation successful") } } // Helper functions func timePtr(t int64) *int64 { return &t } func hashPassword(password string) string { return password }
Output: Token validation successful
Index ¶
- Variables
- func Example()
- func ExtractSecurityInfoFromRequest(r *http.Request) (ipAddress, userAgent, requestID string)
- func IsSecurityEvent(err error) bool
- func SecurityLoggerMiddleware(logger *SecurityLogger) func(http.Handler) http.Handler
- func WithAuthContext(ctx context.Context, authCtx *AuthContext) context.Context
- func WithCredentials(ctx context.Context, creds Credentials) context.Context
- type APIKeyCredentials
- type AuditEvent
- type AuditEventFilter
- type AuditEventType
- type AuditLogger
- type AuthConfig
- type AuthContext
- type AuthHooks
- func (ah *AuthHooks) AddPostValidationHook(hook PostValidationHook)
- func (ah *AuthHooks) AddPreValidationHook(hook PreValidationHook)
- func (ah *AuthHooks) AuthenticateFromContext(ctx context.Context) (*AuthContext, error)
- func (ah *AuthHooks) AuthorizeEvent(ctx context.Context, authCtx *AuthContext, event events.Event) error
- func (ah *AuthHooks) Disable()
- func (ah *AuthHooks) Enable()
- func (ah *AuthHooks) ExecutePostValidationHooks(ctx context.Context, event events.Event, authCtx *AuthContext, ...) error
- func (ah *AuthHooks) ExecutePreValidationHooks(ctx context.Context, event events.Event, authCtx *AuthContext) error
- func (ah *AuthHooks) GetConfig() *AuthConfig
- func (ah *AuthHooks) GetMetrics() map[string]interface{}
- func (ah *AuthHooks) GetProvider() AuthProvider
- func (ah *AuthHooks) IsEnabled() bool
- func (ah *AuthHooks) SetProvider(provider AuthProvider)
- type AuthProvider
- type AuthValidationRule
- type AuthenticatedValidator
- func (av *AuthenticatedValidator) AddPostValidationHook(hook PostValidationHook)
- func (av *AuthenticatedValidator) AddPreValidationHook(hook PreValidationHook)
- func (av *AuthenticatedValidator) DisableAuthentication()
- func (av *AuthenticatedValidator) EnableAuthentication()
- func (av *AuthenticatedValidator) GetAuthHooks() *AuthHooks
- func (av *AuthenticatedValidator) GetMetrics() map[string]interface{}
- func (av *AuthenticatedValidator) GetValidator() *events.EventValidator
- func (av *AuthenticatedValidator) IsAuthenticationEnabled() bool
- func (av *AuthenticatedValidator) SetAuthProvider(provider AuthProvider)
- func (av *AuthenticatedValidator) StartCleanupRoutine(ctx context.Context, interval time.Duration)
- func (av *AuthenticatedValidator) ValidateEvent(ctx context.Context, event events.Event) *events.ValidationResult
- func (av *AuthenticatedValidator) ValidateEventWithAuth(ctx context.Context, event events.Event, authCtx *AuthContext) *events.ValidationResult
- func (av *AuthenticatedValidator) ValidateEventWithCredentials(ctx context.Context, event events.Event, credentials Credentials) *events.ValidationResult
- func (av *AuthenticatedValidator) ValidateSequence(ctx context.Context, events []events.Event) *events.ValidationResult
- func (av *AuthenticatedValidator) ValidateWithAPIKey(ctx context.Context, event events.Event, apiKey string) *events.ValidationResult
- func (av *AuthenticatedValidator) ValidateWithBasicAuth(ctx context.Context, event events.Event, username, password string) *events.ValidationResult
- func (av *AuthenticatedValidator) ValidateWithToken(ctx context.Context, event events.Event, token string) *events.ValidationResult
- type BasicAuthProvider
- func (p *BasicAuthProvider) AddUser(user *User) error
- func (p *BasicAuthProvider) Authenticate(ctx context.Context, credentials Credentials) (*AuthContext, error)
- func (p *BasicAuthProvider) Authorize(ctx context.Context, authCtx *AuthContext, resource string, action string) error
- func (p *BasicAuthProvider) CleanupExpiredSessions()
- func (p *BasicAuthProvider) CleanupOldAuditEvents() error
- func (p *BasicAuthProvider) GetAuditEvents(filter *AuditEventFilter) ([]*AuditEvent, error)
- func (p *BasicAuthProvider) GetProviderType() string
- func (p *BasicAuthProvider) Refresh(ctx context.Context, authCtx *AuthContext) (*AuthContext, error)
- func (p *BasicAuthProvider) RemoveUser(username string) error
- func (p *BasicAuthProvider) Revoke(ctx context.Context, authCtx *AuthContext) error
- func (p *BasicAuthProvider) SetUserPassword(username, password string) error
- func (p *BasicAuthProvider) StopTokenRotation()
- func (p *BasicAuthProvider) ValidateContext(ctx context.Context, authCtx *AuthContext) error
- type BasicCredentials
- type CSRFConfig
- type CSRFManager
- func (c *CSRFManager) CleanupExpiredTokens()
- func (c *CSRFManager) ExtractTokenFromRequest(r *http.Request) string
- func (c *CSRFManager) GenerateToken(userID string) (string, error)
- func (c *CSRFManager) GetTokenCount() int
- func (c *CSRFManager) Middleware() func(http.Handler) http.Handler
- func (c *CSRFManager) RevokeToken(token string)
- func (c *CSRFManager) RevokeUserTokens(userID string)
- func (c *CSRFManager) SetTokenCookie(w http.ResponseWriter, token string)
- func (c *CSRFManager) ValidateToken(token, userID string) error
- type CSRFToken
- type Credentials
- type MemoryAuditLogger
- type PostValidationHook
- type PostValidationRule
- type PreValidationHook
- type SecurityEvent
- type SecurityEventFilter
- type SecurityEventType
- type SecurityLogger
- func (sl *SecurityLogger) Close() error
- func (sl *SecurityLogger) GetEvents(filter *SecurityEventFilter) []*SecurityEvent
- func (sl *SecurityLogger) LogAuthFailure(userID, username, ipAddress, userAgent, errorMsg string)
- func (sl *SecurityLogger) LogAuthSuccess(userID, username, ipAddress, userAgent string)
- func (sl *SecurityLogger) LogCORSViolation(ipAddress, userAgent, origin string)
- func (sl *SecurityLogger) LogCSRFAttempt(userID, ipAddress, userAgent, origin string)
- func (sl *SecurityLogger) LogEvent(event *SecurityEvent)
- func (sl *SecurityLogger) LogInputValidationError(userID, ipAddress, userAgent, field, errorMsg string)
- func (sl *SecurityLogger) LogPermissionDenied(userID, username, ipAddress, resource, action string)
- func (sl *SecurityLogger) LogRateLimitExceeded(userID, ipAddress, userAgent, endpoint string)
- func (sl *SecurityLogger) LogSuspiciousActivity(userID, ipAddress, userAgent, activity, details string)
- type SecurityLoggerConfig
- type TokenCredentials
- type TokenRotationInfo
- type User
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrNoAuthProvider = errors.New("no authentication provider configured") ErrInvalidCredentials = errors.New("invalid credentials") ErrTokenExpired = errors.New("authentication token expired") ErrInsufficientPermissions = errors.New("insufficient permissions") )
Common authentication errors
Functions ¶
func ExtractSecurityInfoFromRequest ¶
ExtractSecurityInfoFromRequest extracts security-relevant information from HTTP request
func IsSecurityEvent ¶
IsSecurityEvent checks if an error is security-related
func SecurityLoggerMiddleware ¶
func SecurityLoggerMiddleware(logger *SecurityLogger) func(http.Handler) http.Handler
SecurityLoggerMiddleware returns HTTP middleware for security logging
func WithAuthContext ¶
func WithAuthContext(ctx context.Context, authCtx *AuthContext) context.Context
WithAuthContext adds an authentication context to the context
func WithCredentials ¶
func WithCredentials(ctx context.Context, creds Credentials) context.Context
WithCredentials adds credentials to the context
Types ¶
type APIKeyCredentials ¶
type APIKeyCredentials struct { APIKey string `json:"api_key"` Secret string `json:"secret,omitempty"` }
APIKeyCredentials represents API key credentials
func (*APIKeyCredentials) GetType ¶
func (c *APIKeyCredentials) GetType() string
GetType returns the credential type
func (*APIKeyCredentials) Validate ¶
func (c *APIKeyCredentials) Validate() error
Validate validates the API key credentials with security checks
type AuditEvent ¶
type AuditEvent struct { ID string `json:"id"` Timestamp time.Time `json:"timestamp"` EventType AuditEventType `json:"event_type"` UserID string `json:"user_id,omitempty"` Username string `json:"username,omitempty"` Result string `json:"result"` // SUCCESS, FAILURE Error string `json:"error,omitempty"` TokenID string `json:"token_id,omitempty"` IPAddress string `json:"ip_address,omitempty"` UserAgent string `json:"user_agent,omitempty"` Metadata map[string]interface{} `json:"metadata,omitempty"` }
AuditEvent represents an authentication audit event
type AuditEventFilter ¶
type AuditEventFilter struct { EventTypes []AuditEventType `json:"event_types,omitempty"` UserID string `json:"user_id,omitempty"` Username string `json:"username,omitempty"` Result string `json:"result,omitempty"` StartTime *time.Time `json:"start_time,omitempty"` EndTime *time.Time `json:"end_time,omitempty"` Limit int `json:"limit,omitempty"` Offset int `json:"offset,omitempty"` }
AuditEventFilter filters audit events
type AuditEventType ¶
type AuditEventType string
AuditEventType represents the type of audit event
const ( AuditEventLogin AuditEventType = "login" AuditEventLogout AuditEventType = "logout" AuditEventAuthFailure AuditEventType = "auth_failure" AuditEventTokenRefresh AuditEventType = "token_refresh" AuditEventTokenRotation AuditEventType = "token_rotation" AuditEventPermissionDenied AuditEventType = "permission_denied" )
type AuditLogger ¶
type AuditLogger interface { LogEvent(event *AuditEvent) error GetEvents(filter *AuditEventFilter) ([]*AuditEvent, error) CleanupOldEvents(before time.Time) error }
AuditLogger interface for audit logging
type AuthConfig ¶
type AuthConfig struct { // Enabled determines if authentication is enabled Enabled bool `json:"enabled"` // RequireAuth determines if authentication is required for all operations RequireAuth bool `json:"require_auth"` // AllowAnonymous allows anonymous access for certain operations AllowAnonymous bool `json:"allow_anonymous"` // TokenExpiration is the default token expiration duration TokenExpiration time.Duration `json:"token_expiration"` // RefreshEnabled allows token refresh RefreshEnabled bool `json:"refresh_enabled"` // RefreshExpiration is the refresh token expiration duration RefreshExpiration time.Duration `json:"refresh_expiration"` // AutoRotateTokens enables automatic token rotation AutoRotateTokens bool `json:"auto_rotate_tokens"` // TokenRotationInterval specifies how often tokens should be rotated TokenRotationInterval time.Duration `json:"token_rotation_interval"` // EnableAuditLogging enables audit logging for authentication events EnableAuditLogging bool `json:"enable_audit_logging"` // AuditLogRetention specifies how long audit logs are retained AuditLogRetention time.Duration `json:"audit_log_retention"` // ProviderConfig contains provider-specific configuration ProviderConfig map[string]interface{} `json:"provider_config,omitempty"` }
AuthConfig represents configuration for authentication
func DefaultAuthConfig ¶
func DefaultAuthConfig() *AuthConfig
DefaultAuthConfig returns the default authentication configuration
type AuthContext ¶
type AuthContext struct { // UserID is the unique identifier of the authenticated user UserID string `json:"user_id"` // Username is the human-readable username Username string `json:"username"` // Roles contains the roles assigned to the user Roles []string `json:"roles"` // Permissions contains the specific permissions granted Permissions []string `json:"permissions"` // Token is the authentication token (if applicable) Token string `json:"token,omitempty"` // ExpiresAt is when the authentication expires ExpiresAt *time.Time `json:"expires_at,omitempty"` // IssuedAt is when the authentication was issued IssuedAt time.Time `json:"issued_at"` // Metadata contains additional provider-specific data Metadata map[string]interface{} `json:"metadata,omitempty"` // ProviderType indicates which provider authenticated this context ProviderType string `json:"provider_type"` }
AuthContext represents an authenticated session context
func GetAuthContext ¶
func GetAuthContext(ctx context.Context) (*AuthContext, bool)
GetAuthContext retrieves the authentication context from context
func (*AuthContext) HasAllRoles ¶
func (ac *AuthContext) HasAllRoles(roles ...string) bool
HasAllRoles checks if the user has all of the specified roles
func (*AuthContext) HasAnyRole ¶
func (ac *AuthContext) HasAnyRole(roles ...string) bool
HasAnyRole checks if the user has any of the specified roles
func (*AuthContext) HasPermission ¶
func (ac *AuthContext) HasPermission(permission string) bool
HasPermission checks if the user has a specific permission
func (*AuthContext) HasRole ¶
func (ac *AuthContext) HasRole(role string) bool
HasRole checks if the user has a specific role
func (*AuthContext) IsExpired ¶
func (ac *AuthContext) IsExpired() bool
IsExpired checks if the authentication context has expired
type AuthHooks ¶
type AuthHooks struct {
// contains filtered or unexported fields
}
AuthHooks provides authentication integration for the event validation system
func NewAuthHooks ¶
func NewAuthHooks(provider AuthProvider, config *AuthConfig) *AuthHooks
NewAuthHooks creates new authentication hooks
func (*AuthHooks) AddPostValidationHook ¶
func (ah *AuthHooks) AddPostValidationHook(hook PostValidationHook)
AddPostValidationHook adds a post-validation hook
func (*AuthHooks) AddPreValidationHook ¶
func (ah *AuthHooks) AddPreValidationHook(hook PreValidationHook)
AddPreValidationHook adds a pre-validation hook
func (*AuthHooks) AuthenticateFromContext ¶
func (ah *AuthHooks) AuthenticateFromContext(ctx context.Context) (*AuthContext, error)
AuthenticateFromContext extracts authentication from context
func (*AuthHooks) AuthorizeEvent ¶
func (ah *AuthHooks) AuthorizeEvent(ctx context.Context, authCtx *AuthContext, event events.Event) error
AuthorizeEvent checks if the authenticated context can validate this event
func (*AuthHooks) ExecutePostValidationHooks ¶
func (ah *AuthHooks) ExecutePostValidationHooks(ctx context.Context, event events.Event, authCtx *AuthContext, result *events.ValidationResult) error
ExecutePostValidationHooks executes all post-validation hooks
func (*AuthHooks) ExecutePreValidationHooks ¶
func (ah *AuthHooks) ExecutePreValidationHooks(ctx context.Context, event events.Event, authCtx *AuthContext) error
ExecutePreValidationHooks executes all pre-validation hooks
func (*AuthHooks) GetConfig ¶
func (ah *AuthHooks) GetConfig() *AuthConfig
GetConfig returns the authentication configuration
func (*AuthHooks) GetMetrics ¶
GetMetrics returns authentication metrics
func (*AuthHooks) GetProvider ¶
func (ah *AuthHooks) GetProvider() AuthProvider
GetProvider returns the current authentication provider
func (*AuthHooks) SetProvider ¶
func (ah *AuthHooks) SetProvider(provider AuthProvider)
SetProvider sets the authentication provider
type AuthProvider ¶
type AuthProvider interface { // Authenticate validates credentials and returns an authentication context Authenticate(ctx context.Context, credentials Credentials) (*AuthContext, error) // Authorize checks if the authenticated context has permission for a specific action Authorize(ctx context.Context, authCtx *AuthContext, resource string, action string) error // Refresh refreshes the authentication context (e.g., refresh tokens) Refresh(ctx context.Context, authCtx *AuthContext) (*AuthContext, error) // Revoke revokes the authentication context Revoke(ctx context.Context, authCtx *AuthContext) error // ValidateContext validates if an authentication context is still valid ValidateContext(ctx context.Context, authCtx *AuthContext) error // GetProviderType returns the type of authentication provider GetProviderType() string }
AuthProvider defines the interface for authentication providers This interface can be implemented by various authentication backends like JWT, OAuth, RBAC, etc.
type AuthValidationRule ¶
type AuthValidationRule struct { *events.BaseValidationRule // contains filtered or unexported fields }
AuthValidationRule implements authentication and authorization validation for events
func NewAuthValidationRule ¶
func NewAuthValidationRule(authHooks *AuthHooks) *AuthValidationRule
NewAuthValidationRule creates a new authentication validation rule
func (*AuthValidationRule) CreateInfo ¶
func (r *AuthValidationRule) CreateInfo(event events.Event, message string, context map[string]interface{}) *events.ValidationError
CreateInfo creates an informational validation message
func (*AuthValidationRule) Validate ¶
func (r *AuthValidationRule) Validate(event events.Event, context *events.ValidationContext) *events.ValidationResult
Validate implements the ValidationRule interface
type AuthenticatedValidator ¶
type AuthenticatedValidator struct {
// contains filtered or unexported fields
}
AuthenticatedValidator wraps the EventValidator to add authentication support
func CreateWithBasicAuth ¶
func CreateWithBasicAuth() *AuthenticatedValidator
CreateWithBasicAuth creates an authenticated validator with basic auth
func CreateWithRequiredAuth ¶
func CreateWithRequiredAuth() *AuthenticatedValidator
CreateWithRequiredAuth creates an authenticated validator that requires authentication
func NewAuthenticatedValidator ¶
func NewAuthenticatedValidator(config *events.ValidationConfig, authProvider AuthProvider, authConfig *AuthConfig) *AuthenticatedValidator
NewAuthenticatedValidator creates a new validator with authentication support
func (*AuthenticatedValidator) AddPostValidationHook ¶
func (av *AuthenticatedValidator) AddPostValidationHook(hook PostValidationHook)
AddPostValidationHook adds a post-validation authentication hook
func (*AuthenticatedValidator) AddPreValidationHook ¶
func (av *AuthenticatedValidator) AddPreValidationHook(hook PreValidationHook)
AddPreValidationHook adds a pre-validation authentication hook
func (*AuthenticatedValidator) DisableAuthentication ¶
func (av *AuthenticatedValidator) DisableAuthentication()
DisableAuthentication disables authentication
func (*AuthenticatedValidator) EnableAuthentication ¶
func (av *AuthenticatedValidator) EnableAuthentication()
EnableAuthentication enables authentication
func (*AuthenticatedValidator) GetAuthHooks ¶
func (av *AuthenticatedValidator) GetAuthHooks() *AuthHooks
GetAuthHooks returns the authentication hooks
func (*AuthenticatedValidator) GetMetrics ¶
func (av *AuthenticatedValidator) GetMetrics() map[string]interface{}
GetMetrics returns validation and authentication metrics
func (*AuthenticatedValidator) GetValidator ¶
func (av *AuthenticatedValidator) GetValidator() *events.EventValidator
GetValidator returns the underlying event validator
func (*AuthenticatedValidator) IsAuthenticationEnabled ¶
func (av *AuthenticatedValidator) IsAuthenticationEnabled() bool
IsAuthenticationEnabled returns whether authentication is enabled
func (*AuthenticatedValidator) SetAuthProvider ¶
func (av *AuthenticatedValidator) SetAuthProvider(provider AuthProvider)
SetAuthProvider sets the authentication provider
func (*AuthenticatedValidator) StartCleanupRoutine ¶
func (av *AuthenticatedValidator) StartCleanupRoutine(ctx context.Context, interval time.Duration)
StartCleanupRoutine starts a background cleanup routine for expired sessions
func (*AuthenticatedValidator) ValidateEvent ¶
func (av *AuthenticatedValidator) ValidateEvent(ctx context.Context, event events.Event) *events.ValidationResult
ValidateEvent validates an event with authentication
func (*AuthenticatedValidator) ValidateEventWithAuth ¶
func (av *AuthenticatedValidator) ValidateEventWithAuth(ctx context.Context, event events.Event, authCtx *AuthContext) *events.ValidationResult
ValidateEventWithAuth validates an event with explicit authentication
func (*AuthenticatedValidator) ValidateEventWithCredentials ¶
func (av *AuthenticatedValidator) ValidateEventWithCredentials(ctx context.Context, event events.Event, credentials Credentials) *events.ValidationResult
ValidateEventWithCredentials validates an event with credentials
func (*AuthenticatedValidator) ValidateSequence ¶
func (av *AuthenticatedValidator) ValidateSequence(ctx context.Context, events []events.Event) *events.ValidationResult
ValidateSequence validates a sequence of events with authentication
func (*AuthenticatedValidator) ValidateWithAPIKey ¶
func (av *AuthenticatedValidator) ValidateWithAPIKey(ctx context.Context, event events.Event, apiKey string) *events.ValidationResult
ValidateWithAPIKey is a helper function to validate with an API key
func (*AuthenticatedValidator) ValidateWithBasicAuth ¶
func (av *AuthenticatedValidator) ValidateWithBasicAuth(ctx context.Context, event events.Event, username, password string) *events.ValidationResult
ValidateWithBasicAuth is a helper function to validate with basic auth
func (*AuthenticatedValidator) ValidateWithToken ¶
func (av *AuthenticatedValidator) ValidateWithToken(ctx context.Context, event events.Event, token string) *events.ValidationResult
ValidateWithToken is a helper function to validate with a token
type BasicAuthProvider ¶
type BasicAuthProvider struct {
// contains filtered or unexported fields
}
BasicAuthProvider provides a simple in-memory authentication implementation This can be used for testing or as a foundation for more complex providers
func NewBasicAuthProvider ¶
func NewBasicAuthProvider(config *AuthConfig) *BasicAuthProvider
NewBasicAuthProvider creates a new basic authentication provider
func (*BasicAuthProvider) AddUser ¶
func (p *BasicAuthProvider) AddUser(user *User) error
AddUser adds a user to the provider
func (*BasicAuthProvider) Authenticate ¶
func (p *BasicAuthProvider) Authenticate(ctx context.Context, credentials Credentials) (*AuthContext, error)
Authenticate validates credentials and returns an authentication context
func (*BasicAuthProvider) Authorize ¶
func (p *BasicAuthProvider) Authorize(ctx context.Context, authCtx *AuthContext, resource string, action string) error
Authorize checks if the authenticated context has permission for a specific action
func (*BasicAuthProvider) CleanupExpiredSessions ¶
func (p *BasicAuthProvider) CleanupExpiredSessions()
CleanupExpiredSessions removes expired sessions and old revoked tokens
func (*BasicAuthProvider) CleanupOldAuditEvents ¶
func (p *BasicAuthProvider) CleanupOldAuditEvents() error
CleanupOldAuditEvents removes audit events older than the retention period
func (*BasicAuthProvider) GetAuditEvents ¶
func (p *BasicAuthProvider) GetAuditEvents(filter *AuditEventFilter) ([]*AuditEvent, error)
GetAuditEvents returns audit events based on the provided filter
func (*BasicAuthProvider) GetProviderType ¶
func (p *BasicAuthProvider) GetProviderType() string
GetProviderType returns the type of authentication provider
func (*BasicAuthProvider) Refresh ¶
func (p *BasicAuthProvider) Refresh(ctx context.Context, authCtx *AuthContext) (*AuthContext, error)
Refresh refreshes the authentication context
func (*BasicAuthProvider) RemoveUser ¶
func (p *BasicAuthProvider) RemoveUser(username string) error
RemoveUser removes a user from the provider
func (*BasicAuthProvider) Revoke ¶
func (p *BasicAuthProvider) Revoke(ctx context.Context, authCtx *AuthContext) error
Revoke revokes the authentication context
func (*BasicAuthProvider) SetUserPassword ¶
func (p *BasicAuthProvider) SetUserPassword(username, password string) error
SetUserPassword sets a user's password (stores hash)
func (*BasicAuthProvider) StopTokenRotation ¶
func (p *BasicAuthProvider) StopTokenRotation()
StopTokenRotation stops the automatic token rotation process
func (*BasicAuthProvider) ValidateContext ¶
func (p *BasicAuthProvider) ValidateContext(ctx context.Context, authCtx *AuthContext) error
ValidateContext validates if an authentication context is still valid
type BasicCredentials ¶
type BasicCredentials struct { Username string `json:"username"` Password string `json:"password"` }
BasicCredentials represents username/password credentials
func (*BasicCredentials) GetType ¶
func (c *BasicCredentials) GetType() string
GetType returns the credential type
func (*BasicCredentials) Validate ¶
func (c *BasicCredentials) Validate() error
Validate validates the basic credentials with security checks
type CSRFConfig ¶
type CSRFConfig struct { // Secret key for HMAC signing SecretKey []byte // TokenHeader is the header name for CSRF tokens TokenHeader string // TokenField is the form field name for CSRF tokens TokenField string // CookieName is the cookie name for CSRF tokens CookieName string // TokenExpiration is how long CSRF tokens are valid TokenExpiration time.Duration // SecureOnly sets secure flag on cookies SecureOnly bool // SameSite sets SameSite attribute on cookies SameSite http.SameSite // SkipMethods lists HTTP methods to skip CSRF protection SkipMethods []string // TrustedOrigins lists trusted origins for CSRF protection TrustedOrigins []string }
CSRFConfig configures CSRF protection
func DefaultCSRFConfig ¶
func DefaultCSRFConfig() *CSRFConfig
DefaultCSRFConfig returns default CSRF configuration
type CSRFManager ¶
type CSRFManager struct {
// contains filtered or unexported fields
}
CSRFManager handles CSRF token generation and validation
func NewCSRFManager ¶
func NewCSRFManager(config *CSRFConfig) (*CSRFManager, error)
NewCSRFManager creates a new CSRF manager
func (*CSRFManager) CleanupExpiredTokens ¶
func (c *CSRFManager) CleanupExpiredTokens()
CleanupExpiredTokens removes expired CSRF tokens
func (*CSRFManager) ExtractTokenFromRequest ¶
func (c *CSRFManager) ExtractTokenFromRequest(r *http.Request) string
ExtractTokenFromRequest extracts CSRF token from HTTP request
func (*CSRFManager) GenerateToken ¶
func (c *CSRFManager) GenerateToken(userID string) (string, error)
GenerateToken generates a new CSRF token for a user
func (*CSRFManager) GetTokenCount ¶
func (c *CSRFManager) GetTokenCount() int
GetTokenCount returns the number of active CSRF tokens
func (*CSRFManager) Middleware ¶
func (c *CSRFManager) Middleware() func(http.Handler) http.Handler
Middleware returns a CSRF protection middleware
func (*CSRFManager) RevokeToken ¶
func (c *CSRFManager) RevokeToken(token string)
RevokeToken revokes a specific CSRF token
func (*CSRFManager) RevokeUserTokens ¶
func (c *CSRFManager) RevokeUserTokens(userID string)
RevokeUserTokens revokes all CSRF tokens for a specific user
func (*CSRFManager) SetTokenCookie ¶
func (c *CSRFManager) SetTokenCookie(w http.ResponseWriter, token string)
SetTokenCookie sets a CSRF token as a cookie
func (*CSRFManager) ValidateToken ¶
func (c *CSRFManager) ValidateToken(token, userID string) error
ValidateToken validates a CSRF token
type Credentials ¶
type Credentials interface { // GetType returns the type of credentials (e.g., "basic", "token", "api_key") GetType() string // Validate performs basic validation of the credentials Validate() error }
Credentials represents authentication credentials
func GetCredentials ¶
func GetCredentials(ctx context.Context) (Credentials, bool)
GetCredentials retrieves credentials from context
type MemoryAuditLogger ¶
type MemoryAuditLogger struct {
// contains filtered or unexported fields
}
MemoryAuditLogger is a simple in-memory implementation of AuditLogger
func NewMemoryAuditLogger ¶
func NewMemoryAuditLogger() *MemoryAuditLogger
NewMemoryAuditLogger creates a new in-memory audit logger
func (*MemoryAuditLogger) CleanupOldEvents ¶
func (mal *MemoryAuditLogger) CleanupOldEvents(before time.Time) error
CleanupOldEvents removes audit events older than the specified time
func (*MemoryAuditLogger) GetEvents ¶
func (mal *MemoryAuditLogger) GetEvents(filter *AuditEventFilter) ([]*AuditEvent, error)
GetEvents returns audit events based on the provided filter
func (*MemoryAuditLogger) LogEvent ¶
func (mal *MemoryAuditLogger) LogEvent(event *AuditEvent) error
LogEvent logs an audit event
type PostValidationHook ¶
type PostValidationHook func(ctx context.Context, event events.Event, authCtx *AuthContext, result *events.ValidationResult) error
PostValidationHook is called after validation occurs
func AuditHook ¶
func AuditHook() PostValidationHook
AuditHook logs validation results for audit purposes
func EnrichResultHook ¶
func EnrichResultHook() PostValidationHook
EnrichResultHook adds authentication information to validation results
type PostValidationRule ¶
type PostValidationRule struct { *events.BaseValidationRule // contains filtered or unexported fields }
PostValidationRule provides a rule that executes post-validation hooks
func NewPostValidationRule ¶
func NewPostValidationRule(authHooks *AuthHooks) *PostValidationRule
NewPostValidationRule creates a new post-validation rule
func (*PostValidationRule) Validate ¶
func (r *PostValidationRule) Validate(event events.Event, context *events.ValidationContext) *events.ValidationResult
Validate implements the ValidationRule interface for post-validation
type PreValidationHook ¶
PreValidationHook is called before validation occurs
func LogAuthenticationHook ¶
func LogAuthenticationHook() PreValidationHook
LogAuthenticationHook logs authentication information
func RateLimitHook ¶
func RateLimitHook(limits map[string]int) PreValidationHook
RateLimitHook implements rate limiting based on authentication
func RequireAuthenticationHook ¶
func RequireAuthenticationHook() PreValidationHook
RequireAuthenticationHook ensures authentication is present
type SecurityEvent ¶
type SecurityEvent struct { ID string `json:"id"` Timestamp time.Time `json:"timestamp"` EventType SecurityEventType `json:"event_type"` Severity string `json:"severity"` UserID string `json:"user_id,omitempty"` Username string `json:"username,omitempty"` IPAddress string `json:"ip_address,omitempty"` UserAgent string `json:"user_agent,omitempty"` Resource string `json:"resource,omitempty"` Action string `json:"action,omitempty"` Result string `json:"result"` ErrorCode string `json:"error_code,omitempty"` ErrorMsg string `json:"error_message,omitempty"` Metadata map[string]interface{} `json:"metadata,omitempty"` Location string `json:"location,omitempty"` RequestID string `json:"request_id,omitempty"` SessionID string `json:"session_id,omitempty"` RiskScore int `json:"risk_score,omitempty"` Remediation string `json:"remediation,omitempty"` }
SecurityEvent represents a security-related event
type SecurityEventFilter ¶
type SecurityEventFilter struct { EventTypes []SecurityEventType `json:"event_types,omitempty"` UserID string `json:"user_id,omitempty"` IPAddress string `json:"ip_address,omitempty"` StartTime *time.Time `json:"start_time,omitempty"` EndTime *time.Time `json:"end_time,omitempty"` MinRiskScore int `json:"min_risk_score,omitempty"` Limit int `json:"limit,omitempty"` }
SecurityEventFilter filters security events
type SecurityEventType ¶
type SecurityEventType string
SecurityEventType represents the type of security event
const ( SecurityEventAuthFailure SecurityEventType = "auth_failure" SecurityEventAuthSuccess SecurityEventType = "auth_success" SecurityEventAuthAttempt SecurityEventType = "auth_attempt" SecurityEventTokenGeneration SecurityEventType = "token_generation" SecurityEventTokenValidation SecurityEventType = "token_validation" SecurityEventPasswordChange SecurityEventType = "password_change" SecurityEventAccountLockout SecurityEventType = "account_lockout" SecurityEventSuspiciousActivity SecurityEventType = "suspicious_activity" SecurityEventPermissionDenied SecurityEventType = "permission_denied" SecurityEventCSRFAttempt SecurityEventType = "csrf_attempt" SecurityEventCORSViolation SecurityEventType = "cors_violation" SecurityEventRateLimitExceeded SecurityEventType = "rate_limit_exceeded" SecurityEventInputValidationError SecurityEventType = "input_validation_error" SecurityEventPrivilegeEscalation SecurityEventType = "privilege_escalation" SecurityEventDataBreach SecurityEventType = "data_breach" )
type SecurityLogger ¶
type SecurityLogger struct {
// contains filtered or unexported fields
}
SecurityLogger handles security event logging
func NewSecurityLogger ¶
func NewSecurityLogger(config *SecurityLoggerConfig) (*SecurityLogger, error)
NewSecurityLogger creates a new security logger
func (*SecurityLogger) Close ¶
func (sl *SecurityLogger) Close() error
Close closes the security logger
func (*SecurityLogger) GetEvents ¶
func (sl *SecurityLogger) GetEvents(filter *SecurityEventFilter) []*SecurityEvent
GetEvents returns security events with optional filtering
func (*SecurityLogger) LogAuthFailure ¶
func (sl *SecurityLogger) LogAuthFailure(userID, username, ipAddress, userAgent, errorMsg string)
LogAuthFailure logs authentication failure
func (*SecurityLogger) LogAuthSuccess ¶
func (sl *SecurityLogger) LogAuthSuccess(userID, username, ipAddress, userAgent string)
LogAuthSuccess logs successful authentication
func (*SecurityLogger) LogCORSViolation ¶
func (sl *SecurityLogger) LogCORSViolation(ipAddress, userAgent, origin string)
LogCORSViolation logs CORS policy violation
func (*SecurityLogger) LogCSRFAttempt ¶
func (sl *SecurityLogger) LogCSRFAttempt(userID, ipAddress, userAgent, origin string)
LogCSRFAttempt logs CSRF attack attempt
func (*SecurityLogger) LogEvent ¶
func (sl *SecurityLogger) LogEvent(event *SecurityEvent)
LogEvent logs a security event
func (*SecurityLogger) LogInputValidationError ¶
func (sl *SecurityLogger) LogInputValidationError(userID, ipAddress, userAgent, field, errorMsg string)
LogInputValidationError logs input validation error
func (*SecurityLogger) LogPermissionDenied ¶
func (sl *SecurityLogger) LogPermissionDenied(userID, username, ipAddress, resource, action string)
LogPermissionDenied logs permission denied
func (*SecurityLogger) LogRateLimitExceeded ¶
func (sl *SecurityLogger) LogRateLimitExceeded(userID, ipAddress, userAgent, endpoint string)
LogRateLimitExceeded logs rate limit exceeded
func (*SecurityLogger) LogSuspiciousActivity ¶
func (sl *SecurityLogger) LogSuspiciousActivity(userID, ipAddress, userAgent, activity, details string)
LogSuspiciousActivity logs suspicious activity
type SecurityLoggerConfig ¶
type SecurityLoggerConfig struct { // Enabled enables security logging Enabled bool // LogLevel defines minimum log level LogLevel string // LogFile specifies the log file path LogFile string // MaxLogSize maximum log file size before rotation MaxLogSize int64 // MaxLogFiles maximum number of log files to keep MaxLogFiles int // FlushInterval how often to flush logs to disk FlushInterval time.Duration // StructuredLogging enables structured JSON logging StructuredLogging bool // IncludeStackTrace includes stack trace in error logs IncludeStackTrace bool // SyslogEnabled enables syslog output SyslogEnabled bool // SyslogAddress syslog server address SyslogAddress string // AlertThresholds defines thresholds for security alerts AlertThresholds map[SecurityEventType]int // RetentionDays how long to keep security logs RetentionDays int }
SecurityLoggerConfig configures the security logger
func DefaultSecurityLoggerConfig ¶
func DefaultSecurityLoggerConfig() *SecurityLoggerConfig
DefaultSecurityLoggerConfig returns default security logger configuration
type TokenCredentials ¶
type TokenCredentials struct { Token string `json:"token"` TokenType string `json:"token_type"` // e.g., "Bearer", "API" }
TokenCredentials represents token-based credentials
func (*TokenCredentials) GetType ¶
func (c *TokenCredentials) GetType() string
GetType returns the credential type
func (*TokenCredentials) Validate ¶
func (c *TokenCredentials) Validate() error
Validate validates the token credentials with security checks
type TokenRotationInfo ¶
type TokenRotationInfo struct { OldTokenID string `json:"old_token_id"` NewTokenID string `json:"new_token_id"` RotatedAt time.Time `json:"rotated_at"` NextRotation time.Time `json:"next_rotation"` RotationCount int `json:"rotation_count"` }
TokenRotationInfo tracks token rotation history