Documentation
¶
Overview ¶
Package audit provides a unified audit logging toolkit for Go services: a common Storage interface, built-in file and SQL database backends, an asynchronous Writer, destination masking and a Logger that ties them together.
Layout ¶
The root package links no database driver and no Redis client. A service that writes its audit log to a file links neither, and one that writes to Postgres links only the driver it registers itself:
- The SQL backend (NewDatabaseStorage, NewDatabaseStorageFromDB) is built on database/sql alone. The program registers its own driver, the usual way, with a blank import -- github.com/lib/pq, github.com/go-sql-driver/mysql, modernc.org/sqlite or any other driver speaking one of those three dialects.
- The Redis backend lives in github.com/soulteary/audit-kit/v2/redisstore, and with it go-redis. Only importing that package links it in.
Getting started ¶
storage, err := audit.NewFileStorage("/var/log/app/audit.log")
if err != nil {
return err
}
logger := audit.NewLoggerWithWriter(storage, audit.DefaultConfig())
defer logger.Stop()
logger.LogAuth(ctx, audit.EventLoginSuccess, userID, audit.ResultSuccess,
audit.WithRecordIP(clientIP))
NewLoggerWithWriter enqueues each record and persists it on a background worker, so a slow or unavailable backend never blocks the request path. It is the right default for a service; NewLogger writes synchronously, which is simpler for a CLI or a test. Either way, Logger.Stop must run before the process exits or queued records are lost. A full queue drops records rather than blocking, which is what Config.OnEnqueueFailed is there to make visible.
Masking ¶
DefaultConfig masks the destination of every record it writes, so 13812345678 reaches storage as 138****5678 and user@example.com as u***@example.com. The record the caller passes to Logger.Log is never modified. Masking applies to Record.Destination only: anything sensitive put in Record.Metadata, Record.Reason or Record.Resource is stored verbatim.
Writing another backend ¶
A backend is a Storage: Write, Query and Close. Query takes a QueryFilter, and QueryFilter.Matches is exported so that a backend which cannot push the whole filter down to its query language finishes the job in memory exactly as the built-in ones do. The redisstore subpackage is a worked example, including how it takes a narrow client interface rather than a concrete client type.
Example ¶
The common case: an asynchronous logger writing JSON Lines to a file.
package main
import (
"context"
"fmt"
"os"
"path/filepath"
// A program using the SQL backend registers its own driver. This example
// uses SQLite; a service would blank-import github.com/lib/pq or
// github.com/go-sql-driver/mysql instead.
audit "github.com/soulteary/audit-kit/v2"
_ "modernc.org/sqlite"
)
func main() {
dir, err := os.MkdirTemp("", "audit-example")
if err != nil {
panic(err)
}
defer func() { _ = os.RemoveAll(dir) }()
storage, err := audit.NewFileStorage(filepath.Join(dir, "audit.log"))
if err != nil {
panic(err)
}
logger := audit.NewLoggerWithWriter(storage, audit.DefaultConfig())
logger.LogAuth(context.Background(), audit.EventLoginSuccess, "user-42", audit.ResultSuccess,
audit.WithRecordIP("203.0.113.9"),
audit.WithRecordChannel("email"),
audit.WithRecordDestination("user@example.com"),
)
// Stop drains the queue, so every record is on disk after it returns.
if err := logger.Stop(); err != nil {
panic(err)
}
records, err := storage.Query(context.Background(), audit.DefaultQueryFilter().WithUserID("user-42"))
if err != nil {
panic(err)
}
for _, r := range records {
// The destination is masked; the caller's own record was not modified.
fmt.Println(r.EventType, r.UserID, r.Result, r.Destination)
}
}
Output: login_success user-42 success u***@example.com
Index ¶
- Constants
- func MaskDestination(dest string, channel string) string
- func MaskEmail(email string) string
- func MaskIP(ip string) string
- func MaskPhone(phone string) string
- func MaskString(s string, keepChars int) string
- type Config
- type DatabaseConfig
- type DatabaseStorage
- type EventType
- type FileStorage
- type Logger
- func (l *Logger) GetStats() *Stats
- func (l *Logger) Log(ctx context.Context, record *Record)
- func (l *Logger) LogAccess(ctx context.Context, eventType EventType, userID, resource string, ...)
- func (l *Logger) LogAuth(ctx context.Context, eventType EventType, userID string, result Result, ...)
- func (l *Logger) LogChallenge(ctx context.Context, eventType EventType, challengeID, userID string, ...)
- func (l *Logger) Query(ctx context.Context, filter *QueryFilter) ([]*Record, error)
- func (l *Logger) SetLogCallback(fn func(record *Record))
- func (l *Logger) Stop() error
- type MultiStorage
- type NoopStorage
- type QueryFilter
- func (f *QueryFilter) Matches(record *Record) bool
- func (f *QueryFilter) Normalize()
- func (f *QueryFilter) WithChallengeID(challengeID string) *QueryFilter
- func (f *QueryFilter) WithChannel(channel string) *QueryFilter
- func (f *QueryFilter) WithEventType(eventType string) *QueryFilter
- func (f *QueryFilter) WithIP(ip string) *QueryFilter
- func (f *QueryFilter) WithLimit(limit int) *QueryFilter
- func (f *QueryFilter) WithOffset(offset int) *QueryFilter
- func (f *QueryFilter) WithResult(result string) *QueryFilter
- func (f *QueryFilter) WithSessionID(sessionID string) *QueryFilter
- func (f *QueryFilter) WithTimeRange(startTime, endTime int64) *QueryFilter
- func (f *QueryFilter) WithUserID(userID string) *QueryFilter
- type Record
- func (r *Record) Copy() *Record
- func (r *Record) SetTimestamp(ts int64) *Record
- func (r *Record) ToJSON() ([]byte, error)
- func (r *Record) WithChallengeID(challengeID string) *Record
- func (r *Record) WithChannel(channel string) *Record
- func (r *Record) WithDestination(destination string) *Record
- func (r *Record) WithDuration(durationMS int64) *Record
- func (r *Record) WithIP(ip string) *Record
- func (r *Record) WithMetadata(key string, value interface{}) *Record
- func (r *Record) WithProvider(provider, messageID string) *Record
- func (r *Record) WithPurpose(purpose string) *Record
- func (r *Record) WithReason(reason string) *Record
- func (r *Record) WithRequestID(requestID string) *Record
- func (r *Record) WithResource(resource string) *Record
- func (r *Record) WithSessionID(sessionID string) *Record
- func (r *Record) WithTraceID(traceID string) *Record
- func (r *Record) WithUserAgent(ua string) *Record
- func (r *Record) WithUserID(userID string) *Record
- type RecordOption
- func WithRecordChannel(channel string) RecordOption
- func WithRecordDestination(dest string) RecordOption
- func WithRecordIP(ip string) RecordOption
- func WithRecordMetadata(key string, value interface{}) RecordOption
- func WithRecordProvider(provider, messageID string) RecordOption
- func WithRecordPurpose(purpose string) RecordOption
- func WithRecordReason(reason string) RecordOption
- func WithRecordRequestID(requestID string) RecordOption
- func WithRecordTraceID(traceID string) RecordOption
- func WithRecordUserAgent(ua string) RecordOption
- type Result
- type Stats
- type Storage
- type StorageOptions
- type StorageType
- type Writer
- type WriterConfig
Examples ¶
Constants ¶
const MaxRecordJSONSize = 1 << 20
MaxRecordJSONSize is the maximum allowed size for RecordFromJSON input (1MB). Larger payloads are rejected to avoid DoS from unbounded unmarshaling.
Variables ¶
This section is empty.
Functions ¶
func MaskDestination ¶
MaskDestination masks a destination (phone or email) based on channel
Example ¶
Masking helpers are usable on their own, for a log line that is not an audit record.
package main
import (
"fmt"
// A program using the SQL backend registers its own driver. This example
// uses SQLite; a service would blank-import github.com/lib/pq or
// github.com/go-sql-driver/mysql instead.
audit "github.com/soulteary/audit-kit/v2"
_ "modernc.org/sqlite"
)
func main() {
fmt.Println(audit.MaskDestination("13812345678", "sms"))
fmt.Println(audit.MaskDestination("user@example.com", "email"))
fmt.Println(audit.MaskDestination("somewhere-else", "push"))
}
Output: 138****5678 u***@example.com ****
func MaskIP ¶
MaskIP masks an IP address, keeping the first and last IPv4 octet (192.168.1.5 -> 192.***.5).
Note this is pseudonymisation, not anonymisation: with the first and last octet retained an address is narrowed to 1 of 65536, and often far fewer in practice. Use MaskString if a stronger reduction is required.
Example ¶
MaskIP keeps an IPv4 address's first and last octet, which is enough to tell two clients apart in a log without storing the address itself.
package main
import (
"fmt"
// A program using the SQL backend registers its own driver. This example
// uses SQLite; a service would blank-import github.com/lib/pq or
// github.com/go-sql-driver/mysql instead.
audit "github.com/soulteary/audit-kit/v2"
_ "modernc.org/sqlite"
)
func main() {
fmt.Println(audit.MaskIP("192.168.1.5"))
fmt.Println(audit.MaskIP("::ffff:192.168.1.5"))
}
Output: 192.***.5 192.***.5
func MaskString ¶
MaskString masks a string, keeping first and last n characters. A negative keepChars is treated as 0.
Types ¶
type Config ¶
type Config struct {
// Enabled controls whether audit logging is enabled
Enabled bool
// MaskDestination controls whether destinations (phone/email) should be masked
MaskDestination bool
// Writer configuration (for async writing)
Writer *WriterConfig
// OnEnqueueFailed, if set, is invoked when an async record is dropped
// because the writer queue is full. Callers can use it to increment a
// drop-counter metric or emit an alert so silent audit loss is observable.
OnEnqueueFailed func(record *Record)
// OnWriteFailed, if set, is invoked when a record fails to persist to the
// backing storage.
OnWriteFailed func(record *Record, err error)
}
Config holds configuration for the audit logger
type DatabaseConfig ¶
type DatabaseConfig struct {
TableName string // Custom table name (default: "audit_logs")
// DriverName overrides the database/sql driver name derived from the URL
// scheme ("postgres", "mysql" or "sqlite"). Set it when the driver the
// program registers is not named after its dialect: "pgx" for
// jackc/pgx's stdlib driver, "sqlite3" for mattn/go-sqlite3,
// "mysql+instrumented" for a wrapped driver, and so on. The dialect --
// which SQL this package generates -- still comes from the URL scheme.
DriverName string
}
DatabaseConfig holds configuration for database storage
func DefaultDatabaseConfig ¶
func DefaultDatabaseConfig() *DatabaseConfig
DefaultDatabaseConfig returns default database configuration
type DatabaseStorage ¶
type DatabaseStorage struct {
// contains filtered or unexported fields
}
DatabaseStorage implements Storage interface for database-based audit logging. It generates PostgreSQL, MySQL and SQLite flavoured SQL, and works with any database/sql driver the program registers for one of those dialects.
func NewDatabaseStorage ¶
func NewDatabaseStorage(databaseURL string) (*DatabaseStorage, error)
NewDatabaseStorage creates a new database storage instance from a URL.
This package imports no database driver, so the program must register one itself -- a blank import of github.com/lib/pq, github.com/go-sql-driver/mysql or modernc.org/sqlite is the usual way. Without it the call fails with a message naming the missing import; nothing is dialled. Use NewDatabaseStorageFromDB to hand over a *sql.DB the program already has.
Example (DriverNotRegistered) ¶
Without a registered driver the URL constructors fail before dialling, and the error names the import to add.
package main
import (
"fmt"
// A program using the SQL backend registers its own driver. This example
// uses SQLite; a service would blank-import github.com/lib/pq or
// github.com/go-sql-driver/mysql instead.
audit "github.com/soulteary/audit-kit/v2"
_ "modernc.org/sqlite"
)
func main() {
_, err := audit.NewDatabaseStorage("postgres://user:pass@localhost:5432/app")
fmt.Println(err != nil)
}
Output: true
func NewDatabaseStorageFromDB ¶
func NewDatabaseStorageFromDB(db *sql.DB, dbType string, config *DatabaseConfig) (*DatabaseStorage, error)
NewDatabaseStorageFromDB creates a new database storage from an existing *sql.DB. dbType selects the SQL flavour and must be "postgres", "mysql" or "sqlite"; the driver behind db is the caller's choice, so a wrapped or instrumented driver works as long as it speaks one of those dialects.
Prefer this constructor in a service that already owns a connection pool: it shares the pool and its lifecycle, and needs no URL parsing. Note that DatabaseStorage.Close closes the pool it is given.
Example ¶
The SQL backend takes a *sql.DB the program already owns, so the connection pool, its settings and its lifecycle stay in one place.
package main
import (
"context"
"database/sql"
"fmt"
"os"
"path/filepath"
// A program using the SQL backend registers its own driver. This example
// uses SQLite; a service would blank-import github.com/lib/pq or
// github.com/go-sql-driver/mysql instead.
audit "github.com/soulteary/audit-kit/v2"
_ "modernc.org/sqlite"
)
func main() {
dir, err := os.MkdirTemp("", "audit-example")
if err != nil {
panic(err)
}
defer func() { _ = os.RemoveAll(dir) }()
db, err := sql.Open("sqlite", filepath.Join(dir, "audit.db"))
if err != nil {
panic(err)
}
storage, err := audit.NewDatabaseStorageFromDB(db, "sqlite", &audit.DatabaseConfig{
TableName: "audit_logs",
})
if err != nil {
panic(err)
}
defer func() { _ = storage.Close() }()
logger := audit.NewLogger(storage, audit.DefaultConfig())
logger.LogAccess(context.Background(), audit.EventAccessDenied, "user-42", "/admin", audit.ResultFailure,
audit.WithRecordReason("not an admin"),
)
records, err := storage.Query(context.Background(), audit.DefaultQueryFilter().WithResult(string(audit.ResultFailure)))
if err != nil {
panic(err)
}
fmt.Println(records[0].EventType, records[0].Resource, records[0].Reason)
}
Output: access_denied /admin not an admin
func NewDatabaseStorageWithConfig ¶
func NewDatabaseStorageWithConfig(databaseURL string, config *DatabaseConfig) (*DatabaseStorage, error)
NewDatabaseStorageWithConfig creates a new database storage instance with config.
The URL scheme picks the dialect and the default driver name: postgres:// and postgresql:// use "postgres", mysql:// uses "mysql", sqlite:// uses "sqlite". Set DatabaseConfig.DriverName when the registered driver goes by another name, such as "pgx" or "sqlite3". As with NewDatabaseStorage, the driver must already be registered with database/sql by the program.
func (*DatabaseStorage) Close ¶
func (s *DatabaseStorage) Close() error
Close closes the database connection
func (*DatabaseStorage) DB ¶
func (s *DatabaseStorage) DB() *sql.DB
DB returns the underlying database connection
func (*DatabaseStorage) DBType ¶
func (s *DatabaseStorage) DBType() string
DBType returns the database type
func (*DatabaseStorage) Query ¶
func (s *DatabaseStorage) Query(ctx context.Context, filter *QueryFilter) ([]*Record, error)
Query queries audit records from the database
type EventType ¶
type EventType string
EventType represents the type of audit event
const ( // Challenge lifecycle events EventChallengeCreated EventType = "challenge_created" EventChallengeVerified EventType = "challenge_verified" EventChallengeRevoked EventType = "challenge_revoked" EventChallengeExpired EventType = "challenge_expired" // Send events EventSendSuccess EventType = "send_success" EventSendFailed EventType = "send_failed" // Verification events EventVerificationSuccess EventType = "verification_success" EventVerificationFailed EventType = "verification_failed" // Authentication events EventLoginSuccess EventType = "login_success" EventLoginFailed EventType = "login_failed" EventLogout EventType = "logout" EventSessionCreate EventType = "session_create" EventSessionExpire EventType = "session_expire" // Authorization events EventAccessGranted EventType = "access_granted" EventAccessDenied EventType = "access_denied" // User management events EventUserCreated EventType = "user_created" EventUserUpdated EventType = "user_updated" EventUserDeleted EventType = "user_deleted" EventUserLocked EventType = "user_locked" EventUserUnlocked EventType = "user_unlocked" // Rate limit events EventRateLimited EventType = "rate_limited" // Generic events EventCustom EventType = "custom" )
Common event types for OTP/Authentication services
type FileStorage ¶
type FileStorage struct {
// contains filtered or unexported fields
}
FileStorage implements Storage interface for file-based audit logging Uses JSON Lines format (one JSON object per line)
func NewFileStorage ¶
func NewFileStorage(filePath string) (*FileStorage, error)
NewFileStorage creates a new file storage instance. filePath must come from trusted configuration only; do not pass user-controlled paths (path traversal or symlinks could write audit logs to unintended locations).
func (*FileStorage) Close ¶
func (s *FileStorage) Close() error
Close closes the file and releases resources
func (*FileStorage) FilePath ¶
func (s *FileStorage) FilePath() string
FilePath returns the file path
func (*FileStorage) Query ¶
func (s *FileStorage) Query(ctx context.Context, filter *QueryFilter) ([]*Record, error)
Query reads audit records from the file matching the filter Note: File storage query is simple and may be slow for large files For production use, consider using database storage
func (*FileStorage) Rotate ¶
func (s *FileStorage) Rotate() error
Rotate rotates the audit log file Creates a new file with timestamp suffix and reopens the main file
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger handles audit logging with optional async writing
func NewLoggerWithWriter ¶
NewLoggerWithWriter creates a new audit logger with async writer
func (*Logger) Log ¶
Log records an audit event. The provided record is never modified; a copy is made for masking and writing, so the caller may safely reuse the record.
func (*Logger) LogAccess ¶
func (l *Logger) LogAccess(ctx context.Context, eventType EventType, userID, resource string, result Result, opts ...RecordOption)
LogAccess logs an access control event
func (*Logger) LogAuth ¶
func (l *Logger) LogAuth(ctx context.Context, eventType EventType, userID string, result Result, opts ...RecordOption)
LogAuth logs an authentication event
func (*Logger) LogChallenge ¶
func (l *Logger) LogChallenge(ctx context.Context, eventType EventType, challengeID, userID string, result Result, opts ...RecordOption)
LogChallenge logs a challenge-related event
func (*Logger) Query ¶
Query queries audit records from storage. Filter is normalized (limit/offset) before being passed to storage so behavior is consistent across backends.
func (*Logger) SetLogCallback ¶
SetLogCallback sets a callback that is called for each log entry Useful for also logging to standard logger
type MultiStorage ¶
type MultiStorage struct {
// contains filtered or unexported fields
}
MultiStorage combines multiple storage backends
func NewMultiStorage ¶
func NewMultiStorage(storages ...Storage) *MultiStorage
NewMultiStorage creates a storage that writes to multiple backends
func (*MultiStorage) Query ¶
func (m *MultiStorage) Query(ctx context.Context, filter *QueryFilter) ([]*Record, error)
Query queries from the first storage backend
func (*MultiStorage) Storages ¶
func (m *MultiStorage) Storages() []Storage
Storages returns all storage backends
type NoopStorage ¶
type NoopStorage struct{}
NoopStorage is a no-op storage that discards all records
func (*NoopStorage) Query ¶
func (s *NoopStorage) Query(ctx context.Context, filter *QueryFilter) ([]*Record, error)
Query returns empty results
type QueryFilter ¶
type QueryFilter struct {
// Filter by event type
EventType string `json:"event_type,omitempty"`
// Filter by subject
UserID string `json:"user_id,omitempty"`
ChallengeID string `json:"challenge_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
// Filter by channel and result
Channel string `json:"channel,omitempty"`
Result string `json:"result,omitempty"`
// Time range filters (Unix timestamps)
StartTime int64 `json:"start_time,omitempty"`
EndTime int64 `json:"end_time,omitempty"`
// Filter by IP
IP string `json:"ip,omitempty"`
// Pagination
Limit int `json:"limit,omitempty"` // Maximum number of records (default: 100)
Offset int `json:"offset,omitempty"` // Offset for pagination (default: 0)
}
QueryFilter defines filter criteria for querying audit records
func DefaultQueryFilter ¶
func DefaultQueryFilter() *QueryFilter
DefaultQueryFilter returns a default query filter with sensible defaults
func (*QueryFilter) Matches ¶
func (f *QueryFilter) Matches(record *Record) bool
Matches reports whether a record satisfies every criterion the filter sets. An empty or zero field is not a criterion, so the zero filter matches every record.
Backends that cannot push the whole filter down to their query language use it to finish the job in memory: FileStorage applies it line by line, and the redisstore subpackage applies it to each record it loads. It is exported so that a Storage implemented outside this package filters identically to the built-in ones instead of reimplementing the comparisons.
Example ¶
A record can be filtered in memory with the same rules a Storage applies, which is what a custom backend uses to finish a query its query language cannot express.
package main
import (
"fmt"
// A program using the SQL backend registers its own driver. This example
// uses SQLite; a service would blank-import github.com/lib/pq or
// github.com/go-sql-driver/mysql instead.
audit "github.com/soulteary/audit-kit/v2"
_ "modernc.org/sqlite"
)
func main() {
record := audit.NewRecord(audit.EventLoginFailed, audit.ResultFailure).
WithUserID("user-42").
WithChannel("sms")
fmt.Println(audit.DefaultQueryFilter().WithUserID("user-42").Matches(record))
fmt.Println(audit.DefaultQueryFilter().WithChannel("email").Matches(record))
}
Output: true false
func (*QueryFilter) Normalize ¶
func (f *QueryFilter) Normalize()
Normalize ensures filter has valid values
func (*QueryFilter) WithChallengeID ¶
func (f *QueryFilter) WithChallengeID(challengeID string) *QueryFilter
WithChallengeID sets the challenge ID filter
func (*QueryFilter) WithChannel ¶
func (f *QueryFilter) WithChannel(channel string) *QueryFilter
WithChannel sets the channel filter
func (*QueryFilter) WithEventType ¶
func (f *QueryFilter) WithEventType(eventType string) *QueryFilter
WithEventType sets the event type filter
func (*QueryFilter) WithIP ¶
func (f *QueryFilter) WithIP(ip string) *QueryFilter
WithIP sets the IP filter
func (*QueryFilter) WithLimit ¶
func (f *QueryFilter) WithLimit(limit int) *QueryFilter
WithLimit sets the limit
func (*QueryFilter) WithOffset ¶
func (f *QueryFilter) WithOffset(offset int) *QueryFilter
WithOffset sets the offset
func (*QueryFilter) WithResult ¶
func (f *QueryFilter) WithResult(result string) *QueryFilter
WithResult sets the result filter
func (*QueryFilter) WithSessionID ¶
func (f *QueryFilter) WithSessionID(sessionID string) *QueryFilter
WithSessionID sets the session ID filter
func (*QueryFilter) WithTimeRange ¶
func (f *QueryFilter) WithTimeRange(startTime, endTime int64) *QueryFilter
WithTimeRange sets the time range filter
func (*QueryFilter) WithUserID ¶
func (f *QueryFilter) WithUserID(userID string) *QueryFilter
WithUserID sets the user ID filter
type Record ¶
type Record struct {
// Event identification
EventType EventType `json:"event_type"`
EventID string `json:"event_id,omitempty"` // Unique event identifier
// Subject identification
UserID string `json:"user_id,omitempty"`
ChallengeID string `json:"challenge_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
// Event details
Channel string `json:"channel,omitempty"` // sms, email, push, etc.
Destination string `json:"destination,omitempty"` // May be masked
Purpose string `json:"purpose,omitempty"` // login, reset, bind, etc.
Resource string `json:"resource,omitempty"` // Accessed resource
// Result
Result Result `json:"result"`
Reason string `json:"reason,omitempty"` // Failure reason
// Provider info (for external services)
Provider string `json:"provider,omitempty"`
ProviderMessageID string `json:"provider_message_id,omitempty"`
// Request context
IP string `json:"ip,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
RequestID string `json:"request_id,omitempty"`
TraceID string `json:"trace_id,omitempty"`
// Timing
Timestamp int64 `json:"timestamp"` // Unix timestamp
DurationMS int64 `json:"duration_ms,omitempty"` // Operation duration
// Extensible metadata
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Record represents an audit log entry
func RecordFromJSON ¶
RecordFromJSON deserializes a record from JSON. Input larger than MaxRecordJSONSize is rejected to prevent memory exhaustion. Metadata is unmarshaled as map[string]interface{} without depth limit; do not pass untrusted JSON with deeply nested metadata.
func (*Record) Copy ¶
Copy returns a shallow copy of the record. The caller's record is unchanged. Used internally so Log() can mask and write without mutating the original.
func (*Record) SetTimestamp ¶
SetTimestamp sets the timestamp (useful for testing)
func (*Record) WithChallengeID ¶
WithChallengeID sets the challenge ID
func (*Record) WithChannel ¶
WithChannel sets the channel (sms, email, etc.)
func (*Record) WithDestination ¶
WithDestination sets the destination (phone, email, etc.)
func (*Record) WithDuration ¶
WithDuration sets the operation duration in milliseconds
func (*Record) WithMetadata ¶
WithMetadata sets custom metadata
func (*Record) WithProvider ¶
WithProvider sets the provider info
func (*Record) WithPurpose ¶
WithPurpose sets the purpose (login, reset, etc.)
func (*Record) WithReason ¶
WithReason sets the failure reason
func (*Record) WithRequestID ¶
WithRequestID sets the request ID
func (*Record) WithResource ¶
WithResource sets the accessed resource
func (*Record) WithSessionID ¶
WithSessionID sets the session ID
func (*Record) WithTraceID ¶
WithTraceID sets the trace ID
func (*Record) WithUserAgent ¶
WithUserAgent sets the user agent
func (*Record) WithUserID ¶
WithUserID sets the user ID
type RecordOption ¶
type RecordOption func(*Record)
RecordOption is a function that modifies a record
func WithRecordChannel ¶
func WithRecordChannel(channel string) RecordOption
WithRecordChannel returns an option that sets the channel
func WithRecordDestination ¶
func WithRecordDestination(dest string) RecordOption
WithRecordDestination returns an option that sets the destination
func WithRecordIP ¶
func WithRecordIP(ip string) RecordOption
WithRecordIP returns an option that sets the IP
func WithRecordMetadata ¶
func WithRecordMetadata(key string, value interface{}) RecordOption
WithRecordMetadata returns an option that sets metadata
func WithRecordProvider ¶
func WithRecordProvider(provider, messageID string) RecordOption
WithRecordProvider returns an option that sets the provider
func WithRecordPurpose ¶
func WithRecordPurpose(purpose string) RecordOption
WithRecordPurpose returns an option that sets the purpose
func WithRecordReason ¶
func WithRecordReason(reason string) RecordOption
WithRecordReason returns an option that sets the reason
func WithRecordRequestID ¶
func WithRecordRequestID(requestID string) RecordOption
WithRecordRequestID returns an option that sets the request ID
func WithRecordTraceID ¶
func WithRecordTraceID(traceID string) RecordOption
WithRecordTraceID returns an option that sets the trace ID
func WithRecordUserAgent ¶
func WithRecordUserAgent(ua string) RecordOption
WithRecordUserAgent returns an option that sets the user agent
type Storage ¶
type Storage interface {
// Write writes an audit record to the storage backend
Write(ctx context.Context, record *Record) error
// Query queries audit records based on filter criteria
// Returns records matching the filter, ordered by timestamp (newest first)
Query(ctx context.Context, filter *QueryFilter) ([]*Record, error)
// Close closes the storage connection and releases resources
Close() error
}
Storage defines the interface for audit log storage backends
func NewStorageFromType ¶
func NewStorageFromType(storageType StorageType, opts *StorageOptions) (Storage, error)
NewStorageFromType creates a storage instance based on type
type StorageOptions ¶
type StorageOptions struct {
// File storage options
FilePath string
// Database storage options
DatabaseURL string
TableName string
// DriverName overrides the database/sql driver name derived from
// DatabaseURL's scheme; see [DatabaseConfig.DriverName].
DriverName string
// RedisStorage is a Redis-backed storage for [StorageTypeRedis]. Build it
// with the redisstore subpackage and assign it here:
//
// opts.RedisStorage = redisstore.New(client)
//
// The root package keeps no go-redis types of its own, so that a program
// which never selects Redis does not link go-redis. The field is a
// [Storage], so any backend can stand in for Redis in a test.
RedisStorage Storage
}
StorageOptions holds options for creating storage
type StorageType ¶
type StorageType string
StorageType represents the type of storage backend
const ( StorageTypeFile StorageType = "file" StorageTypeDatabase StorageType = "database" StorageTypeDB StorageType = "db" // Alias for database StorageTypeRedis StorageType = "redis" StorageTypeNone StorageType = "none" )
func ParseStorageType ¶
func ParseStorageType(s string) StorageType
ParseStorageType parses a storage type string
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer handles asynchronous writing of audit records to persistent storage
func NewWriter ¶
func NewWriter(storage Storage, config *WriterConfig) *Writer
NewWriter creates a new asynchronous audit writer
func (*Writer) Enqueue ¶
Enqueue enqueues an audit record for asynchronous writing. Returns false if record is nil, the writer is stopped, or the queue is full (non-blocking). Safe to call after Stop(); will return false instead of panicking.
func (*Writer) OnEnqueueFailed ¶
OnEnqueueFailed sets a callback for when enqueue fails (queue full)
func (*Writer) OnWriteFailed ¶
OnWriteFailed sets a callback for when write fails
func (*Writer) Stop ¶
Stop stops the writer workers gracefully.
Ordering matters here, and used to be wrong in two ways.
The context was cancelled *before* the queue was drained, so every record still queued was written with a dead context and the storage backend rejected it immediately -- the carefully written drain loop lost everything it was draining.
The queue was also closed while an Enqueue could still be mid-send, because Enqueue checked the stopped flag under the lock and then sent after releasing it. That interleaving panics with "send on closed channel", despite Enqueue documenting itself as safe to call after Stop.
Now: mark stopped and wait for in-flight Enqueue calls to finish (the write lock does that), signal the drain, let workers finish with a live context, and only then cancel and close storage. The queue is never closed.
type WriterConfig ¶
type WriterConfig struct {
QueueSize int // Size of the async queue (default: 1000)
Workers int // Number of worker goroutines (default: 2)
StopTimeout time.Duration // Timeout for graceful shutdown (default: 10s)
}
WriterConfig holds configuration for the async writer
func DefaultWriterConfig ¶
func DefaultWriterConfig() *WriterConfig
DefaultWriterConfig returns default writer configuration
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package integrationtest holds the tests that talk to a real PostgreSQL or MySQL server.
|
Package integrationtest holds the tests that talk to a real PostgreSQL or MySQL server. |
|
Package redisstore stores audit records in Redis for audit-kit.
|
Package redisstore stores audit records in Redis for audit-kit. |