audit.go46 lines, 1.6 KB
| 1 | // Package audit keeps a record of sensitive actions, in an audit_log table in |
| 2 | // the service's own database: who did what, to what, when, and from where. |
| 3 | // Services may add rows, and nothing else: their role can only INSERT. |
| 4 | package audit |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "fmt" |
| 9 | |
| 10 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 11 | "github.com/fiston-user/payments/internal/platform/mtls" |
| 12 | "github.com/jackc/pgx/v5/pgconn" |
| 13 | "go.opentelemetry.io/otel/trace" |
| 14 | ) |
| 15 | |
| 16 | // An Event is one sensitive action. |
| 17 | type Event struct { |
| 18 | Actor string // who: a user's ID |
| 19 | Action string // what, like transfer.approve |
| 20 | Target string // to what: a transfer's ID, say |
| 21 | Details any // anything else worth keeping, as JSON |
| 22 | } |
| 23 | |
| 24 | // DB is a pool or a transaction: anything that runs a statement. |
| 25 | type DB interface { |
| 26 | Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) |
| 27 | } |
| 28 | |
| 29 | // Record adds e to the audit log in db: the transaction that does the action, |
| 30 | // so the action and its record commit together, or not at all. Where it came |
| 31 | // from is read from ctx: the service that called us, by its certificate, the |
| 32 | // request ID, and the trace. |
| 33 | func Record(ctx context.Context, db DB, e Event) error { |
| 34 | var traceID string |
| 35 | if sc := trace.SpanContextFromContext(ctx); sc.HasTraceID() { |
| 36 | traceID = sc.TraceID().String() |
| 37 | } |
| 38 | _, err := db.Exec(ctx, `INSERT INTO audit_log |
| 39 | (actor, action, target, details, client, request_id, trace_id) |
| 40 | VALUES ($1, $2, $3, $4, $5, $6, $7)`, |
| 41 | e.Actor, e.Action, e.Target, e.Details, mtls.PeerFrom(ctx), httpx.RequestIDFrom(ctx), traceID) |
| 42 | if err != nil { |
| 43 | return fmt.Errorf("audit %s: %w", e.Action, err) |
| 44 | } |
| 45 | return nil |
| 46 | } |