bunaudit

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package bunaudit audits registered Bun models with a bun.QueryHook.

Bun hooks cannot fail the audited query, so a failed audit write is reported to Hook.OnError and, inside a transaction, rolls that transaction back so Commit fails. Outside a transaction the change itself is already committed.

Limits: single-column primary keys only; map-based inserts are not audited; updates cost two extra SELECTs (before and after) so the diff is exact.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Conn

func Conn(ctx context.Context) (*bun.DB, bun.IConn)

Conn returns the DB and connection (the caller's transaction, if any) an audited write is running on, so a Store can insert its row atomically:

db, conn := bunaudit.Conn(ctx)
db.NewInsert().Conn(conn).Model(&row).Exec(ctx)

Both are nil outside a bunaudit write.

func NewStore

func NewStore() witness.Store

NewStore returns a witness.Store that inserts a LogEntry on the audited write's own connection (the caller's transaction, if any), so the entry and the change commit or roll back together. It only works behind the bunaudit hook; do not register LogEntry with the Registry.

Types

type Hook

type Hook struct {

	// OnError receives audit failures. New sets it to log them; it may be replaced.
	OnError func(error)
	// contains filtered or unexported fields
}

Hook is a bun.QueryHook: db.AddQueryHook(bunaudit.New(&reg, store)).

func New

func New(reg *witness.Registry, store witness.Store) *Hook

func (*Hook) AfterQuery

func (h *Hook) AfterQuery(ctx context.Context, ev *bun.QueryEvent)

func (*Hook) BeforeQuery

func (h *Hook) BeforeQuery(ctx context.Context, ev *bun.QueryEvent) context.Context

BeforeQuery stashes the rows an UPDATE or DELETE is about to touch.

type LogEntry

type LogEntry struct {
	bun.BaseModel `bun:"table:witness_log_entries"`

	ID         int64 `bun:",pk,autoincrement"`
	Timestamp  time.Time
	Action     witness.Action
	ObjectType string
	ObjectID   string
	ObjectRepr string
	Changes    map[string]witness.Change
	Actor      string
	RemoteAddr string
	Additional map[string]any
}

LogEntry is the table row for a witness.Entry (django-auditlog's LogEntry). Create the table with db.NewCreateTable().Model((*bunaudit.LogEntry)(nil)).Exec(ctx); add indexes on (object_type, object_id) and actor yourself if you query by them.

func (LogEntry) Entry

func (l LogEntry) Entry() witness.Entry

Entry converts a stored row back to a witness.Entry. JSON round-tripping turns numbers in Changes into float64.

Jump to

Keyboard shortcuts

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