// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini package main import ( "context" "database/sql" "errors" "fmt" "strings" ) const ( auditKindRead = "read" auditKindChange = "change" auditOutcomeSuccess = "success" auditOutcomeError = "error" auditMaxActorRunes = 64 auditMaxOriginRunes = 45 auditMaxErrorRunes = 255 auditMaxOperationLen = 32 auditMaxListLimit = 1000 ) var auditStoreChangeOperations = []string{ "login", "logout", "password_change", "zone_create", "zone_delete", "record_create", "record_update", "record_delete", "record_bulk_delete", "soa_update", "zone_import", "delegation_grant", "delegation_revoke", "user_create", "user_role", "user_password", "user_delete", } type auditFilter struct { Zone string Actor string Operation string Kind string Outcome string BeforeID int64 Limit int RestrictToUserID sql.NullInt64 } type auditRow struct { auditEntry TargetUsername sql.NullString } type auditStore struct { q dbtx t tableNames } func newAuditStore(q dbtx, t tableNames) auditStore { return auditStore{q: q, t: t} } func cropRunes(s string, max int) string { if len(s) <= max { return s } n := 0 for i := range s { if n == max { return s[:i] } n++ } return s } func nullJSON(b []byte) any { if b == nil { return nil } return string(b) } func (s auditStore) InsertAudit(ctx context.Context, e auditEntry) (int64, error) { if len(e.Operation) > auditMaxOperationLen { return 0, errors.New("insert audit: operation name too long") } errMsg := e.Error if errMsg.Valid { errMsg.String = cropRunes(errMsg.String, auditMaxErrorRunes) } res, err := s.q.ExecContext(ctx, s.t.sql("INSERT INTO {audit} (`time`, `user_id`, `actor`, `origin`, `operation`, `status`, `error`, `zone`, `record_id`, `target_user_id`, `before_value`, `after_value`) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"), dbTime(e.Time), e.UserID, cropRunes(e.Actor, auditMaxActorRunes), cropRunes(e.Origin, auditMaxOriginRunes), e.Operation, e.Status, errMsg, e.Zone, e.RecordID, e.TargetUserID, nullJSON(e.Before), nullJSON(e.After)) if err != nil { return 0, fmt.Errorf("insert audit: %w", err) } id, err := res.LastInsertId() if err != nil { return 0, fmt.Errorf("insert audit: %w", err) } return id, nil } const auditSelect = "SELECT a.`id`, a.`time`, a.`user_id`, a.`actor`, a.`origin`, a.`operation`, a.`status`, a.`error`, a.`zone`, " + "a.`record_id`, a.`target_user_id`, a.`before_value`, a.`after_value`, tu.`username` FROM {audit} a " + "LEFT JOIN {users} tu ON tu.`id` = a.`target_user_id` " func auditFilterSQL(f auditFilter) (string, []any, error) { var conds []string var args []any if f.Zone != "" { conds = append(conds, "a.`zone` = ?") args = append(args, f.Zone) } if f.Actor != "" { conds = append(conds, "a.`actor` = ?") args = append(args, f.Actor) } if f.Operation != "" { conds = append(conds, "a.`operation` = ?") args = append(args, f.Operation) } switch f.Kind { case "": case auditKindRead, auditKindChange: op := "IN" if f.Kind == auditKindRead { op = "NOT IN" } marks := strings.TrimSuffix(strings.Repeat("?, ", len(auditStoreChangeOperations)), ", ") conds = append(conds, "a.`operation` "+op+" ("+marks+")") for _, o := range auditStoreChangeOperations { args = append(args, o) } default: return "", nil, errors.New("invalid audit kind") } switch f.Outcome { case "": case auditOutcomeSuccess: conds = append(conds, "(a.`status` IS NULL OR a.`status` < 400)") case auditOutcomeError: conds = append(conds, "a.`status` >= 400") default: return "", nil, errors.New("invalid audit outcome") } if f.BeforeID > 0 { conds = append(conds, "a.`id` < ?") args = append(args, f.BeforeID) } if f.RestrictToUserID.Valid { conds = append(conds, "(a.`user_id` = ? OR a.`zone` IN (SELECT d.`zone` FROM {delegations} d WHERE d.`user_id` = ?))") args = append(args, f.RestrictToUserID.Int64, f.RestrictToUserID.Int64) } if len(conds) == 0 { return "", args, nil } return "WHERE " + strings.Join(conds, " AND ") + " ", args, nil } func (s auditStore) ListAudit(ctx context.Context, f auditFilter) ([]auditRow, error) { if f.Limit < 1 || f.Limit > auditMaxListLimit { return nil, errors.New("list audit: invalid limit") } where, args, err := auditFilterSQL(f) if err != nil { return nil, fmt.Errorf("list audit: %w", err) } args = append(args, f.Limit) return s.queryAudit(ctx, s.t.sql(auditSelect+where+"ORDER BY a.`id` DESC LIMIT ?"), args...) } func (s auditStore) LatestAudit(ctx context.Context, n int) ([]auditRow, error) { if n < 1 { return nil, errors.New("latest audit: invalid count") } rows, err := s.queryAudit(ctx, s.t.sql(auditSelect+"ORDER BY a.`id` DESC LIMIT ?"), n) if err != nil { return nil, err } for i, j := 0, len(rows)-1; i < j; i, j = i+1, j-1 { rows[i], rows[j] = rows[j], rows[i] } return rows, nil } func (s auditStore) queryAudit(ctx context.Context, query string, args ...any) ([]auditRow, error) { rows, err := s.q.QueryContext(ctx, query, args...) if err != nil { return nil, fmt.Errorf("read audit: %w", err) } defer rows.Close() var out []auditRow for rows.Next() { var r auditRow e := &r.auditEntry if err := rows.Scan(&e.ID, &e.Time, &e.UserID, &e.Actor, &e.Origin, &e.Operation, &e.Status, &e.Error, &e.Zone, &e.RecordID, &e.TargetUserID, &e.Before, &e.After, &r.TargetUsername); err != nil { return nil, fmt.Errorf("read audit: %w", err) } scanUTC(&e.Time) out = append(out, r) } if err := rows.Err(); err != nil { return nil, fmt.Errorf("read audit: %w", err) } return out, nil }