feat(store): audit log with retention-based purge

This commit is contained in:
2026-06-21 23:45:57 +01:00
parent a4e72b2178
commit 5fb022bbaf
2 changed files with 107 additions and 0 deletions
+61
View File
@@ -0,0 +1,61 @@
package store
import (
"strconv"
"time"
)
type AuditEntry struct {
TS string
Account string
Action string
Target string
Result string
Reason string
}
func (s *Store) Audit(now time.Time, e AuditEntry) error {
var reason any
if e.Reason != "" {
reason = e.Reason
}
_, err := s.db.Exec(
"INSERT INTO audit_log(ts,account,action,target,result,reason) VALUES(?,?,?,?,?,?)",
now.UTC().Format(time.RFC3339), e.Account, e.Action, e.Target, e.Result, reason)
return err
}
func (s *Store) PurgeAudit(now time.Time) (int64, error) {
v, err := s.GetSetting("audit_retention_days")
if err != nil { // unset => no retention policy
return 0, nil
}
days, err := strconv.Atoi(v)
if err != nil || days <= 0 {
return 0, nil
}
cutoff := now.UTC().AddDate(0, 0, -days).Format(time.RFC3339)
res, err := s.db.Exec("DELETE FROM audit_log WHERE ts < ?", cutoff)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
func (s *Store) RecentAudit(limit int) ([]AuditEntry, error) {
rows, err := s.db.Query(
"SELECT ts,account,action,target,result,COALESCE(reason,'') FROM audit_log ORDER BY id DESC LIMIT ?", limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []AuditEntry
for rows.Next() {
var e AuditEntry
if err := rows.Scan(&e.TS, &e.Account, &e.Action, &e.Target, &e.Result, &e.Reason); err != nil {
return nil, err
}
out = append(out, e)
}
return out, rows.Err()
}