trail

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package trail provides a comprehensive audit trail and logging system

Package trail provides a comprehensive audit trail and logging system

Package trail provides a comprehensive audit trail and logging system

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrLoggerNotFound        = errors.New("logger not found")
	ErrInvalidLogFormat      = errors.New("invalid log format")
	ErrInvalidLogLevel       = errors.New("invalid log level")
	ErrStorageFailure        = errors.New("storage failure")
	ErrInvalidTimeRange      = errors.New("invalid time range")
	ErrSignatureGeneration   = errors.New("failed to generate signature")
	ErrSignatureVerification = errors.New("failed to verify signature")
)

Common errors

Functions

This section is empty.

Types

type AuditConfig

type AuditConfig struct {
	// Minimum log level to record
	MinLogLevel LogLevel `json:"min_log_level"`

	// Whether to enable tamper-evident logging
	TamperEvident bool `json:"tamper_evident"`

	// Secret key for HMAC signatures (if tamper-evident is enabled)
	SigningKey string `json:"signing_key,omitempty"`

	// Whether to redact sensitive information
	RedactSensitiveInfo bool `json:"redact_sensitive_info"`

	// Fields to redact if redaction is enabled
	RedactFields []string `json:"redact_fields,omitempty"`

	// Maximum log retention period in days
	RetentionDays int `json:"retention_days"`

	// Whether to include stack traces for errors
	IncludeStackTraces bool `json:"include_stack_traces"`

	// Whether to compress logs for storage
	CompressLogs bool `json:"compress_logs"`

	// Whether to encrypt logs for storage
	EncryptLogs bool `json:"encrypt_logs"`

	// Encryption key ID (if encryption is enabled)
	EncryptionKeyID string `json:"encryption_key_id,omitempty"`
}

AuditConfig defines the configuration for the audit trail system

func DefaultAuditConfig

func DefaultAuditConfig() *AuditConfig

DefaultAuditConfig returns the default audit configuration

type AuditExporter

type AuditExporter interface {
	AuditLogger

	// Export exports audit logs in the specified format
	Export(ctx context.Context, logs []*AuditLog, format ExportFormat) ([]byte, error)
}

AuditExporter extends AuditLogger with export capabilities

type AuditLog

type AuditLog struct {
	// ID is a unique identifier for the log entry
	ID string `json:"id"`

	// Timestamp is the time when the event occurred (with timezone)
	Timestamp time.Time `json:"timestamp"`

	// Level is the severity level of the log entry
	Level LogLevel `json:"level"`

	// Operation is the type of operation being performed
	Operation OperationType `json:"operation"`

	// Component is the system component affected
	Component string `json:"component"`

	// SubComponent is a more specific part of the component
	SubComponent string `json:"sub_component,omitempty"`

	// User is the user or process that performed the operation
	User string `json:"user,omitempty"`

	// UserID is the unique identifier of the user
	UserID string `json:"user_id,omitempty"`

	// SessionID is the session identifier
	SessionID string `json:"session_id,omitempty"`

	// RequestID is used to correlate multiple log entries for a single request
	RequestID string `json:"request_id,omitempty"`

	// TraceID is used for distributed tracing
	TraceID string `json:"trace_id,omitempty"`

	// IPAddress is the IP address where the operation originated
	IPAddress string `json:"ip_address,omitempty"`

	// UserAgent is the user agent that performed the operation
	UserAgent string `json:"user_agent,omitempty"`

	// Resource is the resource being operated on
	Resource string `json:"resource,omitempty"`

	// ResourceID is the identifier of the resource
	ResourceID string `json:"resource_id,omitempty"`

	// Action is the specific action being performed
	Action string `json:"action,omitempty"`

	// Status is the result status of the operation
	Status string `json:"status"`

	// StatusCode is a numeric status code
	StatusCode int `json:"status_code,omitempty"`

	// Message is a human-readable description of the event
	Message string `json:"message"`

	// ErrorCode is the error code if the operation failed
	ErrorCode string `json:"error_code,omitempty"`

	// ErrorMessage is the error message if the operation failed
	ErrorMessage string `json:"error_message,omitempty"`

	// Duration is the duration of the operation in milliseconds
	Duration int64 `json:"duration,omitempty"`

	// Version contains version information
	Version *VersionInfo `json:"version,omitempty"`

	// Changes contains details about what changed
	Changes *ChangeInfo `json:"changes,omitempty"`

	// Verification contains verification results
	Verification *VerificationInfo `json:"verification,omitempty"`

	// Metadata contains additional contextual information
	Metadata map[string]interface{} `json:"metadata,omitempty"`

	// Tags for categorizing and filtering logs
	Tags []string `json:"tags,omitempty"`

	// Signature is a cryptographic signature for tamper evidence
	Signature string `json:"signature,omitempty"`
}

AuditLog represents a structured audit log entry

func FromJSON

func FromJSON(data string) (*AuditLog, error)

FromJSON parses a JSON string into an audit log

func NewAuditLog

func NewAuditLog(operation OperationType, component string, message string) *AuditLog

NewAuditLog creates a new audit log entry with default values

func (*AuditLog) ToJSON

func (l *AuditLog) ToJSON() (string, error)

ToJSON converts the audit log to a JSON string

func (*AuditLog) WithAction

func (l *AuditLog) WithAction(action string) *AuditLog

WithAction sets the action information

func (*AuditLog) WithChanges

func (l *AuditLog) WithChanges(before, after map[string]interface{}, fields []string, summary string) *AuditLog

WithChanges sets the change information

func (*AuditLog) WithClient

func (l *AuditLog) WithClient(ipAddress, userAgent string) *AuditLog

WithClient sets the client information

func (*AuditLog) WithDuration

func (l *AuditLog) WithDuration(durationMs int64) *AuditLog

WithDuration sets the operation duration

func (*AuditLog) WithError

func (l *AuditLog) WithError(errorCode, errorMessage string) *AuditLog

WithError sets the error information

func (*AuditLog) WithLevel

func (l *AuditLog) WithLevel(level LogLevel) *AuditLog

WithLevel sets the severity level

func (*AuditLog) WithMetadata

func (l *AuditLog) WithMetadata(key string, value interface{}) *AuditLog

WithMetadata adds metadata to the audit log

func (*AuditLog) WithRequest

func (l *AuditLog) WithRequest(requestID, traceID string) *AuditLog

WithRequest sets the request information

func (*AuditLog) WithResource

func (l *AuditLog) WithResource(resource, resourceID string) *AuditLog

WithResource sets the resource information

func (*AuditLog) WithSession

func (l *AuditLog) WithSession(sessionID string) *AuditLog

WithSession sets the session information

func (*AuditLog) WithStatus

func (l *AuditLog) WithStatus(status string, statusCode int) *AuditLog

WithStatus sets the status information

func (*AuditLog) WithTags

func (l *AuditLog) WithTags(tags ...string) *AuditLog

WithTags adds tags to the audit log

func (*AuditLog) WithUser

func (l *AuditLog) WithUser(userID, username string) *AuditLog

WithUser sets the user information

func (*AuditLog) WithVerification

func (l *AuditLog) WithVerification(success bool, method string, details map[string]interface{}) *AuditLog

WithVerification sets the verification information

func (*AuditLog) WithVersion

func (l *AuditLog) WithVersion(previous, current, changeType string) *AuditLog

WithVersion sets the version information

type AuditLogger

type AuditLogger interface {
	// GetID returns the unique identifier for this logger
	GetID() string

	// Log records an audit log entry
	Log(ctx context.Context, log *AuditLog) error

	// Close releases any resources used by the logger
	Close() error
}

AuditLogger defines the interface for basic audit logging

type AuditQueryLogger

type AuditQueryLogger interface {
	AuditLogger

	// Query searches for audit logs matching the specified criteria
	Query(ctx context.Context, query *LogQuery) (*LogQueryResult, error)
}

AuditQueryLogger extends AuditLogger with query capabilities

type AuditTrailManager

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

AuditTrailManager is responsible for managing the audit trail and logging system

func NewAuditTrailManager

func NewAuditTrailManager(config *AuditConfig) (*AuditTrailManager, error)

NewAuditTrailManager creates a new audit trail manager

func (*AuditTrailManager) AddLogger

func (m *AuditTrailManager) AddLogger(logger AuditLogger)

AddLogger adds a logger to the manager

func (*AuditTrailManager) Close

func (m *AuditTrailManager) Close() error

Close closes all loggers and releases resources

func (*AuditTrailManager) Export

func (m *AuditTrailManager) Export(ctx context.Context, query *LogQuery, format ExportFormat) ([]byte, error)

Export exports audit logs in the specified format

func (*AuditTrailManager) GetConfig

func (m *AuditTrailManager) GetConfig() *AuditConfig

GetConfig returns the current configuration

func (*AuditTrailManager) GetLogLevel

func (m *AuditTrailManager) GetLogLevel() LogLevel

GetLogLevel returns the current minimum log level

func (*AuditTrailManager) Log

func (m *AuditTrailManager) Log(ctx context.Context, log *AuditLog) error

Log records an audit log entry

func (*AuditTrailManager) Query

func (m *AuditTrailManager) Query(ctx context.Context, query *LogQuery) (*LogQueryResult, error)

Query searches for audit logs matching the specified criteria

func (*AuditTrailManager) RemoveLogger

func (m *AuditTrailManager) RemoveLogger(loggerID string) error

RemoveLogger removes a logger from the manager

func (*AuditTrailManager) SetLogLevel

func (m *AuditTrailManager) SetLogLevel(level LogLevel)

SetLogLevel sets the minimum log level

func (*AuditTrailManager) VerifyLogIntegrity

func (m *AuditTrailManager) VerifyLogIntegrity(log *AuditLog) (bool, error)

VerifyLogIntegrity verifies the integrity of a log entry

type ChangeInfo

type ChangeInfo struct {
	// Before contains the state before the change
	Before map[string]interface{} `json:"before,omitempty"`

	// After contains the state after the change
	After map[string]interface{} `json:"after,omitempty"`

	// Fields lists the specific fields that changed
	Fields []string `json:"fields,omitempty"`

	// Summary provides a human-readable summary of the changes
	Summary string `json:"summary,omitempty"`
}

ChangeInfo contains details about what changed in an update operation

type ExportFormat

type ExportFormat string

ExportFormat defines the format for exporting audit logs

const (
	// FormatJSON exports logs in JSON format
	FormatJSON ExportFormat = "json"

	// FormatCSV exports logs in CSV format
	FormatCSV ExportFormat = "csv"

	// FormatPDF exports logs in PDF format
	FormatPDF ExportFormat = "pdf"
)

type FileLogger

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

FileLogger implements audit logging to files

func NewFileLogger

func NewFileLogger(directory string, maxFileSize int64, maxFiles int, compress bool) (*FileLogger, error)

NewFileLogger creates a new file-based audit logger

func (*FileLogger) Close

func (l *FileLogger) Close() error

Close closes the file logger

func (*FileLogger) Export

func (l *FileLogger) Export(ctx context.Context, logs []*AuditLog, format ExportFormat) ([]byte, error)

Export exports audit logs in the specified format

func (*FileLogger) GetID

func (l *FileLogger) GetID() string

GetID returns the unique identifier for this logger

func (*FileLogger) Log

func (l *FileLogger) Log(ctx context.Context, log *AuditLog) error

Log records an audit log entry to a file

func (*FileLogger) Query

func (l *FileLogger) Query(ctx context.Context, query *LogQuery) (*LogQueryResult, error)

Query searches for audit logs matching the specified criteria

type InMemoryLogger

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

InMemoryLogger implements in-memory audit logging

func NewInMemoryLogger

func NewInMemoryLogger(maxLogs int) *InMemoryLogger

NewInMemoryLogger creates a new in-memory audit logger

func (*InMemoryLogger) Close

func (l *InMemoryLogger) Close() error

Close closes the in-memory logger

func (*InMemoryLogger) Export

func (l *InMemoryLogger) Export(ctx context.Context, logs []*AuditLog, format ExportFormat) ([]byte, error)

Export exports audit logs in the specified format

func (*InMemoryLogger) GetID

func (l *InMemoryLogger) GetID() string

GetID returns the unique identifier for this logger

func (*InMemoryLogger) Log

func (l *InMemoryLogger) Log(ctx context.Context, log *AuditLog) error

Log records an audit log entry in memory

func (*InMemoryLogger) Query

func (l *InMemoryLogger) Query(ctx context.Context, query *LogQuery) (*LogQueryResult, error)

Query searches for audit logs matching the specified criteria

type LineScanner

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

LineScanner is a simple line scanner that handles both LF and CRLF

func NewLineScanner

func NewLineScanner(reader io.Reader) *LineScanner

NewLineScanner creates a new line scanner

func (*LineScanner) Scan

func (s *LineScanner) Scan() bool

Scan advances to the next line

func (*LineScanner) Text

func (s *LineScanner) Text() string

Text returns the current line

type LogLevel

type LogLevel string

LogLevel represents the severity level of a log entry

const (
	// LogLevelDebug is used for detailed debugging information
	LogLevelDebug LogLevel = "debug"
	// LogLevelInfo is used for general information
	LogLevelInfo LogLevel = "info"
	// LogLevelWarning is used for warning conditions
	LogLevelWarning LogLevel = "warning"
	// LogLevelError is used for error conditions
	LogLevelError LogLevel = "error"
	// LogLevelCritical is used for critical conditions
	LogLevelCritical LogLevel = "critical"
)

type LogQuery

type LogQuery struct {
	// Start time for the query range
	StartTime time.Time `json:"start_time,omitempty"`

	// End time for the query range
	EndTime time.Time `json:"end_time,omitempty"`

	// Minimum log level to include
	MinLevel LogLevel `json:"min_level,omitempty"`

	// Operation types to include
	Operations []OperationType `json:"operations,omitempty"`

	// Components to include
	Components []string `json:"components,omitempty"`

	// Users to include
	Users []string `json:"users,omitempty"`

	// Resources to include
	Resources []string `json:"resources,omitempty"`

	// Status values to include
	Statuses []string `json:"statuses,omitempty"`

	// Tags to filter by (must match all)
	Tags []string `json:"tags,omitempty"`

	// Full-text search query
	Query string `json:"query,omitempty"`

	// Pagination limit
	Limit int `json:"limit,omitempty"`

	// Pagination offset
	Offset int `json:"offset,omitempty"`

	// Sort field
	SortBy string `json:"sort_by,omitempty"`

	// Sort direction (asc or desc)
	SortDirection string `json:"sort_direction,omitempty"`
}

LogQuery defines parameters for querying audit logs

type LogQueryResult

type LogQueryResult struct {
	// Logs matching the query
	Logs []*AuditLog `json:"logs"`

	// Total number of logs matching the query (before pagination)
	TotalCount int `json:"total_count"`

	// Whether there are more logs available
	HasMore bool `json:"has_more"`
}

LogQueryResult contains the results of a log query

type OperationType

type OperationType string

OperationType represents the type of operation being logged

const (
	// OperationCreate represents a creation operation
	OperationCreate OperationType = "create"
	// OperationRead represents a read operation
	OperationRead OperationType = "read"
	// OperationUpdate represents an update operation
	OperationUpdate OperationType = "update"
	// OperationDelete represents a deletion operation
	OperationDelete OperationType = "delete"
	// OperationVerify represents a verification operation
	OperationVerify OperationType = "verify"
	// OperationAuth represents an authentication operation
	OperationAuth OperationType = "auth"
	// OperationConfig represents a configuration change
	OperationConfig OperationType = "config"
	// OperationExport represents an export operation
	OperationExport OperationType = "export"
	// OperationImport represents an import operation
	OperationImport OperationType = "import"
	// OperationDeploy represents a deployment operation
	OperationDeploy OperationType = "deploy"
	// OperationExecute represents an execution operation
	OperationExecute OperationType = "execute"
	// OperationAccess represents an access control operation
	OperationAccess OperationType = "access"
)

type SyslogLogger

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

SyslogLogger implements audit logging to syslog

func NewSyslogLogger

func NewSyslogLogger(facility syslog.Priority, tag string) (*SyslogLogger, error)

NewSyslogLogger creates a new syslog-based audit logger

func (*SyslogLogger) Close

func (l *SyslogLogger) Close() error

Close closes the syslog logger

func (*SyslogLogger) GetID

func (l *SyslogLogger) GetID() string

GetID returns the unique identifier for this logger

func (*SyslogLogger) Log

func (l *SyslogLogger) Log(ctx context.Context, log *AuditLog) error

Log records an audit log entry to syslog

type VerificationInfo

type VerificationInfo struct {
	// Success indicates if verification was successful
	Success bool `json:"success"`

	// Method is the verification method used
	Method string `json:"method,omitempty"`

	// Details contains additional verification details
	Details map[string]interface{} `json:"details,omitempty"`
}

VerificationInfo contains verification results

type VersionInfo

type VersionInfo struct {
	// Previous is the previous version
	Previous string `json:"previous,omitempty"`

	// Current is the current version
	Current string `json:"current,omitempty"`

	// ChangeType describes the type of version change
	ChangeType string `json:"change_type,omitempty"`
}

VersionInfo contains version information for the affected resource

Jump to

Keyboard shortcuts

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