Keep late report arrivals in digests and invalidate rejected mail
5 files changed,
+107
−18
docs/superpowers/notes/demo-abuse-alerts.md+11 −10internal/console/consolemail.go+1 −0internal/console/demo_alerts.go+52 −7internal/console/demo_alerts_test.go+42 −0internal/console/store_gate.go+1 −1
diff --git a/docs/superpowers/notes/demo-abuse-alerts.md b/docs/superpowers/notes/demo-abuse-alerts.md| index d8cc27352..268a9ce25 100644 |
| --- a/docs/superpowers/notes/demo-abuse-alerts.md |
| +++ b/docs/superpowers/notes/demo-abuse-alerts.md |
| @@ -27,7 +27,7 @@ recipient rules and daily digest is larger than this local alert source. |
| Use the existing direct notification path: recipient grants from |
| `internal/console/alertwatch.go:64`, `Server.sendApp` from `server.go:1254`, and |
| per-recipient success state from `store.go:2721` and `:2738`. Email uses the |
| -existing console sender (`consolemail.go:190`), with a cached-verified-only |
| +existing console sender (`consolemail.go:191`), with a cached-verified-only |
| entry point: an alert must never call the identity ensure/verify path, which |
| can read S3 (`consolemail.go:122`, `:154`). The existing startup ensure primes |
| the cache from its returned record (`consolemail.go:132`); alerts add no S3 reads. |
| @@ -47,7 +47,7 @@ parameters, not interpolated operator input. |
| | One prefix | largest `count(*) GROUP BY prefix_hash`, excluding NULL | 30 attempts in 1h | |
| | Refusals | `sum(refusals) FROM demo_admission_refusals WHERE minute >= ? AND minute <= ?` | 30 in 10 minute buckets | |
| | Reports now | `count(*) FROM demo_reports WHERE created_at > ? AND created_at <= ?` | more than 5 in a rolling hour | |
| -| Report digest | count reports from this recipient's last successful digest cutoff | once per UTC day, if any arrived | |
| +| Report digest | `SELECT id,created_at FROM demo_reports WHERE created_at < ?`; count IDs not in the recipient's receipt | once per UTC day, if any arrived | |
| Prefix hashes use the admission salt and HMAC-SHA256 over the masked IPv4 /24 |
| or IPv6 /48 string. /48 catches rotation across the /64 budgets inside a common |
| @@ -61,11 +61,12 @@ A persistent firing bit per recipient prevents repeated mail while a condition |
| stays true. A quiet observation rearms it without sending a clear. Failed sends |
| retry on later passes; a crash after mail acceptance but before recording |
| success can duplicate mail. Failed transient conditions retry while still firing. |
| -No reminders are added. Digests retain a cutoff |
| -per recipient, so failures do not advance it. Each digest excludes its current second to |
| -leave concurrent arrivals for the next digest. The first |
| -digest covers the preceding 24h; later digests cover surviving reports since |
| -the previous successful cutoff. Resolved reports still count as arrivals. |
| +No reminders are added. Digests remember the report IDs in each successful |
| +snapshot, bounded by the existing 2,000-report queue. A late commit with an |
| +older request timestamp still appears next time. Failed sends never advance |
| +the receipt. The first digest covers the preceding 24h; later digests cover |
| +surviving arrivals not previously included, even if already resolved. Each |
| +snapshot drops IDs for pruned reports; an empty day also prunes receipts. |
| ## Operator settings |
| @@ -101,9 +102,9 @@ local counter writes on refused admissions, and mail only on transitions or |
| nonempty digests. Alert text contains aggregate counts, never IP hashes, |
| report details, demo names or claim tokens. |
| -Implementation: `internal/console/demo_alerts.go:99` evaluates signals and |
| -`:160` runs the guarded pass before fleet reads. `:233` handles digests. |
| -The settings loader is at `:26`; `demo_alert_admission.go:76` persists refusals. |
| +Implementation: `internal/console/demo_alerts.go:101` evaluates signals and |
| +`:162` runs the guarded pass before fleet reads. `:235` handles digests. |
| +The settings loader is at `:27`; `demo_alert_admission.go:76` persists refusals. |
| ## Open questions before activation |
diff --git a/internal/console/consolemail.go b/internal/console/consolemail.go| index 2c78b87f8..09598e220 100644 |
| --- a/internal/console/consolemail.go |
| +++ b/internal/console/consolemail.go |
| @@ -167,6 +167,7 @@ func (m *sesConsoleMailer) ready(ctx context.Context) (string, error) { |
| } |
| st := rec.Regions[m.dep.Region] |
| if st == nil || st.Status != mail.StatusVerified { |
| + m.ensuredConfigSet = "" |
| return "", ErrConsoleMailNotReady |
| } |
| m.verified, m.configSet = true, st.ConfigSet |
diff --git a/internal/console/demo_alerts.go b/internal/console/demo_alerts.go| index 4f4b3c4e5..447788739 100644 |
| --- a/internal/console/demo_alerts.go |
| +++ b/internal/console/demo_alerts.go |
| @@ -3,6 +3,7 @@ package console |
| import ( |
| "context" |
| "database/sql" |
| + "encoding/json" |
| "errors" |
| "fmt" |
| "slices" |
| @@ -83,7 +84,8 @@ func (c DemoAlertConfig) validate() error { |
| func (s *Store) migrateDemoAlerts() error { |
| _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS demo_alert_digests ( |
| - address TEXT PRIMARY KEY, through_at INTEGER NOT NULL, sent_day INTEGER NOT NULL |
| + address TEXT PRIMARY KEY, through_at INTEGER NOT NULL, sent_day INTEGER NOT NULL, |
| + report_ids TEXT NOT NULL DEFAULT '[]' |
| ) WITHOUT ROWID`) |
| return err |
| } |
| @@ -232,28 +234,71 @@ func (s *Server) sendDemoAlert(ctx context.Context, recipient operatorGrant, sub |
| func (s *Server) demoReportDigest(ctx context.Context, recipient operatorGrant, now time.Time) error { |
| var through, day int64 |
| - err := s.store.db.QueryRowContext(ctx, `SELECT through_at,sent_day FROM demo_alert_digests WHERE address=?`, recipient.address).Scan(&through, &day) |
| - if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + var raw string |
| + err := s.store.db.QueryRowContext(ctx, `SELECT through_at,sent_day,report_ids FROM demo_alert_digests WHERE address=?`, recipient.address).Scan(&through, &day, &raw) |
| + first := errors.Is(err, sql.ErrNoRows) |
| + if err != nil && !first { |
| return err |
| } |
| today := now.Truncate(24 * time.Hour).Unix() |
| if day >= today { |
| return nil |
| } |
| - if through == 0 { |
| + if first { |
| through = now.Add(-24 * time.Hour).Unix() |
| } |
| + var previous []string |
| + if !first { |
| + if err := json.Unmarshal([]byte(raw), &previous); err != nil { |
| + return err |
| + } |
| + } |
| + seen := make(map[string]bool, len(previous)) |
| + for _, id := range previous { |
| + seen[id] = true |
| + } |
| + // Report timestamps are captured before the request body is read. A time |
| + // watermark alone can skip a late commit forever. Remember the IDs actually |
| + // observed instead. The report table is capped at 2,000 rows; each successful |
| + // digest replaces this snapshot, dropping IDs whose reports were pruned. |
| + rows, err := s.store.db.QueryContext(ctx, `SELECT id,created_at FROM demo_reports WHERE created_at<? ORDER BY id`, now.Unix()) |
| + if err != nil { |
| + return err |
| + } |
| + var ids []string |
| var count int64 |
| - if err := s.store.db.QueryRowContext(ctx, `SELECT count(*) FROM demo_reports WHERE created_at>=? AND created_at<?`, through, now.Unix()).Scan(&count); err != nil { |
| + for rows.Next() { |
| + var id string |
| + var created int64 |
| + if err := rows.Scan(&id, &created); err != nil { |
| + rows.Close() |
| + return err |
| + } |
| + ids = append(ids, id) |
| + if !seen[id] && (!first || created >= through) { |
| + count++ |
| + } |
| + } |
| + err = rows.Err() |
| + rows.Close() |
| + if err != nil { |
| + return err |
| + } |
| + encoded, err := json.Marshal(ids) |
| + if err != nil { |
| return err |
| } |
| if count == 0 { |
| - return nil |
| + // Prune acknowledged IDs even on an empty day. Do not spend today's send. |
| + if !first { |
| + _, err = s.store.db.ExecContext(ctx, `UPDATE demo_alert_digests SET report_ids=? WHERE address=?`, string(encoded), recipient.address) |
| + } |
| + return err |
| } |
| body := fmt.Sprintf(demoAlertDigestBody, count, time.Unix(through, 0).UTC().Format(time.RFC3339), now.Format(time.RFC3339), s.cfg.Origin) |
| if err := s.sendDemoAlert(ctx, recipient, demoAlertDigestSubject, body); err != nil { |
| return fmt.Errorf(demoAlertDeliveryError, recipient.address, err) |
| } |
| - _, err = s.store.db.ExecContext(ctx, `INSERT INTO demo_alert_digests(address,through_at,sent_day) VALUES(?,?,?) ON CONFLICT(address) DO UPDATE SET through_at=excluded.through_at,sent_day=excluded.sent_day`, recipient.address, now.Unix(), today) |
| + _, err = s.store.db.ExecContext(ctx, `INSERT INTO demo_alert_digests(address,through_at,sent_day,report_ids) VALUES(?,?,?,?) ON CONFLICT(address) DO UPDATE SET through_at=excluded.through_at,sent_day=excluded.sent_day,report_ids=excluded.report_ids`, recipient.address, now.Unix(), today, string(encoded)) |
| return err |
| } |
diff --git a/internal/console/demo_alerts_test.go b/internal/console/demo_alerts_test.go| index f6155269c..81725db3c 100644 |
| --- a/internal/console/demo_alerts_test.go |
| +++ b/internal/console/demo_alerts_test.go |
| @@ -421,3 +421,45 @@ func TestDemoAlertStateExcludedFromFleetCutover(t *testing.T) { |
| t.Fatalf("demo notice leaked into fleet migration: %v", seen) |
| } |
| } |
| + |
| +func TestDemoAlertDigestIncludesLateCommittedReports(t *testing.T) { |
| + s, m, now := demoAlertServer(t) |
| + s.cfg.DemoAlerts.Digest = true |
| + alertReport(t, s.store, now.Add(-time.Minute), "first") |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The HTTP handler captures created_at before reading the request body. |
| + // This request began before the digest, but committed after it was sent. |
| + alertReport(t, s.store, now.Add(-2*time.Second), "slow-request") |
| + *now = now.Add(24 * time.Hour) |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(m.calls) != 2 || !strings.Contains(m.calls[1], "1 abuse reports") { |
| + t.Fatalf("late-committed report omitted: %v", m.calls) |
| + } |
| +} |
| + |
| +func TestDemoAlertEmailDiscardsRejectedCachedIdentity(t *testing.T) { |
| + st := release.NewDirStore(t.TempDir()) |
| + prov := mail.NewMemProvisioner("1") |
| + prov.StatusOnEnsure = verifiedStatus |
| + ses := &fakeSES{} |
| + dep := testMailDeployment() |
| + original := newSESConsoleMailer("noreply@example.test", st, prov, dnsrec.NewMemWriter(), dep, ses) |
| + if err := original.Send(t.Context(), "ops@example.test", "subject", "body"); err != nil { |
| + t.Fatal(err) |
| + } |
| + restarted := newSESConsoleMailer("noreply@example.test", st, prov, dnsrec.NewMemWriter(), dep, ses) |
| + if err := restarted.Ensure(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + prov.SetIdentityStatus(dep.Region, "example.test", mail.Status{DKIM: "PENDING", MailFrom: "PENDING", Sending: "PENDING"}) |
| + if restarted.Ready(t.Context()) { |
| + t.Fatal("pending identity accepted") |
| + } |
| + if err := restarted.SendReady(t.Context(), "ops@example.test", "subject", "body"); !errors.Is(err, ErrConsoleMailNotReady) { |
| + t.Fatalf("known rejected identity still used: %v", err) |
| + } |
| +} |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index 0832724b0..45eb91140 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -198,7 +198,7 @@ var claimSQLTables = map[string]claimSQLTable{ |
| "demo_claim_flows": {App: "demo_id", Refuse: "anonymous demo claim flows require claims mode off"}, |
| "demo_reports": {App: "demo_id", Refuse: "anonymous demo reports require claims mode off"}, |
| "demo_admission_refusals": {NonApp: "deployment admission refusal counts by minute; names no app"}, |
| - "demo_alert_digests": {NonApp: "operator digest cursor by recipient and time; names no app"}, |
| + "demo_alert_digests": {NonApp: "operator digest receipt by recipient and opaque report IDs; grants no app authority"}, |
| "demo_report_attempts": {NonApp: "deployment report attempt budget keyed by salted IP hash and time; names no app"}, |
| "demo_serving": {NonApp: "deployment-wide serving switch and revision; names no app; demo handlers refuse claims mode"}, |
| "demo_caps": {App: "demo_id", Refuse: "anonymous demo caps require claims mode off"}, |