security

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package security provides comprehensive security mechanisms for the observability plugin, including audit logging, rate limiting, request validation, and secrets management. This package implements defense-in-depth security patterns to protect against unauthorized access, malicious queries, and resource abuse.

Package security provides security mechanisms including secrets management, authentication, authorization, and audit logging for the observability plugin.

Index

Constants

View Source
const (
	EventTypeAPIAccess      = "api_access"
	EventTypeAuthentication = "authentication"
	EventTypeAuthorization  = "authorization"
	EventTypeSecretAccess   = "secret_access"
	EventTypeRateLimit      = "rate_limit"
	EventTypeValidation     = "validation"
	EventTypeError          = "error"
)

EventType constants for different types of auditable events

Variables

This section is empty.

Functions

func AuditMiddleware

func AuditMiddleware(logger *AuditLogger) func(http.HandlerFunc) http.HandlerFunc

AuditMiddleware creates HTTP middleware for audit logging

func RateLimitMiddleware

func RateLimitMiddleware(rateLimiter *RateLimiter, config RateLimitConfig) func(http.HandlerFunc) http.HandlerFunc

RateLimitMiddleware creates HTTP middleware for rate limiting

func ValidationMiddleware

func ValidationMiddleware(validator *RequestValidator) func(http.HandlerFunc) http.HandlerFunc

ValidationMiddleware creates HTTP middleware for request validation

Types

type AuditConfig

type AuditConfig struct {
	// Enable audit logging
	Enabled bool `yaml:"enabled" json:"enabled"`

	// Log file path (if empty, logs to stdout)
	LogFile string `yaml:"logFile" json:"logFile"`

	// Log level: "info", "warn", "error"
	LogLevel string `yaml:"logLevel" json:"logLevel"`

	// Maximum log file size in MB before rotation
	MaxFileSizeMB int `yaml:"maxFileSizeMB" json:"maxFileSizeMB"`

	// Maximum number of log files to keep
	MaxFiles int `yaml:"maxFiles" json:"maxFiles"`

	// Include request/response bodies in logs (security risk)
	IncludeBodies bool `yaml:"includeBodies" json:"includeBodies"`

	// Log sensitive operations only (vs all operations)
	SensitiveOnly bool `yaml:"sensitiveOnly" json:"sensitiveOnly"`

	// Additional fields to log from request headers
	LogHeaders []string `yaml:"logHeaders" json:"logHeaders"`
}

AuditConfig contains audit logging configuration

func DefaultAuditConfig

func DefaultAuditConfig() AuditConfig

DefaultAuditConfig returns default audit configuration

type AuditEvent

type AuditEvent struct {
	Timestamp    time.Time              `json:"timestamp"`
	EventType    string                 `json:"event_type"`
	UserID       string                 `json:"user_id,omitempty"`
	ClientIP     string                 `json:"client_ip"`
	Method       string                 `json:"method"`
	Path         string                 `json:"path"`
	Query        string                 `json:"query,omitempty"`
	StatusCode   int                    `json:"status_code"`
	Duration     time.Duration          `json:"duration"`
	Error        string                 `json:"error,omitempty"`
	Headers      map[string]string      `json:"headers,omitempty"`
	RequestBody  string                 `json:"request_body,omitempty"`
	ResponseBody string                 `json:"response_body,omitempty"`
	Sensitive    bool                   `json:"sensitive"`
	Metadata     map[string]interface{} `json:"metadata,omitempty"`
}

AuditEvent represents an auditable event

type AuditLogger

type AuditLogger struct {
	// contains filtered or unexported fields
}

AuditLogger handles audit logging for sensitive operations

func NewAuditLogger

func NewAuditLogger(config *AuditConfig) (*AuditLogger, error)

NewAuditLogger creates a new audit logger

func (*AuditLogger) Close

func (al *AuditLogger) Close() error

Close closes the audit logger and any open files

func (*AuditLogger) GetStats

func (al *AuditLogger) GetStats() map[string]interface{}

GetStats returns audit logging statistics

func (*AuditLogger) LogAPIRequest

func (al *AuditLogger) LogAPIRequest(r *http.Request, statusCode int, duration time.Duration, err error)

LogAPIRequest logs an API request with response details

func (*AuditLogger) LogAuthenticationAttempt

func (al *AuditLogger) LogAuthenticationAttempt(clientIP, userID string, success bool, err error)

LogAuthenticationAttempt logs authentication attempts

func (*AuditLogger) LogEvent

func (al *AuditLogger) LogEvent(event *AuditEvent)

LogEvent logs an audit event

func (*AuditLogger) LogRateLimit

func (al *AuditLogger) LogRateLimit(clientIP, userID, rateLimitType string)

LogRateLimit logs rate limiting events

func (*AuditLogger) LogSecretAccess

func (al *AuditLogger) LogSecretAccess(secretID, operation, userID string, success bool, err error)

LogSecretAccess logs secret access operations

func (*AuditLogger) LogValidationFailure

func (al *AuditLogger) LogValidationFailure(r *http.Request, validationError error)

LogValidationFailure logs request validation failures

type ClientLimiter

type ClientLimiter struct {
	// contains filtered or unexported fields
}

ClientLimiter tracks rate limiting for a specific client

type RateLimitConfig

type RateLimitConfig struct {
	// Requests per minute allowed per client
	RequestsPerMinute int

	// Enable global rate limiting (across all clients)
	EnableGlobalLimit bool

	// Global requests per minute limit
	GlobalRequestsPerMinute int

	// Burst size (how many requests can be made immediately)
	BurstSize int

	// Cleanup interval for removing inactive clients
	CleanupInterval time.Duration

	// Client identification method: "ip", "token", "user-agent"
	ClientIDMethod string

	// Custom headers to use for client identification
	ClientIDHeader string
}

RateLimitConfig contains rate limiting configuration

func DefaultRateLimitConfig

func DefaultRateLimitConfig() RateLimitConfig

DefaultRateLimitConfig returns default rate limiting configuration

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter implements token bucket rate limiting

func NewRateLimiter

func NewRateLimiter(config RateLimitConfig) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(clientID string, config RateLimitConfig) bool

Allow checks if a request should be allowed

func (*RateLimiter) GetStats

func (rl *RateLimiter) GetStats() map[string]interface{}

GetStats returns rate limiting statistics

func (*RateLimiter) Stop

func (rl *RateLimiter) Stop()

Stop stops the rate limiter and cleanup routine

type RequestValidator

type RequestValidator struct {
	// contains filtered or unexported fields
}

RequestValidator handles request validation for API endpoints

func NewRequestValidator

func NewRequestValidator(config *ValidationConfig) (*RequestValidator, error)

NewRequestValidator creates a new request validator

func (*RequestValidator) GetStats

func (v *RequestValidator) GetStats() map[string]interface{}

GetStats returns validation statistics

func (*RequestValidator) ValidateRequest

func (v *RequestValidator) ValidateRequest(r *http.Request) error

ValidateRequest validates an HTTP request

type Secret

type Secret struct {
	Name      string            `json:"name"`
	Type      SecretType        `json:"type"`
	Value     string            `json:"-"` // Never serialize the actual value
	Source    SecretSource      `json:"source"`
	CreatedAt time.Time         `json:"created_at"`
	UpdatedAt time.Time         `json:"updated_at"`
	ExpiresAt *time.Time        `json:"expires_at,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	Encrypted bool              `json:"encrypted"`
	Rotatable bool              `json:"rotatable"`
}

Secret represents a secret with metadata

type SecretAccess

type SecretAccess struct {
	SecretName string    `json:"secret_name"`
	Operation  string    `json:"operation"`
	Success    bool      `json:"success"`
	Timestamp  time.Time `json:"timestamp"`
	Source     string    `json:"source,omitempty"`
	Error      string    `json:"error,omitempty"`
}

SecretAccess represents an audit log entry for secret access

type SecretConfig

type SecretConfig struct {
	// Storage configuration
	StorageDir    string `json:"storage_dir" yaml:"storageDir"`
	EncryptAtRest bool   `json:"encrypt_at_rest" yaml:"encryptAtRest"`

	// Master key configuration
	MasterKeySource SecretSource `json:"master_key_source" yaml:"masterKeySource"`
	MasterKeyPath   string       `json:"master_key_path,omitempty" yaml:"masterKeyPath,omitempty"`
	MasterKeyEnv    string       `json:"master_key_env,omitempty" yaml:"masterKeyEnv,omitempty"`

	// Rotation configuration
	EnableRotation   bool          `json:"enable_rotation" yaml:"enableRotation"`
	RotationInterval time.Duration `json:"rotation_interval" yaml:"rotationInterval"`

	// Security settings
	RequireEncryption  bool `json:"require_encryption" yaml:"requireEncryption"`
	AllowInlineSecrets bool `json:"allow_inline_secrets" yaml:"allowInlineSecrets"`
}

SecretConfig represents configuration for secret management

type SecretReference

type SecretReference struct {
	Name   string       `json:"name"`
	Type   SecretType   `json:"type"`
	Source SecretSource `json:"source"`
}

SecretReference represents a reference to a secret without the actual value

type SecretSource

type SecretSource string

SecretSource represents where secrets can be loaded from

const (
	// SecretSourceEnvironment is the secret source for environment variables.
	SecretSourceEnvironment SecretSource = "environment"
	// SecretSourceFile is the secret source for files.
	SecretSourceFile SecretSource = "file"
	// SecretSourceVault is the secret source for HashiCorp Vault.
	SecretSourceVault SecretSource = "vault"
	// SecretSourceK8sSecret is the secret source for Kubernetes secrets.
	SecretSourceK8sSecret SecretSource = "kubernetes"
	// SecretSourceInline is the secret source for inline values.
	SecretSourceInline SecretSource = "inline"
)

type SecretType

type SecretType string

SecretType represents different types of secrets

const (
	// SecretTypeAPIToken is the secret type for API tokens.
	SecretTypeAPIToken SecretType = "api_token"
	// SecretTypeBasicAuth is the secret type for basic authentication.
	SecretTypeBasicAuth SecretType = "basic_auth"
	// SecretTypeBearerToken is the secret type for bearer tokens.
	SecretTypeBearerToken SecretType = "bearer_token"
	// SecretTypeTLSCert is the secret type for TLS certificates.
	SecretTypeTLSCert SecretType = "tls_cert"
	// SecretTypeTLSKey is the secret type for TLS private keys.
	SecretTypeTLSKey SecretType = "tls_key"
	// SecretTypeDatabase is the secret type for database credentials.
	SecretTypeDatabase SecretType = "database"
	// SecretTypeEncryptionKey is the secret type for encryption keys.
	SecretTypeEncryptionKey SecretType = "encryption_key"
)

type SecretsManager

type SecretsManager struct {
	// contains filtered or unexported fields
}

SecretsManager manages secrets with encryption and rotation capabilities

func NewSecretsManager

func NewSecretsManager(ctx context.Context, config *SecretConfig) (*SecretsManager, error)

NewSecretsManager creates a new secrets manager

func (*SecretsManager) DeleteSecret

func (sm *SecretsManager) DeleteSecret(name string) error

DeleteSecret removes a secret

func (*SecretsManager) GetAuditLog

func (sm *SecretsManager) GetAuditLog() []SecretAccess

GetAuditLog returns the secret access audit log

func (*SecretsManager) GetSecretValue

func (sm *SecretsManager) GetSecretValue(name string) (string, error)

GetSecretValue retrieves just the secret value

func (*SecretsManager) Health

func (sm *SecretsManager) Health() map[string]interface{}

Health returns the health status of the secrets manager

func (*SecretsManager) ListSecrets

func (sm *SecretsManager) ListSecrets() []SecretReference

ListSecrets returns references to all secrets (without values)

func (*SecretsManager) RetrieveSecret

func (sm *SecretsManager) RetrieveSecret(name string) (*Secret, error)

RetrieveSecret retrieves a secret by name

func (*SecretsManager) RotateSecret

func (sm *SecretsManager) RotateSecret(name, newValue string) error

RotateSecret manually rotates a secret

func (*SecretsManager) Stop

func (sm *SecretsManager) Stop() error

Stop gracefully stops the secrets manager

func (*SecretsManager) StoreSecret

func (sm *SecretsManager) StoreSecret(name string, secretType SecretType, value string, source SecretSource, metadata map[string]string) error

StoreSecret stores a secret with encryption

type StorageSecret

type StorageSecret struct {
	Name      string            `json:"name"`
	Type      SecretType        `json:"type"`
	Value     string            `json:"value"` // Include value for storage
	Source    SecretSource      `json:"source"`
	CreatedAt time.Time         `json:"created_at"`
	UpdatedAt time.Time         `json:"updated_at"`
	ExpiresAt *time.Time        `json:"expires_at,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	Encrypted bool              `json:"encrypted"`
	Rotatable bool              `json:"rotatable"`
}

StorageSecret represents a secret for storage (with value included)

type ValidationConfig

type ValidationConfig struct {
	// Enable request validation
	Enabled bool `yaml:"enabled" json:"enabled"`

	// Maximum query length
	MaxQueryLength int `yaml:"maxQueryLength" json:"maxQueryLength"`

	// Maximum time range for queries
	MaxTimeRange time.Duration `yaml:"maxTimeRange" json:"maxTimeRange"`

	// Allowed metric patterns (regex)
	AllowedMetricPatterns []string `yaml:"allowedMetricPatterns" json:"allowedMetricPatterns"`

	// Blocked metric patterns (regex)
	BlockedMetricPatterns []string `yaml:"blockedMetricPatterns" json:"blockedMetricPatterns"`

	// Maximum number of time series that can be returned
	MaxTimeSeries int `yaml:"maxTimeSeries" json:"maxTimeSeries"`

	// Enable query complexity validation
	EnableComplexityValidation bool `yaml:"enableComplexityValidation" json:"enableComplexityValidation"`

	// Maximum query complexity score
	MaxComplexityScore int `yaml:"maxComplexityScore" json:"maxComplexityScore"`
}

ValidationConfig contains validation settings

func DefaultValidationConfig

func DefaultValidationConfig() ValidationConfig

DefaultValidationConfig returns default validation configuration

Jump to

Keyboard shortcuts

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