// SPDX-License-Identifier: AGPL-3.0-or-later // Package audit records who changed what and when: every successful change // made through the API, plus sign-in events. Entries name the actor, the // route and the ids in its path, never request bodies (which can hold // passwords and documents). Writing happens in the background, so requests // never wait on it; if the queue overflows, entries are dropped and logged. package audit import ( "context" "encoding/csv" "fmt" "io" "log/slog" "net" "net/http" "strings" "sync" "time" "docwell/server/internal/access" "docwell/server/internal/store/pocketbase" ) // Entry is one thing that happened. type Entry struct { // Action is a dotted name ("auth.login") or a route ("PATCH /pages/{id}"). Action string ActorID string ActorEmail string // Org is the actor's organization, so organization admins see their entries. Org string TargetType string TargetID string // Status is the HTTP status the request ended with (0 when not a request). Status int IP string UserAgent string Meta map[string]any } // Logger writes entries to the audit_log collection. type Logger struct { pb *pocketbase.Client log *slog.Logger queue chan Entry wg sync.WaitGroup } func New(pb *pocketbase.Client, log *slog.Logger) *Logger { l := &Logger{pb: pb, log: log, queue: make(chan Entry, 1000)} l.wg.Add(1) go l.run() return l } // Record queues e (never blocks). func (l *Logger) Record(e Entry) { if l == nil { return } select { case l.queue <- e: default: l.log.Warn("audit: queue full, entry dropped", "action", e.Action, "actor", e.ActorID) } } // Close writes what is queued and stops. func (l *Logger) Close() { close(l.queue) l.wg.Wait() } func clip(s string, n int) string { if len(s) > n { return s[:n] } return s } func (l *Logger) run() { defer l.wg.Done() for e := range l.queue { body := map[string]any{ "action": clip(e.Action, 120), "actor_email": clip(e.ActorEmail, 255), "target_type": clip(e.TargetType, 40), "target_id": clip(e.TargetID, 64), "status": e.Status, "ip": clip(e.IP, 64), "user_agent": clip(e.UserAgent, 300), } if e.ActorID != "" { body["actor"] = e.ActorID } if e.Org != "" { body["organization"] = e.Org } if len(e.Meta) > 0 { body["meta"] = e.Meta } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) if _, err := pocketbase.Create[struct{}](ctx, l.pb, "audit_log", body); err != nil { l.log.Error("audit: write", "action", e.Action, "err", err) } cancel() } } // ClientIP is the request's client address: the first X-Forwarded-For hop // when a proxy set one (Docwell expects to sit behind one), else the peer. func ClientIP(r *http.Request) string { if f := r.Header.Get("X-Forwarded-For"); f != "" { ip, _, _ := strings.Cut(f, ",") return strings.TrimSpace(ip) } host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return r.RemoteAddr } return host } // ---- Reading the log ------------------------------------------------------- // View is an entry as the admin panel shows it. type View struct { ID string `json:"id"` Created string `json:"created"` Action string `json:"action"` ActorID string `json:"actorId"` ActorEmail string `json:"actorEmail"` TargetType string `json:"targetType"` TargetID string `json:"targetId"` Status int `json:"status"` IP string `json:"ip"` UserAgent string `json:"userAgent"` Meta map[string]any `json:"meta"` } type record struct { ID string `json:"id"` Created string `json:"created"` Action string `json:"action"` Actor string `json:"actor"` ActorEmail string `json:"actor_email"` TargetType string `json:"target_type"` TargetID string `json:"target_id"` Status int `json:"status"` IP string `json:"ip"` UserAgent string `json:"user_agent"` Meta map[string]any `json:"meta"` } func (r record) view() View { return View{ ID: r.ID, Created: r.Created, Action: r.Action, ActorID: r.Actor, ActorEmail: r.ActorEmail, TargetType: r.TargetType, TargetID: r.TargetID, Status: r.Status, IP: r.IP, UserAgent: r.UserAgent, Meta: r.Meta, } } // Query filters the log. type Query struct { // Search matches the action, actor email, target id or IP. Search string Since string Until string Page int PerPage int } type Page struct { Items []View `json:"items"` Total int `json:"total"` Page int `json:"page"` } func quote(s string) string { return strings.NewReplacer(`\`, `\\`, `'`, `\'`).Replace(s) } func (q Query) filter(c access.Caller) (string, error) { all, org, err := access.UserScope(c) if err != nil { return "", err } var parts []string if !all { if org == "" { // An admin without an organization sees only their own entries. parts = append(parts, fmt.Sprintf("actor = '%s'", quote(c.ID))) } else { parts = append(parts, fmt.Sprintf("organization = '%s'", quote(org))) } } if s := strings.TrimSpace(q.Search); s != "" { v := quote(s) parts = append(parts, fmt.Sprintf("(action ~ '%s' || actor_email ~ '%s' || target_id = '%s' || ip = '%s')", v, v, v, v)) } if q.Since != "" { parts = append(parts, fmt.Sprintf("created >= '%s'", quote(q.Since))) } if q.Until != "" { parts = append(parts, fmt.Sprintf("created <= '%s'", quote(q.Until))) } return strings.Join(parts, " && "), nil } // List returns a page of the log, newest first: everything for superadmins, // the actor's organization for admins. func (l *Logger) List(ctx context.Context, c access.Caller, q Query) (Page, error) { filter, err := q.filter(c) if err != nil { return Page{}, err } q.Page = max(q.Page, 1) if q.PerPage <= 0 || q.PerPage > 200 { q.PerPage = 50 } res, err := pocketbase.List[record](ctx, l.pb, "audit_log", pocketbase.ListOptions{ Page: q.Page, PerPage: q.PerPage, Filter: filter, Sort: "-created,-id", }) if err != nil { return Page{}, err } out := Page{Items: make([]View, 0, len(res.Items)), Total: res.TotalItems, Page: q.Page} for _, r := range res.Items { out.Items = append(out.Items, r.view()) } return out, nil } // ExportCSV writes the matching entries (up to 50 000) as CSV. func (l *Logger) ExportCSV(ctx context.Context, c access.Caller, q Query, w io.Writer) error { filter, err := q.filter(c) if err != nil { return err } cw := csv.NewWriter(w) _ = cw.Write([]string{"time", "action", "actor_id", "actor_email", "target_type", "target_id", "status", "ip", "user_agent"}) for page := 1; page <= 50; page++ { res, err := pocketbase.List[record](ctx, l.pb, "audit_log", pocketbase.ListOptions{ Page: page, PerPage: 1000, Filter: filter, Sort: "-created,-id", }) if err != nil { return err } for _, r := range res.Items { _ = cw.Write([]string{r.Created, r.Action, r.Actor, r.ActorEmail, r.TargetType, r.TargetID, fmt.Sprint(r.Status), r.IP, r.UserAgent}) } if page >= res.TotalPages { break } } cw.Flush() return cw.Error() } // Prune deletes entries older than keep. It is a background job. func (l *Logger) Prune(ctx context.Context, keep time.Duration) error { cutoff := time.Now().Add(-keep).UTC().Format("2006-01-02 15:04:05.000Z") for { res, err := pocketbase.List[record](ctx, l.pb, "audit_log", pocketbase.ListOptions{ PerPage: 500, Filter: fmt.Sprintf("created < '%s'", cutoff), Fields: "id", }) if err != nil || len(res.Items) == 0 { return err } for _, r := range res.Items { if err := l.pb.Delete(ctx, "audit_log", r.ID); err != nil && !pocketbase.IsNotFound(err) { return err } } } }