Add opt-in SQLite demo abuse alerts with operator email delivery
14 files changed,
+1,140
−39
cmd/console/main.go+5 −0docs/superpowers/notes/demo-abuse-alerts.md+21 −13internal/console/alertengine_pass.go+4 −3internal/console/alertstore.go+2 −2internal/console/apidemo.go+19 −0internal/console/consolemail.go+38 −7internal/console/demo_alert_admission.go+103 −0internal/console/demo_alert_admission_test.go+214 −0internal/console/demo_alert_copy.go+21 −0internal/console/demo_alerts.go+259 −0internal/console/demo_alerts_test.go+423 −0internal/console/demo_store.go+14 −1internal/console/server.go+2 −0internal/console/store_gate.go+15 −13
diff --git a/cmd/console/main.go b/cmd/console/main.go| index 6f7092c0c..111f1f64f 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -479,7 +479,12 @@ func serve() { |
| if err != nil { |
| log.Fatalf("%v: %v", console.DemoConfigError(), err) |
| } |
| + demoAlerts, err := console.LoadDemoAlertConfig(os.Getenv) |
| + if err != nil { |
| + log.Fatal(err) |
| + } |
| cfg := console.Config{ |
| + DemoAlerts: demoAlerts, |
| DemoAPIOrigin: os.Getenv("CONSOLE_DEMO_API_ORIGIN"), |
| Demo: demoConfig, |
| Origin: origin, |
diff --git a/docs/superpowers/notes/demo-abuse-alerts.md b/docs/superpowers/notes/demo-abuse-alerts.md| index ceadac888..d8cc27352 100644 |
| --- a/docs/superpowers/notes/demo-abuse-alerts.md |
| +++ b/docs/superpowers/notes/demo-abuse-alerts.md |
| @@ -6,30 +6,31 @@ adds an opt-in console worker; activation and copy review remain with Paul. |
| ## Findings and choice |
| Admission budgets already use SQLite and salted HMAC-SHA256 |
| -(`internal/console/demo_store.go:139`, `:162`). They count charged attempts, |
| +(`internal/console/demo_store.go:135`, `:171`). They count charged attempts, |
| including invalid uploads, rather than successful deployments. IPv6 budgets |
| already group by /64 (`internal/demo/config.go:151`). There is a rolling daily |
| budget; there is no separate hourly create budget in this implementation. |
| -Reports and report attempts are local (`internal/console/demo_reports.go:33`). |
| +Reports and report attempts are local (`internal/console/demo_reports.go:34`). |
| The Plan 2 report-key cache exception is unchanged. |
| The fleet engine has operator scope, not just tenant scope |
| (`internal/console/alertsignals.go:444`). Its incident step, reminders and |
| -outbox are useful (`alertengine.go:98`, `alertstore.go:366`, `alertnotify.go:41`, |
| +outbox are useful (`alertengine.go:95`, `alertstore.go:366`, `alertnotify.go:41`, |
| all under `internal/console`). But its pass requires a release store and reads |
| -box objects before evaluating signals (`alertengine_pass.go:124`, `:157`). Its |
| -first notification waits five minutes (`alertengine.go:79`), and its default |
| -recipients are every confirmed fleet connector (`alertengine_pass.go:369`). |
| +box objects before evaluating signals (`alertengine_pass.go:126`, `:158`). Its |
| +first notification waits five minutes (`alertengine.go:77`), and its default |
| +recipients are every confirmed fleet connector (`alertengine_pass.go:367`). |
| Demo managers instead include configured system operators and ops owners |
| (`internal/console/apisystemupdate.go:144`). Reworking that engine's scheduling, |
| 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:1248`, and |
| +`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:209`), with a cached-verified-only |
| +existing console sender (`consolemail.go:190`), with a cached-verified-only |
| entry point: an alert must never call the identity ensure/verify path, which |
| -can read S3 (`consolemail.go:128`, `:147`). No new S3 read, list or polling. |
| +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. |
| A missing verified sender or grant leaves delivery retryable and visible in |
| the worker error. Each pass rechecks the recipient list. |
| @@ -46,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 after this recipient's last successful digest cutoff | once per UTC day, if any arrived | |
| +| Report digest | count reports from this recipient's last successful digest cutoff | 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 |
| @@ -59,8 +60,10 @@ Existing app abuse metadata and its retention are unchanged. |
| 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. No reminders are added. Digests retain a cutoff |
| -per recipient, so failed sends and midnight do not lose reports. The first |
| +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. |
| @@ -88,7 +91,8 @@ Counts are bounded positive integers except REPORTS_PER_HOUR, which permits |
| zero. Windows must be whole minutes from 1m through 24h. Invalid settings fail |
| startup. To enable, set ENABLED=true, configure CARLOS_SYSTEM_OPERATORS (ops |
| owners also receive notices), and use an already verified console mail sender |
| -or the operator's existing Keymail grant. Settings do not change demo limits. |
| +or the operator's existing Keymail grant. A newly verified identity needs an |
| +ordinary mail readiness check or a console restart before alerts can use it. Settings do not change demo limits. |
| The worker runs once a minute while enabled, including when serving is off. |
| Immediate reports therefore arrive on the next pass rather than waiting for |
| @@ -97,6 +101,10 @@ 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. |
| + |
| ## Open questions before activation |
| - Paul edits the draft strings in `internal/console/demo_alert_copy.go`. |
diff --git a/internal/console/alertengine_pass.go b/internal/console/alertengine_pass.go| index f45cc8071..b15f80e15 100644 |
| --- a/internal/console/alertengine_pass.go |
| +++ b/internal/console/alertengine_pass.go |
| @@ -122,8 +122,9 @@ func (s *Server) alertEnginePass(ctx context.Context) error { |
| if s.cfg.HostClaim { |
| return errAlertEngineRefused // StartAlertEngine never gets here |
| } |
| + demoErr := s.demoAlertPass(ctx) |
| if s.cfg.Releases == nil { |
| - return nil |
| + return demoErr |
| } |
| now := s.alertClockNow() |
| open, sig, stepErr := s.alertEngineStep(ctx, now) |
| @@ -142,11 +143,11 @@ func (s *Server) alertEnginePass(ctx context.Context) error { |
| log.Printf("console: alert engine: drain: %v", drainErr) |
| jobFailed(ctx, fmt.Errorf("drain: %w", drainErr)) |
| } |
| - return stepErr |
| + return errors.Join(stepErr, demoErr) |
| } |
| s.noteUnreachableOperators(ctx, now) |
| s.writeAlertEngineBeat(ctx, now) |
| - return drainErr |
| + return errors.Join(drainErr, demoErr) |
| } |
| // alertEngineStep reads the signals and commits one step: the incident |
diff --git a/internal/console/alertstore.go b/internal/console/alertstore.go| index c7c5a78f8..9bd0966b9 100644 |
| --- a/internal/console/alertstore.go |
| +++ b/internal/console/alertstore.go |
| @@ -486,7 +486,7 @@ func insertAlertIncidentTx(tx *sql.Tx, in alertIncident) (int64, error) { |
| // alertSeenFiring is the watcher's delivery history the cutover imports: |
| // for each (box, rule), the addresses alert_seen says were last told it is |
| // firing. Only box alert rows: the claim-SQL receipt rows, geoip's per |
| -// reason rows and the no-mailbox stand-in are not box alerts anyone was told. |
| +// reason rows, demo notices and the no-mailbox stand-in are not box alerts. |
| func alertSeenFiring(tx *sql.Tx) (map[[2]string][]string, error) { |
| rows, err := tx.Query(`SELECT box, rule, address FROM alert_seen WHERE firing != 0 ORDER BY box, rule, address`) |
| if err != nil { |
| @@ -499,7 +499,7 @@ func alertSeenFiring(tx *sql.Tx) (map[[2]string][]string, error) { |
| if err := rows.Scan(&box, &rule, &addr); err != nil { |
| return nil, err |
| } |
| - if box == sqlReceiptAlertBox || addr == noMailboxAddress || strings.Contains(rule, "@") { |
| + if box == sqlReceiptAlertBox || box == demoAlertSeenBox || addr == noMailboxAddress || strings.Contains(rule, "@") { |
| continue |
| } |
| k := [2]string{box, rule} |
diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go| index 91cabd920..124d92371 100644 |
| --- a/internal/console/apidemo.go |
| +++ b/internal/console/apidemo.go |
| @@ -360,6 +360,9 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| } |
| setting, settingErr := s.demoServingSetting(r.Context()) |
| if settingErr != nil || !setting.Enabled || !s.cfg.Demo.EdgeProtections || s.cfg.HostClaim { |
| + if _, isUpdate := r.Header["Authorization"]; !isUpdate { |
| + s.recordDemoAdmissionRefusal(r.Context()) |
| + } |
| jsonError(w, 503, demoCopy["DEMO-CONFIG"]) |
| return |
| } |
| @@ -406,24 +409,31 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| }) |
| } else { |
| if err := s.store.CheckDemoLiveCeiling(r.Context(), s.cfg.Demo); err != nil { |
| + s.recordDemoAdmissionRefusal(r.Context()) |
| demoError(w, err) |
| return |
| } |
| if err := s.store.CheckDemoCreateBudget(r.Context(), clientIP(), time.Now(), s.cfg.Demo); err != nil { |
| + s.recordDemoAdmissionRefusal(r.Context()) |
| demoError(w, err) |
| return |
| } |
| if err := s.demoAdmissionReady(r.Context()); err != nil { |
| + s.recordDemoAdmissionRefusal(r.Context()) |
| jsonError(w, 503, demoCopy["DEMO-CONFIG"]) |
| return |
| } |
| if err := s.demoPublishReady(r.Context(), ""); err != nil { |
| + s.recordDemoAdmissionRefusal(r.Context()) |
| demoError(w, err) |
| return |
| } |
| err = s.store.SpendDemoCreate(r.Context(), clientIP(), time.Now(), s.cfg.Demo) |
| } |
| if err != nil { |
| + if update == nil { |
| + s.recordDemoAdmissionRefusal(r.Context()) |
| + } |
| demoError(w, err) |
| return |
| } |
| @@ -463,10 +473,16 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| // Check writer authority and a connected, root-ready worker before reserving |
| // the anonymous name. No weaker fallback is available. |
| if len(s.demoEligiblePeers()) == 0 { |
| + if update == nil { |
| + s.recordDemoAdmissionRefusal(r.Context()) |
| + } |
| demoError(w, errDemoJob) |
| return |
| } |
| if _, ref := s.policyWriter(r.Context()); ref != nil { |
| + if update == nil { |
| + s.recordDemoAdmissionRefusal(r.Context()) |
| + } |
| demoError(w, errDemoJob) |
| return |
| } |
| @@ -485,6 +501,9 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| row = *update |
| } |
| if err != nil { |
| + if update == nil && (errors.Is(err, ErrDemoLiveLimit) || errors.Is(err, ErrDemoCreateLimit)) { |
| + s.recordDemoAdmissionRefusal(r.Context()) |
| + } |
| demoError(w, err) |
| return |
| } |
diff --git a/internal/console/consolemail.go b/internal/console/consolemail.go| index 6e6152589..2c78b87f8 100644 |
| --- a/internal/console/consolemail.go |
| +++ b/internal/console/consolemail.go |
| @@ -63,11 +63,12 @@ type sesConsoleMailer struct { |
| // lock is a one-slot mutex a waiter can give up on: an ensure stalled |
| // inside an AWS call must not hold a Send past its own deadline. |
| // Everything below it is guarded by it. |
| - lock chan struct{} |
| - ensured bool |
| - verified bool |
| - configSet string |
| - checkedAt time.Time |
| + lock chan struct{} |
| + ensured bool |
| + verified bool |
| + configSet string |
| + ensuredConfigSet string |
| + checkedAt time.Time |
| } |
| func newSESConsoleMailer(from string, s release.Store, p mail.Provisioner, w dnsrec.Writer, d mail.Deployment, ses mail.EmailSender) *sesConsoleMailer { |
| @@ -118,7 +119,7 @@ func (m *sesConsoleMailer) ensureLocked(ctx context.Context) error { |
| if m.ensured { |
| return nil |
| } |
| - _, pending, err := mail.EnsureDomain(ctx, m.store, m.prov, m.dns, m.dep, |
| + rec, pending, err := mail.EnsureDomain(ctx, m.store, m.prov, m.dns, m.dep, |
| release.OpsAccount, consoleMailApp, m.domain, m.now()) |
| if err != nil { |
| return fmt.Errorf("console mail: ensure %s: %w", m.domain, err) |
| @@ -126,6 +127,11 @@ func (m *sesConsoleMailer) ensureLocked(ctx context.Context) error { |
| for _, r := range pending { |
| log.Printf("console mail: publish %s %s %s so %s can verify", r.Type, r.Name, strings.Join(r.Values, " "), m.domain) |
| } |
| + // Reuse the record returned by the existing startup ensure. Demo alerts |
| + // can send after a restart without making another control-store read. |
| + if st := rec.Regions[m.dep.Region]; st != nil && st.Status == mail.StatusVerified { |
| + m.ensuredConfigSet = st.ConfigSet |
| + } |
| m.ensured = true |
| return nil |
| } |
| @@ -156,6 +162,7 @@ func (m *sesConsoleMailer) ready(ctx context.Context) (string, error) { |
| // recheck (after consoleMailPendingRecheck) re-runs EnsureDomain |
| // instead. |
| m.ensured = false |
| + m.ensuredConfigSet = "" |
| return "", fmt.Errorf("%w: %v", ErrConsoleMailNotReady, err) |
| } |
| st := rec.Regions[m.dep.Region] |
| @@ -185,7 +192,31 @@ func (m *sesConsoleMailer) Send(ctx context.Context, to, subject, body string) e |
| if err != nil { |
| return err |
| } |
| - _, err = m.ses.SendEmail(ctx, mail.SimpleEmailInput(m.from, to, subject, body, |
| + return m.sendVerified(ctx, configSet, to, subject, body) |
| +} |
| + |
| +// SendReady never provisions or verifies an identity. Callers that must avoid |
| +// control-store reads use the existing startup ensure or ordinary mail cache. |
| +func (m *sesConsoleMailer) SendReady(ctx context.Context, to, subject, body string) error { |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + if err := m.acquire(ctx); err != nil { |
| + return err |
| + } |
| + verified, configSet := m.verified, m.configSet |
| + if !verified && m.ensuredConfigSet != "" { |
| + verified, configSet = true, m.ensuredConfigSet |
| + } |
| + m.unlock() |
| + if !verified { |
| + return ErrConsoleMailNotReady |
| + } |
| + return m.sendVerified(ctx, configSet, to, subject, body) |
| +} |
| + |
| +func (m *sesConsoleMailer) sendVerified(ctx context.Context, configSet, to, subject, body string) error { |
| + _, err := m.ses.SendEmail(ctx, mail.SimpleEmailInput(m.from, to, subject, body, |
| mail.TenantName(release.OpsAccount), configSet)) |
| if err != nil { |
| return fmt.Errorf("console mail: send to %s: %w", to, err) |
diff --git a/internal/console/demo_alert_admission.go b/internal/console/demo_alert_admission.go| new file mode 100644 |
| index 000000000..7d5dc8576 |
| --- /dev/null |
| +++ b/internal/console/demo_alert_admission.go |
| @@ -0,0 +1,103 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "database/sql" |
| + "log" |
| + "net/netip" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| +) |
| + |
| +const demoAlertAdmissionWindow = 24 * time.Hour |
| + |
| +// migrateDemoAlertAdmissions adds the alert-pass inputs to the admission |
| +// tables. prefix_hash is a salted /24 (IPv4) or /48 (IPv6) hash, never an |
| +// address; rows from before this migration keep NULL. Refusals are minute |
| +// aggregates with no IP at all. |
| +func (s *Store) migrateDemoAlertAdmissions() error { |
| + var n int |
| + if err := s.db.QueryRow(`SELECT count(*) FROM pragma_table_info('demo_admissions') WHERE name='prefix_hash'`).Scan(&n); err != nil { |
| + return err |
| + } |
| + if n == 0 { |
| + if _, err := s.db.Exec(`ALTER TABLE demo_admissions ADD COLUMN prefix_hash BLOB CHECK(prefix_hash IS NULL OR length(prefix_hash)=32)`); err != nil { |
| + return err |
| + } |
| + } |
| + _, err := s.db.Exec(`CREATE INDEX IF NOT EXISTS demo_admissions_prefix_time ON demo_admissions(prefix_hash, attempted_at); |
| +CREATE TABLE IF NOT EXISTS demo_admission_refusals(minute INTEGER PRIMARY KEY, refusals INTEGER NOT NULL CHECK(refusals>0)) WITHOUT ROWID;`) |
| + return err |
| +} |
| + |
| +// demoAdmissionPrefixHash keys the same salt and HMAC as demoCreateBudget on |
| +// the masked /24 or /48, so one actor cycling through /64 budgets still lands |
| +// on one prefix. |
| +func demoAdmissionPrefixHash(ctx context.Context, q demoQuery, ip string) ([]byte, error) { |
| + canon, err := demo.CanonicalIP(ip) |
| + if err != nil { |
| + return nil, err |
| + } |
| + addr, err := netip.ParseAddr(canon) |
| + if err != nil { |
| + return nil, err |
| + } |
| + bits := 48 |
| + if addr.Is4() { |
| + bits = 24 |
| + } |
| + prefix, err := addr.Prefix(bits) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var salt []byte |
| + if err := q.QueryRowContext(ctx, `SELECT ip_salt FROM demo_settings WHERE id=1`).Scan(&salt); err != nil { |
| + return nil, err |
| + } |
| + if len(salt) != 32 { |
| + return nil, demo.ErrConfig |
| + } |
| + mac := hmac.New(sha256.New, salt) |
| + mac.Write([]byte(prefix.String())) |
| + return mac.Sum(nil), nil |
| +} |
| + |
| +// RecordDemoAdmissionRefusal counts one refused anonymous create in its UTC |
| +// minute. No address is stored; at most 1440 buckets survive. |
| +func (s *Store) RecordDemoAdmissionRefusal(ctx context.Context, now time.Time) error { |
| + tx, err := s.demoTx(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + if _, err = tx.ExecContext(ctx, `DELETE FROM demo_admission_refusals WHERE minute<=?`, now.Add(-demoAlertAdmissionWindow).Truncate(time.Minute).Unix()); err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `INSERT INTO demo_admission_refusals(minute,refusals) VALUES(?,1) ON CONFLICT(minute) DO UPDATE SET refusals=refusals+1`, now.Truncate(time.Minute).Unix()); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| + |
| +// pruneDemoAlertAdmissions drops admissions and refusal buckets older than 24 |
| +// hours. The prefix hash lives and dies with its admission row. |
| +func pruneDemoAlertAdmissions(ctx context.Context, tx *sql.Tx, now time.Time) error { |
| + if _, err := tx.ExecContext(ctx, `DELETE FROM demo_admissions WHERE attempted_at<=?`, now.Add(-demoAlertAdmissionWindow).UnixNano()); err != nil { |
| + return err |
| + } |
| + _, err := tx.ExecContext(ctx, `DELETE FROM demo_admission_refusals WHERE minute<=?`, now.Add(-demoAlertAdmissionWindow).Truncate(time.Minute).Unix()) |
| + return err |
| +} |
| + |
| +// recordDemoAdmissionRefusal is called once, at the return that refuses an |
| +// anonymous create. A recording failure is logged and never changes the reply. |
| +func (s *Server) recordDemoAdmissionRefusal(ctx context.Context) { |
| + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) |
| + defer cancel() |
| + if err := s.store.RecordDemoAdmissionRefusal(ctx, s.alertClockNow()); err != nil { |
| + log.Printf(demoAlertRefusalLog, err) |
| + } |
| +} |
diff --git a/internal/console/demo_alert_admission_test.go b/internal/console/demo_alert_admission_test.go| new file mode 100644 |
| index 000000000..ea9160ef3 |
| --- /dev/null |
| +++ b/internal/console/demo_alert_admission_test.go |
| @@ -0,0 +1,214 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "net/netip" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| +) |
| + |
| +func demoAlertTestCfg(t *testing.T) demo.Config { |
| + t.Helper() |
| + return demoTestDeploymentConfig(t).Demo |
| +} |
| + |
| +func demoAlertPrefixOf(t *testing.T, st *Store, ip string) []byte { |
| + t.Helper() |
| + h, err := demoAdmissionPrefixHash(context.Background(), st.db, ip) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return h |
| +} |
| + |
| +func TestDemoAlertAdmissionMigrationIdempotentAndOldSchema(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "old.db") |
| + st, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer st.Close() |
| + // Rebuild the pre-migration shape: no column, NULL rows, no refusals table. |
| + for _, q := range []string{ |
| + `DROP INDEX demo_admissions_prefix_time`, |
| + `ALTER TABLE demo_admissions DROP COLUMN prefix_hash`, |
| + `DROP TABLE demo_admission_refusals`, |
| + `INSERT INTO demo_admissions(ip_hash,attempted_at) VALUES(x'00',1)`, |
| + } { |
| + if _, err := st.db.Exec(q); err != nil { |
| + t.Fatalf("%s: %v", q, err) |
| + } |
| + } |
| + for i := 0; i < 2; i++ { |
| + if err := st.migrateDemoAlertAdmissions(); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var nulls, cols int |
| + if err := st.db.QueryRow(`SELECT count(*) FROM demo_admissions WHERE prefix_hash IS NULL`).Scan(&nulls); err != nil || nulls != 1 { |
| + t.Fatalf("old rows nulls=%d err=%v", nulls, err) |
| + } |
| + if err := st.db.QueryRow(`SELECT count(*) FROM pragma_table_info('demo_admission_refusals')`).Scan(&cols); err != nil || cols != 2 { |
| + t.Fatalf("refusal columns=%d err=%v", cols, err) |
| + } |
| + if err := st.migrateDemo(); err != nil { |
| + t.Fatalf("full migrate rerun: %v", err) |
| + } |
| +} |
| + |
| +func TestDemoAlertAdmissionPrefixes(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + same := [][2]string{ |
| + {"192.0.2.1", "192.0.2.250"}, |
| + {"192.0.2.9", "::ffff:192.0.2.77"}, |
| + {"2001:db8:1:1::1", "2001:db8:1:ffff::9"}, // different /64s, one /48 |
| + } |
| + for _, p := range same { |
| + if string(demoAlertPrefixOf(t, st, p[0])) != string(demoAlertPrefixOf(t, st, p[1])) { |
| + t.Fatalf("%v should share a prefix", p) |
| + } |
| + } |
| + diff := [][2]string{ |
| + {"192.0.2.1", "192.0.3.1"}, |
| + {"2001:db8:1::1", "2001:db8:2::1"}, |
| + {"192.0.2.1", "2001:db8:1::1"}, |
| + } |
| + for _, p := range diff { |
| + if string(demoAlertPrefixOf(t, st, p[0])) == string(demoAlertPrefixOf(t, st, p[1])) { |
| + t.Fatalf("%v should differ", p) |
| + } |
| + } |
| + for _, bad := range []string{"", "nope", "fe80::1%eth0", "192.0.2.1/24"} { |
| + if _, err := demoAdmissionPrefixHash(context.Background(), st.db, bad); err == nil { |
| + t.Fatalf("%q accepted", bad) |
| + } |
| + } |
| + if _, err := st.db.Exec(`PRAGMA ignore_check_constraints=1`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := st.db.Exec(`UPDATE demo_settings SET ip_salt=x'0102'`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := demoAdmissionPrefixHash(context.Background(), st.db, "192.0.2.1"); err == nil { |
| + t.Fatal("short salt accepted") |
| + } |
| +} |
| + |
| +func TestDemoAlertAdmissionSaltEquivalenceAndNoRawData(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + now := time.Unix(1_800_000_000, 0) |
| + const ip = "2001:db8:abcd:1234::7" |
| + if err := st.SpendDemoCreate(context.Background(), ip, now, demoAlertTestCfg(t)); err != nil { |
| + t.Fatal(err) |
| + } |
| + var salt, ipHash, prefix []byte |
| + if err := st.db.QueryRow(`SELECT ip_salt FROM demo_settings`).Scan(&salt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := st.db.QueryRow(`SELECT ip_hash,prefix_hash FROM demo_admissions`).Scan(&ipHash, &prefix); err != nil { |
| + t.Fatal(err) |
| + } |
| + mac := hmac.New(sha256.New, salt) |
| + mac.Write([]byte(netip.MustParsePrefix("2001:db8:abcd::/48").String())) |
| + if string(mac.Sum(nil)) != string(prefix) || len(prefix) != 32 || string(prefix) == string(ipHash) { |
| + t.Fatal("prefix hash is not the salted HMAC of the masked /48") |
| + } |
| + if err := st.RecordDemoAdmissionRefusal(context.Background(), now); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, q := range []string{ |
| + `SELECT count(*) FROM demo_admissions WHERE instr(CAST(prefix_hash AS TEXT),'2001')>0 OR instr(CAST(ip_hash AS TEXT),'2001')>0`, |
| + } { |
| + var n int |
| + if err := st.db.QueryRow(q).Scan(&n); err != nil || n != 0 { |
| + t.Fatalf("raw ip leaked n=%d err=%v", n, err) |
| + } |
| + } |
| + var cols int |
| + if err := st.db.QueryRow(`SELECT count(*) FROM pragma_table_info('demo_admission_refusals') WHERE name NOT IN('minute','refusals')`).Scan(&cols); err != nil || cols != 0 { |
| + t.Fatalf("refusals table has extra columns: %d", cols) |
| + } |
| +} |
| + |
| +func TestDemoAlertAdmissionRefusalsBoundedAndPruned(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + ctx := context.Background() |
| + base := time.Unix(1_800_000_000, 0).Truncate(time.Minute) |
| + for i := 0; i < 3; i++ { |
| + if err := st.RecordDemoAdmissionRefusal(ctx, base.Add(time.Duration(i)*time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := st.RecordDemoAdmissionRefusal(ctx, base.Add(time.Minute)); err != nil { |
| + t.Fatal(err) |
| + } |
| + var n, total int |
| + st.db.QueryRow(`SELECT count(*), sum(refusals) FROM demo_admission_refusals`).Scan(&n, &total) |
| + if n != 2 || total != 4 { |
| + t.Fatalf("buckets=%d total=%d", n, total) |
| + } |
| + // Writing 25h of minutes keeps at most 1440 buckets. |
| + for i := 0; i <= 25*60; i++ { |
| + if err := st.RecordDemoAdmissionRefusal(ctx, base.Add(time.Duration(i)*time.Minute)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + st.db.QueryRow(`SELECT count(*) FROM demo_admission_refusals`).Scan(&n) |
| + if n > 1440 { |
| + t.Fatalf("buckets=%d", n) |
| + } |
| + |
| + // Pruning runs from WipeDemoAbuse with no admissions in flight. |
| + if err := st.SpendDemoCreate(ctx, "192.0.2.1", base, demoAlertTestCfg(t)); err != nil { |
| + t.Fatal(err) |
| + } |
| + later := base.Add(50 * time.Hour) |
| + if err := st.WipeDemoAbuse(ctx, later); err != nil { |
| + t.Fatal(err) |
| + } |
| + var adm, ref int |
| + st.db.QueryRow(`SELECT count(*) FROM demo_admissions`).Scan(&adm) |
| + st.db.QueryRow(`SELECT count(*) FROM demo_admission_refusals`).Scan(&ref) |
| + if adm != 0 || ref != 0 { |
| + t.Fatalf("after wipe admissions=%d refusals=%d", adm, ref) |
| + } |
| +} |
| + |
| +func TestDemoAlertAdmissionHandlerCountsOncePerCreateRefusal(t *testing.T) { |
| + s := demoTestServer(t) |
| + now := time.Unix(1_800_000_000, 0) |
| + s.alertClock = func() time.Time { return now } |
| + refusals := func() (n int) { |
| + s.store.db.QueryRow(`SELECT coalesce(sum(refusals),0) FROM demo_admission_refusals`).Scan(&n) |
| + return n |
| + } |
| + // Invalid source is not an admission refusal. |
| + if w := demoRequest(s, "", "198.51.100.1"); w.Code != 400 || refusals() != 0 { |
| + t.Fatalf("invalid source: %d refusals=%d", w.Code, refusals()) |
| + } |
| + // Updates and bad tokens never count. |
| + if w := demoRequest(s, "Bearer nope", "198.51.100.1"); w.Code != 401 || refusals() != 0 { |
| + t.Fatalf("bad token: %d refusals=%d", w.Code, refusals()) |
| + } |
| + for i := 0; i < s.cfg.Demo.CreatePerIPDay-1; i++ { |
| + demoRequest(s, "", "198.51.100.1") |
| + } |
| + if w := demoRequest(s, "", "198.51.100.1"); w.Code != 429 || refusals() != 1 { |
| + t.Fatalf("per-ip limit: %d refusals=%d", w.Code, refusals()) |
| + } |
| + if w := demoRequest(s, "", "198.51.100.1"); w.Code != 429 || refusals() != 2 { |
| + t.Fatalf("second refusal: %d refusals=%d", w.Code, refusals()) |
| + } |
| + // A recording failure must not change the refusal. |
| + if _, err := s.store.db.Exec(`DROP TABLE demo_admission_refusals`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if w := demoRequest(s, "", "198.51.100.1"); w.Code != 429 { |
| + t.Fatalf("recording failure changed reply: %d", w.Code) |
| + } |
| +} |
diff --git a/internal/console/demo_alert_copy.go b/internal/console/demo_alert_copy.go| new file mode 100644 |
| index 000000000..295f3aa27 |
| --- /dev/null |
| +++ b/internal/console/demo_alert_copy.go |
| @@ -0,0 +1,21 @@ |
| +package console |
| + |
| +// Draft operator copy. Paul reviews these strings before this branch lands. |
| +const ( |
| + demoAlertConfigError = "console: invalid demo alert setting %s" |
| + demoAlertNoRecipients = "console: demo alerts have no system operator or ops owner recipient" |
| + demoAlertDeliveryError = "console: demo alert delivery failed for %s: %w" |
| + demoAlertRefusalLog = "console: could not record a demo admission refusal: %v" |
| + demoAlertSubject = "[carlos] Demo activity needs attention" |
| + demoAlertDigestSubject = "[carlos] Daily demo abuse reports" |
| + demoAlertBody = "%s\n\nConsole: %s\nCheck demos with carlos system demos status and reports with carlos system demos reports.\nThese counts are signals to investigate, not proof of abuse.\n" |
| + demoAlertDigestBody = "%d abuse reports arrived since %s (UTC), before %s (UTC).\n\nConsole: %s\nReview them with carlos system demos reports. Resolved reports are included in this count.\n" |
| +) |
| + |
| +var demoAlertText = map[string]string{ |
| + "budget": "%d demo create attempts used at least %d%% of the rolling daily budget of %d.", |
| + "ips": "%d demo create attempts came from the busiest %d IP budgets within %s. An IPv6 budget covers a /64.", |
| + "prefix": "%d demo create attempts came from one IPv4 /24 or IPv6 /48 within %s.", |
| + "refusals": "%d demo admissions were refused across the latest %s of minute buckets, including the current partial minute.", |
| + "reports": "%d abuse reports arrived in the last hour, more than the threshold of %d.", |
| +} |
diff --git a/internal/console/demo_alerts.go b/internal/console/demo_alerts.go| new file mode 100644 |
| index 000000000..4f4b3c4e5 |
| --- /dev/null |
| +++ b/internal/console/demo_alerts.go |
| @@ -0,0 +1,259 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +const demoAlertSeenBox = "demo-abuse" |
| + |
| +// DemoAlertConfig is independent of demo serving and admission limits. |
| +type DemoAlertConfig struct { |
| + Enabled, Digest bool |
| + BudgetPercent, IPCount, FewIPs, PrefixCount int |
| + CreateWindow time.Duration |
| + RefusalCount int |
| + RefusalWindow time.Duration |
| + ReportsPerHour int |
| +} |
| + |
| +func LoadDemoAlertConfig(getenv func(string) string) (DemoAlertConfig, error) { |
| + c := DemoAlertConfig{Digest: true, BudgetPercent: 80, IPCount: 20, FewIPs: 3, |
| + PrefixCount: 30, CreateWindow: time.Hour, RefusalCount: 30, RefusalWindow: 10 * time.Minute, ReportsPerHour: 5} |
| + for key, dst := range map[string]*bool{"ENABLED": &c.Enabled, "DIGEST": &c.Digest} { |
| + key = "CONSOLE_DEMO_ALERT_" + key |
| + if raw := strings.TrimSpace(getenv(key)); raw != "" { |
| + v, err := strconv.ParseBool(raw) |
| + if err != nil { |
| + return c, fmt.Errorf(demoAlertConfigError, key) |
| + } |
| + *dst = v |
| + } |
| + } |
| + for key, dst := range map[string]*int{"BUDGET_PERCENT": &c.BudgetPercent, "IP_COUNT": &c.IPCount, |
| + "FEW_IPS": &c.FewIPs, "PREFIX_COUNT": &c.PrefixCount, "REFUSAL_COUNT": &c.RefusalCount, "REPORTS_PER_HOUR": &c.ReportsPerHour} { |
| + key = "CONSOLE_DEMO_ALERT_" + key |
| + if raw := strings.TrimSpace(getenv(key)); raw != "" { |
| + v, err := strconv.Atoi(raw) |
| + if err != nil { |
| + return c, fmt.Errorf(demoAlertConfigError, key) |
| + } |
| + *dst = v |
| + } |
| + } |
| + for key, dst := range map[string]*time.Duration{"CREATE_WINDOW": &c.CreateWindow, "REFUSAL_WINDOW": &c.RefusalWindow} { |
| + key = "CONSOLE_DEMO_ALERT_" + key |
| + if raw := strings.TrimSpace(getenv(key)); raw != "" { |
| + v, err := time.ParseDuration(raw) |
| + if err != nil { |
| + return c, fmt.Errorf(demoAlertConfigError, key) |
| + } |
| + *dst = v |
| + } |
| + } |
| + return c, c.validate() |
| +} |
| + |
| +func (c DemoAlertConfig) validate() error { |
| + for _, p := range []struct { |
| + name string |
| + value, min, max int |
| + }{ |
| + {"BUDGET_PERCENT", c.BudgetPercent, 1, 100}, {"IP_COUNT", c.IPCount, 1, 1000000}, |
| + {"FEW_IPS", c.FewIPs, 1, 100}, {"PREFIX_COUNT", c.PrefixCount, 1, 1000000}, |
| + {"REFUSAL_COUNT", c.RefusalCount, 1, 1000000}, {"REPORTS_PER_HOUR", c.ReportsPerHour, 0, 1000000}, |
| + } { |
| + if p.value < p.min || p.value > p.max { |
| + return fmt.Errorf(demoAlertConfigError, "CONSOLE_DEMO_ALERT_"+p.name) |
| + } |
| + } |
| + for key, v := range map[string]time.Duration{"CREATE_WINDOW": c.CreateWindow, "REFUSAL_WINDOW": c.RefusalWindow} { |
| + if v < time.Minute || v > 24*time.Hour || v%time.Minute != 0 { |
| + return fmt.Errorf(demoAlertConfigError, "CONSOLE_DEMO_ALERT_"+key) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +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 |
| +) WITHOUT ROWID`) |
| + return err |
| +} |
| + |
| +type demoAlertSignal struct { |
| + rule string |
| + count int64 |
| + firing bool |
| + text string |
| +} |
| + |
| +// A single transaction prunes expired inputs and reads a consistent snapshot. |
| +func (s *Store) demoAlertSignals(ctx context.Context, c DemoAlertConfig, dailyBudget int, now time.Time) ([]demoAlertSignal, error) { |
| + tx, err := s.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer tx.Rollback() |
| + if err := pruneDemoAlertAdmissions(ctx, tx, now); err != nil { |
| + return nil, err |
| + } |
| + var daily, ips, prefix, refusals, reports int64 |
| + queries := []struct { |
| + dst *int64 |
| + query string |
| + args []any |
| + }{ |
| + {&daily, `SELECT count(*) FROM demo_admissions WHERE attempted_at>? AND attempted_at<=?`, []any{now.Add(-24 * time.Hour).UnixNano(), now.UnixNano()}}, |
| + {&ips, `SELECT coalesce(sum(n),0) FROM (SELECT count(*) n FROM demo_admissions WHERE attempted_at>? AND attempted_at<=? GROUP BY ip_hash ORDER BY n DESC LIMIT ?)`, []any{now.Add(-c.CreateWindow).UnixNano(), now.UnixNano(), c.FewIPs}}, |
| + {&prefix, `SELECT coalesce(max(n),0) FROM (SELECT count(*) n FROM demo_admissions WHERE attempted_at>? AND attempted_at<=? AND prefix_hash IS NOT NULL GROUP BY prefix_hash)`, []any{now.Add(-c.CreateWindow).UnixNano(), now.UnixNano()}}, |
| + {&refusals, `SELECT coalesce(sum(refusals),0) FROM demo_admission_refusals WHERE minute>=? AND minute<=?`, []any{now.Truncate(time.Minute).Add(-c.RefusalWindow + time.Minute).Unix(), now.Truncate(time.Minute).Unix()}}, |
| + {&reports, `SELECT count(*) FROM demo_reports WHERE created_at>? AND created_at<=?`, []any{now.Add(-time.Hour).Unix(), now.Unix()}}, |
| + } |
| + for _, q := range queries { |
| + if err := tx.QueryRowContext(ctx, q.query, q.args...).Scan(q.dst); err != nil { |
| + return nil, err |
| + } |
| + } |
| + if err := tx.Commit(); err != nil { |
| + return nil, err |
| + } |
| + // Compute the integer ceiling without multiplying an unbounded configured |
| + // budget, which also keeps 32-bit CLI builds out of this arithmetic. |
| + budget := int64(dailyBudget) |
| + threshold := (budget/100)*int64(c.BudgetPercent) + (budget%100*int64(c.BudgetPercent)+99)/100 |
| + return []demoAlertSignal{ |
| + {"budget", daily, budget > 0 && daily >= threshold, fmt.Sprintf(demoAlertText["budget"], daily, c.BudgetPercent, dailyBudget)}, |
| + {"ips", ips, ips >= int64(c.IPCount), fmt.Sprintf(demoAlertText["ips"], ips, c.FewIPs, c.CreateWindow)}, |
| + {"prefix", prefix, prefix >= int64(c.PrefixCount), fmt.Sprintf(demoAlertText["prefix"], prefix, c.CreateWindow)}, |
| + {"refusals", refusals, refusals >= int64(c.RefusalCount), fmt.Sprintf(demoAlertText["refusals"], refusals, c.RefusalWindow)}, |
| + {"reports", reports, reports > int64(c.ReportsPerHour), fmt.Sprintf(demoAlertText["reports"], reports, c.ReportsPerHour)}, |
| + }, nil |
| +} |
| + |
| +// The recipient authority matches apiSystemRoller: configured system operators |
| +// plus ops owners. Fleet-operator status alone does not receive demo mail. |
| +func (s *Server) demoAlertRecipients() (*alertRun, error) { |
| + members, err := s.store.Members(OpsAccountID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + addrs := slices.Clone(s.cfg.SystemOperators) |
| + for _, member := range members { |
| + if member.Role == RoleOwner { |
| + addrs = append(addrs, member.Name) |
| + } |
| + } |
| + return s.grantRecipients(addrs) |
| +} |
| + |
| +// Runs before the fleet engine's bucket-dependent step, on its existing minute |
| +// cadence. The server mutex prevents overlapping passes; serve already holds |
| +// the deployment's exclusive console database lock. |
| +func (s *Server) demoAlertPass(ctx context.Context) error { |
| + c := s.cfg.DemoAlerts |
| + if !c.Enabled || s.cfg.HostClaim || s.store.claimGated() { |
| + return nil |
| + } |
| + if err := c.validate(); err != nil { |
| + return err |
| + } |
| + s.demoAlertMu.Lock() |
| + defer s.demoAlertMu.Unlock() |
| + now := s.alertClockNow().UTC() |
| + signals, err := s.store.demoAlertSignals(ctx, c, s.cfg.Demo.CreateGlobalDay, now) |
| + if err != nil { |
| + return err |
| + } |
| + run, err := s.demoAlertRecipients() |
| + if err != nil { |
| + return err |
| + } |
| + if len(run.to)+len(run.missing) == 0 { |
| + return errors.New(demoAlertNoRecipients) |
| + } |
| + var failures []error |
| + for _, addr := range run.missing { |
| + run.to = append(run.to, operatorGrant{address: addr}) |
| + } |
| + for _, recipient := range run.to { |
| + for _, signal := range signals { |
| + seen, _, err := s.store.AlertSeen(demoAlertSeenBox, signal.rule, recipient.address) |
| + if err != nil { |
| + failures = append(failures, err) |
| + continue |
| + } |
| + if !signal.firing { |
| + if seen { |
| + failures = append(failures, s.store.SetAlertSeen(demoAlertSeenBox, signal.rule, recipient.address, false)) |
| + } |
| + continue |
| + } |
| + if seen { |
| + continue |
| + } |
| + body := fmt.Sprintf(demoAlertBody, signal.text, s.cfg.Origin) |
| + if err := s.sendDemoAlert(ctx, recipient, demoAlertSubject, body); err != nil { |
| + failures = append(failures, fmt.Errorf(demoAlertDeliveryError, recipient.address, err)) |
| + continue |
| + } |
| + failures = append(failures, s.store.SetAlertSeen(demoAlertSeenBox, signal.rule, recipient.address, true)) |
| + } |
| + if c.Digest { |
| + failures = append(failures, s.demoReportDigest(ctx, recipient, now)) |
| + } |
| + } |
| + return errors.Join(failures...) |
| +} |
| + |
| +func (s *Server) sendDemoAlert(ctx context.Context, recipient operatorGrant, subject, body string) error { |
| + ctx, cancel := context.WithTimeout(ctx, alertEmailTimeout) |
| + defer cancel() |
| + if recipient.token != "" && s.sendApp != nil { |
| + _, err := s.sendApp(ctx, recipient.token, recipient.address, subject, body) |
| + return err |
| + } |
| + // Send would ensure/verify the identity on a cold cache, including S3 |
| + // reads. This optional interface uses only an already verified identity. |
| + if sender, ok := s.consoleMail.(interface { |
| + SendReady(context.Context, string, string, string) error |
| + }); ok { |
| + return sender.SendReady(ctx, recipient.address, subject, body) |
| + } |
| + return ErrConsoleMailNotReady |
| +} |
| + |
| +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) { |
| + return err |
| + } |
| + today := now.Truncate(24 * time.Hour).Unix() |
| + if day >= today { |
| + return nil |
| + } |
| + if through == 0 { |
| + through = now.Add(-24 * time.Hour).Unix() |
| + } |
| + 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 { |
| + return err |
| + } |
| + if count == 0 { |
| + return nil |
| + } |
| + 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) |
| + return err |
| +} |
diff --git a/internal/console/demo_alerts_test.go b/internal/console/demo_alerts_test.go| new file mode 100644 |
| index 000000000..f6155269c |
| --- /dev/null |
| +++ b/internal/console/demo_alerts_test.go |
| @@ -0,0 +1,423 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/dnsrec" |
| + "github.com/carlosframework/platform/internal/mail" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func demoAlertDefaults(t *testing.T) DemoAlertConfig { |
| + t.Helper() |
| + c, err := LoadDemoAlertConfig(func(string) string { return "" }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return c |
| +} |
| + |
| +func TestDemoAlertConfig(t *testing.T) { |
| + c := demoAlertDefaults(t) |
| + if c.Enabled || !c.Digest || c.BudgetPercent != 80 || c.IPCount != 20 || c.FewIPs != 3 || c.PrefixCount != 30 || c.CreateWindow != time.Hour || c.RefusalCount != 30 || c.RefusalWindow != 10*time.Minute || c.ReportsPerHour != 5 { |
| + t.Fatalf("defaults: %+v", c) |
| + } |
| + env := map[string]string{"ENABLED": "true", "DIGEST": "false", "BUDGET_PERCENT": "90", "IP_COUNT": "25", "FEW_IPS": "2", "PREFIX_COUNT": "40", "CREATE_WINDOW": "2h", "REFUSAL_COUNT": "50", "REFUSAL_WINDOW": "5m", "REPORTS_PER_HOUR": "0"} |
| + c, err := LoadDemoAlertConfig(func(k string) string { return env[strings.TrimPrefix(k, "CONSOLE_DEMO_ALERT_")] }) |
| + if err != nil || !c.Enabled || c.Digest || c.BudgetPercent != 90 || c.IPCount != 25 || c.FewIPs != 2 || c.PrefixCount != 40 || c.CreateWindow != 2*time.Hour || c.RefusalCount != 50 || c.RefusalWindow != 5*time.Minute || c.ReportsPerHour != 0 { |
| + t.Fatalf("settings: %+v %v", c, err) |
| + } |
| + for _, tt := range []struct{ k, v string }{{"ENABLED", "yes"}, {"DIGEST", "wat"}, {"BUDGET_PERCENT", "0"}, {"BUDGET_PERCENT", "101"}, {"IP_COUNT", "-1"}, {"FEW_IPS", "101"}, {"PREFIX_COUNT", "0"}, {"REFUSAL_COUNT", "1000001"}, {"REPORTS_PER_HOUR", "-1"}, {"CREATE_WINDOW", "1s"}, {"CREATE_WINDOW", "25h"}, {"REFUSAL_WINDOW", "90s"}, {"REFUSAL_WINDOW", "nope"}, {"IP_COUNT", "100000000000000000000000"}} { |
| + t.Run(tt.k+tt.v, func(t *testing.T) { |
| + _, err := LoadDemoAlertConfig(func(k string) string { |
| + if k == "CONSOLE_DEMO_ALERT_"+tt.k { |
| + return tt.v |
| + } |
| + return "" |
| + }) |
| + if err == nil { |
| + t.Fatal("accepted invalid setting") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +var demoAlertTime = time.Date(2026, 11, 8, 12, 0, 30, 0, time.UTC) |
| + |
| +func alertAttempt(t *testing.T, st *Store, at time.Time, ip, prefix byte) { |
| + t.Helper() |
| + a, b := make([]byte, 32), make([]byte, 32) |
| + a[0] = ip |
| + b[0] = prefix |
| + if _, err := st.db.Exec(`INSERT INTO demo_admissions(ip_hash,prefix_hash,attempted_at) VALUES(?,?,?)`, a, b, at.UnixNano()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func alertReport(t *testing.T, st *Store, at time.Time, id string) { |
| + t.Helper() |
| + if _, err := st.db.Exec(`INSERT INTO demo_reports(id,demo_id,host,category,details,created_at,ip_hash) VALUES(?, 'fixture', 'demo.example.test','other','private report detail',?,?)`, id, at.Unix(), make([]byte, 32)); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func signalNamed(t *testing.T, st *Store, c DemoAlertConfig, budget int, now time.Time, name string) demoAlertSignal { |
| + t.Helper() |
| + sigs, err := st.demoAlertSignals(t.Context(), c, budget, now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, s := range sigs { |
| + if s.rule == name { |
| + return s |
| + } |
| + } |
| + t.Fatal("signal missing") |
| + return demoAlertSignal{} |
| +} |
| + |
| +func TestDemoAlertSignalThresholds(t *testing.T) { |
| + for _, rule := range []string{"budget", "ips", "prefix", "refusals", "reports"} { |
| + t.Run(rule, func(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + c := demoAlertDefaults(t) |
| + c.IPCount = 3 |
| + c.FewIPs = 2 |
| + c.PrefixCount = 3 |
| + c.RefusalCount = 3 |
| + c.ReportsPerHour = 2 |
| + for i := 0; i < 4; i++ { |
| + if rule == "refusals" { |
| + if err := st.RecordDemoAdmissionRefusal(t.Context(), demoAlertTime); err != nil { |
| + t.Fatal(err) |
| + } |
| + } else if rule == "reports" { |
| + alertReport(t, st, demoAlertTime.Add(-time.Second), fmt.Sprint(i)) |
| + } else { |
| + alertAttempt(t, st, demoAlertTime.Add(-time.Second), byte(i%2), 1) |
| + } |
| + s := signalNamed(t, st, c, 3, demoAlertTime, rule) // ceil(3 * 80%) = 3 |
| + if s.firing != (i >= 2) { |
| + t.Fatalf("%s count=%d firing=%v", rule, i+1, s.firing) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoAlertSignalWindowsAndConcentration(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + c := demoAlertDefaults(t) |
| + c.IPCount = 4 |
| + c.FewIPs = 2 |
| + c.PrefixCount = 4 |
| + for i := 0; i < 4; i++ { |
| + alertAttempt(t, st, demoAlertTime.Add(-time.Second), byte(i), byte(i)) |
| + } |
| + if signalNamed(t, st, c, 100, demoAlertTime, "ips").firing || signalNamed(t, st, c, 100, demoAlertTime, "prefix").firing { |
| + t.Fatal("dispersed traffic fired") |
| + } |
| + // Busy sources must still be found among unrelated background traffic. |
| + alertAttempt(t, st, demoAlertTime.Add(-time.Second), 0, 0) |
| + alertAttempt(t, st, demoAlertTime.Add(-time.Second), 1, 0) |
| + if !signalNamed(t, st, c, 100, demoAlertTime, "ips").firing { |
| + t.Fatal("top K missed busy sources") |
| + } |
| + alertAttempt(t, st, demoAlertTime.Add(-time.Second), 2, 0) |
| + if !signalNamed(t, st, c, 100, demoAlertTime, "prefix").firing { |
| + t.Fatal("shared prefix missed") |
| + } |
| + for _, stamp := range []time.Time{demoAlertTime.Add(-time.Hour), demoAlertTime.Add(time.Second)} { |
| + for i := 0; i < 10; i++ { |
| + alertAttempt(t, st, stamp, 9, 9) |
| + alertReport(t, st, stamp, fmt.Sprintf("%d-%d", stamp.Unix(), i)) |
| + } |
| + } |
| + if s := signalNamed(t, st, c, 100, demoAlertTime, "ips"); s.count != 4 { |
| + t.Fatalf("boundary/future included: %+v", s) |
| + } |
| + if s := signalNamed(t, st, c, 100, demoAlertTime, "reports"); s.count != 0 { |
| + t.Fatalf("report boundary/future included: %+v", s) |
| + } |
| + c.RefusalWindow = 2 * time.Minute |
| + for _, at := range []time.Time{demoAlertTime.Add(-2 * time.Minute), demoAlertTime.Add(-time.Minute), demoAlertTime, demoAlertTime.Add(time.Minute)} { |
| + if err := st.RecordDemoAdmissionRefusal(t.Context(), at); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if s := signalNamed(t, st, c, 100, demoAlertTime, "refusals"); s.count != 2 { |
| + t.Fatalf("refusal window: %+v", s) |
| + } |
| + if _, err := st.db.Exec(`INSERT INTO demo_admissions(ip_hash,attempted_at) VALUES(?,?)`, make([]byte, 32), demoAlertTime.UnixNano()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if s := signalNamed(t, st, c, 100, demoAlertTime, "prefix"); s.count != 4 { |
| + t.Fatalf("legacy NULL prefix counted: %+v", s) |
| + } |
| +} |
| + |
| +type demoAlertMail struct { |
| + calls []string |
| + fail bool |
| +} |
| + |
| +func (m *demoAlertMail) Ready(context.Context) bool { panic("alert called readiness") } |
| +func (m *demoAlertMail) Send(context.Context, string, string, string) error { |
| + panic("alert used uncached mail") |
| +} |
| +func (m *demoAlertMail) SendReady(_ context.Context, to, subject, body string) error { |
| + if m.fail { |
| + return errors.New("offline") |
| + } |
| + m.calls = append(m.calls, to+"\n"+subject+"\n"+body) |
| + return nil |
| +} |
| +func demoAlertServer(t *testing.T) (*Server, *demoAlertMail, *time.Time) { |
| + t.Helper() |
| + st, _ := demoTestStore(t) |
| + now := demoAlertTime |
| + mailer := &demoAlertMail{} |
| + c := demoAlertDefaults(t) |
| + c.Enabled = true |
| + c.Digest = false |
| + s := &Server{store: st, cfg: Config{DemoAlerts: c, Demo: demo.Config{CreateGlobalDay: 1}, SystemOperators: []string{"ops@example.test"}}, consoleMail: mailer, alertClock: func() time.Time { return now }} |
| + return s, mailer, &now |
| +} |
| + |
| +func TestDemoAlertOffAndHostClaim(t *testing.T) { |
| + // No store at all proves these guards run before any SQL or sender access. |
| + s := &Server{} |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.cfg.DemoAlerts.Enabled = true |
| + s.cfg.HostClaim = true |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestDemoAlertDedupeRetryRestartAndRearm(t *testing.T) { |
| + s, m, now := demoAlertServer(t) |
| + alertAttempt(t, s.store, *now, 1, 1) |
| + m.fail = true |
| + if err := s.demoAlertPass(t.Context()); err == nil { |
| + t.Fatal("failure hidden") |
| + } |
| + seen, _, err := s.store.AlertSeen("demo-abuse", "budget", "ops@example.test") |
| + if err != nil || seen { |
| + t.Fatal("failed delivery marked sent") |
| + } |
| + m.fail = false |
| + for i := 0; i < 3; i++ { |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if len(m.calls) != 1 { |
| + t.Fatalf("duplicates: %v", m.calls) |
| + } |
| + // A replacement server starts with no in-memory firing state. |
| + other := &Server{store: s.store, cfg: s.cfg, consoleMail: m, alertClock: s.alertClock} |
| + if err := other.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(m.calls) != 1 { |
| + t.Fatal("restart duplicated mail") |
| + } |
| + *now = now.Add(25 * time.Hour) |
| + if err := other.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + alertAttempt(t, s.store, *now, 1, 1) |
| + if err := other.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(m.calls) != 2 { |
| + t.Fatal("quiet period did not rearm") |
| + } |
| + s.cfg.DemoAlerts.Enabled = false |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(m.calls) != 2 { |
| + t.Fatal("disabled sent mail") |
| + } |
| +} |
| + |
| +func TestDemoAlertReportDigestAndImmediate(t *testing.T) { |
| + s, m, now := demoAlertServer(t) |
| + s.cfg.DemoAlerts.Digest = true |
| + s.cfg.DemoAlerts.ReportsPerHour = 1 |
| + alertReport(t, s.store, now.Add(-time.Second), "a") |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(m.calls) != 1 || !strings.Contains(m.calls[0], demoAlertDigestSubject) { |
| + t.Fatalf("first digest: %v", m.calls) |
| + } |
| + alertReport(t, s.store, *now, "b") |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(m.calls) != 2 || !strings.Contains(m.calls[1], demoAlertSubject) { |
| + t.Fatalf("immediate reports: %v", m.calls) |
| + } |
| + *now = now.Add(time.Hour) |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(m.calls) != 2 { |
| + t.Fatal("second digest same day") |
| + } |
| + *now = time.Date(2026, 11, 9, 0, 0, 0, 0, time.UTC) |
| + m.fail = true |
| + if err := s.demoAlertPass(t.Context()); err == nil { |
| + t.Fatal("digest failure hidden") |
| + } |
| + m.fail = false |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(m.calls) != 3 || !strings.Contains(m.calls[2], "1 abuse reports") { |
| + t.Fatalf("next digest lost same-second report or repeated prior reports: %v", m.calls) |
| + } |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(m.calls) != 3 { |
| + t.Fatal("digest repeated") |
| + } |
| + alertReport(t, s.store, *now, "c") |
| + *now = now.Add(24 * time.Hour) |
| + s.cfg.DemoAlerts.Digest = false |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(m.calls) != 3 { |
| + t.Fatal("disabled digest sent") |
| + } |
| + for _, msg := range m.calls { |
| + if strings.Contains(msg, "private report detail") || strings.Contains(msg, "demo.example.test") { |
| + t.Fatal("alert leaked report contents") |
| + } |
| + } |
| +} |
| + |
| +func TestDemoAlertRecipientsAndIndependentRetry(t *testing.T) { |
| + s, m, now := demoAlertServer(t) |
| + s.cfg.SystemOperators = []string{" OPS@example.test ", "ops@example.test"} |
| + if err := s.store.AddMember(OpsAccountID, "owner@example.test", RoleOwner, *now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.store.SetOperator("fleet@example.test", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.store.SetGrantToken("owner@example.test", "owner-grant", *now); err != nil { |
| + t.Fatal(err) |
| + } |
| + fail := true |
| + grants := 0 |
| + s.sendApp = func(_ context.Context, token, to, subject, body string) (string, error) { |
| + if token != "owner-grant" || to != "owner@example.test" { |
| + t.Fatal("wrong recipient grant") |
| + } |
| + if fail { |
| + return "", errors.New("offline") |
| + } |
| + grants++ |
| + return "ok", nil |
| + } |
| + alertAttempt(t, s.store, *now, 1, 1) |
| + if err := s.demoAlertPass(t.Context()); err == nil { |
| + t.Fatal("grant failure hidden") |
| + } |
| + fail = false |
| + if err := s.demoAlertPass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(m.calls) != 1 || grants != 1 { |
| + t.Fatalf("per recipient retry failed: mail=%v grants=%d", m.calls, grants) |
| + } |
| + if _, err := s.store.db.Exec(`DELETE FROM memberships WHERE account_id=? AND address=?`, OpsAccountID, "owner@example.test"); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.cfg.SystemOperators = nil |
| + if err := s.demoAlertPass(t.Context()); err == nil { |
| + t.Fatal("no recipients hidden") |
| + } |
| +} |
| + |
| +func TestDemoAlertEmailUsesVerifiedCacheOnly(t *testing.T) { |
| + ses := &fakeSES{} |
| + // Nil control-store/provisioner make any attempt to ensure or verify fail. |
| + m := newSESConsoleMailer("noreply@example.test", nil, nil, nil, testMailDeployment(), ses) |
| + if err := m.SendReady(t.Context(), "ops@example.test", "subject", "body"); !errors.Is(err, ErrConsoleMailNotReady) { |
| + t.Fatalf("cold: %v", err) |
| + } |
| + if len(ses.sent) != 0 { |
| + t.Fatal("cold sender sent") |
| + } |
| + m.verified = true |
| + m.configSet = "verified-config" |
| + if err := m.SendReady(t.Context(), "ops@example.test", "subject", "body"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(ses.sent) != 1 { |
| + t.Fatal("verified sender did not send") |
| + } |
| + // An already verified persisted record is learned by the existing startup |
| + // ensure; no separate read is made on the alert path after a restart. |
| + st := release.NewDirStore(t.TempDir()) |
| + prov := mail.NewMemProvisioner("1") |
| + prov.StatusOnEnsure = verifiedStatus |
| + warm := newSESConsoleMailer("noreply@example.test", st, prov, dnsrec.NewMemWriter(), testMailDeployment(), ses) |
| + if err := warm.Send(t.Context(), "ops@example.test", "subject", "body"); err != nil { |
| + t.Fatal(err) |
| + } |
| + restart := newSESConsoleMailer("noreply@example.test", st, prov, dnsrec.NewMemWriter(), testMailDeployment(), ses) |
| + if err := restart.Ensure(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + restart.store = nil |
| + restart.prov = nil |
| + if err := restart.SendReady(t.Context(), "ops@example.test", "subject", "body"); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestDemoAlertEngineRunsWithoutBucket(t *testing.T) { |
| + s, m, now := demoAlertServer(t) |
| + alertAttempt(t, s.store, *now, 1, 1) |
| + if err := s.alertEnginePass(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(m.calls) != 1 { |
| + t.Fatal("bucket-free pass did not send") |
| + } |
| +} |
| + |
| +func TestDemoAlertStateExcludedFromFleetCutover(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + for _, box := range []string{demoAlertSeenBox, "real-box"} { |
| + if err := st.SetAlertSeen(box, "budget", "ops@example.test", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + tx, err := st.db.BeginTx(t.Context(), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer tx.Rollback() |
| + seen, err := alertSeenFiring(tx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(seen) != 1 || len(seen[[2]string{"real-box", "budget"}]) != 1 { |
| + t.Fatalf("demo notice leaked into fleet migration: %v", seen) |
| + } |
| +} |
diff --git a/internal/console/demo_store.go b/internal/console/demo_store.go| index d23ac3021..ffd1d4af4 100644 |
| --- a/internal/console/demo_store.go |
| +++ b/internal/console/demo_store.go |
| @@ -93,6 +93,12 @@ CREATE TABLE IF NOT EXISTS demo_retirements(demo_id TEXT PRIMARY KEY, wire BLOB |
| if err := s.migrateDemoReports(); err != nil { |
| return err |
| } |
| + if err := s.migrateDemoAlertAdmissions(); err != nil { |
| + return err |
| + } |
| + if err := s.migrateDemoAlerts(); err != nil { |
| + return err |
| + } |
| if err := s.migrateDemoClaims(); err != nil { |
| return err |
| } |
| @@ -142,7 +148,11 @@ func (s *Store) SpendDemoCreate(ctx context.Context, ip string, now time.Time, c |
| if err != nil { |
| return err |
| } |
| - if _, err = tx.ExecContext(ctx, `INSERT INTO demo_admissions(ip_hash,attempted_at) VALUES(?,?)`, hash, now.UnixNano()); err != nil { |
| + prefix, err := demoAdmissionPrefixHash(ctx, tx, ip) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `INSERT INTO demo_admissions(ip_hash,attempted_at,prefix_hash) VALUES(?,?,?)`, hash, now.UnixNano(), prefix); err != nil { |
| return err |
| } |
| return tx.Commit() |
| @@ -484,6 +494,9 @@ func (s *Store) WipeDemoAbuse(ctx context.Context, now time.Time) error { |
| if _, err = tx.ExecContext(ctx, `DELETE FROM demo_report_attempts WHERE attempted_at<=?`, now.Add(-24*time.Hour).UnixNano()); err != nil { |
| return err |
| } |
| + if err = pruneDemoAlertAdmissions(ctx, tx, now); err != nil { |
| + return err |
| + } |
| if _, err = tx.ExecContext(ctx, `DELETE FROM demo_reports WHERE demo_id IN (SELECT demo_id FROM demo_apps WHERE purged_at>0 AND purged_at<=?)`, cutoff); err != nil { |
| return err |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index 3639f5299..9276d541b 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -532,6 +532,7 @@ const ( |
| // Config is everything the server reads its world through. |
| type Config struct { |
| Demo demo.Config |
| + DemoAlerts DemoAlertConfig |
| Registrar registrar.Registrar |
| ZoneHost zonehost.Host |
| DomainApex zonehost.ApexSource |
| @@ -1011,6 +1012,7 @@ type Server struct { |
| demoClaimAdmission demoClaimAdmissionCache |
| demoStatus demoStatusLimiter |
| demoControlMu sync.RWMutex |
| + demoAlertMu sync.Mutex |
| demoStopMu sync.Mutex |
| demoStopDeadlines map[int64]time.Time |
| demoJobs demoJobHub |
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go| index da130566a..0832724b0 100644 |
| --- a/internal/console/store_gate.go |
| +++ b/internal/console/store_gate.go |
| @@ -189,19 +189,21 @@ var claimAppsTerminal = map[string][]string{ |
| // audit and mail telemetry are app-scoped and are gated like the rest. |
| // Demo operation rows include kept_hash; browser rows include operation_id and reveal. |
| var claimSQLTables = map[string]claimSQLTable{ |
| - "demo_claim_progress": {App: "operation_id", Refuse: "anonymous demo claims require claims mode off"}, |
| - "demo_claim_commits": {App: "operation_id", Refuse: "anonymous demo claims require claims mode off"}, |
| - "demo_claim_outbox": {App: "operation_id", Refuse: "anonymous demo claims require claims mode off"}, |
| - "demo_moved_notices": {App: "demo_id", Refuse: "anonymous demo claims require claims mode off"}, |
| - "demo_claim_ops": {Account: "account_id", App: "app", Refuse: "anonymous demo claims require claims mode off"}, |
| - "demo_claim_browsers": {App: "flow_hash", Refuse: "anonymous demo browser claims require claims mode off"}, |
| - "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_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"}, |
| - "demo_retirements": {App: "demo_id", Refuse: "anonymous demo retirement requires claims mode off"}, |
| - "demo_host_tombstones": {App: "demo_id", Refuse: "anonymous demo host reservations require claims mode off"}, |
| + "demo_claim_progress": {App: "operation_id", Refuse: "anonymous demo claims require claims mode off"}, |
| + "demo_claim_commits": {App: "operation_id", Refuse: "anonymous demo claims require claims mode off"}, |
| + "demo_claim_outbox": {App: "operation_id", Refuse: "anonymous demo claims require claims mode off"}, |
| + "demo_moved_notices": {App: "demo_id", Refuse: "anonymous demo claims require claims mode off"}, |
| + "demo_claim_ops": {Account: "account_id", App: "app", Refuse: "anonymous demo claims require claims mode off"}, |
| + "demo_claim_browsers": {App: "flow_hash", Refuse: "anonymous demo browser claims require claims mode off"}, |
| + "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_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"}, |
| + "demo_retirements": {App: "demo_id", Refuse: "anonymous demo retirement requires claims mode off"}, |
| + "demo_host_tombstones": {App: "demo_id", Refuse: "anonymous demo host reservations require claims mode off"}, |
| // Jobs carry demo identity and durable spool metadata; source outbox rows |
| // carry only a job ID. Neither is safe to write with an ordinary app permit. |
| // The opaque IDs below are refusal-only scopes, never matched to a permit. |