carlos / platform Public

console: account-level activity: sign-ins, invites, accounts created and deleted

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 73e264b2cf1d2125d5589babfebc4a7da6f897de parent 4a22422
6 files changed, +334 −1
  • approved_operator_pages_copy_test.go +2 −0
  • internal/console/emailsignin.go +1 −0
  • internal/console/opaudit.go +73 −0
  • internal/console/opaudit_test.go +252 −0
  • internal/console/ownership.go +1 −0
  • internal/console/server.go +5 −1

CI failed — run details

diff --git a/approved_operator_pages_copy_test.go b/approved_operator_pages_copy_test.go
index 516699bc6..97bc8859f 100644
--- a/approved_operator_pages_copy_test.go
+++ b/approved_operator_pages_copy_test.go
@@ -48,6 +48,8 @@ var operatorPagesCopyBuilt = []string{
"OPS-1", "OPS-2", "OPS-3", "OPS-4", "OPS-5", "OPS-6", "OPS-7",
"OPS-8", "OPS-9", "OPS-10", "OPS-11", "OPS-12", "OPS-13", "OPS-14", "OPS-15",
"OPS-16", "OPS-17", "OPS-18", "OPS-19", "OPS-138",
+ // Task 6: the stored Detail text of the account-level audit actions.
+ "OPS-131", "OPS-132", "OPS-133", "OPS-134", "OPS-135", "OPS-136",
}
// operatorPagesBuiltRows is entryBuiltRows for operatorPagesCopyBuilt.
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index dfd863831..9dc3c874f 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -274,6 +274,7 @@ func (s *Server) finishSignin(w http.ResponseWriter, r *http.Request, addr, keym
return
}
s.noteSeen(addr, now)
+ s.auditSignInRow(addr, created)
s.clearCookie(w, authCookie)
s.setCookie(w, sessionCookie, raw, int(SessionTTL.Seconds()))
if created {
diff --git a/internal/console/opaudit.go b/internal/console/opaudit.go
new file mode 100644
index 000000000..f4ee61344
--- /dev/null
+++ b/internal/console/opaudit.go
@@ -0,0 +1,73 @@
+package console
+
+import (
+ "log"
+ "time"
+)
+
+// Account-level audit actions: things a person did that belong to no app, so
+// their rows carry app "" and never show on an app's Activity tab. The
+// operator pages read them (Task 11's kinds use accountAuditActions). Each is
+// recorded after its action has succeeded, and a failed write is logged and
+// never fails the action.
+const (
+ auditFirstSignin = "first-signin"
+ auditSignin = "signin"
+ auditInviteSent = "invite-sent"
+ auditInviteAccepted = "invite-accepted"
+ auditAccountCreated = "account-created"
+ auditAccountDeleted = "account-deleted"
+)
+
+// accountAuditActions is the six actions above.
+var accountAuditActions = []string{
+ auditFirstSignin, auditSignin, auditInviteSent,
+ auditInviteAccepted, auditAccountCreated, auditAccountDeleted,
+}
+
+// auditAccount records one account-level row for accountID (0 when the action
+// belongs to no account, as a sign-in does). The row's address is who acted.
+// The text of every Detail is stored in the row when the action happens, so
+// a later change to the words does not rewrite history.
+func (s *Server) auditAccount(accountID int64, addr string, a Activity) {
+ if err := s.store.RecordActivity(accountID, "", addr, a, time.Now()); err != nil {
+ log.Printf("console: account audit %s: %v", a.Action, err)
+ }
+}
+
+// auditSignInRow is the sign-in row: first-signin when the address was new.
+func (s *Server) auditSignInRow(addr string, first bool) {
+ if first {
+ s.auditAccount(0, addr, Activity{Action: auditFirstSignin, Detail: "Signed in for the first time"})
+ return
+ }
+ s.auditAccount(0, addr, Activity{Action: auditSignin, Detail: "Signed in"})
+}
+
+func (s *Server) auditInviteSent(acct *Account, addr, invitee string) {
+ s.auditAccount(acct.ID, addr, Activity{
+ Action: auditInviteSent, TargetType: "person", Target: invitee,
+ Detail: "Invited " + invitee,
+ })
+}
+
+func (s *Server) auditInviteAccepted(acct *Account, addr string) {
+ s.auditAccount(acct.ID, addr, Activity{
+ Action: auditInviteAccepted, TargetType: "account", Target: acct.Sqid,
+ Detail: "Joined " + acct.Name + " by invitation",
+ })
+}
+
+func (s *Server) auditAccountCreated(acct *Account, addr string) {
+ s.auditAccount(acct.ID, addr, Activity{
+ Action: auditAccountCreated, TargetType: "account", Target: acct.Sqid,
+ Detail: "Created the account " + acct.Name,
+ })
+}
+
+func (s *Server) auditAccountDeleted(acct *Account, addr string) {
+ s.auditAccount(acct.ID, addr, Activity{
+ Action: auditAccountDeleted, TargetType: "account", Target: acct.Sqid,
+ Detail: "Deleted the account " + acct.Name,
+ })
+}
diff --git a/internal/console/opaudit_test.go b/internal/console/opaudit_test.go
new file mode 100644
index 000000000..dbc49a733
--- /dev/null
+++ b/internal/console/opaudit_test.go
@@ -0,0 +1,252 @@
+package console
+
+import (
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+)
+
+// auditRow is one audit row as the operator pages will read it, with the
+// columns Events hides (account_id).
+type auditRow struct {
+ AccountID int64
+ App, Address, TargetType, Target, Detail string
+}
+
+// auditRowsOf is every audit row with this action, oldest first.
+func auditRowsOf(t *testing.T, st *Store, action string) []auditRow {
+ t.Helper()
+ rows, err := st.db.Query(`SELECT account_id, app, address, target_type, target, detail
+FROM audit WHERE action = ? ORDER BY id`, action)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var out []auditRow
+ for rows.Next() {
+ var r auditRow
+ if err := rows.Scan(&r.AccountID, &r.App, &r.Address, &r.TargetType, &r.Target, &r.Detail); err != nil {
+ t.Fatal(err)
+ }
+ out = append(out, r)
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
+
+// wantAuditRows fails unless the action has exactly n rows, and returns them.
+func wantAuditRows(t *testing.T, st *Store, action string, n int) []auditRow {
+ t.Helper()
+ got := auditRowsOf(t, st, action)
+ if len(got) != n {
+ t.Fatalf("%s rows = %+v, want %d", action, got, n)
+ }
+ return got
+}
+
+// emailSignIn signs addr in through the email code door on a fresh browser.
+func emailSignIn(t *testing.T, fx *consoleFixture, m *fakeConsoleMail, addr string) *http.Client {
+ t.Helper()
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ c := newBrowser(t)
+ code, _ := askSignin(t, fx, m, c, addr, "")
+ if status, _, body := postCode(t, fx, c, code); status != http.StatusSeeOther {
+ t.Fatalf("code for %s = %d:\n%s", addr, status, body)
+ }
+ return c
+}
+
+// TestFirstSignInThenSignInAreRecorded: the first sign-in of an address is
+// recorded as such, the next as a plain sign-in, and an account minted at
+// landing as account-created. All three are account-level: no app.
+func TestFirstSignInThenSignInAreRecorded(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := newBrowser(t)
+ signUp(t, fx, c, "code-1")
+ first := wantAuditRows(t, fx.st, auditFirstSignin, 1)[0]
+ if first.App != "" || first.AccountID != 0 || first.Address != "paul@keymail.dev" || first.Detail != "Signed in for the first time" {
+ t.Fatalf("first-signin row = %+v", first)
+ }
+ wantAuditRows(t, fx.st, auditSignin, 0)
+
+ status, _, _ := postForm(t, c, fx.ts.URL+"/auth/signout", url.Values{"csrf": {sessionToken(t, fx, c)}})
+ if status != http.StatusSeeOther {
+ t.Fatalf("signout = %d", status)
+ }
+ signUp(t, fx, c, "code-2")
+ again := wantAuditRows(t, fx.st, auditSignin, 1)[0]
+ if again.App != "" || again.AccountID != 0 || again.Address != "paul@keymail.dev" || again.Detail != "Signed in" {
+ t.Fatalf("signin row = %+v", again)
+ }
+ wantAuditRows(t, fx.st, auditFirstSignin, 1)
+ // Paul already belongs to an account, so nothing was minted for him.
+ wantAuditRows(t, fx.st, auditAccountCreated, 0)
+
+ // A new address lands in an account minted on the spot.
+ fx2, m := newEmailFixture(t, true)
+ const addr = "newbie@example.com"
+ emailSignIn(t, fx2, m, addr)
+ if r := wantAuditRows(t, fx2.st, auditFirstSignin, 1)[0]; r.Address != addr || r.AccountID != 0 || r.App != "" {
+ t.Fatalf("email first-signin row = %+v", r)
+ }
+ accts, err := fx2.st.AccountsFor(addr)
+ if err != nil || len(accts) != 1 {
+ t.Fatalf("accounts for %s = %v, %v", addr, accts, err)
+ }
+ created := wantAuditRows(t, fx2.st, auditAccountCreated, 1)[0]
+ if created.AccountID != accts[0].ID || created.App != "" || created.Address != addr ||
+ created.TargetType != "account" || created.Target != accts[0].Sqid ||
+ created.Detail != "Created the account "+accts[0].Name {
+ t.Fatalf("account-created row = %+v, account %+v", created, accts[0])
+ }
+}
+
+// TestInviteSentAndAcceptedAreRecorded: both rows belong to the inviting
+// account and name the invitee and the account.
+func TestInviteSentAndAcceptedAreRecorded(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ owner := signInPaul(t, fx)
+ const ann = "ann@example.com"
+ lookupAnswers(fx, ann, http.StatusNotFound)
+ csrf := sessionToken(t, fx, owner)
+ if st, _, _ := postForm(t, owner, fx.u("/invite"), url.Values{"csrf": {csrf}, "address": {ann}}); st != http.StatusSeeOther {
+ t.Fatalf("invite = %d", st)
+ }
+ sent := wantAuditRows(t, fx.st, auditInviteSent, 1)[0]
+ if sent.AccountID != OpsAccountID || sent.App != "" || sent.Address != "paul@keymail.dev" ||
+ sent.TargetType != "person" || sent.Target != ann || sent.Detail != "Invited "+ann {
+ t.Fatalf("invite-sent row = %+v", sent)
+ }
+ wantAuditRows(t, fx.st, auditInviteAccepted, 0)
+
+ pending, err := fx.st.PendingInvites(OpsAccountID)
+ if err != nil || len(pending) != 1 {
+ t.Fatalf("pending = %+v, %v", pending, err)
+ }
+ annC := emailSignIn(t, fx, m, ann)
+ status, _, body := postForm(t, annC, fx.ts.URL+"/invite/"+pending[0].Token, url.Values{"csrf": {sessionToken(t, fx, annC)}})
+ if status != http.StatusSeeOther {
+ t.Fatalf("accept = %d:\n%s", status, body)
+ }
+ ops, err := fx.st.AccountByID(OpsAccountID)
+ if err != nil || ops == nil {
+ t.Fatalf("ops account = %v, %v", ops, err)
+ }
+ joined := wantAuditRows(t, fx.st, auditInviteAccepted, 1)[0]
+ if joined.AccountID != OpsAccountID || joined.App != "" || joined.Address != ann ||
+ joined.TargetType != "account" || joined.Target != ops.Sqid ||
+ joined.Detail != "Joined "+ops.Name+" by invitation" {
+ t.Fatalf("invite-accepted row = %+v, account %+v", joined, ops)
+ }
+ wantAuditRows(t, fx.st, auditInviteSent, 1)
+}
+
+// TestAccountDeletedIsRecorded: deleting an empty second account, with its
+// confirmation, leaves one row on that account.
+func TestAccountDeletedIsRecorded(t *testing.T) {
+ fx, c, csrf, sqid := deletableFixture(t)
+ acct, err := fx.st.AccountBySqid(sqid)
+ if err != nil || acct == nil {
+ t.Fatalf("account %s = %v, %v", sqid, acct, err)
+ }
+ wantAuditRows(t, fx.st, auditAccountDeleted, 0)
+ if status, _, body := postGated(t, fx, c, fx.ts.URL+"/a/"+sqid+"/delete",
+ url.Values{"csrf": {csrf}, "confirm": {"Testco"}}); status != http.StatusSeeOther {
+ t.Fatalf("delete = %d:\n%s", status, body)
+ }
+ r := wantAuditRows(t, fx.st, auditAccountDeleted, 1)[0]
+ if r.AccountID != acct.ID || r.App != "" || r.Address != "paul@keymail.dev" ||
+ r.TargetType != "account" || r.Target != sqid || r.Detail != "Deleted the account Testco" {
+ t.Fatalf("account-deleted row = %+v", r)
+ }
+}
+
+// TestRefusedActionsRecordNothing: an invite refused by the rate limit, an
+// invite token nobody holds, and a delete by a non-owner write no row.
+func TestRefusedActionsRecordNothing(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ owner := signInPaul(t, fx)
+ csrf := sessionToken(t, fx, owner)
+ for i := 0; i < maxInvitesPerHour; i++ {
+ if !fx.srv.inviteRate.take(OpsAccountID) {
+ t.Fatalf("take %d refused early", i)
+ }
+ }
+ postForm(t, owner, fx.u("/invite"), url.Values{"csrf": {csrf}, "address": {"late@example.com"}})
+ if kind, msg := inviteFlashAfter(t, owner, fx.ts.URL); kind != "err" || msg != inviteFlashTooManyPerHour() {
+ t.Fatalf("flash = %q %q, want the hourly limit", kind, msg)
+ }
+ wantAuditRows(t, fx.st, auditInviteSent, 0)
+
+ // A member who is not an owner, and a token nobody holds.
+ const kim = "kim@example.com"
+ if err := fx.st.AddMember(OpsAccountID, kim, RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ kimC := emailSignIn(t, fx, m, kim)
+ kcsrf := sessionToken(t, fx, kimC)
+ if status, _, _ := postForm(t, kimC, fx.ts.URL+"/invite/not-a-token", url.Values{"csrf": {kcsrf}}); status == http.StatusSeeOther {
+ t.Fatalf("an unknown token was accepted (%d)", status)
+ }
+ wantAuditRows(t, fx.st, auditInviteAccepted, 0)
+ if status, _, _ := postForm(t, kimC, fx.u("/delete"), url.Values{"csrf": {kcsrf}, "confirm": {"ops"}}); status == http.StatusSeeOther {
+ t.Fatalf("a member's delete was accepted (%d)", status)
+ }
+ wantAuditRows(t, fx.st, auditAccountDeleted, 0)
+}
+
+// TestAccountActivityNeverShowsOnAnAppTab: the rows carry app "", so no app's
+// Activity tab lists them.
+func TestAccountActivityNeverShowsOnAnAppTab(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ owner := signInPaul(t, fx)
+ const ann = "ann@example.com"
+ lookupAnswers(fx, ann, http.StatusNotFound)
+ postForm(t, owner, fx.u("/invite"), url.Values{"csrf": {sessionToken(t, fx, owner)}, "address": {ann}})
+ pending, _ := fx.st.PendingInvites(OpsAccountID)
+ if len(pending) != 1 {
+ t.Fatalf("pending = %+v", pending)
+ }
+ annC := emailSignIn(t, fx, m, ann)
+ postForm(t, annC, fx.ts.URL+"/invite/"+pending[0].Token, url.Values{"csrf": {sessionToken(t, fx, annC)}})
+ if len(auditRowsOf(t, fx.st, auditFirstSignin)) == 0 || len(auditRowsOf(t, fx.st, auditInviteAccepted)) == 0 {
+ t.Fatal("the rows this test is about were not written")
+ }
+ // The invite's flash message ("Invited ann@example.com. ...") shows once on
+ // the next page; read a page first so only the tab's own rows are left.
+ get(t, owner, fx.u("/apps/kass"))
+ status, _, body := get(t, owner, fx.u("/apps/kass/activity"))
+ if status != 200 {
+ t.Fatalf("activity tab = %d", status)
+ }
+ for _, text := range []string{"Signed in", "Invited ", "Joined ", "Created the account", "Deleted the account"} {
+ if strings.Contains(body, text) {
+ t.Errorf("the app's activity tab shows %q", text)
+ }
+ }
+}
+
+// TestAccountAuditFailureNeverFailsTheAction: with the audit table gone every
+// write fails, and signing in, inviting and creating an account still work.
+func TestAccountAuditFailureNeverFailsTheAction(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ if _, err := fx.st.db.Exec(`DROP TABLE audit`); err != nil {
+ t.Fatal(err)
+ }
+ owner := signInPaul(t, fx) // signUp itself requires the redirect into an account
+ lookupAnswers(fx, "ann@example.com", http.StatusNotFound)
+ if st, _, _ := postForm(t, owner, fx.u("/invite"), url.Values{"csrf": {sessionToken(t, fx, owner)}, "address": {"ann@example.com"}}); st != http.StatusSeeOther {
+ t.Fatalf("invite = %d", st)
+ }
+ if kind, _ := inviteFlashAfter(t, owner, fx.ts.URL); kind != "ok" {
+ t.Fatalf("invite flash kind = %q, want ok", kind)
+ }
+ emailSignIn(t, fx, m, "newbie@example.com")
+ if accts, err := fx.st.AccountsFor("newbie@example.com"); err != nil || len(accts) != 1 {
+ t.Fatalf("accounts = %v, %v", accts, err)
+ }
+}
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index 98af50470..df477d28f 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -174,6 +174,7 @@ func (s *Server) handleDeleteAccount(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther)
return
}
+ s.auditAccountDeleted(acct, addr)
s.setFlash(w, "ok", "Deleted “"+acct.Name+"”.")
s.redirectToCurrentAccount(w, r, addr, http.StatusSeeOther)
}
diff --git a/internal/console/server.go b/internal/console/server.go
index b61db99f8..b3359807b 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -2717,7 +2717,9 @@ func (s *Server) mintAccount(ctx context.Context, name, ownerAddr string) (*Acco
if err := s.store.SetLastAccount(ownerAddr, id); err != nil {
log.Printf("console: set last account for %s: %v", ownerAddr, err)
}
- return &Account{ID: id, Sqid: sqid, Name: name, Role: RoleOwner, CreatedAt: now}, nil
+ acct := &Account{ID: id, Sqid: sqid, Name: name, Role: RoleOwner, CreatedAt: now}
+ s.auditAccountCreated(acct, ownerAddr)
+ return acct, nil
}
// account is the gate on every /a/{seg}/… route: a session, and a segment
@@ -2950,6 +2952,7 @@ func (s *Server) handleInvite(w http.ResponseWriter, r *http.Request) {
back("err", "Could not create the invitation. Please try again.")
return
}
+ s.auditInviteSent(acct, addr, to)
link := s.cfg.Origin + "/invite/" + url.PathEscape(tok)
subject, body := inviteMessage(addr, acct.Name, to, link, s.consoleName())
ctx, cancel := context.WithTimeout(r.Context(), s.inviteTimeout)
@@ -3164,6 +3167,7 @@ func (s *Server) handleAcceptInvite(w http.ResponseWriter, r *http.Request) {
if err := s.store.SetLastAccount(addr, accountID); err != nil {
log.Printf("console: set last account: %v", err)
}
+ s.auditInviteAccepted(a, addr)
s.setFlash(w, "ok", "You've joined "+a.Name+".")
http.Redirect(w, r, "/a/"+url.PathEscape(a.Sqid)+"/", http.StatusSeeOther)
}