carlos / platform Public

console: alert store for the token doors, confirmation limit, reasons in lower case (R-33)

The store gains what the Alerts pages and doors need: a confirm link
spent and its connector confirmed in one transaction, an unsubscribe that
suspends and records rather than deletes, a read-only token peek for the
doors' GETs, typed token refusals, a connector added with its verify row
in one transaction, recent incidents and per-rule noise counts.

emailLimits gets the per-scope alert confirmation window (5 an hour, 20
a day). A failed test keeps its reason, which reads in lower case after
the colon.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev dbc2ee9445f299a6032f85e2dc7b88f33efb6f5f parent e947788
5 files changed, +292 −41
  • internal/console/alertcopy_test.go +14 −13
  • internal/console/alertnotify.go +19 −2
  • internal/console/alertstore.go +225 −18
  • internal/console/emailsignin_limits.go +27 −1
  • internal/console/emailsignin_limits_test.go +7 −7

Intent

Human

<task-notification> <task-id>ae3253d9d019a76a8</task-id> <tool-use-id>toolu_01UDoWDnHRvZ6XZWav52bUS7</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/ae3253d9d019a76a8.output</output-file> <status>completed</status> <summary>Agent "Task 9 step 3: apply approved copy" 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 **Commit:** `e9477883` console: lower-case a rule name mid-sentence, email send category text (R-32). Earlier commits are `720682a2` and `fcd03a4a`. **R-32 items:** 1. New helper `alertMidSentence` lower-cases only a rule's display name. The "No further reports of ..." clears use it, so they now read "No further reports of box silent on box-9." The "has cleared" clears and the headlines keep the capital, because the name comes first or after a label. Box, host and service names are never changed. `TestAlertRuleNameCaseByPosition` covers both positions, a capitalised box name, the subjectless variants and an unknown rule ID. I read "mid-sentence" as the "No further reports of" lines only, so "Cleared: Box silent on box-9" keeps its capital. Say if you want the headlines lower-cased too. 2. `box.geoip.2` now reads "the location database on %s expires within 9 days". The deck row is marked "R-32 (case slip)". 3. `sendErr.email` is "Email delivery failed." in the code, and the deck row is marked "derived (R-32)". The dropped-stop handling is unchanged. The deck row for `new:test.failed` no longer says an unlisted category "shows as its code" for `email`. I also turned the old em dash comment at `alertengine_pass.go` into a full stop and a new sentence. The dash grep over the changed Go files is now empty. **Tests:** - Console `Alert|Render|Drain|Engine|Jobs|Step`, host `Alert|Sink|Format|Engine` and `go test . -run PrintLive` all pass. - `go vet` is clean on console, host and alerting. - I changed two expectations in `alertengine_pass_test.go` to the lower-case form. **Concerns:** None new. Items 4-6 stand as before. **Report:** `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-9-report.md` (fix report appended)</result> <usage><subagent_tokens>193031</subagent_tokens><tool_uses>56</tool_uses><duration_ms>1379153</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a82d25d323415161d</task-id> <tool-use-id>toolu_01WAeyFJXKAMHmY4mwW7oAqA</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a82d25d323415161d.output</output-file> <status>completed</status> <summary>Agent "Review Task 9 (copy applied)" 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 for Task 9 steps 1 to 4. The deck covers groups 1 to 18 with the Luna pass applied. Groups 14 to 18 are left as drafts for Task 10. The code carries the approved text for groups 1 to 13, and the commit message is "console: approved alert copy". - ⚠️ Cannot verify from the diff: the census envelopes. I ran `go test ./internal/provision -run 'TestPlan14RootReadCensus$'`. It fails with 10 discrepancies, the same set as `docs/superpowers/notes/census-card-fleet-alerts-1.txt`: `statusLoop`, `CollectBox`, `var engineBeatLstat`, and the envelopes `.`, `internal/alerting`, `internal/host`, `internal/metrics`, `internal/status`. That failure comes from Tasks 1 to 3, so it is not a Task 9 defect. But the census card's "Seal now" hash predates this task. The task adds `ruletext.go` and edits `alertsink.go` and `enginebeat.go`, and any change to a file in an envelope, even a comment, moves that envelope (`census_scope_test.go:12`). Run `make census-card` and the propose step after Task 9, not before. ### Named risks 1. **Verbatim: no deviations except the controller-ruled ones.** I checked about 50 Luna rows against the code. - Group 3: `default.how_long`, `default.what_to_do`, `disk_eta.how_long`, `disk_eta.what_to_do`, `disk.how_long`, `mem.how_long`, `cpu.how_long`, `lag.how_long`, `geoip.how_long`. - Group 3, engine silent: `what` (still keeps `%s`), `how_long`, `what_to_do`. - Group 3, others: `box_silent.what_to_do`, `service_down.what_to_do`, `cert_expiring.how_long` and `.what_to_do`, `alert_delivery_broken.how_long` and `.what_to_do`, and `seal_key.what` and `.what_to_do`. The `seal_key.what` placeholder is intact. - Group 4: `clear.how_long.gone` and `clear.what_to_do.gone`. - Other groups: all `sendErr.*` including `%d`, all 5 `hold.*`, all 8 `url.*` including `%q`, `link.unsubscribe`, `what.value`, `jobnote.seal`, and the three `errAlertTest*`. - Group 11 (`alertsink.go`): `box.body.another`, `box.clear.geoip`, `box.geoip.1` to `.5`, and `.other`. `box.geoip.2` differs only by the R-32 lower-case "location". - Group 13: `status.engine.why.root` and `.path`. `engineBeatEnv + " is not an absolute path"` expands to the Luna text (constant at `enginebeat.go:27`). - Group 3 is shared through `alerting.BoxRuleText`, so the console and box text cannot drift. 2. **Formatting: no `%!(` or empty text can reach a message.** - Every `Sprintf` in `alertEmitNote` and `alertHeadline` gets exactly its own verbs. `%[n]s` indexing suppresses EXTRA in `head.suspended` and `head.verify`. - All 12 rules have `.title`, `.what` and `.what.none`, so the `.none` lookups always hit. - The three `alertCopy["errAlertTest*"]` keys exist. - `TestAlertEmitNoteHasNoFormatErrors` is exhaustive over rule IDs. It takes all 12 from `alertRuleLevels` plus an unknown one. - It is also exhaustive over kinds: fire, update, reminder, and clear (cleared, gone, flapping). It tries 0, 1 and 2 members through email, Slack and webhook, and asserts non-empty `What`, `HowLong`, `WhatToDo`, headline and subject. - It is not fully exhaustive. See Minor 1 and 2. 3. **Box text promises no channel.** `formatAlert` and `BoxRuleText` never say email, Slack or "another". The test also lowercases and rejects "email" and "slack" over 7 rules, both firing states and 8 values (`alertsink_test.go:2140-2154`). 4. **`ruletext.go`:** it is strings only, with no functions. It holds two label consts, the `ReadingFormat` const, the `RuleText` struct and the `BoxRuleText` map, and it imports nothing. - Both sides read it consistently. The console `alertCopy` takes title, how-long, what-to-do, labels and `ReadingFormat` from it. The box takes the same four plus the title for the footer. A mutable exported map is the only wart (Minor 5). 5. **Dashes: none.** I grepped the em and en dash characters over every added line in the diff, including docs, and over the changed Go files. There are no hits. The one old em dash comment was removed, and no ` - ` dash appears in a string. ### Strengths - `alertEmitNote` and `alertHeadline` split cleanly into named and `.none` variants. Each string is rendered with exactly its own arguments. - `alertMidSentence` is scoped to the rule title only. A box name is never touched, and the test pins both capital and lower-case positions. - The box and console share one source (`ruletext.go`), and the box has its own separate `disk_eta` and `engine_silent` sentences, as R-31 required. - Stored codes (`sendErr`, `hold`) are unchanged, and the approved words are made at the edge in `alertWhyText`. - `TestValidConnectorURLWords` and `TestAlertTestFailedWords` pin the exact approved text. - `TestFormatAlertApprovedCopy` guards against raw rule IDs in the footer. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) None. #### Minor (Nice to Have) 1. `internal/console/alertcopy_test.go:72-79`: the comment says the test covers "a test, a confirmation and the suspended notice", but only `alertTestNote` is rendered. The suspended note (`tellAlertSuspended`, `alertnotify.go:~735`) is never rendered. Today it is correct: one `%s`, and `head.suspended` uses `%[2]s`. Render a `Kind: "suspended"` note, or fix the comment. 2. The test cannot see a missing key. A rule without its own `.title`, `.what.none`, `.how_long` or `.what_to_do` silently falls back to the ID or the default text, and the test still passes. Add an assertion that every `alertRuleLevels` key has all five keys. The geoip reading texts (`alertengine_pass.go:721-729`) are also not exercised beyond code 3. 3. `alertnotify.go:813-814` and `alertcopy_test.go:941-952`: the composed line is "The test did not get through: The address did not respond in time." The capital after the colon is the same class as R-32. Luna's two rows compose this way. The implementer reports dropping the doubled full stop but did not get a ruling on the capital. Either lower-case the reason's first letter in `alertTestFailed`, or accept it explicitly. Task 10's `conn.added.webhook.failed "(%s)"` will have the same issue. 4. Console geoip readings still use unreviewed jargon (`alertengine_pass.go:721`, "GeoLite2 database expires within 9 days"; `:729`, "geoip reason N"). They appear after "Reading:" on a console geoip fire. The box text now says "location database", and Luna removed the same term from `box.geoip.2`. Rows she did not list were approved as-is, so this is the controller's call. 5. `ruletext.go:28`: `BoxRuleText` is a mutable exported map. A function returning a copy would be safer if the file stays inside the census scope. Duplicated literals: the box hard-codes `"%.0f hours to full"` (`alertsink.go`, `disk_eta` block), while the console builds the same text in `alertValueText`. Share one constant to prevent drift. 6. Deck staleness (`docs/superpowers/notes/copy-fleet-alerts-1.md:221-230` and `:364-370`). "Flags for the reviewer" 1, 2, 3 and 6 are still written as open (job label, "another email", raw IDs, `%!(EXTRA`). Group 5 notes still say "The last reading was". Mark them resolved. 7. TDD: the report says tests were written after the code. Only the subjectless mutation shows a RED run. ### Assessment **Task quality:** Approved **Reasoning:** The Luna text and the R-27, R-31 and R-32 rulings are applied faithfully. No rendered message can carry format debris, the box text promises no channel, `ruletext.go` is strings only, and the diff has no dashes. The findings are test-coverage gaps and polish. The census envelopes need re-sealing after this task, as flagged above.</result> <usage><subagent_tokens>141600</subagent_tokens><tool_uses>17</tool_uses><duration_ms>228186</duration_ms></usage> </task-notification>

Human

how much left on this session?

Human

Doesn't look too bad

diff --git a/internal/console/alertcopy_test.go b/internal/console/alertcopy_test.go
index 3204f598d..a7f9d777a 100644
--- a/internal/console/alertcopy_test.go
+++ b/internal/console/alertcopy_test.go
@@ -178,21 +178,22 @@ func TestAlertUnsubscribeFooterByKind(t *testing.T) {
}
}
-// A failed test is told in the approved words, whatever the code stored.
+// A failed test is told in the approved words, whatever the code stored,
+// the reason after the colon in lower case (ruling R-33).
func TestAlertTestFailedWords(t *testing.T) {
for code, want := range map[string]string{
- "refused": "The test did not get through: The address resolves to a private or reserved network.",
- "timeout": "The test did not get through: The address did not respond in time.",
- "connect": "The test did not get through: The connection could not be made.",
- "tls": "The test did not get through: The secure connection failed.",
- "status 503": "The test did not get through: The address returned HTTP status 503.",
- "invalid": "The test did not get through: The stored URL is no longer valid.",
- "needs re-entry": "The test did not get through: The connector needs its URL entered again.",
- "suspended": "The test did not get through: The connector is suspended.",
- "unconfirmed": "The test did not get through: The connector is not confirmed.",
- "no seal key": "The test did not get through: The connector key is missing.",
- "seal": "The test did not get through: The connector key could not open the stored address.",
- "email": "The test did not get through: Email delivery failed.",
+ "refused": "The test did not get through: the address resolves to a private or reserved network.",
+ "timeout": "The test did not get through: the address did not respond in time.",
+ "connect": "The test did not get through: the connection could not be made.",
+ "tls": "The test did not get through: the secure connection failed.",
+ "status 503": "The test did not get through: the address returned HTTP status 503.",
+ "invalid": "The test did not get through: the stored URL is no longer valid.",
+ "needs re-entry": "The test did not get through: the connector needs its URL entered again.",
+ "suspended": "The test did not get through: the connector is suspended.",
+ "unconfirmed": "The test did not get through: the connector is not confirmed.",
+ "no seal key": "The test did not get through: the connector key is missing.",
+ "seal": "The test did not get through: the connector key could not open the stored address.",
+ "email": "The test did not get through: email delivery failed.",
} {
if got := alertTestFailed(code).Error(); got != want {
t.Errorf("alertTestFailed(%q) = %q, want %q", code, got, want)
diff --git a/internal/console/alertnotify.go b/internal/console/alertnotify.go
index 1e94b824d..5c066c807 100644
--- a/internal/console/alertnotify.go
+++ b/internal/console/alertnotify.go
@@ -33,6 +33,8 @@ import (
"strings"
"sync"
"time"
+ "unicode"
+ "unicode/utf8"
"github.com/carlosframework/platform/internal/alerting"
)
@@ -810,8 +812,23 @@ var (
// alertTestFailed is the error of a test that did not get through. why is a
// send category (sendErr) or a hold reason (alertWithheld, alertTarget); the
// stored values stay short codes, and the words are made here.
-func alertTestFailed(why string) error {
- return fmt.Errorf(alertCopy["test.failed"], strings.TrimSuffix(alertWhyText(why), "."))
+func alertTestFailed(why string) error { return alertTestFailure{why} }
+
+// alertTestFailure is a test that did not get through, keeping why so a
+// page can put the reason in a sentence of its own.
+type alertTestFailure struct{ why string }
+
+func (f alertTestFailure) Error() string { return fmt.Sprintf(alertCopy["test.failed"], f.Reason()) }
+
+// Reason is why in the approved words, as it reads after a colon or inside
+// brackets: lower case first, no full stop (ruling R-33).
+func (f alertTestFailure) Reason() string {
+ r := strings.TrimSuffix(alertWhyText(f.why), ".")
+ if r == "" {
+ return r
+ }
+ c, size := utf8.DecodeRuneInString(r)
+ return string(unicode.ToLower(c)) + r[size:]
}
// alertHoldKeys maps a hold reason (alertWithheld, alertTarget) to its copy.
diff --git a/internal/console/alertstore.go b/internal/console/alertstore.go
index 8d0416226..5a5557fe0 100644
--- a/internal/console/alertstore.go
+++ b/internal/console/alertstore.go
@@ -164,8 +164,14 @@ const (
)
// errAlertTokenInvalid is every refused token: unknown, for another
-// action, expired, or a confirm already used.
-var errAlertTokenInvalid = errors.New("alert token not valid")
+// action, expired, or a confirm already used. The three refusals of a token
+// that does exist wrap it, so a door can say which (alertpages.go).
+var (
+ errAlertTokenInvalid = errors.New("alert token not valid")
+ errAlertTokenAction = fmt.Errorf("%w: minted for another action", errAlertTokenInvalid)
+ errAlertTokenExpired = fmt.Errorf("%w: expired", errAlertTokenInvalid)
+ errAlertTokenUsed = fmt.Errorf("%w: already used", errAlertTokenInvalid)
+)
// alertSuspendAfter is how long a connector fails before it is suspended
// (spec §5.3).
@@ -186,7 +192,7 @@ type alertConnector struct {
ID int64
Scope, Kind, Name, TargetHint, OwnerAddress string
Confirmed, Suspended, NeedsReentry bool
- FailingSince time.Time
+ FailingSince, SuspendedAt time.Time
// CreatedBy is the address that added it, for the page.
CreatedBy string
}
@@ -656,7 +662,7 @@ func scanAlertConnector(row interface{ Scan(...any) error }) (alertConnector, er
&suspended, &c.NeedsReentry, &failing, &c.CreatedBy); err != nil {
return alertConnector{}, err
}
- c.Confirmed, c.Suspended, c.FailingSince = confirmed != 0, suspended != 0, alertTime(failing)
+ c.Confirmed, c.Suspended, c.FailingSince, c.SuspendedAt = confirmed != 0, suspended != 0, alertTime(failing), alertTime(suspended)
return c, nil
}
@@ -697,6 +703,36 @@ func (s *Store) ResumeAlertConnector(id int64) error {
// operator's seeded sign-in address). A second connector with the same
// scope and OwnerAddress is refused.
func (s *Store) AddAlertConnector(c alertConnector, sealed []byte, plain string) (int64, error) {
+ return insertAlertConnector(s.db, c, sealed, plain, time.Now())
+}
+
+// AddAlertConnectorVerify is AddAlertConnector and the verify row owed to
+// the new connector (its confirm link, or its Slack test with one), queued
+// due at now, in one transaction: a connector is never left waiting for a
+// confirmation nobody queued. verify is the row's note, as the drain reads
+// it.
+func (s *Store) AddAlertConnectorVerify(c alertConnector, sealed []byte, plain string, verify []byte, now time.Time) (int64, error) {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return 0, err
+ }
+ defer tx.Rollback()
+ id, err := insertAlertConnector(tx, c, sealed, plain, now)
+ if err != nil {
+ return 0, err
+ }
+ if err := insertAlertOutbox(tx, alertOutboxRow{ConnectorID: id, Kind: "verify", Body: verify, NextAt: now}); err != nil {
+ return 0, err
+ }
+ if err := tx.Commit(); err != nil {
+ return 0, err
+ }
+ return id, nil
+}
+
+func insertAlertConnector(ex interface {
+ Exec(string, ...any) (sql.Result, error)
+}, c alertConnector, sealed []byte, plain string, at time.Time) (int64, error) {
switch c.Kind {
case alertConnectorEmail:
if plain == "" || sealed != nil {
@@ -712,12 +748,12 @@ func (s *Store) AddAlertConnector(c alertConnector, sealed []byte, plain string)
if c.Scope == "" {
return 0, errors.New("alert connector: no scope")
}
- now := time.Now().Unix()
+ now := at.Unix()
var confirmed int64
if c.Confirmed {
confirmed = now
}
- res, err := s.db.Exec(`INSERT INTO alert_connectors (scope, kind, name, target_sealed, target_plain, target_hint, owner_address,
+ res, err := ex.Exec(`INSERT INTO alert_connectors (scope, kind, name, target_sealed, target_plain, target_hint, owner_address,
confirmed_at, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
c.Scope, c.Kind, c.Name, nullBytes(sealed), sql.NullString{String: plain, Valid: plain != ""}, c.TargetHint,
sql.NullString{String: c.OwnerAddress, Valid: c.OwnerAddress != ""}, confirmed, c.CreatedBy, now)
@@ -795,7 +831,8 @@ func deleteAlertConnectorTx(tx *sql.Tx, scope string, id int64) error {
return err
}
}
- return nil
+ _, err = tx.Exec(`DELETE FROM alert_meta WHERE k = ?`, alertUnsubscribedMarker(id))
+ return err
}
// AlertConnectorTarget is connector id's stored target: sealed for Slack
@@ -1008,11 +1045,38 @@ func (s *Store) UseAlertToken(raw, action string, now time.Time) (alertToken, er
return alertToken{}, err
}
defer tx.Rollback()
- hash := hashToken(raw)
+ t, err := readAlertToken(tx, raw, action, now)
+ if err != nil {
+ return alertToken{}, err
+ }
+ if action == alertTokenConfirm {
+ if t, err = spendAlertToken(tx, raw, t, now); err != nil {
+ return alertToken{}, err
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ return alertToken{}, err
+ }
+ return t, nil
+}
+
+// PeekAlertToken is UseAlertToken's verdict on raw without using it, for a
+// door's GET, which shows a page and acts on nothing. A confirm token
+// already used is refused with errAlertTokenUsed and returned as well, so
+// the page can name its connector.
+func (s *Store) PeekAlertToken(raw, action string, now time.Time) (alertToken, error) {
+ return readAlertToken(s.db, raw, action, now)
+}
+
+// readAlertToken reads raw's row and refuses it as UseAlertToken does. On
+// errAlertTokenUsed the token is returned too.
+func readAlertToken(q interface {
+ QueryRow(string, ...any) *sql.Row
+}, raw, action string, now time.Time) (alertToken, error) {
var t alertToken
var conn, expires, used sql.NullInt64
var rule, subject sql.NullString
- err = tx.QueryRow(`SELECT action, scope, connector_id, rule, subject, expires_at, used_at FROM alert_tokens WHERE hash = ?`, hash).
+ err := q.QueryRow(`SELECT action, scope, connector_id, rule, subject, expires_at, used_at FROM alert_tokens WHERE hash = ?`, hashToken(raw)).
Scan(&t.Action, &t.Scope, &conn, &rule, &subject, &expires, &used)
if err == sql.ErrNoRows {
return alertToken{}, errAlertTokenInvalid
@@ -1024,20 +1088,163 @@ func (s *Store) UseAlertToken(raw, action string, now time.Time) (alertToken, er
t.ExpiresAt, t.UsedAt = alertNullTime(expires), alertNullTime(used)
switch {
case t.Action != action:
- return alertToken{}, fmt.Errorf("%w: minted for %s", errAlertTokenInvalid, t.Action)
+ return alertToken{}, errAlertTokenAction
case !t.ExpiresAt.IsZero() && now.Unix() >= expires.Int64:
- return alertToken{}, fmt.Errorf("%w: expired", errAlertTokenInvalid)
+ return alertToken{}, errAlertTokenExpired
case action == alertTokenConfirm && used.Valid:
- return alertToken{}, fmt.Errorf("%w: already used", errAlertTokenInvalid)
+ return t, errAlertTokenUsed
}
- if action == alertTokenConfirm {
- if _, err := tx.Exec(`UPDATE alert_tokens SET used_at = ? WHERE hash = ? AND used_at IS NULL`, now.Unix(), hash); err != nil {
- return alertToken{}, err
- }
- t.UsedAt = time.Unix(now.Unix(), 0).UTC()
+ return t, nil
+}
+
+// spendAlertToken marks confirm token raw (t, as read) used inside tx. A
+// row some other redemption marked first is refused: one use means one.
+func spendAlertToken(tx *sql.Tx, raw string, t alertToken, now time.Time) (alertToken, error) {
+ res, err := tx.Exec(`UPDATE alert_tokens SET used_at = ? WHERE hash = ? AND used_at IS NULL`, now.Unix(), hashToken(raw))
+ if err != nil {
+ return alertToken{}, err
}
- if err := tx.Commit(); err != nil {
+ if n, err := res.RowsAffected(); err != nil {
return alertToken{}, err
+ } else if n != 1 {
+ return t, errAlertTokenUsed
}
+ t.UsedAt = time.Unix(now.Unix(), 0).UTC()
return t, nil
}
+
+// ConfirmAlertConnectorByToken redeems confirm token raw and confirms the
+// connector it is bound to in one transaction: either the token is spent
+// and its connector confirmed, or neither, so no failure leaves a spent
+// link on a connector still waiting. Refusals are UseAlertToken's;
+// sql.ErrNoRows is a connector no longer there (its tokens go with it, so
+// only a race reaches that), and leaves the token unspent.
+func (s *Store) ConfirmAlertConnectorByToken(raw string, now time.Time) (alertConnector, error) {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return alertConnector{}, err
+ }
+ defer tx.Rollback()
+ t, err := readAlertToken(tx, raw, alertTokenConfirm, now)
+ if err != nil {
+ return alertConnector{}, err
+ }
+ if t, err = spendAlertToken(tx, raw, t, now); err != nil {
+ return alertConnector{}, err
+ }
+ if _, err := tx.Exec(`UPDATE alert_connectors SET confirmed_at = ? WHERE id = ? AND scope = ? AND confirmed_at = 0`,
+ now.Unix(), t.ConnectorID, t.Scope); err != nil {
+ return alertConnector{}, err
+ }
+ c, err := scanAlertConnector(tx.QueryRow(`SELECT `+alertConnectorColumns+` FROM alert_connectors WHERE id = ? AND scope = ?`,
+ t.ConnectorID, t.Scope))
+ if err != nil {
+ return alertConnector{}, err
+ }
+ if err := tx.Commit(); err != nil {
+ return alertConnector{}, err
+ }
+ return c, nil
+}
+
+// UnsubscribeAlertConnector redeems unsubscribe token raw and turns its
+// connector off: suspended (spec §5.1), not deleted, so a seeded
+// operator's connector keeps its seeded marker (ruling R-24) and a test
+// that gets through can turn it back on (ruling R-11). The unsubscribe is
+// recorded as alert_meta unsubscribed:<id>, the first time kept. Using the
+// link again changes nothing. sql.ErrNoRows: the connector is gone.
+func (s *Store) UnsubscribeAlertConnector(raw string, now time.Time) (alertConnector, error) {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return alertConnector{}, err
+ }
+ defer tx.Rollback()
+ t, err := readAlertToken(tx, raw, alertTokenUnsubscribe, now)
+ if err != nil {
+ return alertConnector{}, err
+ }
+ res, err := tx.Exec(`UPDATE alert_connectors SET suspended_at = CASE WHEN suspended_at = 0 THEN ? ELSE suspended_at END
+ WHERE id = ? AND scope = ?`, now.Unix(), t.ConnectorID, t.Scope)
+ if err != nil {
+ return alertConnector{}, err
+ }
+ if n, err := res.RowsAffected(); err != nil {
+ return alertConnector{}, err
+ } else if n == 0 {
+ return alertConnector{}, sql.ErrNoRows
+ }
+ if _, err := tx.Exec(`INSERT OR IGNORE INTO alert_meta (k, v) VALUES (?, ?)`,
+ alertUnsubscribedMarker(t.ConnectorID), now.UTC().Format(time.RFC3339)); err != nil {
+ return alertConnector{}, err
+ }
+ c, err := scanAlertConnector(tx.QueryRow(`SELECT `+alertConnectorColumns+` FROM alert_connectors WHERE id = ?`, t.ConnectorID))
+ if err != nil {
+ return alertConnector{}, err
+ }
+ if err := tx.Commit(); err != nil {
+ return alertConnector{}, err
+ }
+ return c, nil
+}
+
+// alertUnsubscribedMarker is the alert_meta key recording that connector
+// id was turned off from an unsubscribe link.
+func alertUnsubscribedMarker(id int64) string {
+ return fmt.Sprintf("unsubscribed:%d", id)
+}
+
+// ---- the pages ---------------------------------------------------------------
+
+// RecentAlertIncidents is scope's newest limit incidents, open and closed,
+// newest first, for the History page.
+func (s *Store) RecentAlertIncidents(scope string, limit int) ([]alertIncident, error) {
+ rows, err := s.db.Query(`SELECT id, rule, level, opened_at, closed_at, close_reason, members, flapping
+ FROM alert_incidents WHERE scope = ? ORDER BY id DESC LIMIT ?`, scope, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []alertIncident
+ for rows.Next() {
+ in := alertIncident{Scope: scope}
+ var opened int64
+ var closed sql.NullInt64
+ var members string
+ if err := rows.Scan(&in.ID, &in.Rule, &in.Level, &opened, &closed, &in.CloseReason, &members, &in.Flapping); err != nil {
+ return nil, err
+ }
+ if err := json.Unmarshal([]byte(members), &in.Members); err != nil {
+ return nil, fmt.Errorf("alert incident %d members: %w", in.ID, err)
+ }
+ in.OpenedAt, in.ClosedAt = alertTime(opened), alertNullTime(closed)
+ out = append(out, in)
+ }
+ return out, rows.Err()
+}
+
+// alertNoise is one rule's incidents opened since a time, and how many of
+// them cleared within quick of opening (spec §6.6).
+type alertNoise struct{ Fired, QuickClears int }
+
+// AlertRuleNoise is each rule's alertNoise in scope since since. A rule
+// with no incident in that time is absent.
+func (s *Store) AlertRuleNoise(scope string, since time.Time, quick time.Duration) (map[string]alertNoise, error) {
+ rows, err := s.db.Query(`SELECT rule, COUNT(*),
+ SUM(CASE WHEN closed_at IS NOT NULL AND close_reason = ? AND closed_at - opened_at <= ? THEN 1 ELSE 0 END)
+ FROM alert_incidents WHERE scope = ? AND opened_at >= ? GROUP BY rule`,
+ alertCloseCleared, int64(quick/time.Second), scope, since.Unix())
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ out := map[string]alertNoise{}
+ for rows.Next() {
+ var rule string
+ var n alertNoise
+ if err := rows.Scan(&rule, &n.Fired, &n.QuickClears); err != nil {
+ return nil, err
+ }
+ out[rule] = n
+ }
+ return out, rows.Err()
+}
diff --git a/internal/console/emailsignin_limits.go b/internal/console/emailsignin_limits.go
index b4df23f16..f9955dc6c 100644
--- a/internal/console/emailsignin_limits.go
+++ b/internal/console/emailsignin_limits.go
@@ -25,6 +25,11 @@ const (
wrongCodesPerAddrDay = 10 // wrong codes per address
wrongCodesPerIPHour = 30 // wrong codes per IP
+ // Alert confirmations (fleet alerts spec §5.3): every verify row that
+ // carries a confirm link, per alert scope.
+ alertConfirmsPerScopeHour = 5
+ alertConfirmsPerScopeDay = 20
+
emailResendGap = 60 * time.Second
// A key untouched for this long holds nothing that matters to any window.
@@ -135,6 +140,8 @@ type emailLimits struct {
addrWrong keyedWindow // wrong codes, by address
ipWrong keyedWindow // wrong codes, by IP
+ alertConfirms keyedWindow // alert confirmation sends, by alert scope
+
sweepNext int // index into sweepWindows() where the next sweep starts
}
@@ -163,7 +170,7 @@ func (l *emailLimits) submit(ip string) bool {
}
func (l *emailLimits) sweepWindows() []*keyedWindow {
- return []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.addrWrong, &l.ipWrong}
+ return []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.addrWrong, &l.ipWrong, &l.alertConfirms}
}
// sweep is one bounded step of cleanup: it inspects at most limitSweepBudget
@@ -226,6 +233,25 @@ func (l *emailLimits) signinSend(addr, ip string) bool {
return true
}
+// alertConfirmSend reports whether one more alert confirmation (an email
+// connector's confirm link, or a Slack test carrying one) may be queued for
+// scope, at most 5 an hour and 20 a day, and records it if so. All or
+// nothing, as signinSend: a refusal charges neither window. It runs the
+// same bounded cleanup as submit.
+func (l *emailLimits) alertConfirmSend(scope string) bool {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ now := l.clock()
+ l.sweep(now)
+ l.alertConfirms.trim(scope, now)
+ if l.alertConfirms.count(scope, now.Add(-time.Hour)) >= alertConfirmsPerScopeHour ||
+ l.alertConfirms.count(scope, now.Add(-24*time.Hour)) >= alertConfirmsPerScopeDay {
+ return false
+ }
+ l.alertConfirms.add(scope, now)
+ return true
+}
+
// stepUpSend reports whether a step-up email may go to addr (one per 60
// seconds, ten per hour) and records it if so. Its budget is separate from
// signinSend's.
diff --git a/internal/console/emailsignin_limits_test.go b/internal/console/emailsignin_limits_test.go
index 644fb2110..fffd5ba11 100644
--- a/internal/console/emailsignin_limits_test.go
+++ b/internal/console/emailsignin_limits_test.go
@@ -397,21 +397,21 @@ func TestSigninSendSweepIsBounded(t *testing.T) {
func TestSigninSendSweepCleansStaleAcrossCalls(t *testing.T) {
c := newLimitClock()
l := newTestLimits(c)
- // 50 stale keys in each of the six windows: 300 in all, well over one
- // call's budget, including stepUps.
+ // 50 stale keys in each of the seven windows: 350 in all, well over one
+ // call's budget, including stepUps and the alert confirmations.
for i := 0; i < 50; i++ {
for _, w := range l.sweepWindows() {
w.add(fmt.Sprintf("old%d", i), c.now())
}
}
- if got := limitKeyCount(l); got != 300 {
+ if got := limitKeyCount(l); got != 350 {
t.Fatalf("setup: %d keys", got)
}
c.advance(25 * time.Hour)
l.submit("11.0.0.1")
left := limitKeyCount(l)
- if left == 0 || left < 300+1-limitSweepBudget {
- t.Fatalf("one submit left %d of 301 keys; want a bounded step (dropped at most %d)", left, limitSweepBudget)
+ if left == 0 || left < 350+1-limitSweepBudget {
+ t.Fatalf("one submit left %d of 351 keys; want a bounded step (dropped at most %d)", left, limitSweepBudget)
}
for i := 0; i < 20 && limitKeyCount(l) > 1; i++ {
l.submit("11.0.0.1")
@@ -420,7 +420,7 @@ func TestSigninSendSweepCleansStaleAcrossCalls(t *testing.T) {
if got := limitKeyCount(l); got != 1 {
t.Fatalf("%d keys left after repeated submits, want 1", got)
}
- if len(l.stepUps.hits) != 0 {
- t.Fatal("stepUps not swept")
+ if len(l.stepUps.hits) != 0 || len(l.alertConfirms.hits) != 0 {
+ t.Fatal("stepUps or alertConfirms not swept")
}
}