carlos / platform Public

console: alerts fix round 1 (door bodies capped, unsubscribed status, paused confirm, kept threshold, honest history note)

Ruling R-35:
- The public doors' POSTs read at most 4 KiB, URL-encoded only, before
  the token is touched: a large body answers 413, a multipart one 415.
- A connector its recipient turned off says so on the page; a test that
  gets through resumes it and clears the unsubscribed marker in the same
  transaction.
- Confirming a connector that is turned off says alerts are paused.
- A rule saved without a threshold keeps the stored one.
- History reads 201 rows and shows 200, so the older-incidents note
  appears only when one is hidden.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 0d1c147fb60dd4dd166bca45830b7c831099c916 parent 297e535
4 files changed, +273 −24
  • docs/superpowers/notes/copy-fleet-alerts-1.md +2 −0
  • internal/console/alertpages.go +86 −22
  • internal/console/alertpages_test.go +142 −0
  • internal/console/alertstore.go +43 −2

CI failed — run details

Intent

Human

<task-notification> <task-id>a634b77cb82f351e3</task-id> <tool-use-id>toolu_019eGTckgoE712dWSNZWnicc</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a634b77cb82f351e3.output</output-file> <status>completed</status> <summary>Agent "Implement Task 10: /fleet/alerts pages" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **Status:** DONE_WITH_CONCERNS. The `/fleet/alerts` pages, the public token doors, the registry entries and the census re-pin are built and committed; the concerns are small and listed below. - **Commits:** - `dbc2ee94` console: alert store for the token doors, confirmation limit, reasons in lower case (R-33) - `25721132` console: /fleet/alerts pages and token doors - `297e5359` console: fleet alerts routes in the registries; NewServer record-write census re-pinned - **Tests:** both commands from the brief pass, and so does a wider run covering every existing alert test, the shell gate tests and the perf walk. All 13 new claim probes pass when run by name. The parent test then fails only on 43 "reached by no door" lines, because filtering skips the doors; I did not run the full Claim group, per the carry. Two other notes: - `TestPlan14RootReadCensus` fails on Task 1-3 files only (none in `internal/console`); constraints.md leaves that census to Task 11. - **POST route pattern:** the four operator POST routes are registered without a method, following `/fleet/economics/scenarios`, so a wrong method gets the same 404 as an unknown route. The other nearby example, `POST /fleet/store/{account}/{decision}`, uses a method prefix and would answer a wrong method with a 405 that gives the route away. - **Concerns:** 1. An email connector can't be sent a new confirm link. Once its 7-day link expires, the operator has to delete it and add it again. 2. The Slack test is queued, as the carry says, so it is sent within about a minute. On a host-claim console the engine is off and it never goes. 3. A test to an unconfirmed Slack connector uses up one confirmation even if the 10-an-hour test limit then refuses it. 4. The public doors have no per-IP rate limit, so the deck's "too many tries" line is unused. 5. `GET /fleet/alerts` and `GET /alerts/signing-key` are classed as writes (nonApp), not reads, because both create the signing key on first use. The brief expected the page to be a read probe. - **New strings:** seven "derived (Task 10)" strings are in the deck and listed in the report. - **Report:** `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-10-report.md`</result> <usage><subagent_tokens>405720</subagent_tokens><tool_uses>126</tool_uses><duration_ms>2097849</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a08483946148e66be</task-id> <tool-use-id>toolu_012s5Sgi7SMGnvm976ssiCDW</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a08483946148e66be.output</output-file> <status>completed</status> <summary>Agent "Review Task 10 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Spec Compliance - ✅ Spec compliant. I read the diff in five passes: header, deck and alertnotify; alertpages.go; alertpages_test.go; alertstore.go; then registries, limits, templates and census. Every listed file has its hunk, and every brief and carry item is built. - **Copy.** I compared the code mechanically against the deck's groups 14-18 with the Luna rows applied. Every key in `alertPageCopy` (alertpages.go:24-175) matches its Luna row, or the deck draft where Luna has none. Only the 8 keys the report lists go unused. The 7 derived strings are in the deck and marked "derived (Task 10)". - **R-33.** `alertTestFailure.Reason()` (alertnotify.go, diff 275-282) lower-cases the reason after the colon. It is used in `conn.added.webhook.failed` (alertpages.go:541). - **Doors.** - Each GET only peeks. `PeekAlertToken` (alertstore.go:1067) is a read with no transaction. - Tokens are checked against their action, scope and connector. `readAlertToken` refuses another action, `alertDoorConnector` matches scope, and `ConfirmAlertConnectorByToken` and `UnsubscribeAlertConnector` update `WHERE id = ? AND scope = ?`. - Confirm is one transaction that spends the token and confirms the connector. `spendAlertToken` (alertstore.go:1102) checks `RowsAffected`, and `ConfirmAlertConnectorByToken` (alertstore.go:1122) does both steps in one transaction. - Unsubscribe suspends the connector, keeps the first suspension time, and writes the marker with INSERT OR IGNORE (alertstore.go:1156). It never deletes. - Snooze accepts exactly 1h, 1d or 1w and sets the time through `Store.Snooze` (alertpages.go:890-913). - Every door response sends `Referrer-Policy: no-referrer`. - There is no open redirect. `alertsBack` always goes to the fixed `/fleet/alerts#` with a validated rule or an integer id, and door forms post back to their own path. - **Operator gate.** The GETs call `operatorOnly` first. The POSTs check the method, then `operatorOnly`, then `storeFormCSRF` (alertpages.go:431), which applies a 1 MiB cap and a constant-time compare (storepage.go:75-86). - `alertPathConnector` (alertpages.go:455) returns 404 for a connector in another scope. - Rule save rejects a connector id that is not in the fleet (alertpages.go:656) and an unknown rule. - R-29 bounds are enforced (alertpages.go:665). A threshold posted for a box rule is dropped. - **Targets.** Only `TargetHint` reaches the page (alertpages.go `alertConnectorRow`). The refused URL is never echoed, and `TestFleetAlertsSecretNeverRendered` covers both pages. - **Confirmation limits.** I grepped for every producer of a `verify` row. The only one is `AddAlertConnectorVerify` (alertstore.go:714, insert at :724), which is charged at alertpages.go:557. The only other path that mints a confirm link is `sendTestAlert`, which calls `addAlertLinks` for an unconfirmed Slack connector; it is charged at alertpages.go:587. `alertConfirmSend` allows 5 an hour and 20 a day, all or nothing, and is in `sweepWindows`. - **Templates.** - None of alertpages.go or the three templates uses `template.HTML` or `template.URL`. - I checked the helpers the templates use: `opPill`, `opEmpty` and `opHeader` return structs (server.go:230-235), and `op_status`, `op_empty` and `op_flash` print plain auto-escaped fields (opparts.html). - **Registries.** - The `opRail` entry is after Metrics (opshell.go). - claim-routes.txt adds 13 routes. The fixtures classify all 13 (4 claimRead, 9 claimNonApp, the two key GETs per R-34), and there are 13 probes (4 read, 9 nonApp, each nonApp probe with a SQLite effect check). - perf-budgets has 8 skips, and `/fleet/alerts` and `/fleet/alerts/history` are walked. - opshots has both pages. - **Census.** `plan9_b8_census_test.go:369` now selects `fleetAlertsWriteCensusInventory()`, which builds on `fleetPublicRoutesWriteCensusInventory()`, the inventory it selected before. I ran `go test ./internal/provision -run 'TestPlan9B8RecordWriteCensus$' -count=1` (sandbox off because the Go cache is read-only inside it): `ok 2.267s`. The re-pin `09ac87c2…f599` matches `NewServer`. - ⚠️ Cannot verify from the diff: - The report says `TestPlan14RootReadCensus` fails on entries in `internal/host`, `status`, `metrics` and `alerting`, from Tasks 1-3. Constraints put that proposal in Task 11. The controller should confirm it is tracked there. - The report's filtered probe run showed 43 "app-scoped writer … reached by no door's open run" lines. These come from filtering by name, not from this task. The full Claim group still needs one run in CI. ### Strengths - The confirm path closes the Task 4 deferred minor. Spending the token and confirming the connector happen in one transaction, and the `RowsAffected` check makes one use mean one use. A refused token spends nothing, and a test proves it (alertpages_test.go `TestAlertDoorWrongActionRefused`). - The token errors are typed (`errAlertTokenAction`, `errAlertTokenExpired` and `errAlertTokenUsed`, each wrapping `errAlertTokenInvalid`). Doors can now give exact refusals, and existing `errors.Is` callers keep working. - `AddAlertConnectorVerify` means a connector is never stored without its queued confirmation. - The methodless registration for operator POSTs keeps a wrong method on the same 404 as an unknown route, even for an operator, and `TestFleetAlertsNotOperator404` asserts that. - The tests use the real HTTP path and SQLite: drain → Slack request → confirm link → POST → confirmed. The nonApp probes check their effects in SQLite. The copy guard (`TestAlertPageCopyVoice`) and the rule-coverage guard (`TestAlertRuleOrderCoversEveryRule`) are cheap protection against regressions. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) None. #### Minor (Nice to Have) 1. **alertpages.go:899, unbounded body on a public POST.** `handleAlertSnooze` calls `r.FormValue("for")` on an unauthenticated door. Nothing caps the body: `registerRoute` (claim_routes.go:68) adds no limit, and this handler doesn't call `storeFormCSRF`. A multipart body goes through `ParseMultipartForm(32 MiB)`, and file parts can spill to temp files. Only someone holding a valid snooze token can reach it, but those links go to Slack channels and inboxes and last 30 days. Fix: `r.Body = http.MaxBytesReader(w, r.Body, 4&lt;&lt;10)` before reading the form. 2. **alertpages.go:389, an unsubscribe looks like any other suspension.** A connector the recipient turned off reads "Suspended since X. Send a test to turn it back on.", the same as one suspended for failing. The `unsubscribed:&lt;id&gt;` marker is written but nothing reads it. An operator can re-enable an email recipient who opted out without knowing they opted out. R-11 allows the re-enable, but the page should at least say the person stopped the alerts. 3. **alertpages.go:819, confirm wording on a suspended connector.** If a connector is unsubscribed and then confirmed (or confirmed while suspended), the door says "Confirmed. Alerts now go to X." Nothing is sent, because confirm does not lift the suspension. This is an edge case, but the page says something false. 4. **alertpages.go:665, a blank threshold resets to the default.** If `threshold` is empty or missing on `box_silent` or `cert_expiring`, the saved threshold is replaced with nil (the default) without a word. The form always fills the field, so this needs a hand-made POST. Either keep the stored value when the field is absent, or refuse it. 5. **alertpages.go:557 and :587, limit charged before the write.** A failed `AddAlertConnectorVerify` still uses a confirmation. Same family as the deferred "unconfirmed Slack test spends a confirmation". 6. **alertpages.go:495, no cap on the connector name.** Only the 1 MiB form cap applies. Duplicate `connector` values in a rule save (alertpages.go:656) are passed to `SetAlertRule` without being removed. 7. **ops_alerts.html:24 and ops_alerts_history.html:18, an em dash placeholder.** `emptyOrDash` renders "—" in an empty cell. It is the shared operator-page placeholder and not prose, but it is an em dash in user-facing output. Affected is empty for an incident with no members. 8. **Copy polish in approved text, not this task's doing.** `rules.noise` (alertpages.go:121) renders "Fired 1 times." `rules.th.disk_eta` (:106) reads "Default 72 hours." while the other three say "Default: 90 percent." These are worth a deck note. 9. **Test gaps.** No test covers: - test or delete on a connector in another scope (the 404 in `alertPathConnector`); - a rule save naming a connector in another scope; - a second confirm POST rendering `door.confirm.used`. 10. **alertpages.go:699, limit note at exactly 200.** "Older incidents are not shown." appears when exactly 200 exist and nothing is hidden. Fetch 201 rows and show 200 to tell the cases apart. 11. **alertpages.go size.** The new file is 926 lines, about 150 of them copy. The public doors (alertpages.go:737-926) could move to their own `alertdoors.go`. ### Assessment **Task quality:** Approved **Reasoning:** The security boundary holds. GETs never act, tokens stay bound to their action, scope and connector, confirm is atomic, unsubscribe and snooze behave as the rulings say, and every operator route is gated and CSRF-checked. Only `target_hint` is ever rendered. The copy matches the deck with Luna applied, and the census re-pin passes. What remains is hardening and polish, led by a body cap on the public snooze POST.</result> <usage><subagent_tokens>172712</subagent_tokens><tool_uses>26</tool_uses><duration_ms>366324</duration_ms></usage> </task-notification>

Attributed to this commit: 24.7 g CO₂e (3,172,456 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-fleet-alerts, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/superpowers/notes/copy-fleet-alerts-1.md b/docs/superpowers/notes/copy-fleet-alerts-1.md
index 01bd59b5c..43dc96d8d 100644
--- a/docs/superpowers/notes/copy-fleet-alerts-1.md
+++ b/docs/superpowers/notes/copy-fleet-alerts-1.md
@@ -364,6 +364,7 @@ The page is operator-only. Draft layout: page header, a Connectors section, a Ru
| `new:conn.status.unconfirmed` | `Waiting for confirmation` | Status cell | |
| `new:conn.status.suspended` | `Suspended. Sending has failed since %s.` | Status cell | `%s` is a time. A test that gets through turns it back on. |
| `new:conn.status.reentry` | `Enter the URL again` | Status cell | The key that opened it was lost. See `seal_key`. |
+| `conn.status.unsubscribed` | `The recipient turned these alerts off on %s. Send a test to turn them back on.` | Status cell, a connector turned off from its unsubscribe link | derived (R-35). `%s` is the time. A test that gets through turns it back on and drops this. |
| `new:conn.owner` | `Added for %s` | Note under the name of a seeded connector | `%s` is the operator's sign-in address. |
| `new:conn.btn.test` | `Send test` | Button on each row | |
| `new:conn.btn.delete` | `Delete` | Button on each row | |
@@ -487,6 +488,7 @@ Reached from an emailed or posted link. Anyone holding the link can open the pag
| `new:door.confirm.btn` | `Confirm` | Button | |
| `new:door.confirm.done` | `Confirmed. Alerts now go to %s.` | After the POST | |
| `new:door.confirm.used` | `This link has been used already. Alerts to %s are on.` | Reusing a confirm link | One use. |
+| `door.confirm.paused` | `Confirmed. Alerts to %s are paused. An operator can turn them back on.` | After the confirm POST, when the connector is turned off | derived (R-35). Never says alerts go there. |
| `door.confirm.failed` | `Confirming did not work. Ask an operator to send a new link from the Alerts page.` | A confirm POST that failed on the console's side; the link and the connector are left as they were | derived (Task 10), per the carry: on failure, ask for a new link. |
| `new:door.unsub.heading` | `Stop alerts to %s` | Unsubscribe page heading | |
| `new:door.unsub.body` | `This turns off this connector. Nothing more is sent to it. Other connectors are not changed. An operator can add it again from the Alerts page.` | Unsubscribe page | The link turns off the whole connector, not one rule. |
diff --git a/internal/console/alertpages.go b/internal/console/alertpages.go
index 9ffd2abac..c60f1120f 100644
--- a/internal/console/alertpages.go
+++ b/internal/console/alertpages.go
@@ -28,21 +28,23 @@ var alertPageCopy = map[string]string{
// derived (Task 10): the page could not read its own tables.
"page.err": "Alerts could not be read.",
- "conn.heading": "Connectors",
- "conn.help": "A connector is where alerts are sent. Add Slack, an email address or a webhook.",
- "conn.empty": "No connectors. Alerts are recorded but sent nowhere. Add one to receive them.",
- "conn.col.name": "Name",
- "conn.col.kind": "Kind",
- "conn.col.target": "Sent to",
- "conn.col.status": "Status",
- "kind.slack": "Slack",
- "kind.email": "Email",
- "kind.webhook": "Webhook",
- "conn.target.secret": "%s, ends in %s",
- "conn.status.on": "On",
- "conn.status.unconfirmed": "Waiting for confirmation",
- "conn.status.suspended": "Suspended since %s. Send a test to turn it back on.",
- "conn.status.reentry": "Enter the URL again",
+ "conn.heading": "Connectors",
+ "conn.help": "A connector is where alerts are sent. Add Slack, an email address or a webhook.",
+ "conn.empty": "No connectors. Alerts are recorded but sent nowhere. Add one to receive them.",
+ "conn.col.name": "Name",
+ "conn.col.kind": "Kind",
+ "conn.col.target": "Sent to",
+ "conn.col.status": "Status",
+ "kind.slack": "Slack",
+ "kind.email": "Email",
+ "kind.webhook": "Webhook",
+ "conn.target.secret": "%s, ends in %s",
+ "conn.status.on": "On",
+ "conn.status.unconfirmed": "Waiting for confirmation",
+ "conn.status.suspended": "Suspended since %s. Send a test to turn it back on.",
+ "conn.status.reentry": "Enter the URL again",
+ // derived (R-35): a connector turned off from its unsubscribe link.
+ "conn.status.unsubscribed": "The recipient turned these alerts off on %s. Send a test to turn them back on.",
"conn.owner": "Added for %s",
"conn.btn.test": "Send test",
"conn.btn.delete": "Delete",
@@ -149,6 +151,8 @@ var alertPageCopy = map[string]string{
"door.confirm.btn": "Confirm",
"door.confirm.done": "Confirmed. Alerts now go to %s.",
"door.confirm.used": "This link has been used already. Alerts to %s are on.",
+ // derived (R-35): confirmed, but the connector is still turned off.
+ "door.confirm.paused": "Confirmed. Alerts to %s are paused. An operator can turn them back on.",
// derived (Task 10): confirming failed; the link is left as it was.
"door.confirm.failed": "Confirming did not work. Ask an operator to send a new link from the Alerts page.",
"door.unsub.heading": "Stop alerts to %s",
@@ -299,7 +303,7 @@ type alertRuleConnectorView struct {
type alertHistoryView struct {
Rows []alertHistoryRow
- // Full is a page holding alertHistoryLimit rows, with older ones unshown.
+ // Full is a page with older incidents than it shows.
Full bool
}
@@ -352,6 +356,10 @@ func (s *Server) alertsView() (*alertsView, error) {
if err != nil {
return nil, err
}
+ unsubscribed, err := s.store.AlertUnsubscribes()
+ if err != nil {
+ return nil, err
+ }
key, err := s.store.AlertSigningKey()
if err != nil {
return nil, err
@@ -361,7 +369,7 @@ func (s *Server) alertsView() (*alertsView, error) {
PublicKey: alertPublicKey(key),
}
for _, c := range conns {
- v.Connectors = append(v.Connectors, alertConnectorRow(c))
+ v.Connectors = append(v.Connectors, alertConnectorRow(c, unsubscribed[c.ID]))
}
for _, k := range []struct{ kind, input string }{
{alertConnectorSlack, "url"}, {alertConnectorEmail, "email"}, {alertConnectorWebhook, "url"},
@@ -375,7 +383,10 @@ func (s *Server) alertsView() (*alertsView, error) {
return v, nil
}
-func alertConnectorRow(c alertConnector) alertConnectorView {
+// alertConnectorRow is c's row. unsubscribedAt is when its recipient turned
+// it off from an unsubscribe link, zero when they did not: a suspension
+// they asked for says so, not that sending failed (ruling R-35).
+func alertConnectorRow(c alertConnector, unsubscribedAt time.Time) alertConnectorView {
name := alertConnectorName(c)
v := alertConnectorView{ID: c.ID, Name: name, Kind: alertPageCopy["kind."+c.Kind], Target: c.TargetHint,
DeleteAsk: fmt.Sprintf(alertPageCopy["conn.delete.confirm"], name)}
@@ -385,6 +396,8 @@ func alertConnectorRow(c alertConnector) alertConnectorView {
switch {
case c.NeedsReentry:
v.Status, v.Tone = alertPageCopy["conn.status.reentry"], "negative"
+ case c.Suspended && !unsubscribedAt.IsZero():
+ v.Status, v.Tone = fmt.Sprintf(alertPageCopy["conn.status.unsubscribed"], alertPageTime(unsubscribedAt)), "negative"
case c.Suspended:
v.Status, v.Tone = fmt.Sprintf(alertPageCopy["conn.status.suspended"], alertPageTime(c.SuspendedAt)), "negative"
case !c.Confirmed:
@@ -647,6 +660,12 @@ func (s *Server) handleAlertRuleSave(w http.ResponseWriter, r *http.Request) {
anchor := "rule-" + rule
fail := func(msg string) { s.alertsBack(w, r, anchor, "err", msg) }
st := alertRuleSetting{Enabled: r.PostFormValue("enabled") == "on"}
+ settings, err := s.store.AlertRuleSettings(alertScopeFleet)
+ if err != nil {
+ log.Printf("console: alert rule %s: %v", rule, err)
+ fail(alertPageCopy["conn.err.failed"])
+ return
+ }
conns, err := s.store.AlertConnectors(alertScopeFleet)
if err != nil {
log.Printf("console: alert rule %s: %v", rule, err)
@@ -662,6 +681,8 @@ func (s *Server) handleAlertRuleSave(w http.ResponseWriter, r *http.Request) {
st.ConnectorIDs = append(st.ConnectorIDs, id)
}
if b, ok := alertThresholdBounds[rule]; ok {
+ // No threshold in the form keeps the one stored (ruling R-35).
+ st.Threshold = settings[rule].Threshold
if raw := strings.TrimSpace(r.PostFormValue("threshold")); raw != "" {
n, err := strconv.Atoi(raw)
if err != nil || n < b[0] || n > b[1] {
@@ -689,14 +710,17 @@ func (s *Server) handleFleetAlertHistory(w http.ResponseWriter, r *http.Request)
if !ok {
return
}
- ins, err := s.store.RecentAlertIncidents(alertScopeFleet, alertHistoryLimit)
+ // One more than is shown, so "older incidents are not shown" is said
+ // only when one is (ruling R-35).
+ ins, err := s.store.RecentAlertIncidents(alertScopeFleet, alertHistoryLimit+1)
if err != nil {
log.Printf("console: alert history: %v", err)
s.renderMessage(w, r, http.StatusInternalServerError, "Unavailable", alertPageCopy["page.err"])
return
}
now := s.alertClockNow()
- v := &alertHistoryView{Full: len(ins) >= alertHistoryLimit}
+ v := &alertHistoryView{Full: len(ins) > alertHistoryLimit}
+ ins = ins[:min(len(ins), alertHistoryLimit)]
for _, in := range ins {
v.Rows = append(v.Rows, alertHistoryRowOf(in, now))
}
@@ -762,6 +786,33 @@ func (s *Server) alertDoorRefused(w http.ResponseWriter, door string, err error,
s.renderAlertDoor(w, status, alertDoorView{Error: alertPageCopy[key]})
}
+// alertDoorMaxForm is the most of a door POST's body read: its form is one
+// short field at most.
+const alertDoorMaxForm = 4 << 10
+
+// alertDoorForm reads a public door POST's form before anything acts on it
+// (ruling R-35): at most alertDoorMaxForm bytes, URL-encoded only. A
+// multipart body is refused unread; r.FormValue would parse one, files and
+// all, so the doors read r.Form after this and never FormValue. false
+// means the refusal is written.
+func (s *Server) alertDoorForm(w http.ResponseWriter, r *http.Request) bool {
+ r.Body = http.MaxBytesReader(w, r.Body, alertDoorMaxForm)
+ if strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/") {
+ s.renderAlertDoor(w, http.StatusUnsupportedMediaType, alertDoorView{Error: alertPageCopy["door.err.failed"]})
+ return false
+ }
+ if err := r.ParseForm(); err != nil {
+ status := http.StatusBadRequest
+ var tooBig *http.MaxBytesError
+ if errors.As(err, &tooBig) {
+ status = http.StatusRequestEntityTooLarge
+ }
+ s.renderAlertDoor(w, status, alertDoorView{Error: alertPageCopy["door.err.failed"]})
+ return false
+ }
+ return true
+}
+
// alertDoorConnector is the connector token t is bound to; sql.ErrNoRows
// when it is gone or not in the token's scope.
func (s *Server) alertDoorConnector(t alertToken) (alertConnector, error) {
@@ -801,6 +852,9 @@ func (s *Server) handleAlertConfirmPage(w http.ResponseWriter, r *http.Request)
// one transaction (ConfirmAlertConnectorByToken): a failure leaves both as
// they were, and the page says to ask for a new link.
func (s *Server) handleAlertConfirm(w http.ResponseWriter, r *http.Request) {
+ if !s.alertDoorForm(w, r) {
+ return
+ }
raw := r.PathValue("token")
now := s.alertClockNow()
c, err := s.store.ConfirmAlertConnectorByToken(raw, now)
@@ -816,7 +870,11 @@ func (s *Server) handleAlertConfirm(w http.ResponseWriter, r *http.Request) {
return
}
log.Printf("console: alert connector %d confirmed from its link", c.ID)
- s.renderAlertDoor(w, http.StatusOK, alertDoorView{Done: fmt.Sprintf(alertPageCopy["door.confirm.done"], alertConnectorName(c))})
+ done := "door.confirm.done"
+ if c.Suspended {
+ done = "door.confirm.paused" // confirmed, but nothing goes there until it is turned back on
+ }
+ s.renderAlertDoor(w, http.StatusOK, alertDoorView{Done: fmt.Sprintf(alertPageCopy[done], alertConnectorName(c))})
}
// alertConfirmUsed answers a confirm link already used: alerts there are
@@ -853,6 +911,9 @@ func (s *Server) handleAlertUnsubscribePage(w http.ResponseWriter, r *http.Reque
// handleAlertUnsubscribe turns the link's connector off
// (UnsubscribeAlertConnector). Again is the same answer.
func (s *Server) handleAlertUnsubscribe(w http.ResponseWriter, r *http.Request) {
+ if !s.alertDoorForm(w, r) {
+ return
+ }
c, err := s.store.UnsubscribeAlertConnector(r.PathValue("token"), s.alertClockNow())
if err != nil {
s.alertDoorRefused(w, "unsubscribe", err, "door.err.failed")
@@ -888,6 +949,9 @@ func (s *Server) handleAlertSnoozePage(w http.ResponseWriter, r *http.Request) {
// the offered lengths, from now: a later use replaces the snooze and never
// adds to it (Store.Snooze). Any other length is refused.
func (s *Server) handleAlertSnooze(w http.ResponseWriter, r *http.Request) {
+ if !s.alertDoorForm(w, r) {
+ return
+ }
now := s.alertClockNow()
t, err := s.store.UseAlertToken(r.PathValue("token"), alertTokenSnooze, now)
if err != nil {
@@ -896,7 +960,7 @@ func (s *Server) handleAlertSnooze(w http.ResponseWriter, r *http.Request) {
}
var d time.Duration
for _, l := range alertSnoozeLengths {
- if r.FormValue("for") == l.For {
+ if r.Form.Get("for") == l.For {
d = l.D
}
}
diff --git a/internal/console/alertpages_test.go b/internal/console/alertpages_test.go
index f232b8c01..4e9a8370a 100644
--- a/internal/console/alertpages_test.go
+++ b/internal/console/alertpages_test.go
@@ -4,6 +4,7 @@ import (
"html"
"io"
"maps"
+ "mime/multipart"
"net/http"
"net/url"
"regexp"
@@ -594,3 +595,144 @@ func TestFleetAlertsHistoryAnchors(t *testing.T) {
t.Error("history is not newest first")
}
}
+
+// A door's POST reads at most a short URL-encoded form: a large body or a
+// multipart one is refused before the token is touched (ruling R-35).
+func TestAlertDoorRefusesLargeOrMultipartBody(t *testing.T) {
+ af := newAlertsPageFixture(t)
+ id := af.addEmail(t, alertScopeFleet, "a@example.com", "", false)
+ confirm, _, snooze := doorTokens(t, af, id)
+ door := newBrowser(t)
+ post := func(path, ctype string, body io.Reader) int {
+ t.Helper()
+ res, err := door.Post(af.ts.URL+path, ctype, body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ return res.StatusCode
+ }
+ big := "for=1h&pad=" + strings.Repeat("x", 8<<10)
+ if st := post("/alerts/snooze/"+snooze, "application/x-www-form-urlencoded", strings.NewReader(big)); st != http.StatusRequestEntityTooLarge {
+ t.Errorf("a large snooze body = %d, want 413", st)
+ }
+ if st := post("/alerts/confirm/"+confirm, "application/x-www-form-urlencoded", strings.NewReader(big)); st != http.StatusRequestEntityTooLarge {
+ t.Errorf("a large confirm body = %d, want 413", st)
+ }
+ var mp strings.Builder
+ w := multipart.NewWriter(&mp)
+ if err := w.WriteField("for", "1h"); err != nil {
+ t.Fatal(err)
+ }
+ w.Close()
+ if st := post("/alerts/snooze/"+snooze, w.FormDataContentType(), strings.NewReader(mp.String())); st != http.StatusUnsupportedMediaType {
+ t.Errorf("a multipart snooze = %d, want 415", st)
+ }
+ if _, ok := af.snoozeUntil(t); ok {
+ t.Fatal("a refused body snoozed")
+ }
+ if c := af.connector(t, id); c.Confirmed {
+ t.Fatal("a refused body confirmed")
+ }
+ // A short form still works.
+ if st, _, _ := postForm(t, door, af.ts.URL+"/alerts/snooze/"+snooze, url.Values{"for": {"1h"}}); st != http.StatusOK {
+ t.Fatalf("a plain snooze = %d", st)
+ }
+}
+
+// A connector its recipient turned off says so, and a test that gets
+// through turns it back on and clears that (ruling R-35).
+func TestFleetAlertsUnsubscribedStatus(t *testing.T) {
+ af := newAlertsPageFixture(t)
+ id := af.addEmail(t, alertScopeFleet, "a@example.com", "", true)
+ _, unsub, _ := doorTokens(t, af, id)
+ if st, _, _ := postForm(t, newBrowser(t), af.ts.URL+"/alerts/unsubscribe/"+unsub, url.Values{}); st != http.StatusOK {
+ t.Fatalf("unsubscribe = %d", st)
+ }
+ want := "The recipient turned these alerts off on " + alertPageTime(af.now) + ". Send a test to turn them back on."
+ body := af.page(t, "/fleet/alerts")
+ if !strings.Contains(body, want) || strings.Contains(body, "Suspended since") {
+ t.Fatalf("the row does not say the recipient turned it off:\n%s", body)
+ }
+ if st, _ := af.post(t, "/fleet/alerts/connectors/"+itoa(id)+"/test"); st != http.StatusSeeOther {
+ t.Fatalf("test = %d", st)
+ }
+ if c := af.connector(t, id); c.Suspended {
+ t.Fatal("a test that got through left it off")
+ }
+ var n int
+ if err := af.st.db.QueryRow(`SELECT COUNT(*) FROM alert_meta WHERE k = ?`, alertUnsubscribedMarker(id)).Scan(&n); err != nil || n != 0 {
+ t.Fatalf("the unsubscribed marker outlived the resume (%d, %v)", n, err)
+ }
+ if body := af.page(t, "/fleet/alerts"); strings.Contains(body, "The recipient turned these alerts off") {
+ t.Fatal("the row still says the recipient turned it off")
+ }
+}
+
+// Confirming a connector its recipient has turned off does not say alerts
+// go there (ruling R-35).
+func TestAlertDoorConfirmWhilePaused(t *testing.T) {
+ af := newAlertsPageFixture(t)
+ id := af.addEmail(t, alertScopeFleet, "a@example.com", "", false)
+ confirm, unsub, _ := doorTokens(t, af, id)
+ door := newBrowser(t)
+ postForm(t, door, af.ts.URL+"/alerts/unsubscribe/"+unsub, url.Values{})
+ st, _, body := postForm(t, door, af.ts.URL+"/alerts/confirm/"+confirm, url.Values{})
+ if st != http.StatusOK || !strings.Contains(body, "Confirmed. Alerts to a@example.com are paused. An operator can turn them back on.") ||
+ strings.Contains(body, "Alerts now go to") {
+ t.Fatalf("confirm while off = %d %s", st, body)
+ }
+ if c := af.connector(t, id); !c.Confirmed || !c.Suspended {
+ t.Fatalf("connector = %+v, want confirmed and still off", c)
+ }
+}
+
+// A rule saved without a threshold keeps the one stored (ruling R-35).
+func TestFleetAlertsRuleSaveKeepsThreshold(t *testing.T) {
+ af := newAlertsPageFixture(t)
+ threshold := func() *float64 {
+ t.Helper()
+ settings, err := af.st.AlertRuleSettings(alertScopeFleet)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return settings["cert_expiring"].Threshold
+ }
+ af.post(t, "/fleet/alerts/rules/cert_expiring", "enabled", "on", "threshold", "30")
+ af.post(t, "/fleet/alerts/rules/cert_expiring", "enabled", "on")
+ if th := threshold(); th == nil || *th != 30 {
+ t.Fatalf("no threshold field: %v, want 30 kept", th)
+ }
+ af.post(t, "/fleet/alerts/rules/cert_expiring", "threshold", " ")
+ settings, _ := af.st.AlertRuleSettings(alertScopeFleet)
+ if th := settings["cert_expiring"].Threshold; th == nil || *th != 30 || settings["cert_expiring"].Enabled {
+ t.Fatalf("empty threshold, rule off: %+v, want off with 30 kept", settings["cert_expiring"])
+ }
+}
+
+// "Older incidents are not shown" only when one is hidden (ruling R-35).
+func TestFleetAlertsHistoryLimitOnlyWhenHidden(t *testing.T) {
+ af := newAlertsPageFixture(t)
+ add := func(n int) {
+ t.Helper()
+ ins := make([]alertIncident, n)
+ for i := range ins {
+ ins[i] = alertIncident{Scope: alertScopeFleet, Rule: "disk", Level: "incident", OpenedAt: af.now, NotifyAt: af.now,
+ ClosedAt: af.now, CloseReason: alertCloseCleared, Members: []string{"box-1"}}
+ }
+ if err := af.st.CommitAlertStep(ins, nil, nil); err != nil {
+ t.Fatal(err)
+ }
+ }
+ add(alertHistoryLimit)
+ body := af.page(t, "/fleet/alerts/history")
+ if strings.Contains(body, alertPageCopy["hist.limit"]) || strings.Count(body, `id="incident-`) != alertHistoryLimit {
+ t.Fatalf("exactly %d incidents: limit note shown or rows missing", alertHistoryLimit)
+ }
+ add(1)
+ body = af.page(t, "/fleet/alerts/history")
+ if !strings.Contains(body, alertPageCopy["hist.limit"]) || strings.Count(body, `id="incident-`) != alertHistoryLimit ||
+ strings.Contains(body, `id="incident-1"`) {
+ t.Fatalf("%d incidents: want the note, %d rows, the oldest hidden", alertHistoryLimit+1, alertHistoryLimit)
+ }
+}
diff --git a/internal/console/alertstore.go b/internal/console/alertstore.go
index 5a5557fe0..595a3b159 100644
--- a/internal/console/alertstore.go
+++ b/internal/console/alertstore.go
@@ -693,9 +693,50 @@ func (s *Store) AlertConnector(id int64) (alertConnector, error) {
// ResumeAlertConnector lifts connector id's suspension and clears its
// failing clock, after a test send got through (ruling R-11): the way back
// for a suspended connector short of deleting and re-adding it.
+//
+// It also clears the connector's unsubscribed:<id> marker in the same
+// transaction (ruling R-35): once a test has turned it back on, the page no
+// longer says the recipient turned it off.
func (s *Store) ResumeAlertConnector(id int64) error {
- _, err := s.db.Exec(`UPDATE alert_connectors SET suspended_at = 0, failing_since = 0 WHERE id = ?`, id)
- return err
+ tx, err := s.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ if _, err := tx.Exec(`UPDATE alert_connectors SET suspended_at = 0, failing_since = 0 WHERE id = ?`, id); err != nil {
+ return err
+ }
+ if _, err := tx.Exec(`DELETE FROM alert_meta WHERE k = ?`, alertUnsubscribedMarker(id)); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// AlertUnsubscribes is when each connector carrying an unsubscribed:<id>
+// marker was turned off from its link, by connector id.
+func (s *Store) AlertUnsubscribes() (map[int64]time.Time, error) {
+ rows, err := s.db.Query(`SELECT k, v FROM alert_meta WHERE k LIKE 'unsubscribed:%'`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := map[int64]time.Time{}
+ for rows.Next() {
+ var k, v string
+ if err := rows.Scan(&k, &v); err != nil {
+ return nil, err
+ }
+ var id int64
+ if _, err := fmt.Sscanf(k, "unsubscribed:%d", &id); err != nil {
+ continue
+ }
+ at, err := time.Parse(time.RFC3339, v)
+ if err != nil {
+ return nil, fmt.Errorf("alert meta %s: %w", k, err)
+ }
+ out[id] = at.UTC()
+ }
+ return out, rows.Err()
}
// AddAlertConnector stores c with its target: sealed for Slack and webhook,