carlos / platform Public

console: opt-in operator alerts on unusual demo creates (#527)

Off by default; reads console SQLite only. Emails system operators and
ops owners when the daily create budget nears its limit, creates bunch
on few IPs or one /24 or /48, admission refusals spike, or abuse reports
arrive (immediate over N/hour, plus a daily digest). Thresholds via
CONSOLE_DEMO_ALERT_* drop-ins. Email copy is a draft for Paul's review
before switch-on. Opus review R1: no P1, two P2 fixed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from demo-abuse-alerts into main.
claude agent, operated by paul@keymail.dev 06bb3f7eb09cab1e4be7876af1d41a4bfb6991c3 parent fe8df21
19 files changed, +1,636 −23
  • cmd/console/main.go +5 −0
  • docs/superpowers/notes/demo-abuse-alerts.md +118 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-demo-abuse-alerts-R1.md +67 −0
  • docs/superpowers/reviews/REVIEW-CHECK-FINDINGS-demo-abuse-alerts-R1.md +29 −0
  • docs/superpowers/reviews/REVIEW-CHECK-demo-abuse-alerts-R1.md +47 −0
  • docs/superpowers/reviews/REVIEW-FINDINGS-demo-abuse-alerts-R1.md +35 −0
  • docs/superpowers/reviews/VERIFICATION-demo-abuse-alerts.md +70 −0
  • internal/console/alertengine_pass.go +3 −0
  • internal/console/alertstore.go +2 −2
  • internal/console/apidemo.go +19 −0
  • internal/console/consolemail.go +39 −7
  • internal/console/demo_alert_admission.go +103 −0
  • internal/console/demo_alert_admission_test.go +214 −0
  • internal/console/demo_alert_copy.go +23 −0
  • internal/console/demo_alerts.go +319 −0
  • internal/console/demo_alerts_test.go +512 −0
  • internal/console/demo_store.go +14 −1
  • internal/console/server.go +2 −0
  • internal/console/store_gate.go +15 −13

CI passed — run details

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
new file mode 100644
index 000000000..80c2adec6
--- /dev/null
+++ b/docs/superpowers/notes/demo-abuse-alerts.md
@@ -0,0 +1,118 @@
+# Demo abuse alerts (draft)
+
+Paul needs operator alerts before opening the flagship demo window. This branch
+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: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: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: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: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:1254`, and
+per-recipient success state from `store.go:2721` and `:2738`. Email uses the
+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.
+A missing verified sender or grant leaves delivery retryable and visible in
+the worker error. Each pass rechecks the recipient list.
+
+## Signals and SQL
+
+All windows exclude future rows. Create windows are rolling; refusal windows
+are UTC minute buckets, including the current partial minute. Queries use
+parameters, not interpolated operator input.
+
+| Signal | SQL shape | Default |
+| --- | --- | --- |
+| Daily budget | `count(*) FROM demo_admissions WHERE attempted_at > ? AND attempted_at <= ?` | count × 100 >= daily budget × 80 |
+| Few IP budgets | sum the largest K `count(*) GROUP BY ip_hash` in the create window | 20 attempts from the busiest 3 budgets in 1h |
+| 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 | `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
+site allocation; it is a concentration hint, not proof of one person.
+Old admission rows have NULL prefixes until they expire. No raw address is
+added. Prefixes disappear with their admission rows after 24h. Refusals store
+only bounded minute counters, pruned after 24h, including during quiet periods.
+Refusals include serving-off and readiness denials, but exclude invalid uploads
+and updates. Counting remains active while notifications are disabled.
+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 stop or receipt-write failure after mail acceptance
+can duplicate mail. Failed transient conditions retry while still firing.
+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
+
+Use console environment/drop-in settings, followed by a console restart. This
+is the brief's permitted fallback: existing demo limits already use environment
+settings (`internal/demo/config.go:35`), while the operator API currently edits
+only serving (`internal/console/apidemooperator.go:20`). It avoids adding a new
+CLI command and root-binary census changes for this first demo window.
+
+Every name below starts with `CONSOLE_DEMO_ALERT_`:
+
+| Suffix | Default | Meaning |
+| --- | --- | --- |
+| `ENABLED` | `false` | explicit opt-in; off means no signals or delivery |
+| `BUDGET_PERCENT` | `80` | integer 1 through 100 |
+| `IP_COUNT`, `FEW_IPS` | `20`, `3` | attempts across the busiest K IP budgets |
+| `PREFIX_COUNT`, `CREATE_WINDOW` | `30`, `1h` | attempts per /24 or /48 |
+| `REFUSAL_COUNT`, `REFUSAL_WINDOW` | `30`, `10m` | refusal spike |
+| `REPORTS_PER_HOUR` | `5` | send when the count exceeds N; zero means any report |
+| `DIGEST` | `true` | daily report digest, still gated by ENABLED |
+
+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. A newly verified identity needs an
+ordinary mail readiness check or a console restart before alerts can use it.
+The existing minute loop attempts the fleet pass and heartbeat, then demo
+alerts, even if fleet reads failed. Demo sends have a 60s pass budget and stop
+on a transport timeout. Demo errors are logged separately from the fleet job.
+Immediate reports therefore arrive on the next pass rather than waiting for
+the digest. Costs are a handful of indexed SQLite aggregates per minute,
+local counters, digest receipts (up to about 100 KB per recipient on empty
+passes; recorded as a P3), and mail 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:101` evaluates signals;
+`:162` runs the guarded pass. The settings loader is at `:27`;
+`demo_alert_admission.go:76` persists refusals.
+
+## Open questions before activation
+
+- Paul edits the draft strings in `internal/console/demo_alert_copy.go`.
+- Confirm recipients, verified email readiness, thresholds and the switch-on
+ date for the flagship demo window. This branch does not activate anything.
+- Environment settings require a restart. If live tuning becomes routine,
+ extend the demo operator API and CLI in a later reviewed change.
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-demo-abuse-alerts-R1.md b/docs/superpowers/reviews/REVIEW-BRIEF-demo-abuse-alerts-R1.md
new file mode 100644
index 000000000..10393c713
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-demo-abuse-alerts-R1.md
@@ -0,0 +1,67 @@
+# Review brief: demo abuse alerts implementation, round 1 of 3
+
+Repo carlos/platform, branch `demo-abuse-alerts`, implementation commit
+`5c9fb44b5deae7a4236ea019b5c5f2abe48337fc`.
+Under review: diff `9622c65a159480a687f066f7a24e28a31c68360d..5c9fb44b5deae7a4236ea019b5c5f2abe48337fc`.
+Authorities: merged `docs/superpowers/specs/2026-11-02-agent-start-demo-design.md`
+section 4.6 and `docs/superpowers/notes/agent-start-demo-2-rulings.md`.
+The task brief is `/home/paulca/.cache/demo-abuse-basics/ASTRA-BRIEF.md`.
+
+You are an independent Opus reviewer. Read the note, then the code it names,
+and check every claim against that code. Work only in this checkout. Read-only:
+no edits, commits, pushes, AWS, other checkouts or HANDOFF files.
+
+## Fixed: do not re-argue
+
+- Off by default, thresholds adjustable. The task explicitly permits console
+ environment settings if justified and draft copy for Paul to edit later.
+- All alert inputs are SQLite. No new S3 reads or polling. Existing startup
+ mail identity ensure already runs; caching its returned verified record adds
+ no read. SendReady must never ensure or verify anything itself.
+- No merge or activation is authorised. This is a local implementation review,
+ including its changed SQL gate and mail path, before returning the branch.
+- This is round 1; there are no earlier independent review findings.
+
+## What to check
+
+1. Thresholds, UTC windows, top-K IP budgets, salted /24 and /48 hashes,
+ retention, migration idempotence and bounded refusal storage.
+2. HTTP refusal counting must never authorise a request or count an update as
+ a create; failure to persist must preserve the original refusal.
+3. The SQL NonApp classifications must not weaken any app gate. Host-claim
+ mode must refuse alert evaluation. No root-binary files are changed.
+4. Recipient authority matches apiSystemRoller (system operators plus ops
+ owners), and alert text contains no attacker-controlled report/IP data.
+5. No repeated successful notification while firing; quiet observations rearm.
+ Failure retries per recipient, persisted across restart. AlertSeen demo rows
+ must not enter fleet cutover. The direct path's crash-after-send duplicate
+ window and retry-only-while-firing limitation are documented.
+6. Daily report digest and strict greater-than-N immediate report threshold;
+ disable switches; restart behaviour and mail readiness without extra reads.
+7. Existing mail Send semantics must remain intact. SendReady uses only a
+ verified cached identity, including the record returned by startup ensure.
+8. Tests and note accurately describe behaviour. New tests use injected time
+ and no sleeps. Targeted demo/alert regression run is ongoing; initial new
+ tests, vet, build and whole-tree gofmt passed. A fleet-cutover exclusion test
+ was added afterward and its focused run is ongoing.
+
+## Severity
+
+- P1: unsafe, would not compile, a test fails, or it would not work. Blocks merge.
+- P2: wrong or missing. Fixed without reopening this review. The census and
+ review of newly changed security, root, termination or production-storage
+ behaviour still check the fix within the same round budget.
+- P3: clarity or polish. Follow-up only; never a reason for another round.
+
+A P1 states its failure scenario and evidence (file:line). Do not promote a
+P2 to P1 to keep the review open. Two rounds in one fault family stop fixing;
+a fourth round needs Paul. Stop at the first round with no P1.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the problem, verified file:line evidence,
+failure scenario, concrete fix, and invariant or trust boundary (fault family).
+End with exactly one verdict: READY (no P1/P2), READY AFTER FIXES (P2 only), or
+NOT READY (P1). Do not edit files, spawn reviewers or subagents, or run full
+suites. You may run a narrowly targeted test if necessary, nice -n 10, default
+Go cache, disk TMPDIR. Return your findings as the final response.
diff --git a/docs/superpowers/reviews/REVIEW-CHECK-FINDINGS-demo-abuse-alerts-R1.md b/docs/superpowers/reviews/REVIEW-CHECK-FINDINGS-demo-abuse-alerts-R1.md
new file mode 100644
index 000000000..5fe14afbd
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-CHECK-FINDINGS-demo-abuse-alerts-R1.md
@@ -0,0 +1,29 @@
+# Opus round 1 fix check
+
+Reviewed tip: `4f0f08a3aec542f11e3782375befe6864f5d6979`.
+
+**Verdict: READY.** Both P2s are fixed, and the fixes add no P1 or P2. I found two P3 follow-ups. As the brief asked, I ran no tests, made no edits and created no scratch files.
+
+## P2.1, fleet liveness: resolved
+- The demo pass now runs after `s.jobs.Run(..., alertEnginePass)` and outside it (`alertengine_pass.go:99-104`). The fleet step, the drain and the heartbeat all finish first. Demo errors are only logged, through `demoAlertPassLog`. They are no longer joined into the job result (`alertengine_pass.go:128-152`).
+- The whole pass has one 60-second deadline (`alertPassBudget`, `demo_alerts.go:172`). Each send's own 20-second timeout comes from that pass deadline, so a send can't outlast it.
+- The pass stops on the first timeout. `sendDemoAlert` adds the per-send `ctx.Err()` to the send's error (`demo_alerts.go:236`, `:244`), and `demoAlertTimedOut` stops the pass on a signal send (`:209`) or a digest (`:218`). The digest error keeps the timeout visible because `demoAlertDeliveryError` wraps with `%w`.
+- A stalled mail lock is also covered. `acquire` wraps `ctx.Err()` with `%w` (`consolemail.go:113`), so the timeout check sees it.
+- At worst, the next fleet pass now starts about 60 seconds late. The heartbeat counts as stale only after 10 minutes (`host/enginebeat.go:29`), so `engine_silent` won't trip.
+- The signals and recipients still read only SQLite: `demoAlertSignals`, then `GrantToken` in `grantRecipients`. There are no S3 reads.
+
+## P2.2, report completeness: resolved
+- **Schema:** `report_ids TEXT NOT NULL DEFAULT '[]'` (`demo_alerts.go:86-89`). It is added through `CREATE TABLE IF NOT EXISTS`, which is acceptable only because the table was never deployed.
+- **Bound:** the 2,000-row cap is real (`demo_reports.go:131`). IDs are a Unix time plus a random 16-byte nonce (`:137`), so an ID is never reused.
+- **Commit only after success:** the snapshot of IDs is taken from rows with `created_at<now` (`:279`). It is written only after the send succeeds (`:317`). A failed send returns at `:315` without writing anything.
+- **Late commits:**
+ - A report that commits after the read is missing from the saved snapshot. The next digest counts it as unseen, whatever its timestamp.
+ - A report whose ID is already in the snapshot is never counted twice.
+- **Empty days:** the update at `:309` only removes IDs whose reports were deleted. It doesn't use up the day's send.
+- **First digest:** with no row yet, it counts only the last 24 hours. Every ID it sees, older ones included, goes into the snapshot, so older reports are never counted later.
+- **Mail cache (fix 3):** when a later check finds the domain not verified, it clears `ensuredConfigSet` (`consolemail.go:170`). `Send` is unchanged. `SendReady` still reads only memory under the lock, never the control store.
+- **SQL gate (fix 4):** only the NonApp description changed (`store_gate.go:201`). The table carries no app authority.
+
+## New issues from these fixes (P3 only)
+1. **The empty-day prune rewrites the snapshot every minute** (`demo_alerts.go:309`). After a digest day with no new reports, every pass rescans up to 2,000 rows and writes up to about 100 KB of JSON per recipient, even when nothing changed. That adds a needless SQLite write every minute, which a database replica would have to copy. Fix: write only when the encoded list differs from `raw`. Fault family: efficiency, not completeness.
+2. **A digest sent near the 60-second deadline can go out twice** (`demo_alerts.go:317`). The receipt write uses the pass context. If a send succeeds just before the deadline, `ExecContext` fails on the expired context and the receipt is never saved. The next pass then sends the same digest again that day. Reports are never lost, so completeness holds. Fix: write the receipt with `context.WithoutCancel(ctx)` and a short timeout of its own. Fault family: digest dedupe and retry.
diff --git a/docs/superpowers/reviews/REVIEW-CHECK-demo-abuse-alerts-R1.md b/docs/superpowers/reviews/REVIEW-CHECK-demo-abuse-alerts-R1.md
new file mode 100644
index 000000000..74657f6fc
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-CHECK-demo-abuse-alerts-R1.md
@@ -0,0 +1,47 @@
+# Demo abuse alerts: round 1 fix check
+
+Review history: Opus round 1 reviewed `9622c65a..5c9fb44b` and found no P1,
+two P2, verdict READY AFTER FIXES. See REVIEW-FINDINGS-demo-abuse-alerts-R1.md.
+The full review is closed under AGENTS.md. This is the required check of the
+new storage/mail behaviour in its fixes, within round 1, not a new full review.
+
+Repo carlos/platform, branch demo-abuse-alerts. The launch prompt supplies the
+exact tip. Check only `5c9fb44b..tip` in these files:
+
+- internal/console/demo_alerts.go and demo_alerts_test.go
+- internal/console/consolemail.go
+- internal/console/alertengine_pass.go
+- internal/console/store_gate.go
+
+The fixed task and authorities are in REVIEW-BRIEF-demo-abuse-alerts-R1.md.
+No previous P1; no findings declined. P3 suggestions remain follow-ups in the
+findings file. Do not reopen those or review the whole branch again.
+
+## Fixes to check
+
+1. P2.1, fleet liveness: the existing loop finishes its fleet pass and heartbeat
+ before demo delivery. A demo pass has a 60s deadline and stops on the first
+ transport timeout. Demo errors are logged separately; they no longer mark
+ the fleet job failed. The isolated signals still require no S3 reads.
+2. P2.2, report completeness: b9f4b53a replaces timestamp-only delivery progress
+ with a per-recipient JSON snapshot of observed report IDs. Check the schema,
+ bound (existing report queue max 2,000), exact snapshot committed only after
+ successful delivery, late commits, empty-day pruning and first-digest window.
+ The new table does not exist on main; this branch has never been deployed.
+3. Mail cache correction from b9f4b53a: a later readiness check returning a
+ non-verified status clears the startup cached config set. Existing Send
+ semantics remain intact and SendReady still makes no control-store reads.
+4. The only SQL gate change is the NonApp description of the digest receipt;
+ report IDs confer no app mutation authority.
+
+Read code only. Do not run tests: the author has run the focused tests, and the
+longer demo/alert selection is already running. The prior review's broad SQL
+probe command hit the default timeout; do not repeat it. No edits, commits,
+subagents, AWS, other checkouts or HANDOFF. Scratch only under the task scratch
+path if needed; report any file you create so the parent can remove it.
+
+Use the original severity definitions. State resolved/partial/not resolved for
+P2.1 and P2.2, then any concrete regression introduced by these fixes, with
+file:line evidence and its fault family. End with READY, READY AFTER FIXES or
+NOT READY. A missing P1 closes review; P2 fixes do not reopen it. The total
+budget remains at most three rounds and two rounds per fault family.
diff --git a/docs/superpowers/reviews/REVIEW-FINDINGS-demo-abuse-alerts-R1.md b/docs/superpowers/reviews/REVIEW-FINDINGS-demo-abuse-alerts-R1.md
new file mode 100644
index 000000000..3c0d044e6
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-FINDINGS-demo-abuse-alerts-R1.md
@@ -0,0 +1,35 @@
+# Opus review: demo abuse alerts, round 1
+
+I found no P1s and two P2s, so the verdict is **READY AFTER FIXES**. I reviewed `9622c65a..5c9fb44b` against the brief. A follow-up commit, `b9f4b53a` ("Keep late report arrivals in digests and invalidate rejected mail"), landed on the branch while I was reviewing. It is outside the reviewed range and I did not review it.
+
+**Tests run:** the 17 new `TestDemoAlert*` tests plus `TestClaimSQLTablesClassified` and `TestDemoProtectionsSQLScopes` all passed (`-count=1`, niced, default Go cache). That run already included the two new tests from `b9f4b53a`. The sandbox mounts the Go cache read-only, so I ran the tests outside it. A wider first run that also matched the heavy `TestClaimConsoleMutationInvariant` suite hit the 10-minute test timeout, and I did not rerun that suite.
+
+## P1
+None.
+
+## P2
+
+**1. A slow or failing mail path holds up fleet alerting**
+- **Problem:** the demo pass runs inside the fleet alert pass, before the fleet step and its heartbeat (`internal/console/alertengine_pass.go:125`).
+- **Evidence:** each send gets its own 20-second timeout (`alertnotify.go:48`, used at `demo_alerts.go:216`). Sends loop over every recipient, every firing unseen signal and the digest (`demo_alerts.go:186-211`). Failures are retried on every pass, and `SendReady` can also wait on a stalled mail lock.
+- **Failure scenario:** Keymail or SES stops answering while 2 recipients have 5 firing signals each. That is 10 sends plus 2 digests at 20 seconds each, about 4 minutes. This repeats every minute, so fleet incidents and reminders run minutes late, and the heartbeat can be delayed enough to trip `engine_silent`.
+- **Fix:** run the demo pass after the fleet step and heartbeat, or as its own worker. Give the whole pass one deadline, and stop sending for the pass after the first transport timeout.
+- **Fault family:** fleet alert liveness must not depend on demo delivery.
+
+**2. The digest skips late-committed reports for good (fixed by `b9f4b53a`, not reviewed)**
+- **Problem:** in the reviewed commit, the digest counts `created_at>=through AND created_at<now` and then moves `through` to `now` (`demo_alerts.go:247`, `:257`).
+- **Failure scenario:** a report's timestamp is taken before its upload is read. If it commits after a digest has already moved the watermark past that timestamp, no digest ever counts it.
+- **Fix:** `b9f4b53a` keeps a per-recipient list of report IDs already counted. It needs its own check: its migration and that ID list have not been reviewed.
+- **Fault family:** every report reaches the digest.
+
+## P3
+- **Demo errors turn the fleet job red** (`alertengine_pass.go:146`, `:150`). The demo error is joined into the "Alert checks" job result. A demo setup problem, such as no recipients or mail not ready, marks that job failed every minute even when fleet alerts are fine. Report it under its own job name or just log it.
+- **Refusals are written even with alerts off** (`apidemo.go:363`, `demo_alert_admission.go:70`).
+ - Every refused create runs a SQLite write transaction on the request path, which takes the `demo_settings` lock with a 5-second timeout. This happens even when `ENABLED=false` and when edge protections are off, while the budget check before it only reads. Skip recording when alerts are disabled.
+ - Line 362 also counts refusals while serving is switched off. Turning serving off for a takedown will trigger the refusal alert from clients that keep retrying. Either leave serving-off refusals out or say so in the note.
+- **Signals can re-alert as they cross the threshold back and forth** (`demo_alerts.go:193-197`). One quiet pass rearms a signal, and all windows are rolling. A count sitting near the threshold, such as the 80% budget as old rows expire, can send mail on every crossing. This is within the design you fixed, but a minimum quiet time or a small margin below the threshold would cut the noise.
+- **Alerts go silent in claims mode with no log** (`demo_alerts.go:162`). With `ENABLED=true` on a claim-gated store, the pass returns nil and logs nothing. The impact is low because demos refuse claims mode anyway.
+
+Everything else in the brief checked out against the code: the thresholds, UTC windows and top-K grouping, the salted /24 and /48 prefix hashes, 24-hour retention, the migration, refusal counting, the SQL table classifications, recipients, the dedupe and retry state, the fleet-cutover exclusion and the `SendReady` cache-only path.
+
+**Verdict: READY AFTER FIXES**
diff --git a/docs/superpowers/reviews/VERIFICATION-demo-abuse-alerts.md b/docs/superpowers/reviews/VERIFICATION-demo-abuse-alerts.md
new file mode 100644
index 000000000..da2f32682
--- /dev/null
+++ b/docs/superpowers/reviews/VERIFICATION-demo-abuse-alerts.md
@@ -0,0 +1,70 @@
+# Demo abuse alert verification
+
+Source tip: `4f0f08a3aec542f11e3782375befe6864f5d6979` on `demo-abuse-alerts`.
+Later changes only record the review, costs and these results. Nothing was
+pushed, merged, tagged, released or activated. No AWS account was accessed.
+
+## Checks
+
+- `nice -n 10 go test -json ./internal/console -run 'TestDemo|TestAlert|TestConsoleMailer|TestClaimSQLTableCensus|TestClaimSQLSeamCallers|TestClaimAuthoritySourceCensus' -count=1 -timeout=30m`
+ passed in 861.136s: 416 top-level tests passed, two skipped; 1,105 cases
+ passed when subtests are counted. This run used the b9f4b53a source, before
+ the final delivery scheduling change. The first run hit the default 10m
+ timeout in TestDemoClaimUXHeadless; no assertion had failed before timeout.
+- `nice -n 10 go test ./internal/console -run '^TestDemoAlert|^TestAlertEngine|^TestClaimSQLTableCensus$|^TestDemoProtectionsSQLScopes$' -count=1`
+ passed on the final source in 4.154s. The existing engine tests are named
+ TestEngine rather than TestAlertEngine, so they were checked separately below.
+- `nice -n 10 go test ./internal/console -run '^TestEngine|^TestDemoAlert' -count=1`
+ passed on the final source in 12.765s. All 18 new test functions passed.
+ New tests inject time and use no sleeps. The late-report and rejected-mail
+ regressions were each observed failing before their respective fixes.
+- `nice -n 10 go vet ./internal/console/ ./` passed on the final source.
+- `nice -n 10 go build ./...` passed on the final source.
+- `gofmt -l .` produced no output; `git diff --check` passed.
+
+TestDemoClaimDevAcceptance skipped because it requires a designated live
+sandbox and prebuilt host/instance-control witnesses. TestDemoReportBrowser
+skipped because CARLOS_DEMO_BROWSER_TESTS was not enabled. The existing demo
+claim headless tests ran and passed. The full Go suite was not run, as instructed.
+
+Only console source, console tests and documentation changed. The linux amd64
+and arm64 root dependency lists exclude internal/console; no root census
+change, overlay or CLI cross-compile was needed. Go caches stayed at their
+defaults. Both temporary test directories left by the timed-out runs were
+removed by their exact paths after checking that no process referenced them.
+Task-created logs and briefs were removed; unrelated scratch files were kept.
+
+## Review
+
+Opus round 1 found no P1 and two P2. Both were fixed. The bounded check of the
+new digest storage and mail/scheduling behaviour returned READY, with no new
+P1 or P2. Review is closed. The original findings and fix-check findings beside
+this file retain the P3 follow-up lists. The reviewer also ran a wider targeted
+SQL probe that hit its default 10m timeout; its subsequent focused alert and
+SQL scope checks passed. That wider probe was not repeated.
+
+Paul still needs to edit the draft copy, confirm recipients and thresholds,
+and choose the flagship activation date. Settings use the brief's permitted
+CONSOLE_DEMO_ALERT_* fallback and take effect after a console restart.
+
+## Changed files
+
+- `cmd/console/main.go`
+- `docs/superpowers/notes/demo-abuse-alerts.md`
+- `docs/superpowers/reviews/REVIEW-BRIEF-demo-abuse-alerts-R1.md`
+- `docs/superpowers/reviews/REVIEW-CHECK-FINDINGS-demo-abuse-alerts-R1.md`
+- `docs/superpowers/reviews/REVIEW-CHECK-demo-abuse-alerts-R1.md`
+- `docs/superpowers/reviews/REVIEW-FINDINGS-demo-abuse-alerts-R1.md`
+- `docs/superpowers/reviews/VERIFICATION-demo-abuse-alerts.md`
+- `internal/console/alertengine_pass.go`
+- `internal/console/alertstore.go`
+- `internal/console/apidemo.go`
+- `internal/console/consolemail.go`
+- `internal/console/demo_alert_admission.go`
+- `internal/console/demo_alert_admission_test.go`
+- `internal/console/demo_alert_copy.go`
+- `internal/console/demo_alerts.go`
+- `internal/console/demo_alerts_test.go`
+- `internal/console/demo_store.go`
+- `internal/console/server.go`
+- `internal/console/store_gate.go`
diff --git a/internal/console/alertengine_pass.go b/internal/console/alertengine_pass.go
index f45cc8071..7b12d4776 100644
--- a/internal/console/alertengine_pass.go
+++ b/internal/console/alertengine_pass.go
@@ -99,6 +99,9 @@ func (s *Server) StartAlertEngine(ctx context.Context) {
if err := s.jobs.Run(ctx, "StartAlertEngine", s.alertEnginePass); err != nil {
log.Printf("console: alert engine: %v", err)
}
+ if err := s.demoAlertPass(ctx); err != nil {
+ log.Printf(demoAlertPassLog, err)
+ }
select {
case <-ctx.Done():
return
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..09598e220 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,10 +162,12 @@ 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]
if st == nil || st.Status != mail.StatusVerified {
+ m.ensuredConfigSet = ""
return "", ErrConsoleMailNotReady
}
m.verified, m.configSet = true, st.ConfigSet
@@ -185,7 +193,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..45a8fe6dd
--- /dev/null
+++ b/internal/console/demo_alert_copy.go
@@ -0,0 +1,23 @@
+package console
+
+// Draft operator copy, off by default. Paul reviews these strings before
+// demo alerts are switched on.
+const (
+ demoAlertPassLog = "console: demo alerts: %v"
+ 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..c24396bbc
--- /dev/null
+++ b/internal/console/demo_alerts.go
@@ -0,0 +1,319 @@
+package console
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "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,
+ report_ids TEXT NOT NULL DEFAULT '[]'
+) 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 after the fleet engine's pass and heartbeat, 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()
+ ctx, cancel := context.WithTimeout(ctx, alertPassBudget)
+ defer cancel()
+ 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))
+ if demoAlertTimedOut(ctx, err) {
+ return errors.Join(failures...)
+ }
+ continue
+ }
+ failures = append(failures, s.store.SetAlertSeen(demoAlertSeenBox, signal.rule, recipient.address, true))
+ }
+ if c.Digest {
+ err := s.demoReportDigest(ctx, recipient, now)
+ failures = append(failures, err)
+ if demoAlertTimedOut(ctx, err) {
+ return errors.Join(failures...)
+ }
+ }
+ }
+ return errors.Join(failures...)
+}
+
+func demoAlertTimedOut(ctx context.Context, err error) bool {
+ var timeout interface{ Timeout() bool }
+ return ctx.Err() != nil || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) || (errors.As(err, &timeout) && timeout.Timeout())
+}
+
+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 errors.Join(err, ctx.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 {
+ err := sender.SendReady(ctx, recipient.address, subject, body)
+ return errors.Join(err, ctx.Err())
+ }
+ return ErrConsoleMailNotReady
+}
+
+func (s *Server) demoReportDigest(ctx context.Context, recipient operatorGrant, now time.Time) error {
+ var through, day int64
+ 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 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
+ 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 {
+ // 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,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
new file mode 100644
index 000000000..57b270512
--- /dev/null
+++ b/internal/console/demo_alerts_test.go
@@ -0,0 +1,512 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "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
+ err error
+ attempts int
+ onSend func(context.Context)
+}
+
+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(ctx context.Context, to, subject, body string) error {
+ m.attempts++
+ if m.onSend != nil {
+ m.onSend(ctx)
+ }
+ if m.err != nil {
+ return m.err
+ }
+ 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)
+ s.jobs = newJobRegistry(s.alertClock)
+ alertAttempt(t, s.store, *now, 1, 1)
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ m.onSend = func(sendCtx context.Context) {
+ status, ok := jobStatusOf(s, "StartAlertEngine")
+ if !ok || status.Runs != 1 || status.State != JobOK {
+ t.Errorf("demo delivery ran before fleet pass finished: %+v", status)
+ }
+ if _, ok := sendCtx.Deadline(); !ok {
+ t.Error("unbounded demo send")
+ }
+ cancel()
+ }
+ s.StartAlertEngine(ctx)
+ if len(m.calls) != 1 {
+ t.Fatal("bucket-free loop did not send")
+ }
+ status, _ := jobStatusOf(s, "StartAlertEngine")
+ if status.State != JobOK {
+ t.Fatal("demo delivery changed fleet job status")
+ }
+}
+
+func TestDemoAlertPassStopsOnTransportTimeout(t *testing.T) {
+ for _, timeout := range []error{context.DeadlineExceeded, os.ErrDeadlineExceeded} {
+ t.Run(timeout.Error(), func(t *testing.T) {
+ s, m, now := demoAlertServer(t)
+ s.cfg.SystemOperators = append(s.cfg.SystemOperators, "second@example.test")
+ s.cfg.DemoAlerts.IPCount = 1
+ s.cfg.DemoAlerts.PrefixCount = 1
+ s.cfg.DemoAlerts.Digest = true
+ alertAttempt(t, s.store, *now, 1, 1)
+ alertReport(t, s.store, now.Add(-time.Second), "report")
+ m.err = timeout
+ if err := s.demoAlertPass(t.Context()); !errors.Is(err, timeout) {
+ t.Fatalf("timeout lost: %v", err)
+ }
+ if m.attempts != 1 {
+ t.Fatalf("continued sending after timeout: %d", m.attempts)
+ }
+ })
+ }
+}
+
+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)
+ }
+}
+
+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/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..45eb91140 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 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"},
+ "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.