logging

package
v0.0.0-...-101d28d Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: AGPL-3.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	InfoLogger    *log.Logger
	ErrorLogger   *log.Logger
	WarningLogger *log.Logger
	DebugLogger   *log.Logger
)

Functions

func GetCompositeEntityIDForRequest

func GetCompositeEntityIDForRequest(ip net.IP, r *http.Request) string

GetCompositeEntityIDForRequest generates an entity ID from an HTTP request, using IP + User-Agent + Accept-Language for anonymous disambiguation.

func GetEntityIDForIP

func GetEntityIDForIP(ip net.IP) string

GetEntityIDForIP is a convenience function that uses the default service with IP-only input. For better NAT disambiguation, use GetCompositeEntityIDFromContext.

func GetOrCreateEntityID

func GetOrCreateEntityID(c interface{}) string

GetOrCreateEntityID extracts the client IP and HTTP signals from the Echo context and returns a composite entity ID. For authenticated requests where a username is available in the JWT claims, the username is used instead of IP-based identification for more precise per-user rate limiting.

func InitFallbackConsoleLogging

func InitFallbackConsoleLogging()

InitFallbackConsoleLogging initializes console-only loggers for systemd compatibility

func InitLogging

func InitLogging(config *LogConfig) error

func InitializeEntityIDService

func InitializeEntityIDService(config EntityIDConfig) error

InitializeEntityIDService initializes the global entity ID service

func InitializeSecurityEventLogger

func InitializeSecurityEventLogger(config SecurityEventConfig) error

InitializeSecurityEventLogger initializes the global security event logger

func Log

func Log(level LogLevel, format string, v ...interface{})

Log formats and writes log messages with source file information - NO LEVEL FILTERING

func LogSecurityEvent

func LogSecurityEvent(eventType SecurityEventType, ip net.IP, username *string, deviceProfile *string, details map[string]interface{}) error

LogSecurityEvent is a convenience function that uses the default logger

func LogSecurityEventWithEntityID

func LogSecurityEventWithEntityID(eventType SecurityEventType, entityID string, details map[string]interface{}) error

LogSecurityEventWithEntityID logs a security event using a pre-computed entity ID. Use this when the entity ID is already available (e.g., from share access handlers that compute entity IDs for rate limiting) to avoid redundant HMAC computation.

func ValidateEntityID

func ValidateEntityID(entityID string) bool

ValidateEntityID checks if an entity ID has the expected format

Types

type EntityIDConfig

type EntityIDConfig struct {
	RotationPeriod    time.Duration `json:"rotation_period"`    // 24 * time.Hour
	RetentionDays     int           `json:"retention_days"`     // 90
	CleanupInterval   time.Duration `json:"cleanup_interval"`   // 24 * time.Hour
	EmergencyRotation bool          `json:"emergency_rotation"` // true
}

EntityIDConfig configures the entity ID service

type EntityIDInput

type EntityIDInput struct {
	IP             net.IP // Client IP address
	UserAgent      string // HTTP User-Agent header
	AcceptLanguage string // HTTP Accept-Language header
	Username       string // Authenticated username (empty for anonymous requests)
}

EntityIDInput holds the composite inputs for entity ID generation. For authenticated requests, set Username. For unauthenticated requests, provide IP and HTTP header signals to distinguish clients behind shared IPs.

type EntityIDService

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

EntityIDService provides privacy-preserving entity identification using HMAC with daily-rotating keys derived from a master secret.

Entity IDs are computed from composite inputs to distinguish different clients behind shared IP addresses (NAT, VPN, corporate networks):

  • Authenticated requests use the username as input
  • Unauthenticated requests use IP + User-Agent + Accept-Language
var DefaultEntityIDService *EntityIDService

Global entity ID service instance

func NewEntityIDService

func NewEntityIDService(config EntityIDConfig) (*EntityIDService, error)

NewEntityIDService creates a new entity ID service with the given configuration

func (*EntityIDService) CleanupOldWindows

func (e *EntityIDService) CleanupOldWindows(retentionDays int) error

CleanupOldWindows removes old time window data beyond retention period

func (*EntityIDService) GetCompositeEntityID

func (e *EntityIDService) GetCompositeEntityID(input EntityIDInput) string

GetCompositeEntityID returns a privacy-preserving entity identifier from composite inputs. This is the primary method for entity ID generation.

For authenticated requests (Username is set): HMAC(daily_key, "user:" + username) For anonymous requests: HMAC(daily_key, "anon:" + IP + "|" + UserAgent + "|" + AcceptLanguage)

The "user:"/"anon:" prefix prevents collisions between the two input domains. Using User-Agent and Accept-Language for anonymous requests distinguishes different browsers behind the same NAT/VPN without invasive fingerprinting.

func (*EntityIDService) GetCurrentTimeWindow

func (e *EntityIDService) GetCurrentTimeWindow() string

GetCurrentTimeWindow returns the current time window identifier (YYYY-MM-DD format)

func (*EntityIDService) GetEntityID

func (e *EntityIDService) GetEntityID(ip net.IP) string

GetEntityID returns a privacy-preserving entity identifier for the given IP address. This is the legacy method that uses IP-only input. Prefer GetCompositeEntityID for new code to get better disambiguation behind shared IPs.

func (*EntityIDService) GetMasterSecretHash

func (e *EntityIDService) GetMasterSecretHash() string

GetMasterSecretHash returns a hash of the master secret for health monitoring This allows verification of key accessibility without exposing the secret

func (*EntityIDService) GetTimeWindowForTime

func (e *EntityIDService) GetTimeWindowForTime(t time.Time) string

GetTimeWindowForTime returns the time window identifier for a specific time

type LogConfig

type LogConfig struct {
	LogDir     string
	MaxSize    int64 // Maximum size of log file in bytes
	MaxBackups int   // Maximum number of old log files to retain
	LogLevel   LogLevel
}

type LogLevel

type LogLevel int
const (
	DEBUG LogLevel = iota
	INFO
	WARNING
	ERROR
)

type SecurityEvent

type SecurityEvent struct {
	ID            int64                  `json:"id"`
	Timestamp     time.Time              `json:"timestamp"`
	EventType     SecurityEventType      `json:"event_type"`
	EntityID      string                 `json:"entity_id"`      // HMAC-based, non-reversible
	TimeWindow    string                 `json:"time_window"`    // "2025-06-20"
	Username      *string                `json:"username"`       // Only for authenticated events
	DeviceProfile *string                `json:"device_profile"` // OPAQUE export key context
	Severity      SecurityEventSeverity  `json:"severity"`
	Details       map[string]interface{} `json:"details"`
	CreatedAt     time.Time              `json:"created_at"`
}

SecurityEvent represents a security-related event with privacy-preserving entity identification

type SecurityEventConfig

type SecurityEventConfig struct {
	MaxRetentionDays int                       `json:"max_retention_days"` // 90
	EnabledEvents    []SecurityEventType       `json:"enabled_events"`
	AlertThresholds  map[SecurityEventType]int `json:"alert_thresholds"`
}

SecurityEventConfig configures security event logging

type SecurityEventFilters

type SecurityEventFilters struct {
	EventType  SecurityEventType
	EntityID   string
	TimeWindow string
	StartTime  time.Time
	EndTime    time.Time
	Severity   SecurityEventSeverity
	Limit      int
}

SecurityEventFilters defines filtering options for security event queries

type SecurityEventLogger

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

SecurityEventLogger handles logging of security events with privacy protection

var DefaultSecurityEventLogger *SecurityEventLogger

Global security event logger instance

func NewSecurityEventLogger

func NewSecurityEventLogger(db *sql.DB, entityIDService *EntityIDService, config SecurityEventConfig) *SecurityEventLogger

NewSecurityEventLogger creates a new security event logger

func (*SecurityEventLogger) CleanupOldEvents

func (sel *SecurityEventLogger) CleanupOldEvents() error

CleanupOldEvents removes security events older than the retention period

func (*SecurityEventLogger) GetSecurityEvents

func (sel *SecurityEventLogger) GetSecurityEvents(filters SecurityEventFilters) ([]SecurityEvent, error)

GetSecurityEvents retrieves security events with filtering options

func (*SecurityEventLogger) LogAuthenticationEvent

func (sel *SecurityEventLogger) LogAuthenticationEvent(eventType SecurityEventType, ip net.IP, username *string, deviceProfile *string, success bool, details map[string]interface{}) error

LogAuthenticationEvent logs authentication-related events

func (*SecurityEventLogger) LogKeyHealthEvent

func (sel *SecurityEventLogger) LogKeyHealthEvent(eventType SecurityEventType, component string, status string, details map[string]interface{}) error

LogKeyHealthEvent logs key health and rotation events

func (*SecurityEventLogger) LogRateLimitEvent

func (sel *SecurityEventLogger) LogRateLimitEvent(eventType SecurityEventType, ip net.IP, endpoint string, requestCount int, limit int, details map[string]interface{}) error

LogRateLimitEvent logs rate limiting events

func (*SecurityEventLogger) LogSecurityEvent

func (sel *SecurityEventLogger) LogSecurityEvent(eventType SecurityEventType, ip net.IP, username *string, deviceProfile *string, details map[string]interface{}) error

LogSecurityEvent logs a security event with privacy-preserving entity identification. When a username is provided, the entity ID is derived from the username for precise per-user identification. For anonymous events, the entity ID is derived from the IP.

type SecurityEventSeverity

type SecurityEventSeverity string

SecurityEventSeverity defines the severity levels for security events

const (
	SeverityInfo     SecurityEventSeverity = "INFO"
	SeverityWarning  SecurityEventSeverity = "WARNING"
	SeverityCritical SecurityEventSeverity = "CRITICAL"
)

type SecurityEventType

type SecurityEventType string

SecurityEventType defines the types of security events that can be logged

const (
	// Authentication events
	EventOpaqueRegistration SecurityEventType = "opaque_registration"
	EventOpaqueLoginSuccess SecurityEventType = "opaque_login_success"
	EventOpaqueLoginFailure SecurityEventType = "opaque_login_failure"
	EventJWTRefreshSuccess  SecurityEventType = "jwt_refresh_success"
	EventJWTRefreshFailure  SecurityEventType = "jwt_refresh_failure"

	// Rate limiting events
	EventRateLimitViolation SecurityEventType = "rate_limit_violation"
	EventRateLimitRecovery  SecurityEventType = "rate_limit_recovery"
	EventProgressivePenalty SecurityEventType = "progressive_penalty"

	// Access pattern events
	EventSuspiciousPattern    SecurityEventType = "suspicious_pattern"
	EventEndpointAbuse        SecurityEventType = "endpoint_abuse"
	EventUnauthorizedAccess   SecurityEventType = "unauthorized_access"
	EventMultipleFailures     SecurityEventType = "multiple_failures"
	EventShareNotFound        SecurityEventType = "share_not_found"
	EventShareEnumeration     SecurityEventType = "share_enumeration"
	EventInvalidDownloadToken SecurityEventType = "invalid_download_token"

	// Key health events
	EventKeyRotation        SecurityEventType = "key_rotation"
	EventKeyHealthCheck     SecurityEventType = "key_health_check"
	EventEmergencyProcedure SecurityEventType = "emergency_procedure"

	// System security events
	EventConfigurationChange SecurityEventType = "configuration_change"
	EventSecurityAudit       SecurityEventType = "security_audit"
	EventSystemStartup       SecurityEventType = "system_startup"
	EventSystemShutdown      SecurityEventType = "system_shutdown"

	// Admin events
	EventAdminAccess SecurityEventType = "admin_access"
)

Jump to

Keyboard shortcuts

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