audit

package
v0.0.0-...-9e5e0b2 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package audit provides audit logging functionality.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Middleware

func Middleware(config *MiddlewareConfig) echo.MiddlewareFunc

Middleware returns an Echo middleware for audit logging.

Types

type Action

type Action string

Action represents the type of action being audited.

const (
	// Authentication actions
	ActionLogin          Action = "login"
	ActionLoginFailed    Action = "login_failed"
	ActionLogout         Action = "logout"
	ActionPasswordChange Action = "password_change"
	ActionPasswordReset  Action = "password_reset"
	ActionMFASetup       Action = "mfa_setup"
	ActionMFADisable     Action = "mfa_disable"
	ActionMFAVerify      Action = "mfa_verify"

	// User management actions
	ActionUserCreate Action = "user_create"
	ActionUserUpdate Action = "user_update"
	ActionUserDelete Action = "user_delete"
	ActionUserLock   Action = "user_lock"
	ActionUserUnlock Action = "user_unlock"
	ActionRoleChange Action = "role_change"

	// API access actions
	ActionAPIAccess    Action = "api_access"
	ActionConfigChange Action = "config_change"

	// System actions
	ActionSystemStart  Action = "system_start"
	ActionSystemStop   Action = "system_stop"
	ActionConfigReload Action = "config_reload"
)

type ArchiveConfig

type ArchiveConfig struct {
	// ArchivePath is the path to store archived logs.
	ArchivePath string
	// ArchiveAfterDays is the number of days after which to archive logs.
	ArchiveAfterDays int
	// CompressArchives enables compression of archived logs.
	CompressArchives bool
}

ArchiveConfig holds configuration for audit log archiving.

func DefaultArchiveConfig

func DefaultArchiveConfig() *ArchiveConfig

DefaultArchiveConfig returns the default archive configuration.

type AuditAction

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

AuditAction is a helper to create audit entries for specific actions.

func NewAuditAction

func NewAuditAction(logger Logger) *AuditAction

NewAuditAction creates a new AuditAction helper.

func (*AuditAction) LogConfigChange

func (a *AuditAction) LogConfigChange(c echo.Context, userID uuid.UUID, username string, configKey string, oldValue, newValue interface{})

LogConfigChange logs a configuration change event.

func (*AuditAction) LogLogin

func (a *AuditAction) LogLogin(c echo.Context, userID uuid.UUID, username string, success bool)

LogLogin logs a login event.

func (*AuditAction) LogLogout

func (a *AuditAction) LogLogout(c echo.Context, userID uuid.UUID, username string)

LogLogout logs a logout event.

func (*AuditAction) LogMFADisable

func (a *AuditAction) LogMFADisable(c echo.Context, userID uuid.UUID, username string)

LogMFADisable logs an MFA disable event.

func (*AuditAction) LogMFASetup

func (a *AuditAction) LogMFASetup(c echo.Context, userID uuid.UUID, username string, success bool)

LogMFASetup logs an MFA setup event.

func (*AuditAction) LogPasswordChange

func (a *AuditAction) LogPasswordChange(c echo.Context, userID uuid.UUID, username string, success bool)

LogPasswordChange logs a password change event.

func (*AuditAction) LogUserCreate

func (a *AuditAction) LogUserCreate(c echo.Context, actorID uuid.UUID, actorName string, targetID uuid.UUID, targetName string)

LogUserCreate logs a user creation event.

func (*AuditAction) LogUserDelete

func (a *AuditAction) LogUserDelete(c echo.Context, actorID uuid.UUID, actorName string, targetID uuid.UUID, targetName string)

LogUserDelete logs a user deletion event.

func (*AuditAction) LogUserLock

func (a *AuditAction) LogUserLock(c echo.Context, actorID uuid.UUID, actorName string, targetID uuid.UUID, targetName string)

LogUserLock logs a user lock event.

func (*AuditAction) LogUserUnlock

func (a *AuditAction) LogUserUnlock(c echo.Context, actorID uuid.UUID, actorName string, targetID uuid.UUID, targetName string)

LogUserUnlock logs a user unlock event.

func (*AuditAction) LogUserUpdate

func (a *AuditAction) LogUserUpdate(c echo.Context, actorID uuid.UUID, actorName string, targetID uuid.UUID, oldValue, newValue interface{})

LogUserUpdate logs a user update event.

type Entry

type Entry struct {
	// ID is the unique identifier for this entry.
	ID uuid.UUID `json:"id" db:"id"`
	// Timestamp is when the action occurred.
	Timestamp time.Time `json:"timestamp" db:"timestamp"`
	// UserID is the user who performed the action (nil for anonymous).
	UserID *uuid.UUID `json:"user_id,omitempty" db:"user_id"`
	// Username is the username (for display purposes).
	Username string `json:"username,omitempty" db:"username"`
	// Action is the type of action performed.
	Action Action `json:"action" db:"action"`
	// ResourceType is the type of resource affected.
	ResourceType string `json:"resource_type,omitempty" db:"resource_type"`
	// ResourceID is the ID of the resource affected.
	ResourceID string `json:"resource_id,omitempty" db:"resource_id"`
	// IPAddress is the client's IP address.
	IPAddress string `json:"ip_address,omitempty" db:"ip_address"`
	// UserAgent is the client's user agent string.
	UserAgent string `json:"user_agent,omitempty" db:"user_agent"`
	// RequestID is the unique request identifier.
	RequestID string `json:"request_id,omitempty" db:"request_id"`
	// Status is the outcome of the action.
	Status Status `json:"status" db:"status"`
	// Details contains additional action-specific information.
	Details json.RawMessage `json:"details,omitempty" db:"details"`
	// OldValue contains the previous value (for updates).
	OldValue json.RawMessage `json:"old_value,omitempty" db:"old_value"`
	// NewValue contains the new value (for updates).
	NewValue json.RawMessage `json:"new_value,omitempty" db:"new_value"`
}

Entry represents a single audit log entry.

func NewEntry

func NewEntry(action Action, status Status) *Entry

NewEntry creates a new audit entry with default values.

func (*Entry) WithChange

func (e *Entry) WithChange(oldValue, newValue interface{}) *Entry

WithChange sets the old and new values for update actions.

func (*Entry) WithDetails

func (e *Entry) WithDetails(details interface{}) *Entry

WithDetails sets the details field.

func (*Entry) WithRequest

func (e *Entry) WithRequest(ipAddress, userAgent, requestID string) *Entry

WithRequest sets the request information.

func (*Entry) WithResource

func (e *Entry) WithResource(resourceType, resourceID string) *Entry

WithResource sets the resource information.

func (*Entry) WithUser

func (e *Entry) WithUser(userID uuid.UUID, username string) *Entry

WithUser sets the user information.

type ExportRequest

type ExportRequest struct {
	Format       string `query:"format"` // json or csv
	UserID       string `query:"user_id"`
	Action       string `query:"action"`
	ResourceType string `query:"resource_type"`
	ResourceID   string `query:"resource_id"`
	Status       string `query:"status"`
	StartTime    string `query:"start_time"`
	EndTime      string `query:"end_time"`
	IPAddress    string `query:"ip_address"`
}

ExportRequest represents a request to export audit logs.

type Handler

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

Handler handles audit log API endpoints.

func NewHandler

func NewHandler(logger Logger) *Handler

NewHandler creates a new audit handler.

func (*Handler) Export

func (h *Handler) Export(c echo.Context) error

Export handles GET /api/v1/audit/export

func (*Handler) GetByID

func (h *Handler) GetByID(c echo.Context) error

GetByID handles GET /api/v1/audit/:id

func (*Handler) List

func (h *Handler) List(c echo.Context) error

List handles GET /api/v1/audit

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(g *echo.Group)

RegisterRoutes registers the audit routes.

func (*Handler) Stats

func (h *Handler) Stats(c echo.Context) error

Stats handles GET /api/v1/audit/stats

type ListRequest

type ListRequest struct {
	UserID       string `query:"user_id"`
	Action       string `query:"action"`
	ResourceType string `query:"resource_type"`
	ResourceID   string `query:"resource_id"`
	Status       string `query:"status"`
	StartTime    string `query:"start_time"`
	EndTime      string `query:"end_time"`
	IPAddress    string `query:"ip_address"`
	Page         int    `query:"page"`
	PageSize     int    `query:"page_size"`
	SortBy       string `query:"sort_by"`
	SortDir      string `query:"sort_dir"`
}

ListRequest represents a request to list audit logs.

type Logger

type Logger interface {
	// Log records an audit entry.
	Log(ctx context.Context, entry *Entry) error
	// Query retrieves audit entries based on parameters.
	Query(ctx context.Context, params *QueryParams) (*QueryResult, error)
	// GetByID retrieves a single audit entry.
	GetByID(ctx context.Context, id uuid.UUID) (*Entry, error)
	// Close closes the logger and flushes any pending entries.
	Close() error
}

Logger provides audit logging functionality.

type LoggerConfig

type LoggerConfig struct {
	// BatchSize is the number of entries to batch before writing.
	BatchSize int
	// FlushInterval is how often to flush the buffer.
	FlushInterval time.Duration
	// BufferSize is the size of the entry buffer.
	BufferSize int
}

LoggerConfig holds configuration for the logger.

func DefaultLoggerConfig

func DefaultLoggerConfig() *LoggerConfig

DefaultLoggerConfig returns the default logger configuration.

type MiddlewareConfig

type MiddlewareConfig struct {
	// Logger is the audit logger to use.
	Logger Logger
	// SkipPaths are paths to skip auditing.
	SkipPaths []string
	// LogRequestBody enables logging of request bodies.
	LogRequestBody bool
	// LogResponseBody enables logging of response bodies.
	LogResponseBody bool
	// MaxBodySize is the maximum body size to log.
	MaxBodySize int
	// GetUserID extracts the user ID from the request context.
	GetUserID func(c echo.Context) *uuid.UUID
	// GetUsername extracts the username from the request context.
	GetUsername func(c echo.Context) string
}

MiddlewareConfig holds configuration for the audit middleware.

func DefaultMiddlewareConfig

func DefaultMiddlewareConfig() *MiddlewareConfig

DefaultMiddlewareConfig returns the default middleware configuration.

type QueryParams

type QueryParams struct {
	// UserID filters by user.
	UserID *uuid.UUID
	// Action filters by action type.
	Action *Action
	// ResourceType filters by resource type.
	ResourceType string
	// ResourceID filters by resource ID.
	ResourceID string
	// Status filters by status.
	Status *Status
	// StartTime filters entries after this time.
	StartTime *time.Time
	// EndTime filters entries before this time.
	EndTime *time.Time
	// IPAddress filters by IP address.
	IPAddress string
	// Page is the page number (1-indexed).
	Page int
	// PageSize is the number of entries per page.
	PageSize int
	// SortBy is the field to sort by.
	SortBy string
	// SortDir is the sort direction (asc/desc).
	SortDir string
}

QueryParams represents parameters for querying audit logs.

type QueryResult

type QueryResult struct {
	Entries    []*Entry `json:"entries"`
	Total      int64    `json:"total"`
	Page       int      `json:"page"`
	PageSize   int      `json:"page_size"`
	TotalPages int      `json:"total_pages"`
}

QueryResult represents the result of a query.

type RetentionConfig

type RetentionConfig struct {
	// RetentionDays is the number of days to keep audit logs.
	RetentionDays int
	// CleanupInterval is how often to run the cleanup job.
	CleanupInterval time.Duration
	// BatchSize is the number of records to delete per batch.
	BatchSize int
}

RetentionConfig holds configuration for audit log retention.

func DefaultRetentionConfig

func DefaultRetentionConfig() *RetentionConfig

DefaultRetentionConfig returns the default retention configuration.

type RetentionManager

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

RetentionManager manages audit log retention.

func NewRetentionManager

func NewRetentionManager(db *sql.DB, config *RetentionConfig) *RetentionManager

NewRetentionManager creates a new retention manager.

func NewRetentionManagerWithReadDB

func NewRetentionManagerWithReadDB(writeDB, readDB *sql.DB, config *RetentionConfig) *RetentionManager

NewRetentionManagerWithReadDB creates a new retention manager with separate write and read database handles.

func (*RetentionManager) CleanupNow

func (m *RetentionManager) CleanupNow() error

CleanupNow runs the cleanup immediately.

func (*RetentionManager) GetRetentionStats

func (m *RetentionManager) GetRetentionStats(ctx context.Context) (*RetentionStats, error)

GetRetentionStats returns statistics about audit log retention.

func (*RetentionManager) Start

func (m *RetentionManager) Start()

Start starts the retention manager background job.

func (*RetentionManager) Stop

func (m *RetentionManager) Stop()

Stop stops the retention manager.

type RetentionStats

type RetentionStats struct {
	TotalCount    int64      `json:"total_count"`
	ExpiredCount  int64      `json:"expired_count"`
	OldestEntry   *time.Time `json:"oldest_entry,omitempty"`
	NewestEntry   *time.Time `json:"newest_entry,omitempty"`
	RetentionDays int        `json:"retention_days"`
	CutoffDate    time.Time  `json:"cutoff_date"`
}

RetentionStats holds statistics about audit log retention.

type SQLiteLogger

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

SQLiteLogger implements Logger using SQLite.

func NewSQLiteLogger

func NewSQLiteLogger(db *sql.DB, config *LoggerConfig) (*SQLiteLogger, error)

NewSQLiteLogger creates a new SQLite-based audit logger.

func NewSQLiteLoggerWithReadDB

func NewSQLiteLoggerWithReadDB(writeDB, readDB *sql.DB, config *LoggerConfig) (*SQLiteLogger, error)

NewSQLiteLoggerWithReadDB creates a new SQLite-based audit logger with separate write and read database handles.

func (*SQLiteLogger) Close

func (l *SQLiteLogger) Close() error

Close closes the logger and flushes any pending entries.

func (*SQLiteLogger) GetByID

func (l *SQLiteLogger) GetByID(ctx context.Context, id uuid.UUID) (*Entry, error)

GetByID retrieves a single audit entry.

func (*SQLiteLogger) Log

func (l *SQLiteLogger) Log(ctx context.Context, entry *Entry) error

Log records an audit entry.

func (*SQLiteLogger) Query

func (l *SQLiteLogger) Query(ctx context.Context, params *QueryParams) (*QueryResult, error)

Query retrieves audit entries based on parameters.

type Status

type Status string

Status represents the outcome of an action.

const (
	StatusSuccess Status = "success"
	StatusFailure Status = "failure"
)

Jump to

Keyboard shortcuts

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