GoAuth
Modules

Audit Module

The Audit module provides comprehensive security event logging for compliance, debugging, and user transparency. It subscribes to the event categories…

The Audit module provides comprehensive security event logging for compliance, debugging, and user transparency. It subscribes to the event categories listed below and writes structured audit log entries with action names, severity levels, actor IDs, IP addresses, and metadata. It serves two audiences: end users who want to see their own activity history, and administrators who need a full audit trail for compliance and incident investigation.

Capabilities

  • Automatic Event Logging — Subscribes to auth, user, admin, and security events via hooks. No manual logging calls needed — register the module and it starts recording.
  • Four Event Categories — Auth events (login, logout, password changes, 2FA), user events (profile updates, email/phone changes), admin events (user CRUD, role assignments), and security events (suspicious logins, account lockouts, token invalidations). Each category can be independently toggled on or off.
  • Per-Action Retention Policies — Configure how long each category of logs is retained. Use wildcard patterns like "auth.*": 90 (days) or "security.*": -1 (forever). Different compliance requirements can be met per event type.
  • Automatic Background Cleanup — A background goroutine runs every 24 hours to purge expired audit logs according to retention policies. Respects ctx.Done() for graceful shutdown.
  • Manual Cleanup Trigger — Admin endpoint to trigger immediate log cleanup on demand.
  • Sampling Support — SampleRate is currently a configuration field only: the event handler does not apply sampling. Do not rely on it to reduce writes.
  • User Self-Service Endpoints — Users can view their own audit trail, login history, profile changes, and security events. Builds user trust and supports self-service security review.
  • Admin Audit Endpoints — Admins can query the full audit trail, filter by user ID or action type, and trigger manual cleanup.
  • Severity Levels — Each event is logged with a severity (info, warning, critical) for easy filtering and alerting.
  • Custom Audit Storage — Pass a custom AuditLogRepository to store audit logs in a separate database, append-only store, or external SIEM system.

Registration

import "github.com/bete7512/goauth/pkg/modules/audit"

// Default config: all event types tracked, 90/365/forever retention
if err := a.Use(audit.New(nil)); err != nil {
    return err
}

Or with custom settings:

if err := a.Use(audit.New(&audit.Config{
    TrackAuthEvents:     true,
    TrackUserEvents:     true,
    TrackAdminEvents:    true,
    TrackSecurityEvents: true,
    RetentionDays: map[string]int{
        "auth.*":     90,   // Keep auth logs 90 days
        "user.*":     90,   // Keep user logs 90 days
        "admin.*":    365,  // Keep admin logs 1 year
        "security.*": -1,   // Keep security logs forever
    },
    SampleRate: 1.0, // currently not applied by the event handler
})); err != nil {
    return err
}

Configuration

type Config struct {
    AuditLogRepository  models.AuditLogRepository // Custom repo (optional)
    RetentionDays       map[string]int             // Per-action-pattern retention (days, -1 = forever)
    TrackAuthEvents     bool                       // Login, logout, password, 2FA
    TrackUserEvents     bool                       // Profile, email, phone, avatar
    TrackAdminEvents    bool                       // Admin CRUD operations
    TrackSecurityEvents bool                       // Suspicious login, lockout, revocation
    SampleRate          float64                    // Reserved setting; currently not applied
}

Default retention keys

When cfg is nil, New(nil) uses these defaults:

KeyDaysMeaning
auth.*90Auth events kept 90 days
user.*90User events kept 90 days
admin.*365Admin events kept 1 year
security.*-1Security events kept forever

Dependencies

  • Core is the declared module dependency.
  • Admin must also be registered: the audit admin routes reference its authorization middleware, and initialization rejects unresolved middleware.

Endpoints

User Self-Service

MethodPathMiddlewareDescription
GET/me/auditAuthGet your audit logs
GET/me/audit/loginsAuthGet your login history
GET/me/audit/changesAuthGet your profile changes
GET/me/audit/securityAuthGet your security events

Admin

MethodPathMiddlewareDescription
GET/admin/auditAuth + AdminList all audit logs
GET/admin/audit/users/{id}Auth + AdminGet audit logs for a user
GET/admin/audit/actions/{action}Auth + AdminGet logs by action type
POST/admin/audit/cleanupAuth + AdminTrigger manual log cleanup

Tracked Events

The module subscribes to events via RegisterHooks. Each category is independently togglable. A subscription only logs events that an operation actually emits; it is not a guarantee that every route or authentication method emits every listed event. Review the operations your application needs to audit, and add explicit handlers for shared authentication.completed events as needed.

Auth Events (TrackAuthEvents)

EventAudit ActionSeverity
EventAuthLoginSuccessauth.login.successinfo
EventAuthLoginFailedauth.login.failedwarning
EventAuthLogoutauth.logoutinfo
EventAuthPasswordChangedauth.password.changedinfo
EventAuth2FAEnabledauth.2fa.enabledinfo
EventAuth2FADisabledauth.2fa.disabledwarning

User Events (TrackUserEvents)

EventAudit ActionSeverity
EventUserProfileUpdateduser.profile.updatedinfo
EventUserEmailChangeduser.email.changedinfo
EventUserEmailVerifieduser.email.verifiedinfo
EventUserPhoneChangeduser.phone.changedinfo
EventUserAvatarUpdateduser.avatar.updatedinfo

Admin Events (TrackAdminEvents)

EventAudit ActionSeverity
EventAdminUserCreatedadmin.user.createdinfo
EventAdminUserUpdatedadmin.user.updatedinfo
EventAdminUserDeletedadmin.user.deletedwarning
EventAdminUserSuspendedadmin.user.suspendedwarning
EventAdminRoleAssignedadmin.role.assignedinfo
EventAdminRoleRevokedadmin.role.revokedwarning

Security Events (TrackSecurityEvents)

EventAudit ActionSeverity
EventSecuritySuspiciousLoginsecurity.suspicious.logincritical
EventSecurityAccountLockedsecurity.account.lockedwarning
EventSecuritySessionRevokedsecurity.session.revokedinfo
EventSecurityTokenInvalidatedsecurity.token.invalidatedinfo

Extensibility

Custom Audit Storage

Pass a custom AuditLogRepository to store audit logs in a separate database, external SIEM, or append-only store:

if err := a.Use(audit.New(&audit.Config{
    AuditLogRepository: myCustomAuditRepo, // implements models.AuditLogRepository
    TrackAuthEvents:    true,
    TrackSecurityEvents: true,
})); err != nil {
    return err
}

When nil, the repository is obtained from the shared storage layer during initialization.

Sorting and Pagination

Admin audit endpoints support sorting by created_at, action, severity, and actor_id. Pagination uses offset/limit parameters. User self-service endpoints are automatically scoped to the authenticated user's ID.

Next Steps

Edit this page on GitHub

On this page