carlos / platform Public

console: alert store, transactional step, connector seal

The alert engine's console.db tables (connectors, rules, subscriptions,
incidents, the flap history, outbox, tokens, snoozes, a marker table),
each classified NonApp for the claim SQL gate. CommitAlertStep writes a
pass's incident changes, fires and outbox rows in one transaction
(spec §6.1); AlertCutover runs once under the cutover_done marker.

The connector seal is an AES-256-GCM key in its own 0600 file beside
console.db (Config.AlertSealKeyPath), created only when the path does
not exist: an unreadable or malformed key is an error, never replaced.

The authority census fixture gains the seal's two Open calls (the AEAD
open and the key directory's fsync open); neither touches claim state.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 9ee875282ccf9452b16062c880bd466e0b1b45f8 parent 1916e24
9 files changed, +1,683 −2
  • cmd/console/main.go +4 −1
  • internal/console/alertseal.go +120 −0
  • internal/console/alertseal_test.go +120 −0
  • internal/console/alertstore.go +840 −0
  • internal/console/alertstore_test.go +576 −0
  • internal/console/server.go +4 −0
  • internal/console/store.go +5 −1
  • internal/console/store_gate.go +12 −0
  • internal/console/testdata/claim-authority-sites.txt +2 −0

CI failed — run details

Intent

Human

<task-notification> <task-id>a20e0a155120d0ca9</task-id> <tool-use-id>toolu_01RKGLijuGfZ62xNU997hD6m</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a20e0a155120d0ca9.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: Slack sink and engine_silent" 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 - **Commits:** 1916e24f "alerting: URL-free webhook errors; metrics: disarmed engine_silent clears", on top of ce697083. Not pushed. git printed the packed-refs.lock warning again, but `git log -1` shows the commit. - **Fixes:** 1. `PostJSON` errors no longer contain the webhook URL, so a Slack webhook path can't reach the journal. 2. A firing `engine_silent` now clears once and drops its key when the rule is unarmed, and is still never created while unarmed. 3. The symlink setup in the test now fails the test if `os.Symlink` errors. - **Tests:** the alerting, metrics and host tests covering the fixes pass. That includes the four new ones: `TestPostJSONErrorsCarryNoURL`, `TestBoxDeliverLogsNoWebhookURL`, `TestEvaluateEngineSilentDisarmedClears` and `TestEngineSilentDisarmedClearsThroughAlertTick`. Vet and the darwin and windows builds pass. Rerunning `make census-card` gives the same output as the committed card. - **Concern:** fix 2 collided with the 10-minute grace. Inside the grace an armed watch has no reading yet and reported nil, which would now clear an alert still firing after a restart. So `alertTick` now holds the saved firing state during the grace, and nil only ever means unarmed. `TestEngineSilentRestartWhileMissing` passes, so an alert firing before a restart stays firing. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-3-report.md (fix round 1 section appended)</result> <usage><subagent_tokens>197958</subagent_tokens><tool_uses>8</tool_uses><duration_ms>182645</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a12bae9cdfe656bc3</task-id> <tool-use-id>toolu_01LRPTLUPW7zmLDQDVwkFpb4</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a12bae9cdfe656bc3.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 3 fix round 1" 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>### Finding Verdicts - **`PostJSON` / `alertSinks.deliver` leak the webhook URL via `*url.Error`**: ADDRESSED. - `internal/alerting/alerting.go:268-274` unwraps `*url.Error` to `ue.Err` and returns `webhook: post: &lt;cause&gt;`. Any other client error becomes the fixed `webhook: post failed`. The non-2xx error at `:277` carries only the status, as before. - Every consumer of the error is covered, because they all go through `PostJSON`. These are `deliver` at `internal/host/alertsink.go:112`, `deliverRelease` at `:182`, and `Sinks.Page` at `internal/alerting/alerting.go:137`. `httpPostWebhook` (`internal/host/metrics_loop.go:653`) is a plain passthrough. - `TestPostJSONErrorsCarryNoURL` uses `sekrit-XYZ`. It covers a refused connection (the error keeps "refused"), a 500, an unparsable URL, and the `Page` error. - `TestBoxDeliverLogsNoWebhookURL` goes through the real `httpPostWebhook`, runs `deliver`, `deliverRelease` and `PageOperator`, and asserts three counted failures. It also asserts that "alert webhook post" was logged and that the captured log and the page error do not contain the secret. This is the log-output assertion the finding required. - I checked every `log.Printf` and `Errorf` in `alerting.go` and `alertsink.go`. None other formats the webhook URL. - **A firing `engine_silent` stuck forever once unarmed**: ADDRESSED. - `internal/metrics/alert.go:~364-369`: when `EngineSilent` is nil and the stored key is present and firing, `Evaluate` emits one clear (value 0) and deletes the key. When the key is absent or not firing, it does nothing, so the rule is still never created while unarmed. - `Evaluate` copies the state map into `out` before mutating, so the delete never touches the caller's map. - `Evaluate` has one production caller (`metrics_loop.go:549`), so no other path is affected. - `TestEvaluateEngineSilentDisarmedClears` covers the single clear, the key being deleted, a second unarmed tick doing nothing, and a quiet key being left alone. - `TestEngineSilentDisarmedClearsThroughAlertTick` covers an armed fire, then a root restart. The sink gets one clear, the key is gone, and there are zero lstat calls. - **Symlink error discarded in `enginebeat_linux_test.go`**: ADDRESSED. The setup closure at `:~240` now calls `t.Fatal(err)` on a failed `os.Symlink`. ### Side change (`metrics_loop.go:~540-548`): confirmed, no wrong clear or wrong fire on restart `obs.EngineSilent` is set only when `beat != nil`. An armed watch inside its grace returns nil from `silent()`. `alertTick` then substitutes `held := st.Rules["engine_silent"].Firing`. I traced each restart case: - **Fire restored, still in grace, beat missing:** `held` is true, so `Evaluate` sees `cur.Firing == *obs`. There is no event, so no clear and no second page. The existing `TestEngineSilentRestartWhileMissing` guards this, and the report shows it passing. - **Nothing restored, still in grace:** `held` is false, so `Evaluate` sees false equal to false. There is no event and no key is created. A nil map read is safe. - **Fresh beat or stale beat after the grace:** these return real values, so the normal fire and clear paths run. A restored fire that gets a fresh beat clears. One that gets a stale beat stays firing without re-paging. - **Disarmed restart (env removed, or agent now root):** `beat` is nil, so `EngineSilent` stays nil and the leftover fire clears once. This is the intended behaviour from finding 2. - **Publish failure:** `*st` is not advanced, and `held` reads the same uncommitted `*st` that `Evaluate` receives. The two stay consistent. Nil reaching `Evaluate` therefore means only "unarmed". The `Observation.EngineSilent` and `silent()` comments were updated to say so. ### New Breakage in the Fix Diff None. One Minor residual: `ue.Err` for a DNS failure still includes the hostname, such as `lookup &lt;host&gt;: no such host`. Only the path and query are stripped. That is fine for Slack's fixed host, and a webhook whose host label is itself a secret is unlikely. I did not re-run the tests. The report names the covering tests and shows their output, and the diff matches those claims. ### Out-of-Scope Observations None. ### Verdict **Fix round:** All findings addressed, no new Critical/Important breakage.</result> <usage><subagent_tokens>58018</subagent_tokens><tool_uses>6</tool_uses><duration_ms>52841</duration_ms></usage> </task-notification>

Attributed to this commit: 21.5 g CO₂e (2,694,481 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/cmd/console/main.go b/cmd/console/main.go
index 6a3ddddcd..47a94a8c0 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -473,7 +473,10 @@ func serve() {
// --from restores and import spools, next to CONSOLE_DB on disk;
// NewServer clears the pool's own leftovers from it.
SeedScratchDir: filepath.Join(filepath.Dir(envOr("CONSOLE_DB", "/data/console/console.db")), "scratch", "seeds"),
- SeedData: seedData,
+ // The alert connector seal's key, next to CONSOLE_DB and outside it
+ // (fleet alerts spec §5.1).
+ AlertSealKeyPath: filepath.Join(filepath.Dir(envOr("CONSOLE_DB", "/data/console/console.db")), "alert-connectors.key"),
+ SeedData: seedData,
// The feed (geoip spec §10.1). The key goes nowhere but MaxMind.
GeoipFeed: os.Getenv("CONSOLE_GEOIP_FEED"),
GeoipMaxMindAccount: strings.TrimSpace(os.Getenv("CONSOLE_GEOIP_MAXMIND_ACCOUNT")),
diff --git a/internal/console/alertseal.go b/internal/console/alertseal.go
new file mode 100644
index 000000000..21057c345
--- /dev/null
+++ b/internal/console/alertseal.go
@@ -0,0 +1,120 @@
+package console
+
+import (
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/rand"
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+)
+
+// The connector seal (fleet alerts spec §5.1): Slack and webhook URLs are
+// secrets, so alert_connectors keeps them sealed with an AES-256-GCM key
+// that lives in its own 0600 file beside console.db, never in the database.
+// console.db is replicated to the bucket, so a replica or a backup alone
+// must not reveal a Slack URL.
+//
+// A lost key (a restore from the replica alone) is not repaired by
+// generating a fresh one over the old file: the key is created only when the
+// path does not exist at all, and every other failure to read it is an
+// error. The caller (the alert engine) then marks sealed connectors as
+// needing re-entry and raises seal_key, so nothing fails silently.
+
+// alertSealKeyLen is AES-256's key length.
+const alertSealKeyLen = 32
+
+// connectorSeal seals and opens connector targets with the key file's key.
+type connectorSeal struct {
+ aead cipher.AEAD
+}
+
+// openConnectorSeal reads the key at path, or creates a fresh 32-byte key
+// there at 0600 when (and only when) the path does not exist. created
+// reports the second case: anything sealed before it can no longer be
+// opened. An existing file that cannot be read, or holds anything but 32
+// bytes, is an error and is left untouched.
+func openConnectorSeal(path string) (seal *connectorSeal, created bool, err error) {
+ key, err := os.ReadFile(path)
+ if os.IsNotExist(err) {
+ key, err = createAlertSealKey(path)
+ if errors.Is(err, fs.ErrExist) {
+ // Created by someone else between the read and our O_EXCL
+ // create: theirs is the key, so read it like any other.
+ key, err = os.ReadFile(path)
+ } else if err == nil {
+ created = true
+ }
+ }
+ if err != nil {
+ return nil, false, fmt.Errorf("alert seal key: %w", err)
+ }
+ if len(key) != alertSealKeyLen {
+ return nil, false, fmt.Errorf("alert seal key %s: %d bytes, want %d", path, len(key), alertSealKeyLen)
+ }
+ block, err := aes.NewCipher(key)
+ if err != nil {
+ return nil, false, err
+ }
+ aead, err := cipher.NewGCM(block)
+ if err != nil {
+ return nil, false, err
+ }
+ return &connectorSeal{aead: aead}, created, nil
+}
+
+// createAlertSealKey writes a fresh key to path with O_EXCL, so it can never
+// replace a file that appeared in the meantime, and syncs the file and its
+// directory so a key that has sealed anything survives a power cut. A
+// failed write removes the file it created: nothing was sealed with it.
+func createAlertSealKey(path string) ([]byte, error) {
+ key := make([]byte, alertSealKeyLen)
+ if _, err := rand.Read(key); err != nil {
+ return nil, err
+ }
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if err != nil {
+ return nil, err
+ }
+ // The umask can only take bits away from 0600; Chmod pins it exactly.
+ werr := f.Chmod(0o600)
+ if werr == nil {
+ _, werr = f.Write(key)
+ }
+ if werr == nil {
+ werr = f.Sync()
+ }
+ if cerr := f.Close(); werr == nil {
+ werr = cerr
+ }
+ if werr != nil {
+ os.Remove(path)
+ return nil, werr
+ }
+ if d, err := os.Open(filepath.Dir(path)); err == nil {
+ d.Sync()
+ d.Close()
+ }
+ return key, nil
+}
+
+// Seal encrypts p under a fresh random nonce and returns nonce‖ciphertext.
+func (c *connectorSeal) Seal(p []byte) ([]byte, error) {
+ nonce := make([]byte, c.aead.NonceSize(), c.aead.NonceSize()+len(p)+c.aead.Overhead())
+ if _, err := rand.Read(nonce); err != nil {
+ return nil, err
+ }
+ return c.aead.Seal(nonce, nonce, p, nil), nil
+}
+
+// Open reverses Seal. A blob sealed under another key, or altered, is an
+// error.
+func (c *connectorSeal) Open(sealed []byte) ([]byte, error) {
+ n := c.aead.NonceSize()
+ if len(sealed) < n+c.aead.Overhead() {
+ return nil, errors.New("alert seal: sealed target too short")
+ }
+ return c.aead.Open(nil, sealed[:n], sealed[n:], nil)
+}
diff --git a/internal/console/alertseal_test.go b/internal/console/alertseal_test.go
new file mode 100644
index 000000000..7fcf5853a
--- /dev/null
+++ b/internal/console/alertseal_test.go
@@ -0,0 +1,120 @@
+package console
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestConnectorSealRoundTrip(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "alert-connectors.key")
+ seal, created, err := openConnectorSeal(path)
+ if err != nil || !created {
+ t.Fatalf("open = %v, created %v", err, created)
+ }
+ secret := []byte("https://hooks.slack.com/services/T0/B0/sekrit-XYZ")
+ a, err := seal.Seal(secret)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b, _ := seal.Seal(secret)
+ if bytes.Equal(a, b) {
+ t.Fatal("two seals of one target are identical: the nonce is not fresh")
+ }
+ if bytes.Contains(a, []byte("sekrit")) {
+ t.Fatal("sealed target carries the plaintext")
+ }
+
+ // A second start reads the same key and opens what the first sealed.
+ again, created, err := openConnectorSeal(path)
+ if err != nil || created {
+ t.Fatalf("reopen = %v, created %v", err, created)
+ }
+ got, err := again.Open(a)
+ if err != nil || !bytes.Equal(got, secret) {
+ t.Fatalf("open = %q, %v", got, err)
+ }
+
+ tampered := append([]byte(nil), a...)
+ tampered[len(tampered)-1] ^= 1
+ if _, err := again.Open(tampered); err == nil {
+ t.Fatal("a tampered target opened")
+ }
+ if _, err := again.Open(a[:5]); err == nil {
+ t.Fatal("a truncated target opened")
+ }
+ other, _, err := openConnectorSeal(filepath.Join(t.TempDir(), "other.key"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := other.Open(a); err == nil {
+ t.Fatal("another key opened the target")
+ }
+}
+
+func TestConnectorSealKeyMode0600(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "alert-connectors.key")
+ if _, _, err := openConnectorSeal(path); err != nil {
+ t.Fatal(err)
+ }
+ fi, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fi.Mode().Perm() != 0o600 || fi.Size() != 32 {
+ t.Fatalf("key file mode %v size %d, want 0600 and 32", fi.Mode().Perm(), fi.Size())
+ }
+}
+
+// An existing key that cannot be read is an error, and the file is left
+// exactly as it was: generating a fresh key over it would orphan every
+// sealed connector without a word (Review Focus 5).
+func TestConnectorSealUnreadableKeyErrors(t *testing.T) {
+ if os.Geteuid() == 0 {
+ t.Skip("root reads a 0000 file")
+ }
+ path := filepath.Join(t.TempDir(), "alert-connectors.key")
+ orig := bytes.Repeat([]byte{7}, 32)
+ if err := os.WriteFile(path, orig, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(path, 0); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.Chmod(path, 0o600) })
+ seal, created, err := openConnectorSeal(path)
+ if err == nil || seal != nil || created {
+ t.Fatalf("unreadable key: seal %v, created %v, err %v", seal, created, err)
+ }
+ os.Chmod(path, 0o600)
+ got, err := os.ReadFile(path)
+ if err != nil || !bytes.Equal(got, orig) {
+ t.Fatalf("key file changed: %x, %v", got, err)
+ }
+
+ // A key of the wrong length is refused too, and kept.
+ short := filepath.Join(t.TempDir(), "short.key")
+ if err := os.WriteFile(short, []byte("abc"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, created, err := openConnectorSeal(short); err == nil || created {
+ t.Fatalf("short key: created %v, err %v", created, err)
+ }
+ if got, _ := os.ReadFile(short); string(got) != "abc" {
+ t.Fatalf("short key rewritten: %q", got)
+ }
+
+ // A path whose directory cannot be listed is an error, not a new key.
+ dir := filepath.Join(t.TempDir(), "locked")
+ if err := os.Mkdir(dir, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(dir, 0); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.Chmod(dir, 0o700) })
+ if _, created, err := openConnectorSeal(filepath.Join(dir, "k.key")); err == nil || created {
+ t.Fatalf("locked dir: created %v, err %v", created, err)
+ }
+}
diff --git a/internal/console/alertstore.go b/internal/console/alertstore.go
new file mode 100644
index 000000000..7993401f0
--- /dev/null
+++ b/internal/console/alertstore.go
@@ -0,0 +1,840 @@
+package console
+
+import (
+ "crypto/rand"
+ "database/sql"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "time"
+)
+
+// The alert engine's tables (fleet alerts spec §5, §6), kept here so the
+// feature is one file to read: connectors and their subscriptions, rule
+// settings, incidents, the flap history, the outbox, the action tokens the
+// messages carry, snoozes, and a one-row marker table.
+//
+// Times are Unix seconds, and 0 is "never" except where a column is NULL
+// for that. Connector, incident and outbox ids are AUTOINCREMENT, so a
+// deleted connector's id is never handed to a new one: an old unsubscribe
+// link or a queued row can only ever reach the connector it was made for.
+func (s *Store) migrateAlerts() error {
+ for _, stmt := range []string{
+ // A destination owned by a scope ("fleet" or "account:<sqid>").
+ // Email keeps its address in target_plain; Slack and webhook keep
+ // their URL in target_sealed, sealed with the key file beside
+ // console.db (alertseal.go), and target_hint is the part the page
+ // may show. owner_address marks an operator's seeded personal
+ // connector, rechecked against the operator list before each send.
+ `CREATE TABLE IF NOT EXISTS alert_connectors (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ scope TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ name TEXT NOT NULL DEFAULT '',
+ target_sealed BLOB,
+ target_plain TEXT,
+ target_hint TEXT NOT NULL DEFAULT '',
+ owner_address TEXT,
+ confirmed_at INTEGER NOT NULL DEFAULT 0,
+ failing_since INTEGER NOT NULL DEFAULT 0,
+ suspended_at INTEGER NOT NULL DEFAULT 0,
+ needs_reentry INTEGER NOT NULL DEFAULT 0,
+ created_by TEXT NOT NULL DEFAULT '',
+ created_at INTEGER NOT NULL
+);`,
+ // One seeded personal connector per operator and scope, so seeding
+ // twice can never send everything twice.
+ `CREATE UNIQUE INDEX IF NOT EXISTS alert_connectors_owner ON alert_connectors (scope, owner_address) WHERE owner_address IS NOT NULL;`,
+ // A rule's settings in a scope. No row: on, with the rule's default
+ // threshold.
+ `CREATE TABLE IF NOT EXISTS alert_rules (
+ scope TEXT NOT NULL,
+ rule TEXT NOT NULL,
+ enabled INTEGER NOT NULL DEFAULT 1,
+ threshold REAL,
+ PRIMARY KEY (scope, rule)
+);`,
+ `CREATE TABLE IF NOT EXISTS alert_subscriptions (
+ scope TEXT NOT NULL,
+ rule TEXT NOT NULL,
+ connector_id INTEGER NOT NULL,
+ PRIMARY KEY (scope, rule, connector_id)
+);`,
+ // One incident per (scope, rule) group (spec §6.2). closed_at is NULL
+ // while it is open; members is a JSON array of subjects. notify_at is
+ // opened_at + 5 min, and notified stays 0 until the first message is
+ // queued.
+ `CREATE TABLE IF NOT EXISTS alert_incidents (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ scope TEXT NOT NULL,
+ rule TEXT NOT NULL,
+ level TEXT NOT NULL,
+ opened_at INTEGER NOT NULL,
+ notify_at INTEGER NOT NULL,
+ last_seen_at INTEGER NOT NULL,
+ closed_at INTEGER,
+ close_reason TEXT NOT NULL DEFAULT '',
+ members TEXT NOT NULL DEFAULT '[]',
+ flapping INTEGER NOT NULL DEFAULT 0,
+ notified INTEGER NOT NULL DEFAULT 0,
+ last_reminder_at INTEGER NOT NULL DEFAULT 0,
+ last_update_at INTEGER NOT NULL DEFAULT 0
+);`,
+ `CREATE INDEX IF NOT EXISTS alert_incidents_open ON alert_incidents (scope, rule) WHERE closed_at IS NULL;`,
+ // The flap history (spec §6.7): every fire per (scope, rule, subject),
+ // kept an hour and independent of incidents, so fires across
+ // incidents that opened and closed still count.
+ `CREATE TABLE IF NOT EXISTS alert_fires (
+ scope TEXT NOT NULL,
+ rule TEXT NOT NULL,
+ subject TEXT NOT NULL,
+ fired_at INTEGER NOT NULL
+);`,
+ `CREATE INDEX IF NOT EXISTS alert_fires_by_time ON alert_fires (fired_at);`,
+ // Messages owed (spec §6.1). Written in the same transaction as the
+ // incident change that owes them; sent_at stays NULL until a send
+ // succeeds. body_json is the note without its links (ruling R-2):
+ // the sender mints the snooze and unsubscribe tokens as it renders.
+ // err_category is a URL-free category, never a raw error.
+ `CREATE TABLE IF NOT EXISTS alert_outbox (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ delivery_id TEXT NOT NULL UNIQUE,
+ incident_id INTEGER NOT NULL DEFAULT 0,
+ connector_id INTEGER NOT NULL,
+ kind TEXT NOT NULL,
+ body_json BLOB NOT NULL,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_at INTEGER NOT NULL DEFAULT 0,
+ sent_at INTEGER,
+ err_category TEXT NOT NULL DEFAULT ''
+);`,
+ `CREATE INDEX IF NOT EXISTS alert_outbox_due ON alert_outbox (next_at) WHERE sent_at IS NULL;`,
+ // Links in messages, stored as the SHA-256 of the raw token, each
+ // bound to one action and its target.
+ `CREATE TABLE IF NOT EXISTS alert_tokens (
+ hash TEXT PRIMARY KEY,
+ action TEXT NOT NULL,
+ scope TEXT NOT NULL,
+ connector_id INTEGER,
+ rule TEXT,
+ subject TEXT,
+ expires_at INTEGER,
+ used_at INTEGER
+);`,
+ `CREATE TABLE IF NOT EXISTS alert_snoozes (
+ scope TEXT NOT NULL,
+ rule TEXT NOT NULL,
+ subject TEXT NOT NULL,
+ until INTEGER NOT NULL,
+ PRIMARY KEY (scope, rule, subject)
+);`,
+ // One-shot markers; cutover_done is the watcher-to-engine cutover's.
+ `CREATE TABLE IF NOT EXISTS alert_meta (
+ k TEXT PRIMARY KEY,
+ v TEXT NOT NULL
+);`,
+ } {
+ if _, err := s.db.Exec(stmt); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// Connector kinds. SMS is not in this plan.
+const (
+ alertConnectorEmail = "email"
+ alertConnectorSlack = "slack"
+ alertConnectorWebhook = "webhook"
+)
+
+// alertOutboxKinds are the outbox row kinds. verify covers the email
+// confirm link, the Slack test with its link and the signed webhook test:
+// the only rows an unconfirmed connector may receive.
+var alertOutboxKinds = map[string]bool{
+ "fire": true, "clear": true, "update": true, "reminder": true, "verify": true, "suspended": true,
+}
+
+// Token actions.
+const (
+ alertTokenConfirm = "confirm"
+ alertTokenUnsubscribe = "unsubscribe"
+ alertTokenSnooze = "snooze"
+)
+
+// errAlertTokenInvalid is every refused token: unknown, for another
+// action, expired, or a confirm already used.
+var errAlertTokenInvalid = errors.New("alert token not valid")
+
+// alertSuspendAfter is how long a connector fails before it is suspended
+// (spec §5.3).
+const alertSuspendAfter = 24 * time.Hour
+
+// alertFlapWindow is how long the flap history is kept (spec §6.7).
+const alertFlapWindow = time.Hour
+
+// Outbox retries back off from a minute, doubling, to a 12-hour cap.
+const (
+ alertRetryFirst = time.Minute
+ alertRetryCap = 12 * time.Hour
+)
+
+// alertConnector is one alert_connectors row without its target, which
+// only AlertConnectorTarget reads.
+type alertConnector struct {
+ ID int64
+ Scope, Kind, Name, TargetHint, OwnerAddress string
+ Confirmed, Suspended, NeedsReentry bool
+ FailingSince time.Time
+ // CreatedBy is the address that added it, for the page.
+ CreatedBy string
+}
+
+// alertRuleSetting is a rule's settings in one scope. A nil Threshold is
+// the rule's default.
+type alertRuleSetting struct {
+ Enabled bool
+ Threshold *float64
+ ConnectorIDs []int64
+}
+
+// alertIncident is one alert_incidents row. A zero ClosedAt is open. ID 0
+// is an incident CommitAlertStep has not written yet.
+type alertIncident struct {
+ ID int64
+ Scope, Rule, Level string
+ OpenedAt, NotifyAt, LastSeenAt, ClosedAt time.Time
+ CloseReason string
+ Members []string
+ Flapping, Notified bool
+ LastReminderAt, LastUpdateAt time.Time
+}
+
+// alertOutboxRow is one alert_outbox row. An empty DeliveryID is minted at
+// insert; IncidentID 0 is a message tied to no incident (a cutover clear, a
+// verify, a suspension notice).
+type alertOutboxRow struct {
+ ID int64
+ DeliveryID string
+ IncidentID, ConnectorID int64
+ Kind string
+ Body []byte
+ Attempts int
+ NextAt time.Time
+}
+
+// alertKey names one thing a rule fires on: a box, an app, a service.
+type alertKey struct{ Scope, Rule, Subject string }
+
+// alertFire is one entry in the flap history.
+type alertFire struct {
+ Key alertKey
+ At time.Time
+}
+
+// alertToken is one alert_tokens row. confirm and unsubscribe are bound to
+// a connector; snooze to (scope, rule, subject). A zero ExpiresAt never
+// expires.
+type alertToken struct {
+ Action, Scope string
+ ConnectorID int64
+ Rule, Subject string
+ ExpiresAt, UsedAt time.Time
+}
+
+func alertUnix(t time.Time) int64 {
+ if t.IsZero() {
+ return 0
+ }
+ return t.Unix()
+}
+
+func alertTime(v int64) time.Time {
+ if v == 0 {
+ return time.Time{}
+ }
+ return time.Unix(v, 0).UTC()
+}
+
+func alertNullUnix(t time.Time) sql.NullInt64 {
+ return sql.NullInt64{Int64: t.Unix(), Valid: !t.IsZero()}
+}
+
+func alertNullTime(v sql.NullInt64) time.Time {
+ if !v.Valid {
+ return time.Time{}
+ }
+ return time.Unix(v.Int64, 0).UTC()
+}
+
+// ---- the step ----------------------------------------------------------------
+
+// AlertStepInputs is what the incident step reads: every open incident, and
+// the flap history inside the last hour by key, oldest first. Fires older
+// than the hour are pruned here, the one place each pass passes now.
+func (s *Store) AlertStepInputs(now time.Time) (open []alertIncident, recentFires map[alertKey][]time.Time, err error) {
+ since := now.Add(-alertFlapWindow).Unix()
+ if _, err := s.db.Exec(`DELETE FROM alert_fires WHERE fired_at < ?`, since); err != nil {
+ return nil, nil, err
+ }
+ rows, err := s.db.Query(`SELECT id, scope, rule, level, opened_at, notify_at, last_seen_at, close_reason, members,
+ flapping, notified, last_reminder_at, last_update_at FROM alert_incidents WHERE closed_at IS NULL ORDER BY id`)
+ if err != nil {
+ return nil, nil, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var in alertIncident
+ var opened, notify, seen, reminder, update int64
+ var members string
+ if err := rows.Scan(&in.ID, &in.Scope, &in.Rule, &in.Level, &opened, &notify, &seen, &in.CloseReason, &members,
+ &in.Flapping, &in.Notified, &reminder, &update); err != nil {
+ return nil, nil, err
+ }
+ if err := json.Unmarshal([]byte(members), &in.Members); err != nil {
+ return nil, nil, fmt.Errorf("alert incident %d members: %w", in.ID, err)
+ }
+ in.OpenedAt, in.NotifyAt, in.LastSeenAt = alertTime(opened), alertTime(notify), alertTime(seen)
+ in.LastReminderAt, in.LastUpdateAt = alertTime(reminder), alertTime(update)
+ open = append(open, in)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, nil, err
+ }
+ rows.Close()
+
+ recentFires = map[alertKey][]time.Time{}
+ frows, err := s.db.Query(`SELECT scope, rule, subject, fired_at FROM alert_fires WHERE fired_at >= ? ORDER BY fired_at, rowid`, since)
+ if err != nil {
+ return nil, nil, err
+ }
+ defer frows.Close()
+ for frows.Next() {
+ var k alertKey
+ var at int64
+ if err := frows.Scan(&k.Scope, &k.Rule, &k.Subject, &at); err != nil {
+ return nil, nil, err
+ }
+ recentFires[k] = append(recentFires[k], time.Unix(at, 0).UTC())
+ }
+ return open, recentFires, frows.Err()
+}
+
+// CommitAlertStep writes one pass's incident changes, fires and outbox rows
+// in one transaction (spec §6.1): either the transition and every message
+// it owes are recorded, or none of it is, so a crash can lose no clear. An
+// incident with ID 0 is inserted; any other is updated, and one that is not
+// there refuses the whole step.
+func (s *Store) CommitAlertStep(changed []alertIncident, fires []alertFire, outbox []alertOutboxRow) error {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ for _, in := range changed {
+ if err := writeAlertIncident(tx, in); err != nil {
+ return err
+ }
+ }
+ for _, f := range fires {
+ if _, err := tx.Exec(`INSERT INTO alert_fires (scope, rule, subject, fired_at) VALUES (?, ?, ?, ?)`,
+ f.Key.Scope, f.Key.Rule, f.Key.Subject, f.At.Unix()); err != nil {
+ return err
+ }
+ }
+ for _, r := range outbox {
+ if err := insertAlertOutbox(tx, r); err != nil {
+ return err
+ }
+ }
+ return tx.Commit()
+}
+
+func writeAlertIncident(tx *sql.Tx, in alertIncident) error {
+ members := in.Members
+ if members == nil {
+ members = []string{}
+ }
+ mj, err := json.Marshal(members)
+ if err != nil {
+ return err
+ }
+ args := []any{in.Scope, in.Rule, in.Level, alertUnix(in.OpenedAt), alertUnix(in.NotifyAt), alertUnix(in.LastSeenAt),
+ alertNullUnix(in.ClosedAt), in.CloseReason, string(mj), in.Flapping, in.Notified,
+ alertUnix(in.LastReminderAt), alertUnix(in.LastUpdateAt)}
+ if in.ID == 0 {
+ _, err := tx.Exec(`INSERT INTO alert_incidents (scope, rule, level, opened_at, notify_at, last_seen_at, closed_at,
+ close_reason, members, flapping, notified, last_reminder_at, last_update_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, args...)
+ return err
+ }
+ res, err := tx.Exec(`UPDATE alert_incidents SET scope = ?, rule = ?, level = ?, opened_at = ?, notify_at = ?, last_seen_at = ?,
+ closed_at = ?, close_reason = ?, members = ?, flapping = ?, notified = ?, last_reminder_at = ?, last_update_at = ? WHERE id = ?`,
+ append(args, in.ID)...)
+ if err != nil {
+ return err
+ }
+ if n, err := res.RowsAffected(); err != nil || n != 1 {
+ return fmt.Errorf("alert incident %d: not found (%v)", in.ID, err)
+ }
+ return nil
+}
+
+// insertAlertOutbox queues r inside tx, minting a delivery id when r has
+// none. A repeated delivery id is an error. AlertCutover's callback queues
+// through it too.
+func insertAlertOutbox(tx *sql.Tx, r alertOutboxRow) error {
+ if !alertOutboxKinds[r.Kind] {
+ return fmt.Errorf("alert outbox: unknown kind %q", r.Kind)
+ }
+ if r.DeliveryID == "" {
+ b := make([]byte, 16)
+ if _, err := rand.Read(b); err != nil {
+ return err
+ }
+ r.DeliveryID = hex.EncodeToString(b)
+ }
+ body := r.Body
+ if body == nil {
+ body = []byte{}
+ }
+ _, err := tx.Exec(`INSERT INTO alert_outbox (delivery_id, incident_id, connector_id, kind, body_json, attempts, next_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, r.DeliveryID, r.IncidentID, r.ConnectorID, r.Kind, body, r.Attempts, alertUnix(r.NextAt))
+ return err
+}
+
+// AlertCutover runs f and records cutover_done in one transaction, only when
+// the marker is absent: the watcher-to-engine cutover runs once, and a
+// restart after it (or after it failed and rolled back) does the right
+// thing. ran reports that f ran and committed.
+func (s *Store) AlertCutover(f func(tx *sql.Tx) error) (ran bool, err error) {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return false, err
+ }
+ defer tx.Rollback()
+ var n int
+ if err := tx.QueryRow(`SELECT COUNT(*) FROM alert_meta WHERE k = 'cutover_done'`).Scan(&n); err != nil {
+ return false, err
+ }
+ if n > 0 {
+ return false, nil
+ }
+ if err := f(tx); err != nil {
+ return false, err
+ }
+ if _, err := tx.Exec(`INSERT INTO alert_meta (k, v) VALUES ('cutover_done', ?)`, time.Now().UTC().Format(time.RFC3339)); err != nil {
+ return false, err
+ }
+ if err := tx.Commit(); err != nil {
+ return false, err
+ }
+ return true, nil
+}
+
+// ---- the outbox --------------------------------------------------------------
+
+// DueOutbox is up to limit unsent rows due at now, earliest first.
+func (s *Store) DueOutbox(now time.Time, limit int) ([]alertOutboxRow, error) {
+ rows, err := s.db.Query(`SELECT id, delivery_id, incident_id, connector_id, kind, body_json, attempts, next_at
+ FROM alert_outbox WHERE sent_at IS NULL AND next_at <= ? ORDER BY next_at, id LIMIT ?`, now.Unix(), limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []alertOutboxRow
+ for rows.Next() {
+ var r alertOutboxRow
+ var next int64
+ if err := rows.Scan(&r.ID, &r.DeliveryID, &r.IncidentID, &r.ConnectorID, &r.Kind, &r.Body, &r.Attempts, &next); err != nil {
+ return nil, err
+ }
+ r.NextAt = alertTime(next)
+ out = append(out, r)
+ }
+ return out, rows.Err()
+}
+
+// FinishOutbox records one attempt at row id. ok marks it sent; otherwise
+// the attempt is counted and the row is due again after 1 min·2^attempts
+// (attempts before this one), capped at 12 hours. cat is a URL-free error
+// category (alertdial.go), the only error the outbox keeps.
+func (s *Store) FinishOutbox(id int64, cat string, ok bool, now time.Time) error {
+ if ok {
+ _, err := s.db.Exec(`UPDATE alert_outbox SET sent_at = ?, err_category = ? WHERE id = ?`, now.Unix(), cat, id)
+ return err
+ }
+ tx, err := s.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ var attempts int
+ err = tx.QueryRow(`SELECT attempts FROM alert_outbox WHERE id = ?`, id).Scan(&attempts)
+ if err == sql.ErrNoRows {
+ return nil // deleted since it was read (a revoked operator's row)
+ }
+ if err != nil {
+ return err
+ }
+ if _, err := tx.Exec(`UPDATE alert_outbox SET attempts = ?, next_at = ?, err_category = ? WHERE id = ?`,
+ attempts+1, now.Add(alertRetryBackoff(attempts)).Unix(), cat, id); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+func alertRetryBackoff(attempts int) time.Duration {
+ d := alertRetryFirst
+ for i := 0; i < attempts && d < alertRetryCap; i++ {
+ d *= 2
+ }
+ return min(d, alertRetryCap)
+}
+
+// ---- connectors --------------------------------------------------------------
+
+// AlertConnectors is every connector in scope, oldest first.
+func (s *Store) AlertConnectors(scope string) ([]alertConnector, error) {
+ rows, err := s.db.Query(`SELECT id, scope, kind, name, target_hint, COALESCE(owner_address, ''), confirmed_at,
+ suspended_at, needs_reentry, failing_since, created_by FROM alert_connectors WHERE scope = ? ORDER BY id`, scope)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []alertConnector
+ for rows.Next() {
+ var c alertConnector
+ var confirmed, suspended, failing int64
+ if err := rows.Scan(&c.ID, &c.Scope, &c.Kind, &c.Name, &c.TargetHint, &c.OwnerAddress, &confirmed,
+ &suspended, &c.NeedsReentry, &failing, &c.CreatedBy); err != nil {
+ return nil, err
+ }
+ c.Confirmed, c.Suspended, c.FailingSince = confirmed != 0, suspended != 0, alertTime(failing)
+ out = append(out, c)
+ }
+ return out, rows.Err()
+}
+
+// AddAlertConnector stores c with its target: sealed for Slack and webhook,
+// plain for email, never both. c.Confirmed stores it already confirmed (an
+// 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) {
+ switch c.Kind {
+ case alertConnectorEmail:
+ if plain == "" || sealed != nil {
+ return 0, errors.New("alert connector: email keeps a plain address and nothing sealed")
+ }
+ case alertConnectorSlack, alertConnectorWebhook:
+ if len(sealed) == 0 || plain != "" {
+ return 0, fmt.Errorf("alert connector: %s keeps a sealed target and nothing plain", c.Kind)
+ }
+ default:
+ return 0, fmt.Errorf("alert connector: unknown kind %q", c.Kind)
+ }
+ if c.Scope == "" {
+ return 0, errors.New("alert connector: no scope")
+ }
+ now := time.Now().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,
+ 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)
+ if err != nil {
+ return 0, err
+ }
+ return res.LastInsertId()
+}
+
+func nullBytes(b []byte) any {
+ if len(b) == 0 {
+ return nil
+ }
+ return b
+}
+
+// ConfirmAlertConnector marks id confirmed. Confirming twice keeps the first
+// time.
+func (s *Store) ConfirmAlertConnector(id int64) error {
+ _, err := s.db.Exec(`UPDATE alert_connectors SET confirmed_at = ? WHERE id = ? AND confirmed_at = 0`, time.Now().Unix(), id)
+ return err
+}
+
+// DeleteAlertConnector deletes connector id from scope, with its
+// subscriptions, its unsent outbox rows and its tokens. sql.ErrNoRows: no
+// such connector in that scope.
+func (s *Store) DeleteAlertConnector(scope string, id int64) error {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ res, err := tx.Exec(`DELETE FROM alert_connectors WHERE scope = ? AND id = ?`, scope, id)
+ if err != nil {
+ return err
+ }
+ if n, err := res.RowsAffected(); err != nil {
+ return err
+ } else if n == 0 {
+ return sql.ErrNoRows
+ }
+ for _, stmt := range []string{
+ `DELETE FROM alert_subscriptions WHERE connector_id = ?`,
+ `DELETE FROM alert_outbox WHERE connector_id = ? AND sent_at IS NULL`,
+ `DELETE FROM alert_tokens WHERE connector_id = ?`,
+ } {
+ if _, err := tx.Exec(stmt, id); err != nil {
+ return err
+ }
+ }
+ return tx.Commit()
+}
+
+// AlertConnectorTarget is connector id's stored target: sealed for Slack
+// and webhook, plain for email.
+func (s *Store) AlertConnectorTarget(id int64) (sealed []byte, plain string, err error) {
+ var p sql.NullString
+ err = s.db.QueryRow(`SELECT target_sealed, target_plain FROM alert_connectors WHERE id = ?`, id).Scan(&sealed, &p)
+ return sealed, p.String, err
+}
+
+// SetConnectorHealth records a send's outcome. A success clears the failing
+// clock; a failure starts it, and the failure that finds it 24 hours old
+// suspends the connector (spec §5.3). suspendedNow is true for that one
+// call only, so the scope's owners are told once.
+func (s *Store) SetConnectorHealth(id int64, ok bool, now time.Time) (suspendedNow bool, err error) {
+ if ok {
+ _, err := s.db.Exec(`UPDATE alert_connectors SET failing_since = 0 WHERE id = ?`, id)
+ return false, err
+ }
+ tx, err := s.db.Begin()
+ if err != nil {
+ return false, err
+ }
+ defer tx.Rollback()
+ var failing, suspended int64
+ if err := tx.QueryRow(`SELECT failing_since, suspended_at FROM alert_connectors WHERE id = ?`, id).Scan(&failing, &suspended); err != nil {
+ return false, err
+ }
+ switch {
+ case failing == 0:
+ _, err = tx.Exec(`UPDATE alert_connectors SET failing_since = ? WHERE id = ?`, now.Unix(), id)
+ case suspended == 0 && now.Sub(time.Unix(failing, 0)) >= alertSuspendAfter:
+ _, err = tx.Exec(`UPDATE alert_connectors SET suspended_at = ? WHERE id = ?`, now.Unix(), id)
+ suspendedNow = true
+ default:
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ if err := tx.Commit(); err != nil {
+ return false, err
+ }
+ return suspendedNow, nil
+}
+
+// MarkSealedConnectorsNeedReentry marks every connector with a sealed target
+// as needing re-entry, after the seal key was lost and a new one made: what
+// they hold can no longer be opened. Email connectors are left alone, since
+// their addresses are not sealed. n counts the newly marked.
+func (s *Store) MarkSealedConnectorsNeedReentry() (n int, err error) {
+ res, err := s.db.Exec(`UPDATE alert_connectors SET needs_reentry = 1 WHERE target_sealed IS NOT NULL AND needs_reentry = 0`)
+ if err != nil {
+ return 0, err
+ }
+ c, err := res.RowsAffected()
+ return int(c), err
+}
+
+// ---- rules -------------------------------------------------------------------
+
+// AlertRuleSettings is every rule in scope with a settings row or a
+// subscription. A rule absent from the map is on, with its default
+// threshold and no subscriptions of its own.
+func (s *Store) AlertRuleSettings(scope string) (map[string]alertRuleSetting, error) {
+ out := map[string]alertRuleSetting{}
+ rows, err := s.db.Query(`SELECT rule, enabled, threshold FROM alert_rules WHERE scope = ?`, scope)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var rule string
+ var st alertRuleSetting
+ var th sql.NullFloat64
+ if err := rows.Scan(&rule, &st.Enabled, &th); err != nil {
+ return nil, err
+ }
+ if th.Valid {
+ st.Threshold = &th.Float64
+ }
+ out[rule] = st
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ rows.Close()
+ srows, err := s.db.Query(`SELECT rule, connector_id FROM alert_subscriptions WHERE scope = ? ORDER BY rule, connector_id`, scope)
+ if err != nil {
+ return nil, err
+ }
+ defer srows.Close()
+ for srows.Next() {
+ var rule string
+ var id int64
+ if err := srows.Scan(&rule, &id); err != nil {
+ return nil, err
+ }
+ st, ok := out[rule]
+ if !ok {
+ st.Enabled = true
+ }
+ st.ConnectorIDs = append(st.ConnectorIDs, id)
+ out[rule] = st
+ }
+ return out, srows.Err()
+}
+
+// SetAlertRule replaces rule's settings and subscriptions in scope. Every
+// connector must belong to scope: one scope's alerts never reach another's
+// connector.
+func (s *Store) SetAlertRule(scope, rule string, st alertRuleSetting) error {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ var th sql.NullFloat64
+ if st.Threshold != nil {
+ th = sql.NullFloat64{Float64: *st.Threshold, Valid: true}
+ }
+ if _, err := tx.Exec(`INSERT INTO alert_rules (scope, rule, enabled, threshold) VALUES (?, ?, ?, ?)
+ON CONFLICT(scope, rule) DO UPDATE SET enabled = excluded.enabled, threshold = excluded.threshold`, scope, rule, st.Enabled, th); err != nil {
+ return err
+ }
+ if _, err := tx.Exec(`DELETE FROM alert_subscriptions WHERE scope = ? AND rule = ?`, scope, rule); err != nil {
+ return err
+ }
+ for _, id := range st.ConnectorIDs {
+ var n int
+ if err := tx.QueryRow(`SELECT COUNT(*) FROM alert_connectors WHERE id = ? AND scope = ?`, id, scope).Scan(&n); err != nil {
+ return err
+ }
+ if n == 0 {
+ return fmt.Errorf("alert rule %s: connector %d is not in scope %s", rule, id, scope)
+ }
+ if _, err := tx.Exec(`INSERT OR IGNORE INTO alert_subscriptions (scope, rule, connector_id) VALUES (?, ?, ?)`, scope, rule, id); err != nil {
+ return err
+ }
+ }
+ return tx.Commit()
+}
+
+// ---- snoozes -----------------------------------------------------------------
+
+// Snooze silences (scope, rule, subject) until until. A later snooze
+// replaces the earlier one and never adds to it.
+func (s *Store) Snooze(scope, rule, subject string, until time.Time) error {
+ _, err := s.db.Exec(`INSERT INTO alert_snoozes (scope, rule, subject, until) VALUES (?, ?, ?, ?)
+ON CONFLICT(scope, rule, subject) DO UPDATE SET until = excluded.until`, scope, rule, subject, until.Unix())
+ return err
+}
+
+// Snoozed reports whether (scope, rule, subject) is snoozed at now.
+func (s *Store) Snoozed(scope, rule, subject string, now time.Time) (bool, error) {
+ var until int64
+ err := s.db.QueryRow(`SELECT until FROM alert_snoozes WHERE scope = ? AND rule = ? AND subject = ?`, scope, rule, subject).Scan(&until)
+ if err == sql.ErrNoRows {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ return now.Unix() < until, nil
+}
+
+// ---- tokens ------------------------------------------------------------------
+
+// NewAlertToken stores t under a fresh token and returns the raw token for
+// the link. Only its SHA-256 is kept. confirm and unsubscribe need a
+// connector, snooze a rule.
+func (s *Store) NewAlertToken(t alertToken) (raw string, err error) {
+ switch t.Action {
+ case alertTokenConfirm, alertTokenUnsubscribe:
+ if t.ConnectorID == 0 {
+ return "", fmt.Errorf("alert token: %s needs a connector", t.Action)
+ }
+ case alertTokenSnooze:
+ if t.Rule == "" {
+ return "", errors.New("alert token: snooze needs a rule")
+ }
+ default:
+ return "", fmt.Errorf("alert token: unknown action %q", t.Action)
+ }
+ if t.Scope == "" {
+ return "", errors.New("alert token: no scope")
+ }
+ raw, err = randomToken()
+ if err != nil {
+ return "", err
+ }
+ _, err = s.db.Exec(`INSERT INTO alert_tokens (hash, action, scope, connector_id, rule, subject, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ hashToken(raw), t.Action, t.Scope, sql.NullInt64{Int64: t.ConnectorID, Valid: t.ConnectorID != 0},
+ sql.NullString{String: t.Rule, Valid: t.Action == alertTokenSnooze},
+ sql.NullString{String: t.Subject, Valid: t.Action == alertTokenSnooze}, alertNullUnix(t.ExpiresAt))
+ if err != nil {
+ return "", err
+ }
+ return raw, nil
+}
+
+// UseAlertToken redeems raw for action at now. It refuses (with
+// errAlertTokenInvalid) an unknown token, one minted for another action,
+// one at or past its expiry, and a confirm token already used: confirm is
+// one use, and this marks it used in the same transaction. Unsubscribe
+// (idempotent) and snooze (reusable) may be used again.
+func (s *Store) UseAlertToken(raw, action string, now time.Time) (alertToken, error) {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return alertToken{}, err
+ }
+ defer tx.Rollback()
+ hash := hashToken(raw)
+ 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).
+ Scan(&t.Action, &t.Scope, &conn, &rule, &subject, &expires, &used)
+ if err == sql.ErrNoRows {
+ return alertToken{}, errAlertTokenInvalid
+ }
+ if err != nil {
+ return alertToken{}, err
+ }
+ t.ConnectorID, t.Rule, t.Subject = conn.Int64, rule.String, subject.String
+ t.ExpiresAt, t.UsedAt = alertNullTime(expires), alertNullTime(used)
+ switch {
+ case t.Action != action:
+ return alertToken{}, fmt.Errorf("%w: minted for %s", errAlertTokenInvalid, t.Action)
+ case !t.ExpiresAt.IsZero() && now.Unix() >= expires.Int64:
+ return alertToken{}, fmt.Errorf("%w: expired", errAlertTokenInvalid)
+ case action == alertTokenConfirm && used.Valid:
+ return alertToken{}, fmt.Errorf("%w: already used", errAlertTokenInvalid)
+ }
+ 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()
+ }
+ if err := tx.Commit(); err != nil {
+ return alertToken{}, err
+ }
+ return t, nil
+}
diff --git a/internal/console/alertstore_test.go b/internal/console/alertstore_test.go
new file mode 100644
index 000000000..783d379ac
--- /dev/null
+++ b/internal/console/alertstore_test.go
@@ -0,0 +1,576 @@
+package console
+
+import (
+ "database/sql"
+ "errors"
+ "path/filepath"
+ "reflect"
+ "testing"
+ "time"
+)
+
+var alertT0 = time.Date(2026, 10, 30, 12, 0, 0, 0, time.UTC)
+
+func alertTestIncident(rule string, members ...string) alertIncident {
+ return alertIncident{
+ Scope: "fleet", Rule: rule, Level: "warning",
+ OpenedAt: alertT0, NotifyAt: alertT0.Add(5 * time.Minute), LastSeenAt: alertT0,
+ Members: members,
+ }
+}
+
+func alertTestConnector(t *testing.T, s *Store, kind string) int64 {
+ t.Helper()
+ c := alertConnector{Scope: "fleet", Kind: kind, Name: kind, TargetHint: "…XYZ"}
+ var sealed []byte
+ plain := ""
+ if kind == alertConnectorEmail {
+ plain = "ops@example.com"
+ } else {
+ sealed = []byte("sealed-target")
+ }
+ id, err := s.AddAlertConnector(c, sealed, plain)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return id
+}
+
+func alertCount(t *testing.T, s *Store, table string) int {
+ t.Helper()
+ var n int
+ if err := s.db.QueryRow(`SELECT COUNT(*) FROM ` + table).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+func TestAlertTablesMigrateTwice(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "console.db")
+ s, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ id := alertTestConnector(t, s, alertConnectorEmail)
+ if err := s.migrateAlerts(); err != nil {
+ t.Fatalf("second migrate on a live store: %v", err)
+ }
+ s.Close()
+ s, err = Open(path)
+ if err != nil {
+ t.Fatalf("reopen: %v", err)
+ }
+ defer s.Close()
+ cs, err := s.AlertConnectors("fleet")
+ if err != nil || len(cs) != 1 || cs[0].ID != id {
+ t.Fatalf("connectors after reopen = %+v, %v", cs, err)
+ }
+ for _, table := range []string{"alert_connectors", "alert_rules", "alert_subscriptions", "alert_incidents",
+ "alert_fires", "alert_outbox", "alert_tokens", "alert_snoozes", "alert_meta"} {
+ alertCount(t, s, table)
+ }
+}
+
+// Every write of a step is one transaction: when the outbox insert fails,
+// the incident changes and fires written before it in the same call are
+// gone too, so a crash or error can never leave a transition without its
+// messages (spec §6.1).
+func TestCommitAlertStepAtomic(t *testing.T) {
+ s := openTestStore(t)
+ conn := alertTestConnector(t, s, alertConnectorSlack)
+ if err := s.CommitAlertStep([]alertIncident{alertTestIncident("disk", "box-a")}, nil, nil); err != nil {
+ t.Fatal(err)
+ }
+ open, _, err := s.AlertStepInputs(alertT0)
+ if err != nil || len(open) != 1 {
+ t.Fatalf("open = %+v, %v", open, err)
+ }
+ before := open[0]
+
+ if _, err := s.db.Exec(`CREATE TRIGGER alert_outbox_fail BEFORE INSERT ON alert_outbox BEGIN SELECT RAISE(ABORT, 'forced'); END`); err != nil {
+ t.Fatal(err)
+ }
+ changed := before
+ changed.Notified = true
+ changed.Members = []string{"box-a", "box-b"}
+ changed.LastSeenAt = alertT0.Add(5 * time.Minute)
+ err = s.CommitAlertStep(
+ []alertIncident{changed, alertTestIncident("mem", "box-c")},
+ []alertFire{{Key: alertKey{"fleet", "disk", "box-b"}, At: alertT0.Add(5 * time.Minute)}},
+ []alertOutboxRow{{IncidentID: before.ID, ConnectorID: conn, Kind: "fire", Body: []byte(`{}`)}},
+ )
+ if err == nil {
+ t.Fatal("commit succeeded through a failing outbox insert")
+ }
+ if _, err := s.db.Exec(`DROP TRIGGER alert_outbox_fail`); err != nil {
+ t.Fatal(err)
+ }
+
+ open, fires, err := s.AlertStepInputs(alertT0.Add(5 * time.Minute))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(open) != 1 || !reflect.DeepEqual(open[0], before) {
+ t.Fatalf("incidents after failed commit = %+v, want only %+v", open, before)
+ }
+ if len(fires) != 0 || alertCount(t, s, "alert_outbox") != 0 {
+ t.Fatalf("fires %v or outbox rows survived a failed commit", fires)
+ }
+}
+
+func TestCommitAlertStepSurvivesReopen(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "console.db")
+ s, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ conn := alertTestConnector(t, s, alertConnectorWebhook)
+ inc := alertTestIncident("disk_eta", "box-a", "box-b")
+ inc.Flapping = true
+ key := alertKey{"fleet", "disk_eta", "box-a"}
+ if err := s.CommitAlertStep([]alertIncident{inc}, []alertFire{{Key: key, At: alertT0}}, nil); err != nil {
+ t.Fatal(err)
+ }
+ open, _, _ := s.AlertStepInputs(alertT0)
+ if len(open) != 1 || open[0].ID == 0 {
+ t.Fatalf("open = %+v", open)
+ }
+ inc = open[0]
+ inc.Notified = true
+ inc.LastUpdateAt = alertT0.Add(5 * time.Minute)
+ row := alertOutboxRow{IncidentID: inc.ID, ConnectorID: conn, Kind: "fire", Body: []byte(`{"rule":"disk_eta"}`), NextAt: alertT0.Add(5 * time.Minute)}
+ if err := s.CommitAlertStep([]alertIncident{inc}, nil, []alertOutboxRow{row}); err != nil {
+ t.Fatal(err)
+ }
+ s.Close()
+
+ s, err = Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ now := alertT0.Add(6 * time.Minute)
+ open, fires, err := s.AlertStepInputs(now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(open) != 1 || !reflect.DeepEqual(open[0], inc) {
+ t.Fatalf("after reopen open = %+v, want %+v", open, inc)
+ }
+ if got := fires[key]; len(got) != 1 || !got[0].Equal(alertT0) {
+ t.Fatalf("fires after reopen = %v", fires)
+ }
+ due, err := s.DueOutbox(now, 50)
+ if err != nil || len(due) != 1 {
+ t.Fatalf("due = %+v, %v", due, err)
+ }
+ d := due[0]
+ if d.DeliveryID == "" || d.IncidentID != inc.ID || d.ConnectorID != conn || d.Kind != "fire" ||
+ string(d.Body) != string(row.Body) || d.Attempts != 0 || !d.NextAt.Equal(row.NextAt) {
+ t.Fatalf("due row = %+v", d)
+ }
+
+ // Closing it is an update of the same row, and it leaves the open set.
+ inc.ClosedAt, inc.CloseReason = now, "cleared"
+ if err := s.CommitAlertStep([]alertIncident{inc}, nil, nil); err != nil {
+ t.Fatal(err)
+ }
+ if open, _, _ := s.AlertStepInputs(now); len(open) != 0 {
+ t.Fatalf("closed incident still open: %+v", open)
+ }
+ // An update of an incident that is not there is refused, not dropped.
+ ghost := inc
+ ghost.ID = inc.ID + 100
+ if err := s.CommitAlertStep([]alertIncident{ghost}, nil, nil); err == nil {
+ t.Fatal("update of a missing incident succeeded")
+ }
+}
+
+func TestOutboxDeliveryIDUnique(t *testing.T) {
+ s := openTestStore(t)
+ conn := alertTestConnector(t, s, alertConnectorWebhook)
+ rows := []alertOutboxRow{
+ {ConnectorID: conn, Kind: "clear", Body: []byte(`{}`)},
+ {ConnectorID: conn, Kind: "clear", Body: []byte(`{}`)},
+ {DeliveryID: "d-1", ConnectorID: conn, Kind: "verify", Body: []byte(`{}`)},
+ }
+ if err := s.CommitAlertStep(nil, nil, rows); err != nil {
+ t.Fatal(err)
+ }
+ due, _ := s.DueOutbox(alertT0, 50)
+ if len(due) != 3 || due[0].DeliveryID == "" || due[0].DeliveryID == due[1].DeliveryID || due[2].DeliveryID != "d-1" {
+ t.Fatalf("delivery ids = %+v", due)
+ }
+ // A repeated delivery id refuses the whole step.
+ err := s.CommitAlertStep([]alertIncident{alertTestIncident("disk", "box-a")}, nil,
+ []alertOutboxRow{{DeliveryID: "d-1", ConnectorID: conn, Kind: "fire", Body: []byte(`{}`)}})
+ if err == nil {
+ t.Fatal("a repeated delivery id was accepted")
+ }
+ if open, _, _ := s.AlertStepInputs(alertT0); len(open) != 0 {
+ t.Fatalf("incident committed beside a refused outbox row: %+v", open)
+ }
+ if err := s.CommitAlertStep(nil, nil, []alertOutboxRow{{ConnectorID: conn, Kind: "page", Body: []byte(`{}`)}}); err == nil {
+ t.Fatal("an unknown outbox kind was accepted")
+ }
+}
+
+func TestFinishOutboxBackoff(t *testing.T) {
+ s := openTestStore(t)
+ conn := alertTestConnector(t, s, alertConnectorSlack)
+ if err := s.CommitAlertStep(nil, nil, []alertOutboxRow{{ConnectorID: conn, Kind: "fire", Body: []byte(`{}`), NextAt: alertT0}}); err != nil {
+ t.Fatal(err)
+ }
+ due, _ := s.DueOutbox(alertT0, 10)
+ id := due[0].ID
+ now := alertT0
+ want := []time.Duration{1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 720, 720}
+ for i, w := range want {
+ if err := s.FinishOutbox(id, "timeout", false, now); err != nil {
+ t.Fatal(err)
+ }
+ if due, _ := s.DueOutbox(now.Add(w*time.Minute-time.Second), 10); len(due) != 0 {
+ t.Fatalf("failure %d: due before its %v backoff", i+1, w*time.Minute)
+ }
+ due, _ := s.DueOutbox(now.Add(w*time.Minute), 10)
+ if len(due) != 1 || due[0].Attempts != i+1 || !due[0].NextAt.Equal(now.Add(w*time.Minute)) {
+ t.Fatalf("failure %d: due = %+v, want next_at +%v", i+1, due, w*time.Minute)
+ }
+ now = now.Add(w * time.Minute)
+ }
+ var cat string
+ if err := s.db.QueryRow(`SELECT err_category FROM alert_outbox WHERE id = ?`, id).Scan(&cat); err != nil || cat != "timeout" {
+ t.Fatalf("err_category = %q, %v", cat, err)
+ }
+ if err := s.FinishOutbox(id, "", true, now); err != nil {
+ t.Fatal(err)
+ }
+ if due, _ := s.DueOutbox(now.Add(48*time.Hour), 10); len(due) != 0 {
+ t.Fatalf("a sent row is still due: %+v", due)
+ }
+}
+
+func TestMarkSealedNeedReentryLeavesEmail(t *testing.T) {
+ s := openTestStore(t)
+ email := alertTestConnector(t, s, alertConnectorEmail)
+ slack := alertTestConnector(t, s, alertConnectorSlack)
+ hook := alertTestConnector(t, s, alertConnectorWebhook)
+ n, err := s.MarkSealedConnectorsNeedReentry()
+ if err != nil || n != 2 {
+ t.Fatalf("marked %d, %v; want 2", n, err)
+ }
+ cs, _ := s.AlertConnectors("fleet")
+ got := map[int64]bool{}
+ for _, c := range cs {
+ got[c.ID] = c.NeedsReentry
+ }
+ if got[email] || !got[slack] || !got[hook] {
+ t.Fatalf("needs re-entry = %v (email %d, slack %d, webhook %d)", got, email, slack, hook)
+ }
+ if n, _ := s.MarkSealedConnectorsNeedReentry(); n != 0 {
+ t.Fatalf("second mark counted %d again", n)
+ }
+ sealed, plain, err := s.AlertConnectorTarget(email)
+ if err != nil || sealed != nil || plain != "ops@example.com" {
+ t.Fatalf("email target = %q %q %v", sealed, plain, err)
+ }
+ sealed, plain, err = s.AlertConnectorTarget(slack)
+ if err != nil || string(sealed) != "sealed-target" || plain != "" {
+ t.Fatalf("slack target = %q %q %v", sealed, plain, err)
+ }
+
+ // Each kind keeps its target in its own column only.
+ if _, err := s.AddAlertConnector(alertConnector{Scope: "fleet", Kind: alertConnectorEmail}, []byte("x"), ""); err == nil {
+ t.Fatal("email with a sealed target accepted")
+ }
+ if _, err := s.AddAlertConnector(alertConnector{Scope: "fleet", Kind: alertConnectorSlack}, nil, "https://hooks.slack.com/x"); err == nil {
+ t.Fatal("slack with a plain target accepted")
+ }
+ if _, err := s.AddAlertConnector(alertConnector{Scope: "fleet", Kind: "sms"}, nil, "+447700900000"); err == nil {
+ t.Fatal("an unknown kind accepted")
+ }
+}
+
+func TestAlertConnectorLifecycle(t *testing.T) {
+ s := openTestStore(t)
+ id, err := s.AddAlertConnector(alertConnector{Scope: "fleet", Kind: alertConnectorEmail, Name: "Paul",
+ TargetHint: "paul@…", OwnerAddress: "paul@example.com", Confirmed: true, CreatedBy: "paul@example.com"}, nil, "paul@example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // One seeded personal connector per operator and scope.
+ if _, err := s.AddAlertConnector(alertConnector{Scope: "fleet", Kind: alertConnectorEmail, OwnerAddress: "paul@example.com"}, nil, "paul@example.com"); err == nil {
+ t.Fatal("a second seeded connector for one operator accepted")
+ }
+ other := alertTestConnector(t, s, alertConnectorSlack)
+ cs, _ := s.AlertConnectors("fleet")
+ if len(cs) != 2 || !cs[0].Confirmed || cs[0].OwnerAddress != "paul@example.com" || cs[0].TargetHint != "paul@…" || cs[1].Confirmed {
+ t.Fatalf("connectors = %+v", cs)
+ }
+ if err := s.ConfirmAlertConnector(other); err != nil {
+ t.Fatal(err)
+ }
+ if cs, _ := s.AlertConnectors("fleet"); !cs[1].Confirmed {
+ t.Fatalf("confirm did not stick: %+v", cs[1])
+ }
+
+ // Subscriptions name connectors of the rule's own scope only.
+ acct := alertConnector{Scope: "account:abc", Kind: alertConnectorEmail}
+ foreign, err := s.AddAlertConnector(acct, nil, "me@example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ th := 20.0
+ if err := s.SetAlertRule("fleet", "box_silent", alertRuleSetting{Enabled: true, Threshold: &th, ConnectorIDs: []int64{id, foreign}}); err == nil {
+ t.Fatal("a subscription to another scope's connector accepted")
+ }
+ if err := s.SetAlertRule("fleet", "box_silent", alertRuleSetting{Enabled: true, Threshold: &th, ConnectorIDs: []int64{other, id}}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.SetAlertRule("fleet", "mem", alertRuleSetting{}); err != nil {
+ t.Fatal(err)
+ }
+ rules, err := s.AlertRuleSettings("fleet")
+ if err != nil {
+ t.Fatal(err)
+ }
+ bs := rules["box_silent"]
+ if !bs.Enabled || bs.Threshold == nil || *bs.Threshold != 20 || !reflect.DeepEqual(bs.ConnectorIDs, []int64{id, other}) {
+ t.Fatalf("box_silent = %+v", bs)
+ }
+ if m := rules["mem"]; m.Enabled || m.Threshold != nil || len(m.ConnectorIDs) != 0 {
+ t.Fatalf("mem = %+v", m)
+ }
+
+ // Deleting is scoped, and takes the connector's subscriptions, queued
+ // rows and tokens with it.
+ if _, err := s.NewAlertToken(alertToken{Action: alertTokenUnsubscribe, Scope: "fleet", ConnectorID: other}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.CommitAlertStep(nil, nil, []alertOutboxRow{{ConnectorID: other, Kind: "fire", Body: []byte(`{}`)}}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.DeleteAlertConnector("account:abc", other); !errors.Is(err, sql.ErrNoRows) {
+ t.Fatalf("delete from the wrong scope = %v", err)
+ }
+ if err := s.DeleteAlertConnector("fleet", other); err != nil {
+ t.Fatal(err)
+ }
+ if rules, _ := s.AlertRuleSettings("fleet"); !reflect.DeepEqual(rules["box_silent"].ConnectorIDs, []int64{id}) {
+ t.Fatalf("subscriptions after delete = %+v", rules["box_silent"])
+ }
+ if n := alertCount(t, s, "alert_outbox") + alertCount(t, s, "alert_tokens"); n != 0 {
+ t.Fatalf("%d outbox or token rows outlived their connector", n)
+ }
+ // Ids are never reused, so an old token or row can't reach a newcomer.
+ if next := alertTestConnector(t, s, alertConnectorSlack); next <= foreign {
+ t.Fatalf("connector id %d reused (highest was %d)", next, foreign)
+ }
+}
+
+func TestSetConnectorHealthSuspendsOnce(t *testing.T) {
+ s := openTestStore(t)
+ id := alertTestConnector(t, s, alertConnectorWebhook)
+ get := func() alertConnector {
+ cs, _ := s.AlertConnectors("fleet")
+ return cs[0]
+ }
+ if now, err := s.SetConnectorHealth(id, false, alertT0); err != nil || now {
+ t.Fatalf("first failure suspended = %v, %v", now, err)
+ }
+ if c := get(); !c.FailingSince.Equal(alertT0) || c.Suspended {
+ t.Fatalf("after first failure %+v", c)
+ }
+ // A success inside the 24 hours resets the clock.
+ s.SetConnectorHealth(id, true, alertT0.Add(time.Hour))
+ if c := get(); !c.FailingSince.IsZero() {
+ t.Fatalf("success left failing_since %v", c.FailingSince)
+ }
+ start := alertT0.Add(2 * time.Hour)
+ s.SetConnectorHealth(id, false, start)
+ if now, _ := s.SetConnectorHealth(id, false, start.Add(24*time.Hour-time.Second)); now {
+ t.Fatal("suspended before 24 hours of failing")
+ }
+ if now, _ := s.SetConnectorHealth(id, false, start.Add(24*time.Hour)); !now {
+ t.Fatal("not suspended at 24 hours of failing")
+ }
+ if c := get(); !c.Suspended || !c.FailingSince.Equal(start) {
+ t.Fatalf("after suspension %+v", c)
+ }
+ if now, _ := s.SetConnectorHealth(id, false, start.Add(30*time.Hour)); now {
+ t.Fatal("suspension reported twice")
+ }
+}
+
+func TestAlertTokenActionBound(t *testing.T) {
+ s := openTestStore(t)
+ conn := alertTestConnector(t, s, alertConnectorSlack)
+ raw, err := s.NewAlertToken(alertToken{Action: alertTokenConfirm, Scope: "fleet", ConnectorID: conn, ExpiresAt: alertT0.Add(7 * 24 * time.Hour)})
+ if err != nil || len(raw) != 43 {
+ t.Fatalf("token %q, %v", raw, err)
+ }
+ var stored int
+ s.db.QueryRow(`SELECT COUNT(*) FROM alert_tokens WHERE hash = ?`, raw).Scan(&stored)
+ if stored != 0 {
+ t.Fatal("the raw token is stored")
+ }
+ if _, err := s.UseAlertToken(raw, alertTokenUnsubscribe, alertT0); !errors.Is(err, errAlertTokenInvalid) {
+ t.Fatalf("confirm token used as unsubscribe = %v", err)
+ }
+ if _, err := s.UseAlertToken("not-a-token", alertTokenConfirm, alertT0); !errors.Is(err, errAlertTokenInvalid) {
+ t.Fatalf("unknown token = %v", err)
+ }
+ tok, err := s.UseAlertToken(raw, alertTokenConfirm, alertT0)
+ if err != nil || tok.Action != alertTokenConfirm || tok.Scope != "fleet" || tok.ConnectorID != conn {
+ t.Fatalf("confirm = %+v, %v", tok, err)
+ }
+
+ // Each action carries its target.
+ for _, bad := range []alertToken{
+ {Action: alertTokenConfirm, Scope: "fleet"},
+ {Action: alertTokenUnsubscribe, Scope: "fleet"},
+ {Action: alertTokenSnooze, Scope: "fleet", Subject: "box-a"},
+ {Action: "delete", Scope: "fleet", ConnectorID: conn},
+ {Action: alertTokenSnooze, Rule: "disk", Subject: "box-a"},
+ } {
+ if _, err := s.NewAlertToken(bad); err == nil {
+ t.Errorf("token %+v minted", bad)
+ }
+ }
+}
+
+func TestAlertTokenConfirmOneUse(t *testing.T) {
+ s := openTestStore(t)
+ conn := alertTestConnector(t, s, alertConnectorEmail)
+ raw, _ := s.NewAlertToken(alertToken{Action: alertTokenConfirm, Scope: "fleet", ConnectorID: conn, ExpiresAt: alertT0.Add(time.Hour)})
+ if _, err := s.UseAlertToken(raw, alertTokenConfirm, alertT0); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.UseAlertToken(raw, alertTokenConfirm, alertT0.Add(time.Minute)); !errors.Is(err, errAlertTokenInvalid) {
+ t.Fatalf("second confirm = %v", err)
+ }
+
+ // Unsubscribe (idempotent) and snooze (reusable) are not one-use.
+ unsub, _ := s.NewAlertToken(alertToken{Action: alertTokenUnsubscribe, Scope: "fleet", ConnectorID: conn})
+ snooze, _ := s.NewAlertToken(alertToken{Action: alertTokenSnooze, Scope: "fleet", Rule: "disk", Subject: "box-a", ExpiresAt: alertT0.Add(30 * 24 * time.Hour)})
+ for i := 0; i < 2; i++ {
+ if _, err := s.UseAlertToken(unsub, alertTokenUnsubscribe, alertT0); err != nil {
+ t.Fatalf("unsubscribe use %d: %v", i+1, err)
+ }
+ tok, err := s.UseAlertToken(snooze, alertTokenSnooze, alertT0)
+ if err != nil || tok.Rule != "disk" || tok.Subject != "box-a" || tok.ConnectorID != 0 {
+ t.Fatalf("snooze use %d = %+v, %v", i+1, tok, err)
+ }
+ }
+}
+
+func TestAlertTokenExpired(t *testing.T) {
+ s := openTestStore(t)
+ conn := alertTestConnector(t, s, alertConnectorEmail)
+ exp := alertT0.Add(7 * 24 * time.Hour)
+ raw, _ := s.NewAlertToken(alertToken{Action: alertTokenConfirm, Scope: "fleet", ConnectorID: conn, ExpiresAt: exp})
+ if _, err := s.UseAlertToken(raw, alertTokenConfirm, exp); !errors.Is(err, errAlertTokenInvalid) {
+ t.Fatalf("token used at its expiry = %v", err)
+ }
+ if _, err := s.UseAlertToken(raw, alertTokenConfirm, exp.Add(-time.Second)); err != nil {
+ t.Fatalf("token refused before its expiry: %v", err)
+ }
+ // No expiry: the unsubscribe link in an old email still works.
+ unsub, _ := s.NewAlertToken(alertToken{Action: alertTokenUnsubscribe, Scope: "fleet", ConnectorID: conn})
+ if _, err := s.UseAlertToken(unsub, alertTokenUnsubscribe, alertT0.Add(5*365*24*time.Hour)); err != nil {
+ t.Fatalf("unexpiring token refused: %v", err)
+ }
+}
+
+func TestSnoozeExpires(t *testing.T) {
+ s := openTestStore(t)
+ if err := s.Snooze("fleet", "disk", "box-a", alertT0.Add(time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ check := func(subject string, at time.Time, want bool) {
+ t.Helper()
+ got, err := s.Snoozed("fleet", "disk", subject, at)
+ if err != nil || got != want {
+ t.Fatalf("snoozed(%s, %v) = %v, %v; want %v", subject, at, got, err, want)
+ }
+ }
+ check("box-a", alertT0, true)
+ check("box-b", alertT0, false)
+ check("box-a", alertT0.Add(time.Hour), false)
+ // A second snooze replaces the first and never adds to it.
+ s.Snooze("fleet", "disk", "box-a", alertT0.Add(10*time.Minute))
+ check("box-a", alertT0.Add(30*time.Minute), false)
+}
+
+func TestFlapHistoryPrunedAfterHour(t *testing.T) {
+ s := openTestStore(t)
+ key := alertKey{"fleet", "disk", "box-a"}
+ other := alertKey{"fleet", "disk", "box-b"}
+ fires := []alertFire{
+ {Key: key, At: alertT0},
+ {Key: key, At: alertT0.Add(20 * time.Minute)},
+ {Key: other, At: alertT0.Add(40 * time.Minute)},
+ }
+ if err := s.CommitAlertStep(nil, fires, nil); err != nil {
+ t.Fatal(err)
+ }
+ _, recent, err := s.AlertStepInputs(alertT0.Add(40 * time.Minute))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(recent[key]) != 2 || !recent[key][0].Equal(alertT0) || len(recent[other]) != 1 {
+ t.Fatalf("recent = %v", recent)
+ }
+ _, recent, _ = s.AlertStepInputs(alertT0.Add(70 * time.Minute))
+ if len(recent[key]) != 1 || !recent[key][0].Equal(alertT0.Add(20*time.Minute)) {
+ t.Fatalf("recent past the hour = %v", recent)
+ }
+ if n := alertCount(t, s, "alert_fires"); n != 2 {
+ t.Fatalf("%d fire rows kept, want the 2 inside the hour", n)
+ }
+}
+
+func TestAlertCutoverOnce(t *testing.T) {
+ s := openTestStore(t)
+ conn := alertTestConnector(t, s, alertConnectorEmail)
+ queue := func(tx *sql.Tx) error {
+ return insertAlertOutbox(tx, alertOutboxRow{ConnectorID: conn, Kind: "clear", Body: []byte(`{}`)})
+ }
+ // A failing cutover leaves no marker and no rows.
+ if ran, err := s.AlertCutover(func(tx *sql.Tx) error {
+ if err := queue(tx); err != nil {
+ return err
+ }
+ return errors.New("boom")
+ }); err == nil || ran {
+ t.Fatalf("failing cutover = %v, %v", ran, err)
+ }
+ if n := alertCount(t, s, "alert_outbox"); n != 0 {
+ t.Fatalf("%d rows from a failed cutover", n)
+ }
+ if ran, err := s.AlertCutover(queue); err != nil || !ran {
+ t.Fatalf("cutover = %v, %v", ran, err)
+ }
+ if ran, err := s.AlertCutover(queue); err != nil || ran {
+ t.Fatalf("second cutover = %v, %v", ran, err)
+ }
+ if n := alertCount(t, s, "alert_outbox"); n != 1 {
+ t.Fatalf("%d cutover rows, want 1", n)
+ }
+}
+
+// The alert tables are classified for the claim SQL gate, so an armed
+// console opens with them.
+func TestClaimSQLTablesClassified(t *testing.T) {
+ s := openGatedStore(t)
+ present, err := claimSQLCensus(s.bootDB(), claimSQLTables)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{"alert_connectors", "alert_rules", "alert_subscriptions", "alert_incidents",
+ "alert_fires", "alert_outbox", "alert_tokens", "alert_snoozes", "alert_meta"} {
+ if sp, ok := present[name]; !ok || sp.NonApp == "" {
+ t.Errorf("%s classified as %+v (present %v), want NonApp", name, sp, ok)
+ }
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index 016db3b57..249d6a8a3 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -608,6 +608,10 @@ type Config struct {
// crash never leaves an upload behind for good. "" = the OS temp dir,
// not cleared (tests).
GeoipStagingDir string
+ // AlertSealKeyPath is the connector seal's key file (alertseal.go,
+ // fleet alerts spec §5.1): beside console.db, never inside it, so a
+ // replica or backup of the database alone cannot open a Slack URL.
+ AlertSealKeyPath string
// The GeoIP feed (geoip spec §10.1): CONSOLE_GEOIP_FEED and, for
// GeoLite2, the MaxMind account and key. BoxLabel is this console's
// box, named in feed.json so only that box's mirror alerts on feed
diff --git a/internal/console/store.go b/internal/console/store.go
index 3764cc2d7..3953fe5ae 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -652,7 +652,11 @@ func (s *Store) migrate() error {
return err
}
// The operator pages' column and indexes (opstore.go), for the same reason.
- return s.migrateOperatorPages()
+ if err := s.migrateOperatorPages(); err != nil {
+ return err
+ }
+ // The alert engine's tables (alertstore.go), for the same reason.
+ return s.migrateAlerts()
}
// migratePlanSeats adds account_plans.seats (plans 6b): the paid seat count
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index 3a1bf127e..b0f536d85 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -247,6 +247,18 @@ var claimSQLTables = map[string]claimSQLTable{
"billing_retirements": {NonApp: "accounts whose deletion is in progress, keyed by account; names no app"},
"billing_restore_checks": {NonApp: "an account's late-restore verification obligations; names no app"},
"billing_operations": {NonApp: "an account's billing operations, each one prepared provider request and its outcome, keyed by subscription; names no app"},
+
+ // The alert engine's tables (alertstore.go). A scope is "fleet" or an
+ // account; subjects name boxes, services and apps as message text only.
+ "alert_connectors": {NonApp: "alert destinations, keyed by id and owned by a scope (fleet or an account); names no app"},
+ "alert_rules": {NonApp: "alert rule settings per scope and rule; names no app"},
+ "alert_subscriptions": {NonApp: "which connectors a scope's rule notifies; names no app"},
+ "alert_incidents": {NonApp: "alert incidents per scope and rule, with member subjects as text; no app state or lifecycle authority"},
+ "alert_fires": {NonApp: "an hour of alert fire times per scope, rule and subject, for flap detection; no app state"},
+ "alert_outbox": {NonApp: "queued alert messages, keyed by id and bound to a connector and incident; names no app"},
+ "alert_tokens": {NonApp: "alert confirm, unsubscribe and snooze links, keyed by token hash; names no app"},
+ "alert_snoozes": {NonApp: "alert snoozes per scope, rule and subject; no app state"},
+ "alert_meta": {NonApp: "the alert engine's one-shot markers"},
}
// claimSQLReservedName is the TEMP permit table. A main-schema table by that
diff --git a/internal/console/testdata/claim-authority-sites.txt b/internal/console/testdata/claim-authority-sites.txt
index a075f01d7..fa8bfa35d 100644
--- a/internal/console/testdata/claim-authority-sites.txt
+++ b/internal/console/testdata/claim-authority-sites.txt
@@ -47,6 +47,8 @@
../mail/aws.go|NewAWSProvisioner|sesv2.NewFromConfig(cfg)
../mail/aws.go|NewAWSProvisioner|sts.NewFromConfig(cfg)
../mail/sessend.go|NewSESEmailSender|sesv2.NewFromConfig(cfg)
+alertseal.go|Open|c.aead.Open(nil, sealed[:n], sealed[n:], nil)
+alertseal.go|createAlertSealKey|os.Open(filepath.Dir(path))
apihostclaim.go|handleAPIHostResolveInspect|s.cfg.ClaimAuthority.InspectMoveLoss(r.Context(), actor, account, app, r.PathValue("host"), in.Box)
apihostclaim.go|handleAPIHostResolve|s.cfg.ClaimAuthority.DeclareMoveLoss(r.Context(), actor, account, app, r.PathValue("host"), s.claimChallengeBox(in.Submission), in.Submission)
apiinstancemove.go|claimConsoleMove|a.Control.ConsoleMove(ctx, o, action)