Documentation
¶
Index ¶
- Variables
- func GenerateEncryptionKey() (string, error)
- func GenerateSecureEncryptionKey() (string, error)
- func GenerateSecureJWTSecret() (string, error)
- func ValidateEncryptionKey(key string) error
- type APIKeyRequest
- type ActionType
- type AdvancedPattern
- type AttackDetector
- type AuditConfig
- type AuditEvent
- type AuditLogConfig
- type AuditLogEntry
- type AuditLogger
- func (al *AuditLogger) Close() error
- func (al *AuditLogger) GetLogStats() (map[string]interface{}, error)
- func (al *AuditLogger) LogAPIAccess(userID, ipAddress, userAgent, method, endpoint string, statusCode int, ...)
- func (al *AuditLogger) LogAuthentication(userID, ipAddress, userAgent string, success bool, ...)
- func (al *AuditLogger) LogAuthorization(userID, ipAddress, action, resource string, allowed bool, ...)
- func (al *AuditLogger) LogConfigChange(userID, ipAddress, configKey, oldValue, newValue string, ...)
- func (al *AuditLogger) LogDataAccess(userID, ipAddress, action, resource string, details map[string]interface{})
- func (al *AuditLogger) LogEvent(event AuditEvent)
- func (al *AuditLogger) LogSecurityViolation(userID, ipAddress, userAgent, violation string, severity string, ...)
- func (al *AuditLogger) LogSystemEvent(eventType, action, message string, details map[string]interface{})
- type AuthSecurityConfig
- type BehaviorAnalyzer
- type BehaviorProfile
- type CacheEntry
- type CacheKey
- type ContextualRule
- type DetectionEvent
- type EncryptionConfig
- type EncryptionService
- func (e *EncryptionService) Decrypt(ciphertext string) ([]byte, error)
- func (e *EncryptionService) DecryptSensitiveData(data map[string]interface{}) (map[string]interface{}, error)
- func (e *EncryptionService) DecryptString(ciphertext string) (string, error)
- func (e *EncryptionService) Encrypt(plaintext []byte) (string, error)
- func (e *EncryptionService) EncryptSensitiveData(data map[string]interface{}) (map[string]interface{}, error)
- func (e *EncryptionService) EncryptString(plaintext string) (string, error)
- func (e *EncryptionService) RotateEncryptionKey(newKeyString string) error
- type EndpointLimit
- type InputValidator
- func (iv *InputValidator) RegisterCustomValidator(tag string, fn validator.Func) error
- func (iv *InputValidator) SanitizeHTML(input string) string
- func (iv *InputValidator) SanitizeString(input string) string
- func (iv *InputValidator) ValidateAPIKey(key string) ValidationResult
- func (iv *InputValidator) ValidateJSON(data []byte) ValidationResult
- func (iv *InputValidator) ValidatePackageName(name string) ValidationResult
- func (iv *InputValidator) ValidateStruct(s interface{}) ValidationResult
- func (iv *InputValidator) ValidateURL(rawURL string) (string, ValidationResult)
- type JWTSecurityConfig
- type PerformanceConfig
- type PerformanceOptimizer
- func (po *PerformanceOptimizer) CleanupExpiredEntries()
- func (po *PerformanceOptimizer) ClearCaches()
- func (po *PerformanceOptimizer) GetConnection() *SecurityConnection
- func (po *PerformanceOptimizer) GetMetrics() map[string]interface{}
- func (po *PerformanceOptimizer) OptimizePolicyEvaluation(ctx context.Context, policyKey string, ...) (interface{}, *PerformanceResult, error)
- func (po *PerformanceOptimizer) OptimizeRateLimit(ctx context.Context, rateLimitKey string, checkFunc func() (bool, error)) (bool, *PerformanceResult, error)
- func (po *PerformanceOptimizer) OptimizeValidation(ctx context.Context, validationKey string, validationFunc func() (bool, error)) (bool, *PerformanceResult, error)
- func (po *PerformanceOptimizer) ReleaseConnection(conn *SecurityConnection)
- func (po *PerformanceOptimizer) Shutdown(ctx context.Context) error
- func (po *PerformanceOptimizer) UpdateConfig(config *PerformanceConfig)
- type PerformanceResult
- type PolicyAction
- type PolicyContext
- type PolicyEngine
- func (pe *PolicyEngine) AddPolicy(policy *SecurityPolicy) error
- func (pe *PolicyEngine) EvaluateAllPolicies(context *PolicyContext) ([]*PolicyResult, error)
- func (pe *PolicyEngine) EvaluatePolicy(policyID string, context *PolicyContext) (*PolicyResult, error)
- func (pe *PolicyEngine) GetPolicies() map[string]*SecurityPolicy
- func (pe *PolicyEngine) GetPolicy(policyID string) (*SecurityPolicy, bool)
- func (pe *PolicyEngine) RemovePolicy(policyID string) error
- type PolicyResult
- type PolicyRule
- type PolicyType
- type RBACSecurityConfig
- type RateLimitSecurityConfig
- type RequestAnalyzer
- type ResponseFilter
- type ResponseFilterConfig
- type RuleOperator
- type ScanRequest
- type SecureConfigValidator
- func (v *SecureConfigValidator) GenerateSecureSecret(length int) (string, error)
- func (v *SecureConfigValidator) GetSecurityRecommendations() []string
- func (v *SecureConfigValidator) ValidateAPIKeys(keys []string) error
- func (v *SecureConfigValidator) ValidateAdminPassword(password string) error
- func (v *SecureConfigValidator) ValidateEncryptionKey(key string) error
- func (v *SecureConfigValidator) ValidateJWTSecret(secret string) error
- func (v *SecureConfigValidator) ValidateProductionConfig() error
- type SecurityConfig
- type SecurityConnection
- type SecurityPerformanceMetrics
- type SecurityPolicy
- type SequenceDetector
- type SessionConfig
- type UserRequest
- type ValidationError
- type ValidationResult
Constants ¶
This section is empty.
Variables ¶
var ( ErrProcessingTimeout = errors.New("security processing timeout") ErrMemoryLimitExceeded = errors.New("memory limit exceeded") ErrCacheNotAvailable = errors.New("cache not available") )
Performance optimization errors
Functions ¶
func GenerateEncryptionKey ¶ added in v1.0.1
GenerateEncryptionKey generates a new encryption key
func GenerateSecureEncryptionKey ¶ added in v1.0.1
GenerateSecureEncryptionKey generates a cryptographically secure encryption key
func GenerateSecureJWTSecret ¶ added in v1.0.1
GenerateSecureJWTSecret generates a cryptographically secure JWT secret
func ValidateEncryptionKey ¶ added in v1.0.1
ValidateEncryptionKey validates an encryption key
Types ¶
type APIKeyRequest ¶ added in v1.0.1
type APIKeyRequest struct {
Name string `json:"name" validate:"required,min=1,max=100,no_sql_injection,no_xss"`
Description string `json:"description" validate:"max=500,no_xss"`
ExpiresAt time.Time `json:"expires_at" validate:"required"`
Permissions []string `json:"permissions" validate:"required,dive,oneof=read write admin"`
}
APIKeyRequest represents an API key creation request
type ActionType ¶ added in v1.0.1
type ActionType string
ActionType defines types of policy actions
const ( ActionBlock ActionType = "block" ActionAllow ActionType = "allow" ActionLog ActionType = "log" ActionAlert ActionType = "alert" ActionThrottle ActionType = "throttle" ActionRedirect ActionType = "redirect" ActionQuarantine ActionType = "quarantine" )
type AdvancedPattern ¶ added in v1.0.1
type AdvancedPattern struct {
Pattern *regexp.Regexp
Severity string
Category string
Description string
Mitigation string
FalsePositiveRate float64
ContextualRules []ContextualRule
}
AdvancedPattern represents an advanced attack detection pattern
type AttackDetector ¶ added in v1.0.1
type AttackDetector struct {
// contains filtered or unexported fields
}
AttackDetector detects various attack patterns
func NewAttackDetector ¶ added in v1.0.1
func NewAttackDetector() *AttackDetector
NewAttackDetector creates a new attack detector
func (*AttackDetector) DetectInString ¶ added in v1.0.1
func (ad *AttackDetector) DetectInString(input string) (bool, string)
DetectInString detects attack patterns in a string
type AuditConfig ¶ added in v1.0.1
type AuditConfig struct {
Enabled bool `json:"enabled"`
LogLevel string `json:"log_level"`
LogSensitiveData bool `json:"log_sensitive_data"`
RetentionDays int `json:"retention_days"`
AuditEvents []string `json:"audit_events"`
}
AuditConfig contains audit logging settings
type AuditEvent ¶ added in v1.0.1
type AuditEvent struct {
EventType string `json:"event_type"`
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
UserID *string `json:"user_id,omitempty"`
Success bool `json:"success"`
EventData map[string]interface{} `json:"event_data,omitempty"`
}
AuditEvent represents a generic audit event
type AuditLogConfig ¶ added in v1.0.1
type AuditLogConfig struct {
LogPath string `json:"log_path"`
EncryptLogs bool `json:"encrypt_logs"`
MaxFileSize int64 `json:"max_file_size"`
MaxFiles int `json:"max_files"`
LogLevel string `json:"log_level"`
IncludeMetadata bool `json:"include_metadata"`
}
AuditLogConfig holds audit logging configuration
type AuditLogEntry ¶ added in v1.0.1
type AuditLogEntry struct {
Timestamp time.Time `json:"timestamp"`
Level string `json:"level"`
EventType string `json:"event_type"`
UserID string `json:"user_id,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
Action string `json:"action"`
Resource string `json:"resource,omitempty"`
Result string `json:"result"`
Message string `json:"message"`
Details map[string]interface{} `json:"details,omitempty"`
RequestID string `json:"request_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
Fingerprint string `json:"fingerprint"`
}
AuditLogEntry represents a single audit log entry
type AuditLogger ¶ added in v1.0.1
type AuditLogger struct {
// contains filtered or unexported fields
}
AuditLogger provides secure audit logging capabilities
func NewAuditLogger ¶ added in v1.0.1
func NewAuditLogger(config *AuditLogConfig) (*AuditLogger, error)
NewAuditLogger creates a new audit logger
func (*AuditLogger) Close ¶ added in v1.0.1
func (al *AuditLogger) Close() error
Close closes the audit logger
func (*AuditLogger) GetLogStats ¶ added in v1.0.1
func (al *AuditLogger) GetLogStats() (map[string]interface{}, error)
GetLogStats returns statistics about the audit log
func (*AuditLogger) LogAPIAccess ¶ added in v1.0.1
func (al *AuditLogger) LogAPIAccess(userID, ipAddress, userAgent, method, endpoint string, statusCode int, responseTime time.Duration, details map[string]interface{})
LogAPIAccess logs API access events
func (*AuditLogger) LogAuthentication ¶ added in v1.0.1
func (al *AuditLogger) LogAuthentication(userID, ipAddress, userAgent string, success bool, details map[string]interface{})
LogAuthentication logs authentication events
func (*AuditLogger) LogAuthorization ¶ added in v1.0.1
func (al *AuditLogger) LogAuthorization(userID, ipAddress, action, resource string, allowed bool, details map[string]interface{})
LogAuthorization logs authorization events
func (*AuditLogger) LogConfigChange ¶ added in v1.0.1
func (al *AuditLogger) LogConfigChange(userID, ipAddress, configKey, oldValue, newValue string, details map[string]interface{})
LogConfigChange logs configuration changes
func (*AuditLogger) LogDataAccess ¶ added in v1.0.1
func (al *AuditLogger) LogDataAccess(userID, ipAddress, action, resource string, details map[string]interface{})
LogDataAccess logs data access events
func (*AuditLogger) LogEvent ¶ added in v1.0.1
func (al *AuditLogger) LogEvent(event AuditEvent)
LogEvent logs a generic audit event
func (*AuditLogger) LogSecurityViolation ¶ added in v1.0.1
func (al *AuditLogger) LogSecurityViolation(userID, ipAddress, userAgent, violation string, severity string, details map[string]interface{})
LogSecurityViolation logs security violations
func (*AuditLogger) LogSystemEvent ¶ added in v1.0.1
func (al *AuditLogger) LogSystemEvent(eventType, action, message string, details map[string]interface{})
LogSystemEvent logs system-level events
type AuthSecurityConfig ¶ added in v1.0.1
type AuthSecurityConfig struct {
RequireStrongPasswords bool `json:"require_strong_passwords"`
MinPasswordLength int `json:"min_password_length"`
PasswordMinLength int `json:"password_min_length"`
MaxLoginAttempts int `json:"max_login_attempts"`
LockoutDuration time.Duration `json:"lockout_duration"`
RequireMFA bool `json:"require_mfa"`
SessionTimeout time.Duration `json:"session_timeout"`
PasswordHashAlgorithm string `json:"password_hash_algorithm"`
SaltLength int `json:"salt_length"`
RequireUppercase bool `json:"require_uppercase"`
RequireLowercase bool `json:"require_lowercase"`
RequireNumbers bool `json:"require_numbers"`
RequireSymbols bool `json:"require_symbols"`
PasswordMaxAge time.Duration `json:"password_max_age"`
PasswordHistoryCount int `json:"password_history_count"`
}
AuthSecurityConfig contains authentication security settings
type BehaviorAnalyzer ¶ added in v1.0.1
type BehaviorAnalyzer struct {
// contains filtered or unexported fields
}
BehaviorAnalyzer analyzes client behavior patterns
func NewBehaviorAnalyzer ¶ added in v1.0.1
func NewBehaviorAnalyzer() *BehaviorAnalyzer
NewBehaviorAnalyzer creates a new behavior analyzer
func (*BehaviorAnalyzer) AnalyzeBehavior ¶ added in v1.0.1
func (ba *BehaviorAnalyzer) AnalyzeBehavior(clientID string, suspicious bool) float64
AnalyzeBehavior analyzes client behavior
type BehaviorProfile ¶ added in v1.0.1
type BehaviorProfile struct {
ClientID string
RequestCount int
ErrorCount int
LastSeen time.Time
SuspiciousCount int
RiskScore float64
}
BehaviorProfile represents a client's behavior profile
type CacheEntry ¶ added in v1.0.1
CacheEntry represents a cached item with expiration
type ContextualRule ¶ added in v1.0.1
ContextualRule represents a contextual rule for pattern matching
type DetectionEvent ¶ added in v1.0.1
type DetectionEvent struct {
Timestamp time.Time
AttackType string
Severity string
Description string
ClientID string
Blocked bool
}
DetectionEvent represents a detection event
type EncryptionConfig ¶ added in v1.0.1
type EncryptionConfig struct {
Algorithm string `json:"algorithm"`
KeySize int `json:"key_size"`
EncryptionKey string `json:"encryption_key"`
RotationInterval time.Duration `json:"rotation_interval"`
EncryptSensitiveData bool `json:"encrypt_sensitive_data"`
UseArgon2 bool `json:"use_argon2"`
}
EncryptionConfig contains encryption settings
type EncryptionService ¶ added in v1.0.1
type EncryptionService struct {
// contains filtered or unexported fields
}
EncryptionService provides encryption and decryption capabilities
func NewEncryptionService ¶ added in v1.0.1
func NewEncryptionService() (*EncryptionService, error)
NewEncryptionService creates a new encryption service
func (*EncryptionService) Decrypt ¶ added in v1.0.1
func (e *EncryptionService) Decrypt(ciphertext string) ([]byte, error)
Decrypt decrypts ciphertext data
func (*EncryptionService) DecryptSensitiveData ¶ added in v1.0.1
func (e *EncryptionService) DecryptSensitiveData(data map[string]interface{}) (map[string]interface{}, error)
DecryptSensitiveData decrypts sensitive data fields
func (*EncryptionService) DecryptString ¶ added in v1.0.1
func (e *EncryptionService) DecryptString(ciphertext string) (string, error)
DecryptString decrypts to a string
func (*EncryptionService) Encrypt ¶ added in v1.0.1
func (e *EncryptionService) Encrypt(plaintext []byte) (string, error)
Encrypt encrypts plaintext data
func (*EncryptionService) EncryptSensitiveData ¶ added in v1.0.1
func (e *EncryptionService) EncryptSensitiveData(data map[string]interface{}) (map[string]interface{}, error)
EncryptSensitiveData encrypts sensitive data fields
func (*EncryptionService) EncryptString ¶ added in v1.0.1
func (e *EncryptionService) EncryptString(plaintext string) (string, error)
EncryptString encrypts a string
func (*EncryptionService) RotateEncryptionKey ¶ added in v1.0.1
func (e *EncryptionService) RotateEncryptionKey(newKeyString string) error
RotateEncryptionKey rotates the encryption key
type EndpointLimit ¶ added in v1.0.1
type EndpointLimit struct {
RequestsPerSecond int `json:"requests_per_second"`
BurstSize int `json:"burst_size"`
WindowDuration time.Duration `json:"window_duration"`
}
EndpointLimit defines rate limits for specific endpoints
type InputValidator ¶
type InputValidator struct {
// contains filtered or unexported fields
}
InputValidator provides comprehensive input validation and sanitization
func NewInputValidator ¶
func NewInputValidator() *InputValidator
NewInputValidator creates a new input validator
func (*InputValidator) RegisterCustomValidator ¶ added in v1.0.1
func (iv *InputValidator) RegisterCustomValidator(tag string, fn validator.Func) error
RegisterCustomValidator allows registering custom validation functions
func (*InputValidator) SanitizeHTML ¶ added in v1.0.1
func (iv *InputValidator) SanitizeHTML(input string) string
SanitizeHTML sanitizes HTML content
func (*InputValidator) SanitizeString ¶ added in v1.0.1
func (iv *InputValidator) SanitizeString(input string) string
SanitizeString sanitizes a string input
func (*InputValidator) ValidateAPIKey ¶ added in v1.0.1
func (iv *InputValidator) ValidateAPIKey(key string) ValidationResult
ValidateAPIKey validates API key format
func (*InputValidator) ValidateJSON ¶ added in v1.0.1
func (iv *InputValidator) ValidateJSON(data []byte) ValidationResult
ValidateJSON validates JSON structure and depth
func (*InputValidator) ValidatePackageName ¶ added in v1.0.1
func (iv *InputValidator) ValidatePackageName(name string) ValidationResult
ValidatePackageName validates package names
func (*InputValidator) ValidateStruct ¶ added in v1.0.1
func (iv *InputValidator) ValidateStruct(s interface{}) ValidationResult
ValidateStruct validates a struct using validation tags
func (*InputValidator) ValidateURL ¶ added in v1.0.1
func (iv *InputValidator) ValidateURL(rawURL string) (string, ValidationResult)
ValidateURL validates and sanitizes URLs
type JWTSecurityConfig ¶ added in v1.0.1
type JWTSecurityConfig struct {
SecretKey string `json:"secret_key"`
AccessTokenExpiration time.Duration `json:"access_token_expiration"`
RefreshTokenExpiration time.Duration `json:"refresh_token_expiration"`
Issuer string `json:"issuer"`
Audience string `json:"audience"`
Algorithm string `json:"algorithm"`
RequireHTTPS bool `json:"require_https"`
TokenRevocationEnabled bool `json:"token_revocation_enabled"`
}
JWTSecurityConfig contains JWT security settings
type PerformanceConfig ¶ added in v1.0.1
type PerformanceConfig struct {
// Cache settings
PolicyCacheTTL time.Duration `yaml:"policy_cache_ttl" default:"5m"`
ValidationCacheTTL time.Duration `yaml:"validation_cache_ttl" default:"1m"`
RateLimitCacheTTL time.Duration `yaml:"rate_limit_cache_ttl" default:"30s"`
// Cache sizes
PolicyCacheSize int `yaml:"policy_cache_size" default:"1000"`
ValidationCacheSize int `yaml:"validation_cache_size" default:"5000"`
RateLimitCacheSize int `yaml:"rate_limit_cache_size" default:"10000"`
// Performance thresholds
MaxProcessingTime time.Duration `yaml:"max_processing_time" default:"100ms"`
MaxMemoryUsage int64 `yaml:"max_memory_usage" default:"104857600"` // 100MB
// Optimization flags
EnableCaching bool `yaml:"enable_caching" default:"true"`
EnablePooling bool `yaml:"enable_pooling" default:"true"`
EnableMetrics bool `yaml:"enable_metrics" default:"true"`
EnableCompression bool `yaml:"enable_compression" default:"true"`
}
PerformanceConfig holds performance optimization settings
type PerformanceOptimizer ¶ added in v1.0.1
type PerformanceOptimizer struct {
// contains filtered or unexported fields
}
PerformanceOptimizer optimizes security component performance
func NewPerformanceOptimizer ¶ added in v1.0.1
func NewPerformanceOptimizer(config *PerformanceConfig) *PerformanceOptimizer
NewPerformanceOptimizer creates a new performance optimizer
func (*PerformanceOptimizer) CleanupExpiredEntries ¶ added in v1.0.1
func (po *PerformanceOptimizer) CleanupExpiredEntries()
CleanupExpiredEntries removes expired cache entries
func (*PerformanceOptimizer) ClearCaches ¶ added in v1.0.1
func (po *PerformanceOptimizer) ClearCaches()
ClearCaches clears all caches
func (*PerformanceOptimizer) GetConnection ¶ added in v1.0.1
func (po *PerformanceOptimizer) GetConnection() *SecurityConnection
GetConnection gets a connection from the pool
func (*PerformanceOptimizer) GetMetrics ¶ added in v1.0.1
func (po *PerformanceOptimizer) GetMetrics() map[string]interface{}
GetMetrics returns current performance metrics
func (*PerformanceOptimizer) OptimizePolicyEvaluation ¶ added in v1.0.1
func (po *PerformanceOptimizer) OptimizePolicyEvaluation(ctx context.Context, policyKey string, evaluationFunc func() (interface{}, error)) (interface{}, *PerformanceResult, error)
OptimizePolicyEvaluation optimizes policy evaluation performance
func (*PerformanceOptimizer) OptimizeRateLimit ¶ added in v1.0.1
func (po *PerformanceOptimizer) OptimizeRateLimit(ctx context.Context, rateLimitKey string, checkFunc func() (bool, error)) (bool, *PerformanceResult, error)
OptimizeRateLimit optimizes rate limiting performance
func (*PerformanceOptimizer) OptimizeValidation ¶ added in v1.0.1
func (po *PerformanceOptimizer) OptimizeValidation(ctx context.Context, validationKey string, validationFunc func() (bool, error)) (bool, *PerformanceResult, error)
OptimizeValidation optimizes input validation performance
func (*PerformanceOptimizer) ReleaseConnection ¶ added in v1.0.1
func (po *PerformanceOptimizer) ReleaseConnection(conn *SecurityConnection)
ReleaseConnection returns a connection to the pool
func (*PerformanceOptimizer) Shutdown ¶ added in v1.0.1
func (po *PerformanceOptimizer) Shutdown(ctx context.Context) error
Shutdown gracefully shuts down the performance optimizer
func (*PerformanceOptimizer) UpdateConfig ¶ added in v1.0.1
func (po *PerformanceOptimizer) UpdateConfig(config *PerformanceConfig)
UpdateConfig updates the performance configuration
type PerformanceResult ¶ added in v1.0.1
type PerformanceResult struct {
ProcessingTime time.Duration
CacheHit bool
MemoryUsed int64
Optimized bool
Metrics map[string]interface{}
}
PerformanceResult holds performance optimization results
type PolicyAction ¶ added in v1.0.1
type PolicyAction struct {
Type ActionType `json:"type"`
Parameters map[string]interface{} `json:"parameters"`
Description string `json:"description"`
}
PolicyAction defines actions to take when a policy is violated
type PolicyContext ¶ added in v1.0.1
type PolicyContext struct {
UserID string `json:"user_id"`
IPAddress string `json:"ip_address"`
UserAgent string `json:"user_agent"`
Endpoint string `json:"endpoint"`
Method string `json:"method"`
Headers map[string]string `json:"headers"`
Parameters map[string]interface{} `json:"parameters"`
Body string `json:"body"`
Timestamp time.Time `json:"timestamp"`
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Metadata map[string]interface{} `json:"metadata"`
}
PolicyContext provides context for policy evaluation
type PolicyEngine ¶ added in v1.0.1
type PolicyEngine struct {
// contains filtered or unexported fields
}
PolicyEngine enforces security policies
func NewPolicyEngine ¶ added in v1.0.1
func NewPolicyEngine(auditLogger *AuditLogger) *PolicyEngine
NewPolicyEngine creates a new policy engine
func (*PolicyEngine) AddPolicy ¶ added in v1.0.1
func (pe *PolicyEngine) AddPolicy(policy *SecurityPolicy) error
AddPolicy adds a security policy
func (*PolicyEngine) EvaluateAllPolicies ¶ added in v1.0.1
func (pe *PolicyEngine) EvaluateAllPolicies(context *PolicyContext) ([]*PolicyResult, error)
EvaluateAllPolicies evaluates all enabled policies
func (*PolicyEngine) EvaluatePolicy ¶ added in v1.0.1
func (pe *PolicyEngine) EvaluatePolicy(policyID string, context *PolicyContext) (*PolicyResult, error)
EvaluatePolicy evaluates a policy against the given context
func (*PolicyEngine) GetPolicies ¶ added in v1.0.1
func (pe *PolicyEngine) GetPolicies() map[string]*SecurityPolicy
GetPolicies returns all policies
func (*PolicyEngine) GetPolicy ¶ added in v1.0.1
func (pe *PolicyEngine) GetPolicy(policyID string) (*SecurityPolicy, bool)
GetPolicy returns a specific policy
func (*PolicyEngine) RemovePolicy ¶ added in v1.0.1
func (pe *PolicyEngine) RemovePolicy(policyID string) error
RemovePolicy removes a security policy
type PolicyResult ¶ added in v1.0.1
type PolicyResult struct {
PolicyID string `json:"policy_id"`
RuleID string `json:"rule_id"`
Action ActionType `json:"action"`
Allowed bool `json:"allowed"`
Message string `json:"message"`
Details map[string]interface{} `json:"details"`
Timestamp time.Time `json:"timestamp"`
}
PolicyResult represents the result of policy evaluation
type PolicyRule ¶ added in v1.0.1
type PolicyRule struct {
ID string `json:"id"`
Condition string `json:"condition"`
Field string `json:"field"`
Operator RuleOperator `json:"operator"`
Value interface{} `json:"value"`
Description string `json:"description"`
Metadata map[string]interface{} `json:"metadata"`
}
PolicyRule defines a policy rule
type PolicyType ¶ added in v1.0.1
type PolicyType string
PolicyType defines types of security policies
const ( PolicyTypeAccess PolicyType = "access" PolicyTypeInput PolicyType = "input" PolicyTypeRate PolicyType = "rate" PolicyTypeData PolicyType = "data" PolicyTypeCompliance PolicyType = "compliance" PolicyTypeAuthentication PolicyType = "authentication" )
type RBACSecurityConfig ¶ added in v1.0.1
type RBACSecurityConfig struct {
Enabled bool `json:"enabled"`
DefaultRole string `json:"default_role"`
AdminRoles []string `json:"admin_roles"`
RequireExplicitPermissions bool `json:"require_explicit_permissions"`
MaxRoleInheritanceDepth int `json:"max_role_inheritance_depth"`
}
RBACSecurityConfig contains RBAC security settings
type RateLimitSecurityConfig ¶ added in v1.0.1
type RateLimitSecurityConfig struct {
GlobalEnabled bool `json:"global_enabled"`
GlobalRequestsPerSec int `json:"global_requests_per_sec"`
GlobalBurstSize int `json:"global_burst_size"`
EndpointLimits map[string]EndpointLimit `json:"endpoint_limits"`
IPWhitelist []string `json:"ip_whitelist"`
IPBlacklist []string `json:"ip_blacklist"`
EnableDDoSProtection bool `json:"enable_ddos_protection"`
}
RateLimitSecurityConfig contains rate limiting security settings
type RequestAnalyzer ¶ added in v1.0.1
type RequestAnalyzer struct {
// contains filtered or unexported fields
}
RequestAnalyzer analyzes HTTP requests for security threats
type ResponseFilter ¶ added in v1.0.1
type ResponseFilter struct {
// contains filtered or unexported fields
}
ResponseFilter filters HTTP responses for security
type ResponseFilterConfig ¶ added in v1.0.1
type ResponseFilterConfig struct {
Enabled bool
RemoveHeaders []string
AddSecurityHeaders bool
SanitizeContent bool
}
ResponseFilterConfig configures response filtering
type RuleOperator ¶ added in v1.0.1
type RuleOperator string
RuleOperator defines rule operators
const ( OperatorEquals RuleOperator = "equals" OperatorNotEquals RuleOperator = "not_equals" OperatorContains RuleOperator = "contains" OperatorNotContains RuleOperator = "not_contains" OperatorMatches RuleOperator = "matches" OperatorNotMatches RuleOperator = "not_matches" OperatorGreaterThan RuleOperator = "greater_than" OperatorLessThan RuleOperator = "less_than" OperatorIn RuleOperator = "in" OperatorNotIn RuleOperator = "not_in" OperatorStartsWith RuleOperator = "starts_with" OperatorEndsWith RuleOperator = "ends_with" )
type ScanRequest ¶ added in v1.0.1
type ScanRequest struct {
PackageName string `json:"package_name" validate:"required,package_name,no_sql_injection,no_xss"`
Version string `json:"version" validate:"omitempty,version"`
Registry string `json:"registry" validate:"required,oneof=npm pypi rubygems maven"`
RepositoryURL string `json:"repository_url" validate:"omitempty,url"`
Timeout int `json:"timeout" validate:"min=1,max=3600"`
Options map[string]string `json:"options" validate:"dive,no_sql_injection,no_xss"`
}
ScanRequest represents a scan request with validation
type SecureConfigValidator ¶ added in v1.0.1
type SecureConfigValidator struct{}
SecureConfigValidator validates security configuration
func NewSecureConfigValidator ¶ added in v1.0.1
func NewSecureConfigValidator() *SecureConfigValidator
NewSecureConfigValidator creates a new secure config validator
func (*SecureConfigValidator) GenerateSecureSecret ¶ added in v1.0.1
func (v *SecureConfigValidator) GenerateSecureSecret(length int) (string, error)
GenerateSecureSecret generates a cryptographically secure secret
func (*SecureConfigValidator) GetSecurityRecommendations ¶ added in v1.0.1
func (v *SecureConfigValidator) GetSecurityRecommendations() []string
GetSecurityRecommendations provides security configuration recommendations
func (*SecureConfigValidator) ValidateAPIKeys ¶ added in v1.0.1
func (v *SecureConfigValidator) ValidateAPIKeys(keys []string) error
ValidateAPIKeys validates API key configuration
func (*SecureConfigValidator) ValidateAdminPassword ¶ added in v1.0.1
func (v *SecureConfigValidator) ValidateAdminPassword(password string) error
ValidateAdminPassword validates admin password strength
func (*SecureConfigValidator) ValidateEncryptionKey ¶ added in v1.0.1
func (v *SecureConfigValidator) ValidateEncryptionKey(key string) error
ValidateEncryptionKey validates encryption key strength
func (*SecureConfigValidator) ValidateJWTSecret ¶ added in v1.0.1
func (v *SecureConfigValidator) ValidateJWTSecret(secret string) error
ValidateJWTSecret validates JWT secret strength
func (*SecureConfigValidator) ValidateProductionConfig ¶ added in v1.0.1
func (v *SecureConfigValidator) ValidateProductionConfig() error
ValidateProductionConfig validates all security configuration for production
type SecurityConfig ¶ added in v1.0.1
type SecurityConfig struct {
JWT JWTSecurityConfig `json:"jwt"`
Authentication AuthSecurityConfig `json:"authentication"`
RateLimit RateLimitSecurityConfig `json:"rate_limit"`
RBAC RBACSecurityConfig `json:"rbac"`
Encryption EncryptionConfig `json:"encryption"`
SessionManagement SessionConfig `json:"session_management"`
Session SessionConfig `json:"session"`
AuditLogging AuditConfig `json:"audit_logging"`
}
SecurityConfig holds all security-related configuration
func LoadSecurityConfig ¶ added in v1.0.1
func LoadSecurityConfig() (*SecurityConfig, error)
LoadSecurityConfig loads security configuration from environment variables
func (*SecurityConfig) HashPassword ¶ added in v1.0.1
func (sc *SecurityConfig) HashPassword(password string) (string, error)
HashPassword securely hashes a password using bcrypt
func (*SecurityConfig) Validate ¶ added in v1.0.1
func (sc *SecurityConfig) Validate() error
Validate validates the security configuration
func (*SecurityConfig) VerifyPassword ¶ added in v1.0.1
func (sc *SecurityConfig) VerifyPassword(password, hashedPassword string) bool
VerifyPassword verifies a password against its hash
type SecurityConnection ¶ added in v1.0.1
SecurityConnection represents a pooled security connection
type SecurityPerformanceMetrics ¶ added in v1.0.1
type SecurityPerformanceMetrics struct {
// Processing time metrics
PolicyEvaluationCount int64
PolicyEvaluationTime time.Duration
ValidationCount int64
ValidationTime time.Duration
RateLimitCheckCount int64
RateLimitCheckTime time.Duration
EncryptionCount int64
EncryptionTime time.Duration
// Cache metrics
PolicyCacheHits int64
PolicyCacheMisses int64
ValidationCacheHits int64
ValidationCacheMisses int64
// Performance metrics
TotalProcessingTime time.Duration
MemoryUsed int64
ConcurrentRequests int64
// Error metrics
SecurityErrors int64
TimeoutErrors int64
// contains filtered or unexported fields
}
SecurityPerformanceMetrics holds performance metrics for security components
type SecurityPolicy ¶ added in v1.0.1
type SecurityPolicy struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Type PolicyType `json:"type"`
Enabled bool `json:"enabled"`
Priority int `json:"priority"`
Rules []PolicyRule `json:"rules"`
Actions []PolicyAction `json:"actions"`
Metadata map[string]interface{} `json:"metadata"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
SecurityPolicy defines a security policy
type SequenceDetector ¶ added in v1.0.1
type SequenceDetector struct {
// contains filtered or unexported fields
}
SequenceDetector detects attack sequences
func NewSequenceDetector ¶ added in v1.0.1
func NewSequenceDetector() *SequenceDetector
NewSequenceDetector creates a new sequence detector
func (*SequenceDetector) DetectSequence ¶ added in v1.0.1
func (sd *SequenceDetector) DetectSequence(clientID string, pattern string) bool
DetectSequence detects attack sequences
type SessionConfig ¶ added in v1.0.1
type SessionConfig struct {
CookieSecure bool `json:"cookie_secure"`
CookieHTTPOnly bool `json:"cookie_http_only"`
CookieSameSite string `json:"cookie_same_site"`
SessionTimeout time.Duration `json:"session_timeout"`
IdleTimeout time.Duration `json:"idle_timeout"`
MaxConcurrentSessions int `json:"max_concurrent_sessions"`
}
SessionConfig contains session management settings
type UserRequest ¶ added in v1.0.1
type UserRequest struct {
Username string `json:"username" validate:"required,min=3,max=50,alphanum,no_sql_injection"`
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=8,max=128"`
Role string `json:"role" validate:"required,oneof=admin user viewer"`
}
UserRequest represents a user creation request
type ValidationError ¶ added in v1.0.1
type ValidationError struct {
Field string `json:"field"`
Tag string `json:"tag"`
Value string `json:"value"`
Message string `json:"message"`
}
ValidationError represents a validation error
type ValidationResult ¶
type ValidationResult struct {
Valid bool `json:"valid"`
Errors []ValidationError `json:"errors,omitempty"`
}
ValidationResult contains validation results