From c8964cec1260b1534aa0d8b31dd6c41d852fbec7 Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 25 Nov 2026 09:31:33 -0700 Subject: [PATCH] Phase 10, part 8: the audit log, and who made what MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sign-ins and failed ones, everything admins do to users, connections, posting accounts, each post published and email sent, pull requests and deletions go in an audit log (schema 36), kept two years; admins read it under Settings → Activity. Drafts, published posts and outreach emails show who made them. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 25 +++ internal/audit/audit.go | 117 +++++++++++ internal/audit/audit_test.go | 49 +++++ internal/db/migrations.go | 20 ++ internal/outreach/message.go | 11 +- internal/web/access.go | 2 +- internal/web/access_test.go | 21 ++ internal/web/account.go | 4 + internal/web/activity.go | 193 ++++++++++++++++++ internal/web/activity_test.go | 53 +++++ internal/web/connections.go | 12 ++ internal/web/inbox.go | 4 + internal/web/outreach.go | 15 +- internal/web/posting.go | 4 +- internal/web/server.go | 13 ++ internal/web/setup.go | 2 + internal/web/signin.go | 16 +- internal/web/templates/activity.html | 29 +++ internal/web/templates/content-published.html | 2 +- internal/web/templates/inbox.html | 2 +- internal/web/templates/layout.html | 1 + internal/web/templates/outreach.html | 2 +- internal/web/users.go | 15 +- 23 files changed, 601 insertions(+), 11 deletions(-) create mode 100644 internal/audit/audit.go create mode 100644 internal/audit/audit_test.go create mode 100644 internal/web/activity.go create mode 100644 internal/web/activity_test.go create mode 100644 internal/web/templates/activity.html diff --git a/PLAN.md b/PLAN.md index 14684b4..6543c7e 100644 --- a/PLAN.md +++ b/PLAN.md @@ -2344,6 +2344,31 @@ starts** (multi-tenant still doesn't). reminders of running-out sign-ins cover every account. - Agents get the same grid in Phase 11. +**Part 8 built 2026-11-25** on `phase10`. +- Schema 36: `audit_log` (when, who, their name then, person, agent or + system, the action, its target, detail, IP), kept two years (pruned by + the hourly `job:accounts`), and `outreach.created_by`. `internal/audit` + records and lists it. +- Recorded where they happen: the setup, sign-ins, failed sign-ins (with + the address tried, known or not), locks, sign-outs, resets asked and + done, password and two-factor changes, joining; every admin action on + Users (invited, access changed with the new access, resent, withdrawn, + turned off and on, unlocked, two-factor reset, signed out, removed); + connections made and removed; posting accounts signed out and who-may- + post changes; each post published (the account and the post's link, + each copy), and scheduled posts and queued emails sent on their own + (as Supermarket, for the person who scheduled or wrote them). +- Recorded by their route (`auditedRoutes`, in activity.go), when the + request worked (it redirected): scheduling and discarding posts, + queueing and sending emails, CRM queueing, mailing-list adds, + suppression, pull requests (SEO changes, briefs, pages, the theme, + search-engine setup), a new site, IndexNow, the metrics page, restoring + backups, the company profile, and the deletions. +- Settings → Activity (admins): newest first, a hundred at a time, + filtered by person, kind and text. +- *By Jane*: on drafts in Posts (who wrote it), published posts (who + posted it, and as which account) and outreach emails (who drafted it). + 1. **Users and sessions.** - Tables: - `users`: email, name, kind (person or agent), status (invited, diff --git a/internal/audit/audit.go b/internal/audit/audit.go new file mode 100644 index 0000000..584d988 --- /dev/null +++ b/internal/audit/audit.go @@ -0,0 +1,117 @@ +// Package audit is the record of who did what: sign-ins, invitations and +// roles, connections, everything sent or published, and deletions. Admins +// read it under Settings → Activity. +package audit + +import ( + "strings" + "time" + + "supermarket/internal/db" +) + +// Entry is one thing someone did. +type Entry struct { + ID int64 + At time.Time + UserID int64 // 0: Supermarket itself, or the local edition's owner + UserName string // as they were called then + Kind string // person, agent or system + Action string + Target string + Detail string + IP string +} + +// Kinds of actor. +const ( + Person = "person" + Agent = "agent" + System = "system" +) + +const timeFormat = "2006-01-02T15:04:05.000Z" + +// Record adds an entry. Long fields are cut short. +func Record(d *db.DB, e Entry) error { + if e.At.IsZero() { + e.At = time.Now() + } + if e.Kind == "" { + e.Kind = Person + } + _, err := d.Exec(`INSERT INTO audit_log (at, user_id, user_name, kind, action, target, detail, ip) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + e.At.UTC().Format(timeFormat), e.UserID, cut(e.UserName, 200), e.Kind, cut(e.Action, 100), cut(e.Target, 500), cut(e.Detail, 2000), cut(e.IP, 64)) + return err +} + +func cut(s string, n int) string { + if r := []rune(s); len(r) > n { + return string(r[:n-1]) + "…" + } + return s +} + +// Filter narrows the list. +type Filter struct { + UserID int64 // 0: everyone + Action string // a prefix: "signin" matches signin and signin-failed + Text string // in the target or detail + Before int64 // entries older than this ID (paging); 0: the newest +} + +// List is the newest entries first. +func List(d *db.DB, f Filter, limit int) ([]Entry, error) { + q := `SELECT id, at, user_id, user_name, kind, action, target, detail, ip FROM audit_log WHERE 1 = 1` + var args []any + if f.UserID != 0 { + q += ` AND user_id = ?` + args = append(args, f.UserID) + } + if f.Action != "" { + q += ` AND action LIKE ?` + args = append(args, escapeLike(f.Action)+"%") + } + if t := strings.TrimSpace(f.Text); t != "" { + q += ` AND (target LIKE ? OR detail LIKE ? OR user_name LIKE ?)` + like := "%" + escapeLike(t) + "%" + args = append(args, like, like, like) + } + if f.Before != 0 { + q += ` AND id < ?` + args = append(args, f.Before) + } + q += ` ORDER BY id DESC LIMIT ?` + args = append(args, limit) + rows, err := d.Query(q, args...) + if err != nil { + return nil, err + } + defer rows.Close() + var out []Entry + for rows.Next() { + var e Entry + var at string + if err := rows.Scan(&e.ID, &at, &e.UserID, &e.UserName, &e.Kind, &e.Action, &e.Target, &e.Detail, &e.IP); err != nil { + return nil, err + } + e.At, _ = time.Parse(timeFormat, at) + out = append(out, e) + } + return out, rows.Err() +} + +// escapeLike makes % and _ match themselves (with ESCAPE-less LIKE, by +// dropping them: a search for them finds nothing special). +func escapeLike(s string) string { + return strings.NewReplacer("%", "", "_", "").Replace(s) +} + +// Prune deletes entries older than keep. +func Prune(d *db.DB, keep time.Duration, now time.Time) (int64, error) { + res, err := d.Exec(`DELETE FROM audit_log WHERE at < ?`, now.Add(-keep).UTC().Format(timeFormat)) + if err != nil { + return 0, err + } + return res.RowsAffected() +} diff --git a/internal/audit/audit_test.go b/internal/audit/audit_test.go new file mode 100644 index 0000000..1e1646c --- /dev/null +++ b/internal/audit/audit_test.go @@ -0,0 +1,49 @@ +package audit + +import ( + "path/filepath" + "testing" + "time" + + "supermarket/internal/db" +) + +func TestRecordAndList(t *testing.T) { + d, err := db.Open(filepath.Join(t.TempDir(), "app.db")) + if err != nil { + t.Fatal(err) + } + defer d.Close() + now := time.Now() + for _, e := range []Entry{ + {At: now.Add(-400 * 24 * time.Hour), UserID: 1, UserName: "Olu", Action: "signin"}, + {At: now.Add(-time.Hour), UserID: 1, UserName: "Olu", Action: "signin", IP: "203.0.113.1"}, + {At: now.Add(-30 * time.Minute), UserID: 2, UserName: "Sam", Action: "signin-failed", Target: "sam@example.com"}, + {At: now, UserID: 1, UserName: "Olu", Action: "invited", Target: "sam@example.com", Detail: "Member: SEO"}, + {At: now, Kind: System, Action: "published", Target: "X @acme"}, + } { + if err := Record(d, e); err != nil { + t.Fatal(err) + } + } + all, _ := List(d, Filter{}, 10) + if len(all) != 5 || all[0].Action != "published" || all[0].Kind != System || all[4].Kind != Person { + t.Fatalf("all: %+v", all) + } + if l, _ := List(d, Filter{Action: "signin"}, 10); len(l) != 3 { + t.Errorf("signin*: %d", len(l)) + } + if l, _ := List(d, Filter{UserID: 2}, 10); len(l) != 1 { + t.Errorf("Sam: %d", len(l)) + } + if l, _ := List(d, Filter{Text: "SAM@"}, 10); len(l) != 2 { + t.Errorf("text: %d", len(l)) + } + page2, _ := List(d, Filter{Before: all[1].ID}, 2) + if len(page2) != 2 || page2[0].ID != all[2].ID { + t.Errorf("paging: %+v", page2) + } + if n, _ := Prune(d, 365*24*time.Hour, now); n != 1 { + t.Errorf("pruned %d", n) + } +} diff --git a/internal/db/migrations.go b/internal/db/migrations.go index 26866f1..804ee99 100644 --- a/internal/db/migrations.go +++ b/internal/db/migrations.go @@ -145,6 +145,26 @@ ALTER TABLE drafts ADD COLUMN account_id INTEGER NOT NULL DEFAULT 0; -- 0: the c ALTER TABLE drafts ADD COLUMN written_by INTEGER NOT NULL DEFAULT 0; ALTER TABLE drafts ADD COLUMN posted_by INTEGER NOT NULL DEFAULT 0; ALTER TABLE drafts ADD COLUMN posted_as TEXT NOT NULL DEFAULT ''; -- the account it went out as, when it did +`, + }, + // 36 + { + Note: "the audit log: who did what, and who made each outreach email", + SQLite: ` +CREATE TABLE audit_log ( + id INTEGER PRIMARY KEY, + at TEXT NOT NULL, + user_id INTEGER NOT NULL DEFAULT 0, -- 0: Supermarket itself, or the local edition's owner + user_name TEXT NOT NULL DEFAULT '', -- as they were called then + kind TEXT NOT NULL DEFAULT 'person', -- person, agent or system + action TEXT NOT NULL, -- e.g. signin, signin-failed, invited, published, deleted + target TEXT NOT NULL DEFAULT '', -- what it was done to: an address, an account, a page + detail TEXT NOT NULL DEFAULT '', + ip TEXT NOT NULL DEFAULT '' +); +CREATE INDEX audit_log_at ON audit_log(at); +CREATE INDEX audit_log_user ON audit_log(user_id, at); +ALTER TABLE outreach ADD COLUMN created_by INTEGER NOT NULL DEFAULT 0; `, }, } diff --git a/internal/outreach/message.go b/internal/outreach/message.go index e0e81ba..fe9e164 100644 --- a/internal/outreach/message.go +++ b/internal/outreach/message.go @@ -50,6 +50,7 @@ type Message struct { RepliedAt time.Time Reply string Error string + CreatedBy int64 // who drafted it; 0: unknown, or the local edition // Filled in when listing. Contact prospects.Contact @@ -86,7 +87,7 @@ func nullID(id int64) any { } const columns = `o.id, o.contact_id, coalesce(o.signal_id, 0), o.channel, o.status, o.subject, o.body, o.to_addr, - o.message_id, o.created_at, o.queued_at, o.sent_at, o.replied_at, o.reply, o.error, + o.message_id, o.created_at, o.queued_at, o.sent_at, o.replied_at, o.reply, o.error, o.created_by, p.first_name, p.last_name, p.title, p.email, p.email_status, p.linkedin, coalesce(p.company_id, 0), coalesce(c.name, '')` @@ -101,7 +102,7 @@ func scan(rows *sql.Rows) ([]Message, error) { var created string var queued, sent, replied sql.NullString if err := rows.Scan(&m.ID, &m.ContactID, &m.SignalID, &m.Channel, &m.Status, &m.Subject, &m.Body, &m.To, - &m.MessageID, &created, &queued, &sent, &replied, &m.Reply, &m.Error, + &m.MessageID, &created, &queued, &sent, &replied, &m.Reply, &m.Error, &m.CreatedBy, &m.Contact.FirstName, &m.Contact.LastName, &m.Contact.Title, &m.Contact.Email, &m.Contact.EmailStatus, &m.Contact.LinkedIn, &m.Contact.CompanyID, &m.Company); err != nil { return nil, err @@ -405,3 +406,9 @@ func lastSent(d *db.DB) (time.Time, error) { err := d.QueryRow(`SELECT max(sent_at) FROM outreach WHERE channel = 'email'`).Scan(&s) return parseTime(s), err } + +// SetCreatedBy records who drafted a message. +func SetCreatedBy(d *db.DB, id, user int64) error { + _, err := d.Exec(`UPDATE outreach SET created_by = ? WHERE id = ?`, user, id) + return err +} diff --git a/internal/web/access.go b/internal/web/access.go index cef506a..9dc5925 100644 --- a/internal/web/access.go +++ b/internal/web/access.go @@ -120,7 +120,7 @@ func (rt *routes) Handle(pattern string, h http.Handler) { rt.unmapped = append(rt.unmapped, pattern) return } - rt.mux.Handle(pattern, rt.s.allow(area, h)) + rt.mux.Handle(pattern, rt.s.allow(area, rt.s.audited(pattern, h))) } func (rt *routes) err() error { diff --git a/internal/web/access_test.go b/internal/web/access_test.go index 6ba4f8a..c3fb3cf 100644 --- a/internal/web/access_test.go +++ b/internal/web/access_test.go @@ -7,6 +7,7 @@ import ( "testing" "supermarket/internal/appmail" + "supermarket/internal/audit" "supermarket/internal/profile" "supermarket/internal/users" ) @@ -117,6 +118,26 @@ func TestAccessEnforced(t *testing.T) { if rec := as(h, sc, http.MethodPost, "/seo/next/dismiss", url.Values{"page": {"/x"}}); rec.Code == http.StatusForbidden { t.Errorf("member POST in SEO: %d", rec.Code) } + + // The log shows each step, to admins only. + entries, _ := audit.List(s.DB, audit.Filter{}, 100) + var steps []string + for i := len(entries) - 1; i >= 0; i-- { + e := entries[i] + steps = append(steps, e.UserName+" "+e.Action+" "+e.Target) + } + got := strings.Join(steps, "\n") + for _, want := range []string{"owner invited ada@example.com", "owner invited sam@example.com", "X joined ada@example.com", "X joined sam@example.com", "X signin"} { + if !strings.Contains(got, want) { + t.Errorf("the log lacks %q:\n%s", want, got) + } + } + if rec := as(h, sc, http.MethodGet, "/settings/activity", nil); rec.Code != http.StatusForbidden { + t.Errorf("member reads the log: %d", rec.Code) + } + if body := as(h, oc, http.MethodGet, "/settings/activity", nil).Body.String(); !strings.Contains(body, "invited sam@example.com") { + t.Errorf("activity page: %s", body) + } } func TestViewOnlyMember(t *testing.T) { diff --git a/internal/web/account.go b/internal/web/account.go index 0f42b58..836e462 100644 --- a/internal/web/account.go +++ b/internal/web/account.go @@ -176,6 +176,7 @@ func (s *Server) accountPassword(w http.ResponseWriter, r *http.Request) { return } s.Log.Info("account: password changed", "user", u.Email, "sessions ended", n) + s.audit(r, "password-changed", u.Email, "") redirect(w, r, "/settings/account", "password-changed") } @@ -310,6 +311,7 @@ func (s *Server) twoFactorOn(w http.ResponseWriter, r *http.Request) { } _ = users.UseTOTPStep(s.DB, u, step) s.Log.Info("account: two-factor sign-in on", "user", u.Email) + s.audit(r, "two-factor-on", u.Email, "") s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Flash: "Two-factor sign-in is on.", Data: &accountData{U: u, Codes: codes}}) } @@ -333,6 +335,7 @@ func (s *Server) twoFactorOff(w http.ResponseWriter, r *http.Request) { return } s.Log.Info("account: two-factor sign-in off", "user", u.Email) + s.audit(r, "two-factor-off", u.Email, "") redirect(w, r, "/settings/account#two-factor", "two-factor-off") } @@ -375,5 +378,6 @@ func (s *Server) recoveryCodes(w http.ResponseWriter, r *http.Request) { } _ = users.UseTOTPStep(s.DB, u, step) s.Log.Info("account: new recovery codes", "user", u.Email) + s.audit(r, "recovery-codes", u.Email, "") s.render(w, r, "two-factor", page{Title: "Two-factor sign-in", Nav: "settings/account", Flash: "New recovery codes: the old ones no longer work.", Data: &accountData{U: u, Codes: codes}}) } diff --git a/internal/web/activity.go b/internal/web/activity.go new file mode 100644 index 0000000..6364f2e --- /dev/null +++ b/internal/web/activity.go @@ -0,0 +1,193 @@ +package web + +import ( + "net/http" + "strconv" + "strings" + "time" + + "supermarket/internal/audit" + "supermarket/internal/users" +) + +// The audit log: who did what. Sign-ins, accounts and connections are +// recorded where they happen; what's sent, published or deleted, by the +// table below, after the request succeeds. + +// audit records something the viewer did. +func (s *Server) audit(r *http.Request, action, target, detail string) { + v := viewerOf(r) + e := audit.Entry{Action: action, Target: target, Detail: detail, IP: clientIP(r)} + if v.User != nil { + e.UserID, e.UserName = v.User.ID, displayName(v.User) + } + s.record(e) +} + +// auditFor records something done for a user, without a request: a +// scheduled post going out, an email sent from the queue. +func (s *Server) auditFor(user int64, action, target, detail string) { + e := audit.Entry{Kind: audit.System, Action: action, Target: target, Detail: detail, UserID: user} + if user != 0 { + if u, err := users.ByID(s.DB, user); err == nil { + e.UserName = displayName(u) + } + } + s.record(e) +} + +func (s *Server) record(e audit.Entry) { + if err := audit.Record(s.DB, e); err != nil { + s.Log.Error("audit: not recorded", "action", e.Action, "err", err) + } +} + +func displayName(u *users.User) string { + if u.Name != "" { + return u.Name + } + return u.Email +} + +// auditedRoutes are the changes recorded by their route, when they work: +// the route's pattern, then its {action} ("" for routes without one). +var auditedRoutes = map[string]map[string]string{ + "POST /drafts/{id}/{action}": {"schedule": "scheduled", "posted": "marked-posted", "discard": "deleted"}, + "POST /outreach/{id}/{action}": {"queue": "queued-email", "send-now": "sent-email", "mark-sent": "marked-sent", "discard": "deleted"}, + "POST /prospects/{kind}/{id}/{action}": {"accept": "queued-for-crm", "accept-all": "queued-for-crm", "list": "added-to-list", "delete": "deleted", "suppress": "suppressed"}, + "POST /seo/changes/{id}/{action}": {"yes": "opened-pull-request"}, + "POST /seo/briefs/{id}/{action}": {"pr": "opened-pull-request", "drop": "deleted"}, + "POST /sites/pages/{id}/{action}": {"remove": "deleted", "close": "closed-pull-request"}, + "POST /sites/new": {"": "created-site"}, + "POST /sites/pages/add": {"": "opened-pull-request"}, + "POST /sites/theme/update": {"": "opened-pull-request"}, + "POST /sites/previews/delete": {"": "deleted"}, + "POST /seo/engines/setup": {"": "opened-pull-request"}, + "POST /seo/engines/ping": {"": "sent-to-indexnow"}, + "POST /metrics/publish": {"": "published"}, + "POST /market/{id}/delete": {"": "deleted"}, + "POST /signals/{id}/delete": {"": "deleted"}, + "POST /funnel/{id}/delete": {"": "deleted"}, + "POST /metrics/spend/{id}/delete": {"": "deleted"}, + "POST /settings/backups/{action}": {"restore": "restored-backup", "delete": "deleted"}, + "POST /crm/{id}/{action}": {"cancel": "deleted"}, + "POST /prospects/suppressed": {"": "changed-suppression"}, + "POST /settings/email/send-test": {"": "sent-email"}, + "POST /settings/email/listmonk/sync": {"": "synced-mailing-lists"}, + "POST /settings/profile": {"": "changed-profile"}, +} + +// statusWriter notes the response's status. +type statusWriter struct { + http.ResponseWriter + code int +} + +func (w *statusWriter) WriteHeader(code int) { + if w.code == 0 { + w.code = code + } + w.ResponseWriter.WriteHeader(code) +} + +func (w *statusWriter) Write(b []byte) (int, error) { + if w.code == 0 { + w.code = http.StatusOK + } + return w.ResponseWriter.Write(b) +} + +// audited wraps a route in the table: a request that worked (a redirect +// or a page, not an error) is recorded. +func (s *Server) audited(pattern string, next http.Handler) http.Handler { + actions, ok := auditedRoutes[pattern] + if !ok { + return next + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + action, ok := actions[r.PathValue("action")] + if !ok { + next.ServeHTTP(w, r) + return + } + sw := &statusWriter{ResponseWriter: w} + next.ServeHTTP(sw, r) + // A failed form re-renders its page with 200 and an error: only + // redirects count as done. + if sw.code == http.StatusSeeOther || sw.code == http.StatusFound { + target := r.URL.Path + if k := r.PathValue("kind"); k != "" { + target = k + " " + r.PathValue("id") + } + s.audit(r, action, target, "") + } + }) +} + +// Settings → Activity. + +type activityData struct { + Entries []audit.Entry + People []users.TeamUser + Filter audit.Filter + More int64 // the ID to page from; 0: no more +} + +const activityPage = 100 + +func (s *Server) activityPage(w http.ResponseWriter, r *http.Request) { + if s.admin(w, r) == nil { + return + } + q := r.URL.Query() + f := audit.Filter{Action: strings.TrimSpace(q.Get("action")), Text: q.Get("q")} + f.UserID, _ = strconv.ParseInt(q.Get("user"), 10, 64) + f.Before, _ = strconv.ParseInt(q.Get("before"), 10, 64) + entries, err := audit.List(s.DB, f, activityPage+1) + if err != nil { + s.serverError(w, err) + return + } + d := activityData{Filter: f} + if len(entries) > activityPage { + entries = entries[:activityPage] + d.More = entries[len(entries)-1].ID + } + d.Entries = entries + d.People, _ = users.Members(s.DB, users.Team) + s.render(w, r, "activity", page{Title: "Activity", Nav: "settings/activity", Data: d}) +} + +// actionLabels say what an action was, in the Activity list. +var actionLabels = map[string]string{ + "setup": "set up Supermarket as its owner", "signin": "signed in", "signin-failed": "failed to sign in", + "locked": "was locked out", "signout": "signed out", "reset-asked": "asked to reset the password", + "password-reset": "reset the password", "password-changed": "changed the password", + "two-factor-on": "turned two-factor sign-in on", "two-factor-off": "turned two-factor sign-in off", + "recovery-codes": "made new recovery codes", "joined": "joined", + "invited": "invited", "invitation-resent": "sent an invitation again", "invitation-withdrawn": "withdrew an invitation", + "access-changed": "changed the access of", "disabled": "turned off the account of", "enabled": "turned on the account of", + "unlocked": "unlocked", "two-factor-reset": "reset two-factor sign-in for", "signed-out-user": "signed out everywhere", + "removed-user": "removed", "connected": "connected", "disconnected": "removed the connection to", + "account-signed-out": "signed out the posting account", "posting-grants": "changed who may post to which account", + "published": "published", "scheduled": "scheduled", "marked-posted": "marked as posted", "deleted": "deleted", + "queued-email": "queued an email", "sent-email": "sent an email", "marked-sent": "marked an email as sent", + "queued-for-crm": "queued for the CRM", "added-to-list": "added to a mailing list", "suppressed": "added to the suppression list", + "opened-pull-request": "opened a pull request", "closed-pull-request": "closed a pull request", "created-site": "started a site", + "sent-to-indexnow": "sent pages to IndexNow", "restored-backup": "restored a backup", "changed-suppression": "changed the suppression list", + "synced-mailing-lists": "synced the mailing lists", "changed-profile": "changed the company profile", +} + +func actionLabel(a string) string { + if l, ok := actionLabels[a]; ok { + return l + } + return strings.ReplaceAll(a, "-", " ") +} + +// pruneAudit keeps two years of the log. +func (s *Server) pruneAudit(now time.Time) { + if _, err := audit.Prune(s.DB, 2*365*24*time.Hour, now); err != nil { + s.Log.Warn("audit: pruning", "err", err) + } +} diff --git a/internal/web/activity_test.go b/internal/web/activity_test.go new file mode 100644 index 0000000..809f176 --- /dev/null +++ b/internal/web/activity_test.go @@ -0,0 +1,53 @@ +package web + +import ( + "net/http" + "net/url" + "strconv" + "strings" + "testing" + + "supermarket/internal/audit" + "supermarket/internal/inventory" + "supermarket/internal/secrets" + "supermarket/internal/users" +) + +func TestActivityRecords(t *testing.T) { + s, h := newServerEdition(t) + owner := addUser(t, s, "owner@example.com", users.Owner, nil) + owner.Name = "Olu" + users.SaveProfile(s.DB, owner) + oc := sessionFor(t, s, owner) + + // A failed sign-in, a connection, a deletion. + signin(h, "203.0.113.4", url.Values{"email": {"owner@example.com"}, "password": {"nope nope nope"}}) + as(h, oc, http.MethodPost, "/settings/sources", url.Values{secrets.HunterAPIKey: {"hk"}}) + e := &inventory.Entry{Name: "Rival", Relationship: "competitor"} + inventory.Save(s.DB, e) + if rec := as(h, oc, http.MethodPost, "/market/"+itoa64(e.ID)+"/delete", url.Values{}); rec.Code != http.StatusSeeOther { + t.Fatalf("delete: %d", rec.Code) + } + + entries, _ := audit.List(s.DB, audit.Filter{}, 50) + byAction := map[string][]audit.Entry{} + for _, e := range entries { + byAction[e.Action] = append(byAction[e.Action], e) + } + if f := byAction["signin-failed"]; len(f) != 1 || f[0].IP != "203.0.113.4" || f[0].UserID != owner.ID { + t.Errorf("failed sign-in: %+v", f) + } + if c := byAction["connected"]; len(c) != 1 || c[0].Target != "Hunter.io" || c[0].UserName != "Olu" { + t.Errorf("connection: %+v", c) + } + if d := byAction["deleted"]; len(d) != 1 || !strings.Contains(d[0].Target, "/market/") { + t.Errorf("deletions: %+v", d) + } + // Filters. + body := as(h, oc, http.MethodGet, "/settings/activity?action=signin-failed", nil).Body.String() + if !strings.Contains(body, "failed to sign in") || strings.Contains(body, "Hunter.io") { + t.Errorf("filtered: %s", body) + } +} + +func itoa64(n int64) string { return strconv.FormatInt(n, 10) } diff --git a/internal/web/connections.go b/internal/web/connections.go index 14da2f3..7c34f92 100644 --- a/internal/web/connections.go +++ b/internal/web/connections.go @@ -40,6 +40,16 @@ var services = []service{ {"listmonk", "Listmonk", "Mailing lists", "/settings/email", []string{secrets.ListmonkToken}}, } +// serviceName is a service as people say it. +func serviceName(id string) string { + for _, sv := range services { + if sv.ID == id { + return sv.Name + } + } + return id +} + // serviceOf is the service a secret belongs to, by its name's prefix. func serviceOf(secret string) string { prefix, _, _ := strings.Cut(secret, ".") @@ -107,6 +117,7 @@ func (s *Server) setSecrets(r *http.Request, updates map[string]string) error { removed := !set && !s.serviceSet(sv) changes[sv] = connChange{By: who, UserID: id, At: now, Removed: removed} s.Log.Info("connections: changed", "service", sv, "removed", removed, "by", who) + s.audit(r, ifElse(removed, "disconnected", "connected"), serviceName(sv), "") } return s.DB.PutJSON(connChangesKey, changes) } @@ -125,6 +136,7 @@ func (s *Server) recordConnection(r *http.Request, service string, set bool) { } } changes[service] = connChange{By: who, UserID: id, At: time.Now().UTC(), Removed: !set} + s.audit(r, ifElse(set, "connected", "disconnected"), serviceName(service), "") if err := s.DB.PutJSON(connChangesKey, changes); err != nil { s.Log.Warn("connections: recording a change", "err", err) } diff --git a/internal/web/inbox.go b/internal/web/inbox.go index 6e32313..f26b0a3 100644 --- a/internal/web/inbox.go +++ b/internal/web/inbox.go @@ -322,6 +322,7 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) { } reddit = reddit || d.Channel == content.ChannelReddit s.Log.Info("content: published", "draft", did, "as", d.PostedAs, "by", by) + s.audit(r, "published", d.PostedAs, "post "+strconv.FormatInt(did, 10)+": "+d.PostURL) } if reddit { s.forgetRedditHistory() @@ -473,6 +474,9 @@ func (s *Server) publishDue(ctx context.Context, now time.Time) { continue } s.Log.Info("scheduler: published", "draft", d.ID, "channel", d.Channel) + if pd, err := content.GetDraft(s.DB, d.ID); err == nil { + s.auditFor(d.PostedBy, "published", pd.PostedAs, "scheduled post "+strconv.FormatInt(d.ID, 10)+": "+pd.PostURL) + } } } diff --git a/internal/web/outreach.go b/internal/web/outreach.go index 42dac45..3f05ea6 100644 --- a/internal/web/outreach.go +++ b/internal/web/outreach.go @@ -276,6 +276,7 @@ func (s *Server) outreachDraft(w http.ResponseWriter, r *http.Request) { set, _ := s.outreachSettings() var m *outreach.Message if m, err = outreach.Draft(ctx, s.DB, c, p, set, id, channel, time.Now()); err == nil { + s.setCreatedBy(r, m.ID) redirect(w, r, "/outreach#m-"+strconv.FormatInt(m.ID, 10), "drafted-outreach") return } @@ -320,11 +321,13 @@ func (s *Server) outreachDraftMany(w http.ResponseWriter, r *http.Request) { set, _ := s.outreachSettings() var failed []string for _, id := range ids { - if _, err := outreach.Draft(ctx, s.DB, c, p, set, id, channel, time.Now()); err != nil { + if m, err := outreach.Draft(ctx, s.DB, c, p, set, id, channel, time.Now()); err != nil { failed = append(failed, err.Error()) if ctx.Err() != nil { break } + } else { + s.setCreatedBy(r, m.ID) } } if len(failed) > 0 { @@ -433,6 +436,7 @@ func (s *Server) RunOutreach(ctx context.Context) { s.Log.Warn("outreach: sending", "message", idOf(m), "err", err) } else if m != nil { s.Log.Info("outreach: sent", "message", m.ID, "to", m.To) + s.auditFor(m.CreatedBy, "sent-email", m.To, m.Subject+" (from the queue)") } } cancel() @@ -465,3 +469,12 @@ func idOf(m *outreach.Message) int64 { } return m.ID } + +// setCreatedBy records who drafted an outreach email. +func (s *Server) setCreatedBy(r *http.Request, id int64) { + if v := viewerOf(r); v.User != nil { + if err := outreach.SetCreatedBy(s.DB, id, v.User.ID); err != nil { + s.Log.Warn("outreach: recording who drafted it", "err", err) + } + } +} diff --git a/internal/web/posting.go b/internal/web/posting.go index 0c769b4..592c8d2 100644 --- a/internal/web/posting.go +++ b/internal/web/posting.go @@ -376,7 +376,8 @@ func (s *Server) postingSave(w http.ResponseWriter, r *http.Request) { s.serverError(w, err) return } - s.Log.Info("posting accounts: who may post changed", "by", viewerOf(r).User.Email) + s.Log.Info("posting accounts: who may post changed") + s.audit(r, "posting-grants", "", "") redirect(w, r, "/settings/posting", "saved") } @@ -406,6 +407,7 @@ func (s *Server) postingRemove(w http.ResponseWriter, r *http.Request) { s.serverError(w, err) return } + s.audit(r, "account-signed-out", a.Label(), "") back := "/settings/accounts" if strings.HasPrefix(r.URL.Path, "/settings/account/") { back = "/settings/account#posting" diff --git a/internal/web/server.go b/internal/web/server.go index b2b174b..0878fe9 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -40,6 +40,7 @@ import ( "supermarket/internal/signals" "supermarket/internal/sites" "supermarket/internal/tracking" + "supermarket/internal/users" ) //go:embed templates/*.html @@ -342,6 +343,7 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("POST /settings/backups/upload", s.backupUpload) mux.HandleFunc("GET /settings/about", s.aboutPage) mux.HandleFunc("GET /settings/connections", s.connectionsPage) + mux.HandleFunc("GET /settings/activity", s.activityPage) mux.HandleFunc("GET /settings/posting", s.postingPage) mux.HandleFunc("POST /settings/posting", s.postingSave) mux.HandleFunc("POST /settings/posting/{id}/remove", s.postingRemove) @@ -489,6 +491,17 @@ func (s *Server) loadTemplates() error { }, "spendChannel": metrics.ChannelName, "dec1f": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) }, + "actionLabel": actionLabel, + // by is "by Jane" for something a person made; "" if unknown. + "by": func(id int64) string { + if id == 0 { + return "" + } + if u, err := users.ByID(s.DB, id); err == nil { + return "by " + displayName(u) + } + return "by someone since removed" + }, "cents": func(f float64) string { if f < 0 { return "·" diff --git a/internal/web/setup.go b/internal/web/setup.go index bb575e7..3fa269c 100644 --- a/internal/web/setup.go +++ b/internal/web/setup.go @@ -6,6 +6,7 @@ import ( "strings" "time" + "supermarket/internal/audit" "supermarket/internal/users" ) @@ -116,6 +117,7 @@ func (s *Server) setupSave(w http.ResponseWriter, r *http.Request) { } s.setupDone.Store(true) s.Log.Info("setup: the owner is created", "email", u.Email) + s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "setup", Target: u.Email, IP: clientIP(r)}) if err := s.startSession(w, r, u); err != nil { s.serverError(w, err) return diff --git a/internal/web/signin.go b/internal/web/signin.go index 49bc182..7c489ba 100644 --- a/internal/web/signin.go +++ b/internal/web/signin.go @@ -10,6 +10,7 @@ import ( "time" "supermarket/internal/appmail" + "supermarket/internal/audit" "supermarket/internal/users" ) @@ -199,6 +200,7 @@ func (s *Server) finishSignIn(w http.ResponseWriter, r *http.Request, u *users.U return } s.Log.Info("signin", "user", u.Email, "ip", clientIP(r)) + s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "signin", IP: clientIP(r)}) if u.TwoFactor && u.RecoveryLeft < 3 { redirect(w, r, "/settings/account#two-factor", "codes-low") return @@ -220,11 +222,14 @@ func (s *Server) countFailure(ipKey, emailKey string, u *users.User, now time.Ti s.Log.Warn("signin: counting a failure", "err", err) } } + ip := strings.TrimPrefix(ipKey, "signin:ip:") if u == nil { - s.Log.Info("signin: failed, no such account", "key", emailKey, "ip", strings.TrimPrefix(ipKey, "signin:ip:")) + s.Log.Info("signin: failed, no such account", "key", emailKey, "ip", ip) + s.record(audit.Entry{Action: "signin-failed", Target: strings.TrimPrefix(emailKey, "signin:email:"), Detail: "no such account", IP: ip}) return } - s.Log.Info("signin: failed", "user", u.Email, "ip", strings.TrimPrefix(ipKey, "signin:ip:")) + s.Log.Info("signin: failed", "user", u.Email, "ip", ip) + s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "signin-failed", Target: u.Email, IP: ip}) locked, err := users.FailedSignIn(s.DB, u, now) if err != nil { s.Log.Warn("signin: counting a failure", "err", err) @@ -232,6 +237,7 @@ func (s *Server) countFailure(ipKey, emailKey string, u *users.User, now time.Ti } if locked { s.Log.Warn("signin: account locked", "user", u.Email) + s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "locked", Target: u.Email, Detail: strconv.Itoa(users.LockAfter) + " failed sign-ins in a row", IP: ip}) s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Your Supermarket account is locked", Body: "Hello" + nameSuffix(u.Name) + ",\n\n" + "Your account at " + s.PublicURL + " was locked after " + strconv.Itoa(users.LockAfter) + " failed sign-ins in a row.\n\n" + @@ -242,6 +248,9 @@ func (s *Server) countFailure(ipKey, emailKey string, u *users.User, now time.Ti } func (s *Server) signout(w http.ResponseWriter, r *http.Request) { + if viewerOf(r).User != nil { + s.audit(r, "signout", "", "") + } if err := s.endSession(w, r); err != nil { s.serverError(w, err) return @@ -286,6 +295,7 @@ func (s *Server) forgot(w http.ResponseWriter, r *http.Request) { return } s.Log.Info("signin: password reset asked for", "user", u.Email, "ip", clientIP(r)) + s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "reset-asked", Target: u.Email, IP: clientIP(r)}) s.sendMail(appmail.Message{To: u.Email, ToName: u.Name, Subject: "Reset your Supermarket password", Body: "Hello" + nameSuffix(u.Name) + ",\n\n" + "Someone, probably you, asked to reset your password at " + s.PublicURL + ".\n\n" + @@ -361,6 +371,7 @@ func (s *Server) reset(w http.ResponseWriter, r *http.Request) { } _ = users.ClearFails(s.DB, "signin:email:"+u.Email) s.Log.Info("signin: password reset", "user", u.Email, "ip", clientIP(r)) + s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "password-reset", Target: u.Email, IP: clientIP(r)}) redirect(w, r, "/signin?email="+url.QueryEscape(u.Email), "password-reset") } @@ -407,6 +418,7 @@ func (s *Server) RunAccounts(ctx context.Context) { if err := users.PruneThrottle(s.DB, now); err != nil { s.Log.Warn("accounts: pruning counts", "err", err) } + s.pruneAudit(now) }) select { case <-ctx.Done(): diff --git a/internal/web/templates/activity.html b/internal/web/templates/activity.html new file mode 100644 index 0000000..766e11b --- /dev/null +++ b/internal/web/templates/activity.html @@ -0,0 +1,29 @@ +{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}} +

Activity

+

Who did what: sign-ins (and failed ones), invitations and access, connections, everything sent or published, and deletions. Kept for two years.

+
+ + + + +
+
+ {{if .Entries}} + + + + {{range .Entries}} + + + + + {{end}} + +
WhenWhoWhatFrom
{{ago .At}}{{if .UserName}}{{.UserName}}{{else if eq .Kind "system"}}Supermarket{{else}}someone{{end}}{{if eq .Kind "system"}} (on its own){{else if eq .Kind "agent"}} agent{{end}}{{actionLabel .Action}}{{with .Target}} {{.}}{{end}}{{with .Detail}}
{{truncate 200 .}}{{end}}
{{.IP}}
+ {{with .More}}

Older →

{{end}} + {{else}}

Nothing recorded{{if or .Filter.UserID .Filter.Action .Filter.Text}} that matches{{end}}.

{{end}} +
+{{end}}{{template "settings-end"}}{{end}} diff --git a/internal/web/templates/content-published.html b/internal/web/templates/content-published.html index 5c47f18..a89e28f 100644 --- a/internal/web/templates/content-published.html +++ b/internal/web/templates/content-published.html @@ -9,7 +9,7 @@ {{range .Drafts}} {{.PublishedAt.Local.Format "2 Jan 2006 15:04"}} - {{.Where}}{{with .PostedAs}}
as {{.}}{{end}} + {{.Where}}{{with .PostedAs}}
as {{.}}{{end}}{{with by .PostedBy}}
{{.}}{{end}} {{.InventoryName}} {{if .PostURL}}{{if .Title}}{{.Title}} {{end}}{{truncate 200 .Content}}{{else}}{{if .Title}}{{.Title}} {{end}}{{truncate 200 .Content}}{{end}} diff --git a/internal/web/templates/inbox.html b/internal/web/templates/inbox.html index 19c027f..ac68ebe 100644 --- a/internal/web/templates/inbox.html +++ b/internal/web/templates/inbox.html @@ -18,7 +18,7 @@
{{range .Drafts}}
-

{{.Where}}

+

{{.Where}}{{with by .WrittenBy}} {{.}}{{end}}

{{if .Error}}

{{.Error}}

{{end}} {{$rv := index $reddit .ID}} {{if $rv}} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 332c544..6f9ecef 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -157,6 +157,7 @@ {{template "icon" "ai"}}AI {{template "icon" "backups"}}Backups + {{template "icon" "backups"}}Activity {{template "icon" "info"}}About {{end}} diff --git a/internal/web/templates/outreach.html b/internal/web/templates/outreach.html index 30abfe1..5d8e182 100644 --- a/internal/web/templates/outreach.html +++ b/internal/web/templates/outreach.html @@ -39,7 +39,7 @@ {{if eq .Channel "email"}}{{.To}}{{if eq .Contact.EmailStatus "valid"}} verified{{else if eq .Contact.EmailStatus "risky"}} risky{{else if eq .Contact.EmailStatus "invalid"}} bounces{{else}} not verified{{end}} {{else}}LinkedIn profile ↗{{end}} {{with index $d.SignalNames .SignalID}} · signal {{.}}{{end}} - · written {{ago .CreatedAt}}{{if not .SentAt.IsZero}} · sent {{ago .SentAt}}{{end}} + · written {{ago .CreatedAt}}{{with by .CreatedBy}} {{.}}{{end}}{{if not .SentAt.IsZero}} · sent {{ago .SentAt}}{{end}}

diff --git a/internal/web/users.go b/internal/web/users.go index 44d67f5..81917e5 100644 --- a/internal/web/users.go +++ b/internal/web/users.go @@ -9,6 +9,7 @@ import ( "time" "supermarket/internal/appmail" + "supermarket/internal/audit" "supermarket/internal/posting" "supermarket/internal/profile" "supermarket/internal/users" @@ -246,6 +247,7 @@ func (s *Server) userInvite(w http.ResponseWriter, r *http.Request) { return } s.Log.Info("users: invited", "user", u.Email, "role", role, "by", v.User.Email) + s.audit(r, "invited", u.Email, accessText(users.Membership{Role: role, Modules: mods})) redirect(w, r, "/settings/users", "invited") } @@ -357,7 +359,17 @@ func (s *Server) userAction(w http.ResponseWriter, r *http.Request) { s.renderUser(w, r, v, u, m, "You can't change your own access: ask another admin.", http.StatusForbidden) return } - log := func(what string) { s.Log.Info("users: "+what, "user", u.Email, "by", v.User.Email) } + auditAs := map[string]string{"access": "access-changed", "resend": "invitation-resent", "withdraw": "invitation-withdrawn", + "disable": "disabled", "enable": "enabled", "unlock": "unlocked", "reset-two-factor": "two-factor-reset", + "sign-out": "signed-out-user", "remove": "removed-user"} + log := func(what string) { + s.Log.Info("users: "+what, "user", u.Email, "by", v.User.Email) + detail := "" + if action == "access" { + detail = strings.TrimPrefix(what, "access changed to ") + } + s.audit(r, auditAs[action], u.Email, detail) + } var err error switch action { case "access": @@ -572,6 +584,7 @@ func (s *Server) inviteAccept(w http.ResponseWriter, r *http.Request) { return } s.Log.Info("users: joined", "user", u.Email) + s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "joined", Target: u.Email, IP: clientIP(r)}) if err := s.startSession(w, r, u); err != nil { s.serverError(w, err) return