auth

package
v0.0.0-...-2e1155d Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2025 License: MIT Imports: 20 Imported by: 0

README

Event Validation Authentication

This package provides authentication and authorization capabilities for the AG-UI event validation system.

Overview

The authentication system provides:

  • Pluggable authentication providers - Support for different authentication backends
  • Multiple credential types - Basic auth, tokens, API keys
  • Role-based access control - Fine-grained permissions
  • Authentication hooks - Pre and post validation hooks
  • Rate limiting - Per-user and role-based limits
  • Audit logging - Track who validated what

Quick Start

Basic Authentication
import (
    "github.com/mattsp1290/ag-ui/go-sdk/pkg/core/events"
    "github.com/mattsp1290/ag-ui/go-sdk/pkg/core/events/auth"
)

// Create an authenticated validator
validator := auth.CreateWithBasicAuth()

// Validate with credentials
result := validator.ValidateWithBasicAuth(ctx, event, "username", "password")
Custom Authentication Provider
// Create custom auth provider
provider := auth.NewBasicAuthProvider(nil)

// Add users
provider.AddUser(&auth.User{
    Username:     "validator",
    PasswordHash: auth.HashPassword("secret"),
    Roles:        []string{"validator"},
    Permissions:  []string{"event:validate"},
    Active:       true,
})

// Create validator with custom provider
validator := auth.NewAuthenticatedValidator(
    events.DefaultValidationConfig(),
    provider,
    auth.DefaultAuthConfig(),
)

Authentication Flow

  1. Credentials Extraction - Extract credentials from context
  2. Authentication - Validate credentials with provider
  3. Authorization - Check permissions for the operation
  4. Pre-validation Hooks - Execute custom logic before validation
  5. Event Validation - Standard validation with auth context
  6. Post-validation Hooks - Execute custom logic after validation

Credential Types

Basic Authentication
creds := &auth.BasicCredentials{
    Username: "user",
    Password: "pass",
}
Token Authentication
creds := &auth.TokenCredentials{
    Token:     "bearer-token",
    TokenType: "Bearer",
}
API Key Authentication
creds := &auth.APIKeyCredentials{
    APIKey: "key-123",
    Secret: "optional-secret",
}

Permissions Model

The system uses a resource:action permission model:

  • event:validate - General event validation
  • run:validate - Run event validation
  • message:validate - Message event validation
  • tool:validate - Tool event validation
  • state:validate - State event validation
  • *:* - Wildcard (admin) permission

Hooks

Pre-validation Hooks
validator.AddPreValidationHook(func(ctx context.Context, event events.Event, authCtx *auth.AuthContext) error {
    // Custom logic before validation
    return nil
})
Post-validation Hooks
validator.AddPostValidationHook(func(ctx context.Context, event events.Event, authCtx *auth.AuthContext, result *events.ValidationResult) error {
    // Custom logic after validation
    return nil
})
Built-in Hooks
  • RequireAuthenticationHook() - Enforce authentication
  • LogAuthenticationHook() - Log auth events
  • RateLimitHook(limits) - Apply rate limits
  • AuditHook() - Audit validation operations
  • EnrichResultHook() - Add auth info to results

Configuration

config := &auth.AuthConfig{
    Enabled:           true,
    RequireAuth:       false,
    AllowAnonymous:    true,
    TokenExpiration:   24 * time.Hour,
    RefreshEnabled:    true,
    RefreshExpiration: 7 * 24 * time.Hour,
}

Extending the System

Custom Provider

Implement the AuthProvider interface:

type MyProvider struct {
    // provider fields
}

func (p *MyProvider) Authenticate(ctx context.Context, credentials Credentials) (*AuthContext, error) {
    // Authentication logic
}

func (p *MyProvider) Authorize(ctx context.Context, authCtx *AuthContext, resource, action string) error {
    // Authorization logic
}

// ... other interface methods
Integration with JWT
type JWTProvider struct {
    secretKey []byte
    issuer    string
}

func (p *JWTProvider) Authenticate(ctx context.Context, credentials Credentials) (*AuthContext, error) {
    if tokenCreds, ok := credentials.(*TokenCredentials); ok {
        // Parse and validate JWT token
        claims, err := validateJWT(tokenCreds.Token, p.secretKey)
        if err != nil {
            return nil, err
        }
        
        return &AuthContext{
            UserID:      claims.Subject,
            Username:    claims.Username,
            Roles:       claims.Roles,
            Permissions: claims.Permissions,
            Token:       tokenCreds.Token,
            ExpiresAt:   &claims.ExpiresAt,
            IssuedAt:    claims.IssuedAt,
        }, nil
    }
    
    return nil, ErrInvalidCredentials
}

Security Best Practices

  1. Use strong password hashing - Replace SHA-256 with bcrypt or Argon2
  2. Implement token rotation - Regularly refresh authentication tokens
  3. Enable rate limiting - Prevent brute force attacks
  4. Audit all operations - Log authentication and authorization events
  5. Use HTTPS - Encrypt credentials in transit
  6. Implement session timeout - Expire inactive sessions
  7. Validate input - Sanitize all authentication inputs

Metrics

The system tracks authentication metrics:

metrics := validator.GetMetrics()
// Returns:
// - auth_attempts
// - auth_successes
// - auth_failures
// - success_rate
// - validation metrics

Examples

See example_test.go for complete examples including:

  • Basic authentication
  • Token authentication
  • Required authentication
  • Role-based authorization
  • Custom hooks
  • Rate limiting

Troubleshooting

Common Issues and Solutions
Authentication Failures

Problem: Users unable to authenticate despite correct credentials

Error: authentication failed for user 'alice'

Diagnostic Steps:

  1. Check user exists and is active:

    user, exists := provider.GetUser("alice")
    if !exists || !user.Active {
        // User doesn't exist or is disabled
    }
    
  2. Verify password hash:

    if !provider.ValidatePassword("alice", "password") {
        // Password validation failed
    }
    
  3. Check provider configuration:

    config := provider.GetConfig()
    if config == nil {
        // Provider not properly configured
    }
    

Solutions:

  • Ensure user is added with provider.AddUser() and provider.SetUserPassword()
  • Verify user Active field is set to true
  • Check password complexity requirements
  • Validate password hashing algorithm compatibility
Authorization Errors

Problem: User authenticated but validation fails with permission errors

Error: user 'alice' does not have permission 'event:validate'

Diagnostic Steps:

  1. Check user permissions:

    authCtx, _ := provider.Authenticate(ctx, credentials)
    hasPermission := provider.CheckPermission(authCtx, "event", "validate")
    
  2. Verify role assignments:

    user, _ := provider.GetUser("alice")
    log.Printf("User roles: %v", user.Roles)
    log.Printf("User permissions: %v", user.Permissions)
    

Solutions:

  • Add required permissions to user: user.Permissions = append(user.Permissions, "event:validate")
  • Assign appropriate roles with sufficient permissions
  • Use wildcard permission *:* for admin users
  • Check resource and action naming conventions
Token Expiration Issues

Problem: Valid tokens being rejected as expired

Error: token expired at 2024-01-01T12:00:00Z

Diagnostic Steps:

  1. Check token timestamps:

    authCtx, _ := provider.Authenticate(ctx, tokenCredentials)
    if authCtx.ExpiresAt != nil && time.Now().After(*authCtx.ExpiresAt) {
        // Token is expired
    }
    
  2. Verify system time synchronization

  3. Check token refresh configuration

Solutions:

  • Implement token refresh mechanism
  • Adjust token expiration times in AuthConfig
  • Ensure system clocks are synchronized across nodes
  • Use refresh tokens for long-lived sessions
Performance Issues

Problem: Authentication operations taking too long

Warning: authentication took 2.5s for user 'alice'

Diagnostic Commands:

# Monitor authentication metrics
go test -bench=BenchmarkAuthentication ./pkg/core/events/auth/

Solutions:

  • Cache authentication results with short TTL
  • Use more efficient password hashing (consider bcrypt with lower cost)
  • Implement connection pooling for external auth providers
  • Add authentication timeout configurations
Memory Leaks and Resource Issues

Problem: Authentication validator consuming excessive memory

Diagnostic Commands:

# Run memory profiling
go test -memprofile=mem.prof -bench=. ./pkg/core/events/auth/
go tool pprof mem.prof

# Check for goroutine leaks
go test -race -count=10 ./pkg/core/events/auth/

Solutions:

  • Implement proper cleanup in defer statements
  • Use context cancellation for long-running operations
  • Limit concurrent authentication operations
  • Implement user session cleanup
Configuration Problems

Problem: Authentication hooks not being executed

Diagnostic Steps:

  1. Verify hook registration:

    hooks := validator.GetPreValidationHooks()
    log.Printf("Registered hooks: %d", len(hooks))
    
  2. Check hook execution order:

    validator.AddPreValidationHook(func(ctx context.Context, event Event, authCtx *AuthContext) error {
        log.Printf("Hook executed for user: %s", authCtx.Username)
        return nil
    })
    

Solutions:

  • Ensure hooks are added before validation operations
  • Check hook return values (non-nil errors abort validation)
  • Verify context propagation through hook chain
  • Use proper error handling in hook implementations
Debugging Commands
Enable Debug Logging
config := &auth.AuthConfig{
    Enabled:     true,
    DebugMode:   true,
    LogLevel:    "DEBUG",
}
Authentication Metrics
metrics := validator.GetMetrics()
log.Printf("Auth attempts: %d", metrics.AuthAttempts)
log.Printf("Auth successes: %d", metrics.AuthSuccesses)
log.Printf("Auth failures: %d", metrics.AuthFailures)
log.Printf("Success rate: %.2f%%", metrics.SuccessRate*100)
Provider Health Check
health := provider.HealthCheck()
if !health.Healthy {
    log.Printf("Provider unhealthy: %s", health.Message)
    for _, issue := range health.Issues {
        log.Printf("Issue: %s", issue)
    }
}
User Activity Audit
// Enable audit logging
validator.AddPostValidationHook(auth.AuditHook())

// Query audit logs
auditEntries := validator.GetAuditLog()
for _, entry := range auditEntries {
    log.Printf("User: %s, Action: %s, Time: %v", 
        entry.Username, entry.Action, entry.Timestamp)
}
Performance Debugging
Authentication Latency Analysis
func measureAuthLatency() {
    start := time.Now()
    result := validator.ValidateWithBasicAuth(ctx, event, "user", "pass")
    latency := time.Since(start)
    
    if latency > 100*time.Millisecond {
        log.Printf("Slow authentication: %v", latency)
    }
}
Memory Usage Monitoring
import "runtime"

func monitorMemory() {
    var m runtime.MemStats
    runtime.ReadMemStats(&m)
    
    log.Printf("Auth memory usage:")
    log.Printf("  Allocated: %d KB", m.Alloc/1024)
    log.Printf("  Total allocated: %d KB", m.TotalAlloc/1024)
    log.Printf("  System memory: %d KB", m.Sys/1024)
}
Rate Limiting Diagnostics
rateLimiter := validator.GetRateLimiter()
if rateLimiter != nil {
    stats := rateLimiter.GetStats()
    log.Printf("Rate limit stats:")
    log.Printf("  Requests: %d", stats.Requests)
    log.Printf("  Allowed: %d", stats.Allowed)
    log.Printf("  Blocked: %d", stats.Blocked)
    log.Printf("  Current rate: %.2f req/s", stats.CurrentRate)
}
Integration Debugging
External Provider Connectivity
// For LDAP/AD integration
func testLDAPConnection() error {
    conn, err := ldap.Dial("tcp", "ldap.example.com:389")
    if err != nil {
        return fmt.Errorf("LDAP connection failed: %w", err)
    }
    defer conn.Close()
    
    err = conn.Bind("cn=admin,dc=example,dc=com", "password")
    if err != nil {
        return fmt.Errorf("LDAP bind failed: %w", err)
    }
    
    return nil
}
JWT Token Validation
func debugJWTToken(tokenString string) {
    token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        return []byte("secret"), nil
    })
    
    if err != nil {
        log.Printf("JWT parse error: %v", err)
        return
    }
    
    if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
        log.Printf("JWT claims: %v", claims)
        log.Printf("Expires at: %v", claims["exp"])
        log.Printf("Issued at: %v", claims["iat"])
    }
}

Future Enhancements

This foundation can be extended with:

  • JWT token support
  • OAuth2/OIDC integration
  • LDAP/AD authentication
  • SAML support
  • Multi-factor authentication
  • API key management
  • Session management
  • Single sign-on (SSO)

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

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrNoAuthProvider          = errors.New("no authentication provider configured")
	ErrInvalidCredentials      = errors.New("invalid credentials")
	ErrUnauthorized            = errors.New("unauthorized")
	ErrTokenExpired            = errors.New("authentication token expired")
	ErrInsufficientPermissions = errors.New("insufficient permissions")
)

Common authentication errors

Functions

func Example

func Example()

Example demonstrates how to use the authenticated validator

func ExtractSecurityInfoFromRequest

func ExtractSecurityInfoFromRequest(r *http.Request) (ipAddress, userAgent, requestID string)

ExtractSecurityInfoFromRequest extracts security-relevant information from HTTP request

func IsSecurityEvent

func IsSecurityEvent(err error) bool

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) Disable

func (ah *AuthHooks) Disable()

Disable disables authentication hooks

func (*AuthHooks) Enable

func (ah *AuthHooks) Enable()

Enable enables authentication hooks

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

func (ah *AuthHooks) GetMetrics() map[string]interface{}

GetMetrics returns authentication metrics

func (*AuthHooks) GetProvider

func (ah *AuthHooks) GetProvider() AuthProvider

GetProvider returns the current authentication provider

func (*AuthHooks) IsEnabled

func (ah *AuthHooks) IsEnabled() bool

IsEnabled returns whether authentication hooks are enabled

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

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 CSRFToken

type CSRFToken struct {
	Token     string
	UserID    string
	IssuedAt  time.Time
	ExpiresAt time.Time
}

CSRFToken represents a CSRF token with metadata

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

Validate implements the ValidationRule interface for post-validation

type PreValidationHook

type PreValidationHook func(ctx context.Context, event events.Event, authCtx *AuthContext) error

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

type User

type User struct {
	ID           string
	Username     string
	PasswordHash string
	Roles        []string
	Permissions  []string
	Metadata     map[string]interface{}
	Active       bool
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

User represents a user in the basic auth provider

Jump to

Keyboard shortcuts

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