console: alert senders and outbox drain
Slack, signed webhook and email rendering from one alertNote, with the words around it in one alertCopy map of drafts for Task 9. The drain sends up to 50 due rows a pass through the guarded client and deliver(), re-reading each connector first: deleted, suspended or needs-re-entry rows wait, unconfirmed connectors get only verify rows, and a seeded connector whose owner is no longer an operator is deleted with its queue. Snooze (30 d), unsubscribe and confirm (7 d) links are minted per delivery (ruling R-2). A suspension tells the scope's other connectors once, or its owners by email. A cancelled drain leaves the row due and the connector's health alone. sendTestAlert is limited to 10 an hour per connector, refuses unconfirmed email, confirms a webhook on 2xx, and lifts a suspension when it gets through (R-11). Store: AlertConnector(id), ResumeAlertConnector, DropOutbox. Authority census: one new Open site, alertnotify.go alertTarget's seal.Open (opening a connector URL; no claim state).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/console/alertnotify.go+675 −0internal/console/alertnotify_test.go+888 −0internal/console/alertstore.go+41 −12internal/console/server.go+11 −0internal/console/testdata/claim-authority-sites.txt+1 −0
Intent
<task-notification> <task-id>af261fb5bed9a187e</task-id> <tool-use-id>toolu_01MFpxEiugGGuTXoQ6pLyYDF</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/af261fb5bed9a187e.output</output-file> <status>completed</status> <summary>Agent "Implement Task 5: guarded client and signing" 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 - **Commits:** `b1d38187` console: guarded alert client, URL-free errors, alert signing. `21e01baa` console: alert client fix round 1 (no keep-alives, wider refusals, shared Ed25519 signing). Not pushed. - **Tests:** all six fixes are in and the covering tests pass: the alert client and signing tests (including the new `TestAlertClientNewConnectionPerSend` and `TestSignLabelledKeepsEachScheme`) and the existing mailpush tests, unchanged. The census tests also pass. `go vet` is clean for linux, darwin and windows. For each fix I broke the code on purpose (K1-K5) and the matching test failed; the file was restored each time. - **Concerns (minor):** - The mail key's internal error text now names the key row ("stored mail-events-sign key"). Nothing matches on that text, and signatures and keys are byte for byte the same. - `alertPublicKey` and `mailEventsPublicKey` are still two matching one-liners; the ruling named no shared helper for them. - NAT64 is now refused. Still open from the first round: - `context.Canceled` reports as `"connect"`. - TLS errors are recognised by type only. - `AlertSigningKey` is in `store.go`, not beside the mail key in `mailpush.go`. - The URL error messages still need the Task 9 copy review. - **Report:** `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-5-report.md` (fix round appended)</result> <usage><subagent_tokens>129896</subagent_tokens><tool_uses>14</tool_uses><duration_ms>373808</duration_ms></usage> </task-notification>
<task-notification> <task-id>a575146261e159811</task-id> <tool-use-id>toolu_019E5KjPGLHqUw1ecLNNJk4c</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a575146261e159811.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 5 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>**Fix round 1 verdict:** all six findings are addressed, and the fix introduced no new Critical or Important problems. I ran no tests; this is a read of the diff file, the report, and `alertdial.go`, `alertdial_test.go`, `mailpush.go` and `store.go` at HEAD. The report names the tests it ran and shows them passing. ### Finding Verdicts 1. **Idle connections to tenant-chosen hosts were kept** — ADDRESSED. - `internal/console/alertdial.go:185` sets `DisableKeepAlives: true`. - The new test `TestAlertClientNewConnectionPerSend` (`alertdial_test.go`, around line 225) makes two sends, over HTTP/1.1 and again over HTTP/2. It checks the protocol of each request and that the server saw 2 new connections each time. - Go's HTTP/2 transport honours `DisableKeepAlives` (the connection is used once), so the HTTP/2 case tests real behaviour. The report's mutation check K1 shows the test fails when keep-alives are back on. 2. **Signing code duplicated `mailpush.go`** — ADDRESSED. - `Store.ed25519Key(name)` is at `store.go:3012`, with the row name passed as a bound parameter in both the SELECT and the INSERT. `mailpush.go:139` and `store.go:3006` call it. - `signLabelled` (`mailpush.go:160`) and `labelledBytes` (`mailpush.go:168`) are used by `signMailEvent` (`:150`), `mailEventSignedBytes` (`:154`, still used by `VerifyMailEvent` at `:208`) and `signAlert` (`alertsign.go:23`). - `labelledBytes` builds exactly the bytes the old `mailEventSignedBytes` did, so mail output is unchanged. `mailpush_test.go` is not in the diff stat. - The new `TestSignLabelledKeepsEachScheme` rebuilds both headers by hand and checks each key's `keys` row. - What remains is small: `alertPublicKey` and `mailEventsPublicKey` are still parallel one-liners. The required fix named no helper for them. 3. **More refused ranges** — ADDRESSED. - The `refusedPrefixes` table in `alertdial.go` holds every range the finding listed. Table rows include `::10.0.0.1`, `::127.0.0.1`, both NAT64 forms, 6to4, Teredo, `240.0.0.1`, `255.255.255.255`, the `198.18.0.0/15` range and `fec0::1`. - **Does `::/96` catch legitimate addresses?** No. - The only addresses it covers are `::` (unspecified), `::1` (loopback) and the deprecated IPv4-compatible forms. All of them sit inside reserved `::/8`, and none is a routable destination. - IPv4-mapped addresses (`::ffff:0:0/96`) are not inside `::/96`, and `Unmap()` runs first anyway. The test row `::ffff:1.1.1.1` stays allowed. - `netip.Prefix.Contains` is false across address families, so `::/96` never matches a v4 address. - **`2001::/32`** covers only Teredo. The allowed row `2001:4860:4860::8888` shows `2001:4860::` is not caught. 4. **Numeric last label** — ADDRESSED. `numericLastLabel` in `alertdial.go` rejects a last label that is all digits or starts with `0x`. - **Can it reject a real host name?** No. Top-level domains are letters only or `xn--` punycode, so none is all digits or starts with `0x`. - Every numeric host form some resolvers accept (`inet_aton` style: decimal, octal or hex parts, 1 to 4 parts) ends in a decimal, octal or `0x` hex part, so this check catches all of them. - Hosts that should still pass do: `1password.example.com` and `10.example.com.`. - Odd edge: a host ending in two dots, like `a.com..`, leaves an empty last label and is rejected with the "not an IP address" message. That is wrong only in wording, and rejecting it is correct. 5. **Slack host compare** — ADDRESSED. - The check is now `!isASCII(host) || strings.ToLower(host) != slackHookHost`. - `url.Parse` accepts raw non-ASCII bytes in a host, so the long-s and Kelvin-sign test rows really reach `isASCII`. Percent-encoded ASCII in a host is rejected by `url.Parse` itself, so that is no way around it. Mutation check K5 confirms the old `EqualFold` lets both through. - The request is built with an empty URL and then given `req.URL = u`, the validated URL, so there is no re-parse. 6. **Response header limit** — ADDRESSED. `alertdial.go:186` sets `MaxResponseHeaderBytes: 16 << 10`. Go's HTTP/2 transport takes the same limit from this field. `TestPostAlertCategories` now sends 32 KiB of headers and expects `"connect"`. Mutation check K2 confirms the test fails without the limit. ### New Breakage in the Fix Diff None at Critical or Important. Three Minor points: - **Minor:** A host with an empty port, like `hooks.slack.com:`, now keeps that trailing colon in the Host header. The old `NewRequest(u.String())` path stripped it. The connection and TLS server name are unaffected, so this is harmless. - **Minor (test):** In `TestAlertClientNewConnectionPerSend`, `defer mu.Unlock()` sits inside the loop. Each pass has its own mutex, so nothing deadlocks, but each pass's lock is held until the test ends. - **Minor (trade-off):** The whole NAT64 and 6to4 ranges are refused rather than judged by the v4 address inside them. On a box that is IPv6-only with DNS64, every v4-only webhook host would be refused. It fails safe, and the report says the console boxes don't use DNS64. ### Out-of-Scope Observations These are from the earlier report and the fix did not touch them: - `context.Canceled` is still reported as `"connect"`. - TLS errors are still classified by type only. ### Verdict **Fix round:** All findings addressed, no new Critical/Important breakage.</result> <usage><subagent_tokens>68888</subagent_tokens><tool_uses>7</tool_uses><duration_ms>114457</duration_ms></usage> </task-notification>
Attributed to this commit: 16.8 g CO₂e (2,064,692 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/internal/console/alertnotify.go b/internal/console/alertnotify.go| new file mode 100644 |
| index 000000000..cc4e2b80e |
| --- /dev/null |
| +++ b/internal/console/alertnotify.go |
| @@ -0,0 +1,675 @@ |
| +package console |
| + |
| +// Alert messages and the outbox drain (fleet alerts spec §5.1, §5.3, §6). |
| +// The engine writes what a message says into alert_outbox (an alertNote |
| +// with no links, ruling R-2); this file turns each due row into a Slack |
| +// post, a signed webhook or an email, adding its links as it goes, and |
| +// records how the send went. |
| +// |
| +// Before each send the connector is read again, because a queued row can |
| +// outlive the reason it was queued: the connector may have been deleted, |
| +// suspended or left needing re-entry, its owner may no longer be an |
| +// operator, or it may never have been confirmed. Only a verify row (the |
| +// email confirm link, the Slack test with its link, the signed webhook |
| +// test) reaches an unconfirmed connector (R2 #7). |
| +// |
| +// Links are minted per delivery, so a token exists only for a message that |
| +// is actually sent: a snooze bound to the incident's (scope, rule, |
| +// subject) for 30 days, an unsubscribe bound to the connector with no |
| +// expiry, and on a verify row a confirm link for 7 days instead. |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "database/sql" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/alerting" |
| +) |
| + |
| +const ( |
| + // alertDrainBatch is the most rows one drain pass reads. |
| + alertDrainBatch = 50 |
| + // An email send's whole budget, and Keymail's share of it (deliver). |
| + alertEmailTimeout = 20 * time.Second |
| + alertKeymailShare = 12 * time.Second |
| + alertSnoozeLinkTTL = 30 * 24 * time.Hour |
| + alertConfirmLinkTTL = 7 * 24 * time.Hour |
| + // alertTestsPerHour is each connector's test sends in an hour (spec |
| + // §5.3). |
| + alertTestsPerHour = 10 |
| +) |
| + |
| +// alertNote is one message: what the engine stores as body_json, plus the |
| +// links and delivery id the sender adds. Named to stay clear of |
| +// alertwatch.go's alertMessage. ConfirmURL is set only on a verify row to |
| +// an unconfirmed connector, in place of the snooze and unsubscribe links. |
| +type alertNote struct { |
| + Scope string `json:"scope"` |
| + Rule string `json:"rule"` |
| + Level string `json:"level"` |
| + Kind string `json:"kind"` |
| + Subject string `json:"subject"` |
| + What string `json:"what"` |
| + HowLong string `json:"how_long"` |
| + WhatToDo string `json:"what_to_do"` |
| + IncidentURL string `json:"incident_url,omitempty"` |
| + SnoozeURL string `json:"snooze_url,omitempty"` |
| + UnsubscribeURL string `json:"unsubscribe_url,omitempty"` |
| + ConfirmURL string `json:"confirm_url,omitempty"` |
| + Members []string `json:"members"` |
| + At time.Time `json:"at"` |
| + DeliveryID string `json:"delivery_id,omitempty"` |
| +} |
| + |
| +// alertCopy is every word the senders put around a note's own text. These |
| +// are drafts: Task 9's copy review replaces them here, in place. Headlines |
| +// take the rule, then the subject. |
| +var alertCopy = map[string]string{ |
| + "head.fire": "%[1]s on %[2]s", |
| + "head.clear": "Cleared: %[1]s on %[2]s", |
| + "head.update": "More affected: %[1]s on %[2]s", |
| + "head.reminder": "Still open: %[1]s on %[2]s", |
| + "head.suspended": "Alerts to %[2]s have stopped", |
| + "head.verify": "Check alerts reach %[2]s", |
| + |
| + "email.subject": "[carlos] %s", |
| + |
| + "label.what": "What is wrong", |
| + "label.how_long": "How long you have", |
| + "label.what_to_do": "What to do", |
| + "label.members": "Affected", |
| + |
| + "link.incident": "See the incident", |
| + "link.snooze": "Snooze this alert", |
| + "link.confirm": "Confirm alerts here", |
| + "link.unsubscribe": "Stop these alerts", |
| + |
| + "suspended.what": "Sending to %s has failed for 24 hours, so alerts no longer go there.", |
| + "suspended.how_long": "Until it is fixed, every alert meant for it is missed.", |
| + "suspended.what_to_do": "Check it on the alerts page, then send a test. A test that gets through turns it back on.", |
| + |
| + "test.what": "This is a test alert from %s.", |
| + "test.how_long": "Nothing is wrong. There is no rush.", |
| + "test.how_long.confirm": "The confirm link works for 7 days.", |
| + "test.what_to_do": "Nothing. Real alerts will arrive here like this one.", |
| + "test.what_to_do.confirm": "Open the confirm link. Until then, no alerts come here.", |
| + "test.what_to_do.webhook": "Answer with any 2xx status. The first one confirms this webhook.", |
| +} |
| + |
| +func alertHeadline(n alertNote) string { |
| + f, ok := alertCopy["head."+n.Kind] |
| + if !ok { |
| + f = alertCopy["head.fire"] |
| + } |
| + return fmt.Sprintf(f, n.Rule, n.Subject) |
| +} |
| + |
| +// alertSlackEscaper escapes what Slack reads as markup: without it a |
| +// subject holding "<!channel>" would ping the whole channel. |
| +var alertSlackEscaper = strings.NewReplacer("&", "&", "<", "<", ">", ">") |
| + |
| +// renderSlack is n as an incoming-webhook body: blocks, with the headline |
| +// as the plain text fallback (spec §5.1). |
| +func renderSlack(n alertNote) []byte { |
| + esc := alertSlackEscaper.Replace |
| + head := esc(alertHeadline(n)) |
| + var lines []string |
| + line := func(label, v string) { |
| + if v != "" { |
| + lines = append(lines, "*"+esc(alertCopy[label])+":* "+esc(v)) |
| + } |
| + } |
| + line("label.what", n.What) |
| + line("label.how_long", n.HowLong) |
| + line("label.what_to_do", n.WhatToDo) |
| + if len(n.Members) > 1 { |
| + line("label.members", strings.Join(n.Members, ", ")) |
| + } |
| + var links []string |
| + for _, l := range alertNoteLinks(n) { |
| + links = append(links, "<"+l.url+"|"+esc(alertCopy[l.label])+">") |
| + } |
| + type text struct { |
| + Type string `json:"type"` |
| + Text string `json:"text"` |
| + } |
| + type block struct { |
| + Type string `json:"type"` |
| + Text *text `json:"text,omitempty"` |
| + Elements []text `json:"elements,omitempty"` |
| + } |
| + blocks := []block{{Type: "section", Text: &text{"mrkdwn", "*" + head + "*"}}} |
| + if len(lines) > 0 { |
| + blocks = append(blocks, block{Type: "section", Text: &text{"mrkdwn", strings.Join(lines, "\n")}}) |
| + } |
| + if len(links) > 0 { |
| + blocks = append(blocks, block{Type: "context", Elements: []text{{"mrkdwn", strings.Join(links, " · ")}}}) |
| + } |
| + b, _ := json.Marshal(struct { |
| + Text string `json:"text"` |
| + Blocks []block `json:"blocks"` |
| + }{head, blocks}) |
| + return b |
| +} |
| + |
| +type alertLink struct{ label, url string } |
| + |
| +// alertNoteLinks is n's links in the order a message shows them, the |
| +// unsubscribe link last. |
| +func alertNoteLinks(n alertNote) []alertLink { |
| + var out []alertLink |
| + for _, l := range []alertLink{{"link.confirm", n.ConfirmURL}, {"link.incident", n.IncidentURL}, |
| + {"link.snooze", n.SnoozeURL}, {"link.unsubscribe", n.UnsubscribeURL}} { |
| + if l.url != "" { |
| + out = append(out, l) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// renderWebhook is n as the versioned webhook body (spec §5.1, R2 #8). The |
| +// receiver drops a repeat by delivery_id (spec §6.1). |
| +func renderWebhook(n alertNote) []byte { |
| + members := n.Members |
| + if members == nil { |
| + members = []string{} |
| + } |
| + b, _ := json.Marshal(struct { |
| + V int `json:"v"` |
| + DeliveryID string `json:"delivery_id"` |
| + Scope string `json:"scope"` |
| + Rule string `json:"rule"` |
| + Level string `json:"level"` |
| + Kind string `json:"kind"` |
| + Subject string `json:"subject"` |
| + Members []string `json:"members"` |
| + What string `json:"what"` |
| + HowLong string `json:"how_long"` |
| + WhatToDo string `json:"what_to_do"` |
| + At string `json:"at"` |
| + IncidentURL string `json:"incident_url"` |
| + SnoozeURL string `json:"snooze_url"` |
| + }{1, n.DeliveryID, n.Scope, n.Rule, n.Level, n.Kind, n.Subject, members, n.What, n.HowLong, n.WhatToDo, |
| + n.At.UTC().Format(time.RFC3339), n.IncidentURL, n.SnoozeURL}) |
| + return b |
| +} |
| + |
| +// alertHeaderLine keeps a subject to one line, whatever a rule or subject |
| +// name holds. |
| +var alertHeaderLine = strings.NewReplacer("\r", " ", "\n", " ") |
| + |
| +// renderEmail is n as an email. Every alert's body ends with its |
| +// unsubscribe link (spec §5.1); a confirmation, which has none, ends with |
| +// its confirm link. |
| +func renderEmail(n alertNote) (subject, body string) { |
| + subject = alertHeaderLine.Replace(fmt.Sprintf(alertCopy["email.subject"], alertHeadline(n))) |
| + var b strings.Builder |
| + line := func(label, v string) { |
| + if v != "" { |
| + b.WriteString(alertCopy[label] + ": " + v + "\n") |
| + } |
| + } |
| + line("label.what", n.What) |
| + line("label.how_long", n.HowLong) |
| + line("label.what_to_do", n.WhatToDo) |
| + if len(n.Members) > 1 { |
| + b.WriteString("\n") |
| + line("label.members", strings.Join(n.Members, ", ")) |
| + } |
| + if links := alertNoteLinks(n); len(links) > 0 { |
| + b.WriteString("\n") |
| + for _, l := range links { |
| + if l.label == "link.unsubscribe" { |
| + b.WriteString("\n") |
| + } |
| + line(l.label, l.url) |
| + } |
| + } |
| + return subject, b.String() |
| +} |
| + |
| +// ---- the drain --------------------------------------------------------------- |
| + |
| +func (s *Server) alertClockNow() time.Time { |
| + if s.alertClock != nil { |
| + return s.alertClock() |
| + } |
| + return time.Now() |
| +} |
| + |
| +// alertClient is the guarded client (alertdial.go), built on first use. |
| +func (s *Server) alertClient() *http.Client { |
| + s.alertHTTPOnce.Do(func() { |
| + if s.alertHTTP == nil { |
| + s.alertHTTP = newAlertHTTPClient(refusedAddr) |
| + } |
| + }) |
| + return s.alertHTTP |
| +} |
| + |
| +// alertDrainOutbox sends up to alertDrainBatch due outbox rows, each ending |
| +// in FinishOutbox. When ctx ends (the console shutting down) it stops and |
| +// returns ctx's error, leaving the row in hand due and its connector's |
| +// health untouched: shutdown is not a connector failing. |
| +func (s *Server) alertDrainOutbox(ctx context.Context) error { |
| + rows, err := s.store.DueOutbox(s.alertClockNow(), alertDrainBatch) |
| + if err != nil { |
| + return err |
| + } |
| + for _, r := range rows { |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + if err := s.drainAlertRow(ctx, r); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +func (s *Server) drainAlertRow(ctx context.Context, r alertOutboxRow) error { |
| + now := s.alertClockNow() |
| + c, ok, err := s.usableAlertConnector(r.ConnectorID) |
| + if err != nil { |
| + return err |
| + } |
| + if !ok { |
| + // Deleted, or deleted just now for a revoked operator: nothing is |
| + // owed to it any more. |
| + return s.store.DropOutbox(r.ID) |
| + } |
| + if hold := alertWithheld(c, r.Kind); hold != "" { |
| + return s.store.FinishOutbox(r.ID, hold, false, now) |
| + } |
| + var n alertNote |
| + if err := json.Unmarshal(r.Body, &n); err != nil { |
| + log.Printf("console: alert outbox row %d does not decode, dropping it: %v", r.ID, err) |
| + return s.store.DropOutbox(r.ID) |
| + } |
| + n.Kind, n.DeliveryID = r.Kind, r.DeliveryID |
| + if n.At.IsZero() { |
| + n.At = now |
| + } |
| + target, hold, err := s.alertTarget(c) |
| + if err != nil { |
| + return err |
| + } |
| + if hold != "" { |
| + return s.store.FinishOutbox(r.ID, hold, false, now) |
| + } |
| + if err := s.addAlertLinks(c, r.IncidentID, &n, now); err != nil { |
| + return err |
| + } |
| + cat, err := s.sendAlertNote(ctx, c, target, n, now) |
| + if err != nil { |
| + return err |
| + } |
| + if err := ctx.Err(); err != nil { |
| + return err |
| + } |
| + sent := cat == "" |
| + if !sent { |
| + log.Printf("console: alert %s to %s connector %d not sent: %s", r.Kind, c.Kind, c.ID, cat) |
| + } |
| + if err := s.store.FinishOutbox(r.ID, string(cat), sent, now); err != nil { |
| + return err |
| + } |
| + if sent && r.Kind == "verify" && c.Kind == alertConnectorWebhook && !c.Confirmed { |
| + if err := s.store.ConfirmAlertConnector(c.ID); err != nil { |
| + return err |
| + } |
| + } |
| + suspendedNow, err := s.store.SetConnectorHealth(c.ID, sent, now) |
| + if err != nil { |
| + return err |
| + } |
| + if suspendedNow { |
| + if err := s.tellAlertSuspended(ctx, c, now); err != nil { |
| + log.Printf("console: alert connector %d suspended, and telling its owners failed: %v", c.ID, err) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// usableAlertConnector reads connector id before a send. ok is false when |
| +// it is gone, including when its owner is no longer an operator: such a |
| +// connector is deleted here, with its queued rows (Review Focus 4). |
| +func (s *Server) usableAlertConnector(id int64) (c alertConnector, ok bool, err error) { |
| + c, err = s.store.AlertConnector(id) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return c, false, nil |
| + } |
| + if err != nil { |
| + return c, false, err |
| + } |
| + if c.OwnerAddress != "" { |
| + op, err := s.store.IsOperator(c.OwnerAddress) |
| + if err != nil { |
| + return c, false, err |
| + } |
| + if !op { |
| + log.Printf("console: %s is no longer an operator, so their alert connector %d is deleted", c.OwnerAddress, c.ID) |
| + if err := s.store.DeleteAlertConnector(c.Scope, c.ID); err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + return c, false, err |
| + } |
| + return c, false, nil |
| + } |
| + } |
| + return c, true, nil |
| +} |
| + |
| +// alertWithheld is why a row of kind may not go to c now, "" when it may. |
| +// A withheld row is retried on the outbox's backoff and never counts |
| +// against the connector's health. |
| +func alertWithheld(c alertConnector, kind string) string { |
| + switch { |
| + case c.NeedsReentry: |
| + return "needs re-entry" |
| + case c.Suspended: |
| + return "suspended" |
| + case !c.Confirmed && kind != "verify": |
| + return "unconfirmed" |
| + } |
| + return "" |
| +} |
| + |
| +// alertTarget is where c sends: its address, or its opened URL. hold says |
| +// why there is none to use (no seal key yet, or one that cannot open it). |
| +func (s *Server) alertTarget(c alertConnector) (target, hold string, err error) { |
| + sealed, plain, err := s.store.AlertConnectorTarget(c.ID) |
| + if err != nil { |
| + return "", "", err |
| + } |
| + if c.Kind == alertConnectorEmail { |
| + return plain, "", nil |
| + } |
| + seal := s.alertSeal.Load() |
| + if seal == nil { |
| + return "", "no seal key", nil |
| + } |
| + p, err := seal.Open(sealed) |
| + if err != nil { |
| + return "", "seal", nil |
| + } |
| + return string(p), "", nil |
| +} |
| + |
| +// addAlertLinks mints n's links for this delivery to c. A verify note to an |
| +// unconfirmed connector gets a confirm link and nothing else; a webhook |
| +// gets no unsubscribe link, having nowhere to show it. |
| +func (s *Server) addAlertLinks(c alertConnector, incidentID int64, n *alertNote, now time.Time) error { |
| + if n.Scope == "" { |
| + n.Scope = c.Scope |
| + } |
| + origin := s.cfg.Origin |
| + if n.Kind == "verify" && !c.Confirmed { |
| + if c.Kind == alertConnectorWebhook { |
| + return nil // a 2xx confirms it |
| + } |
| + raw, err := s.store.NewAlertToken(alertToken{Action: alertTokenConfirm, Scope: c.Scope, ConnectorID: c.ID, |
| + ExpiresAt: now.Add(alertConfirmLinkTTL)}) |
| + if err != nil { |
| + return err |
| + } |
| + n.ConfirmURL = origin + "/alerts/confirm/" + url.PathEscape(raw) |
| + return nil |
| + } |
| + if n.Rule != "" && n.Kind != "verify" { |
| + raw, err := s.store.NewAlertToken(alertToken{Action: alertTokenSnooze, Scope: n.Scope, Rule: n.Rule, |
| + Subject: n.Subject, ExpiresAt: now.Add(alertSnoozeLinkTTL)}) |
| + if err != nil { |
| + return err |
| + } |
| + n.SnoozeURL = origin + "/alerts/snooze/" + url.PathEscape(raw) |
| + } |
| + if c.Kind != alertConnectorWebhook { |
| + raw, err := s.store.NewAlertToken(alertToken{Action: alertTokenUnsubscribe, Scope: c.Scope, ConnectorID: c.ID}) |
| + if err != nil { |
| + return err |
| + } |
| + n.UnsubscribeURL = origin + "/alerts/unsubscribe/" + url.PathEscape(raw) |
| + } |
| + if incidentID != 0 { |
| + n.IncidentURL = fmt.Sprintf("%s/fleet/alerts/history#incident-%d", origin, incidentID) |
| + } |
| + return nil |
| +} |
| + |
| +// sendAlertNote renders n for c's kind and sends it to target. The sendErr |
| +// is the outcome ("" sent); err is a failure of the console's own, such as |
| +// reading the signing key, which says nothing about the connector. |
| +func (s *Server) sendAlertNote(ctx context.Context, c alertConnector, target string, n alertNote, now time.Time) (sendErr, error) { |
| + switch c.Kind { |
| + case alertConnectorEmail: |
| + subject, body := renderEmail(n) |
| + ectx, cancel := context.WithTimeout(ctx, alertEmailTimeout) |
| + defer cancel() |
| + if _, err := s.deliver(ectx, target, subject, body, alertKeymailShare); err != nil { |
| + return "email", nil // deliver logged why |
| + } |
| + return "", nil |
| + case alertConnectorSlack: |
| + return postAlert(ctx, s.alertClient(), c.Kind, target, renderSlack(n), nil), nil |
| + case alertConnectorWebhook: |
| + key, err := s.store.AlertSigningKey() |
| + if err != nil { |
| + return "", err |
| + } |
| + body := renderWebhook(n) |
| + return postAlert(ctx, s.alertClient(), c.Kind, target, body, |
| + map[string]string{"Carlos-Signature": signAlert(key, now, body)}), nil |
| + } |
| + return "invalid", nil |
| +} |
| + |
| +func alertConnectorLabel(c alertConnector) string { |
| + label := c.Name |
| + if label == "" { |
| + label = c.Kind |
| + } |
| + if c.TargetHint != "" { |
| + label += " (" + c.TargetHint + ")" |
| + } |
| + return label |
| +} |
| + |
| +// tellAlertSuspended tells c's scope, once, that c was suspended (spec |
| +// §5.3): one suspended row to each of the scope's other connectors that can |
| +// take it, or, when there are none, an email straight to the scope's |
| +// owners. |
| +func (s *Server) tellAlertSuspended(ctx context.Context, c alertConnector, now time.Time) error { |
| + label := alertConnectorLabel(c) |
| + n := alertNote{Scope: c.Scope, Level: alerting.LevelWarning, Kind: "suspended", Subject: label, |
| + What: fmt.Sprintf(alertCopy["suspended.what"], label), |
| + HowLong: alertCopy["suspended.how_long"], |
| + WhatToDo: alertCopy["suspended.what_to_do"], |
| + At: now} |
| + body, err := json.Marshal(n) |
| + if err != nil { |
| + return err |
| + } |
| + others, err := s.store.AlertConnectors(c.Scope) |
| + if err != nil { |
| + return err |
| + } |
| + var rows []alertOutboxRow |
| + for _, o := range others { |
| + if o.ID != c.ID && alertWithheld(o, n.Kind) == "" { |
| + rows = append(rows, alertOutboxRow{ConnectorID: o.ID, Kind: n.Kind, Body: body, NextAt: now}) |
| + } |
| + } |
| + if len(rows) > 0 { |
| + return s.store.CommitAlertStep(nil, nil, rows) |
| + } |
| + owners, err := s.alertScopeOwners(c.Scope) |
| + if err != nil { |
| + return err |
| + } |
| + subject, text := renderEmail(n) |
| + for _, addr := range owners { |
| + ectx, cancel := context.WithTimeout(ctx, alertEmailTimeout) |
| + _, err := s.deliver(ectx, addr, subject, text, alertKeymailShare) |
| + cancel() |
| + if err != nil { |
| + log.Printf("console: alert connector %d suspended; telling %s failed", c.ID, addr) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// alertScopeOwners is who owns scope: the operators for the fleet, the |
| +// owners of the account otherwise. |
| +func (s *Server) alertScopeOwners(scope string) ([]string, error) { |
| + if scope == "fleet" { |
| + return s.store.Operators() |
| + } |
| + sqid, ok := strings.CutPrefix(scope, "account:") |
| + if !ok { |
| + return nil, fmt.Errorf("alert scope %q has no owners", scope) |
| + } |
| + acct, err := s.store.AccountBySqid(sqid) |
| + if err != nil || acct == nil { |
| + return nil, err |
| + } |
| + members, err := s.store.Members(acct.ID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var out []string |
| + for _, m := range members { |
| + if m.Role == RoleOwner { |
| + out = append(out, m.Name) // Members puts the address in Name |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +// ---- test sends -------------------------------------------------------------- |
| + |
| +var ( |
| + errAlertTestUnconfirmed = errors.New("alert test: an email connector is tested only once its address is confirmed") |
| + errAlertTestLimit = errors.New("alert test: at most 10 tests a connector an hour") |
| + errAlertTestReentry = errors.New("alert test: the connector needs re-entering") |
| +) |
| + |
| +// sendTestAlert sends connector id in scope a test now, outside the |
| +// outbox. An unconfirmed email is refused: its confirmation is its only |
| +// message (spec §5.3). An unconfirmed Slack's test carries a one-use |
| +// confirm link; an unconfirmed webhook is confirmed by a 2xx answer. A test |
| +// that gets through also lifts a suspension (ruling R-11). sql.ErrNoRows: |
| +// no such connector in scope. |
| +func (s *Server) sendTestAlert(ctx context.Context, scope string, id int64) error { |
| + now := s.alertClockNow() |
| + c, ok, err := s.usableAlertConnector(id) |
| + if err != nil { |
| + return err |
| + } |
| + if !ok || c.Scope != scope { |
| + return sql.ErrNoRows |
| + } |
| + if c.Kind == alertConnectorEmail && !c.Confirmed { |
| + return errAlertTestUnconfirmed |
| + } |
| + if c.NeedsReentry { |
| + return errAlertTestReentry |
| + } |
| + if !s.alertTests.take(c.ID, now) { |
| + return errAlertTestLimit |
| + } |
| + target, hold, err := s.alertTarget(c) |
| + if err != nil { |
| + return err |
| + } |
| + if hold != "" { |
| + return fmt.Errorf("alert test: %s", hold) |
| + } |
| + n := alertTestNote(c, s.consoleName(), now) |
| + if n.DeliveryID, err = newAlertDeliveryID(); err != nil { |
| + return err |
| + } |
| + if err := s.addAlertLinks(c, 0, &n, now); err != nil { |
| + return err |
| + } |
| + cat, err := s.sendAlertNote(ctx, c, target, n, now) |
| + if err != nil { |
| + return err |
| + } |
| + if cat != "" { |
| + return fmt.Errorf("alert test: %s", cat) |
| + } |
| + if c.Kind == alertConnectorWebhook && !c.Confirmed { |
| + if err := s.store.ConfirmAlertConnector(c.ID); err != nil { |
| + return err |
| + } |
| + } |
| + return s.store.ResumeAlertConnector(c.ID) |
| +} |
| + |
| +// alertTestNote is the test message for c. Like every message it says what |
| +// is wrong (nothing), how long you have and what to do. |
| +func alertTestNote(c alertConnector, console string, now time.Time) alertNote { |
| + n := alertNote{Scope: c.Scope, Level: alerting.LevelWarning, Kind: "verify", Subject: alertConnectorLabel(c), |
| + What: fmt.Sprintf(alertCopy["test.what"], console), |
| + HowLong: alertCopy["test.how_long"], |
| + WhatToDo: alertCopy["test.what_to_do"], |
| + At: now} |
| + switch { |
| + case c.Confirmed: |
| + case c.Kind == alertConnectorWebhook: |
| + n.WhatToDo = alertCopy["test.what_to_do.webhook"] |
| + default: |
| + n.HowLong, n.WhatToDo = alertCopy["test.how_long.confirm"], alertCopy["test.what_to_do.confirm"] |
| + } |
| + return n |
| +} |
| + |
| +// newAlertDeliveryID is a fresh delivery id, as insertAlertOutbox mints. |
| +func newAlertDeliveryID() (string, error) { |
| + b := make([]byte, 16) |
| + if _, err := rand.Read(b); err != nil { |
| + return "", err |
| + } |
| + return hex.EncodeToString(b), nil |
| +} |
| + |
| +// alertTestWindow is each connector's test sends in the last hour. In |
| +// memory, like the other send limits (emailsignin_limits.go): a restart |
| +// forgets it. |
| +type alertTestWindow struct { |
| + mu sync.Mutex |
| + sent map[int64][]time.Time |
| +} |
| + |
| +// take records a test for connector id at now and reports true, or reports |
| +// false without recording when id already has alertTestsPerHour in the hour |
| +// before now. |
| +func (w *alertTestWindow) take(id int64, now time.Time) bool { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + cutoff := now.Add(-time.Hour) |
| + kept := w.sent[id][:0] |
| + for _, t := range w.sent[id] { |
| + if t.After(cutoff) { |
| + kept = append(kept, t) |
| + } |
| + } |
| + if len(kept) >= alertTestsPerHour { |
| + w.sent[id] = kept |
| + return false |
| + } |
| + if w.sent == nil { |
| + w.sent = map[int64][]time.Time{} |
| + } |
| + w.sent[id] = append(kept, now) |
| + return true |
| +} |
diff --git a/internal/console/alertnotify_test.go b/internal/console/alertnotify_test.go| new file mode 100644 |
| index 000000000..df2c13e94 |
| --- /dev/null |
| +++ b/internal/console/alertnotify_test.go |
| @@ -0,0 +1,888 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "log" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "path/filepath" |
| + "reflect" |
| + "regexp" |
| + "slices" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// notifyFixture is a console whose alert senders reach a recording TLS |
| +// server (every Slack and webhook name resolves to it) and a recording |
| +// mailer, on a clock the test moves. |
| +type notifyFixture struct { |
| + *consoleFixture |
| + mail *fakeConsoleMail |
| + hook *hookRecorder |
| + // hookSrv is the hook's TLS server, for a test that builds its own |
| + // client to it. |
| + hookSrv *httptest.Server |
| + seal *connectorSeal |
| + now time.Time |
| +} |
| + |
| +// hookRecorder is the far end of every Slack and webhook send. |
| +type hookRecorder struct { |
| + mu sync.Mutex |
| + status int |
| + reqs []hookReq |
| + // hold, when set, keeps each request open until the request's own |
| + // context ends. |
| + hold bool |
| + got chan struct{} |
| +} |
| + |
| +type hookReq struct { |
| + path string |
| + sig string |
| + body []byte |
| +} |
| + |
| +func (h *hookRecorder) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + body, _ := io.ReadAll(r.Body) |
| + h.mu.Lock() |
| + h.reqs = append(h.reqs, hookReq{path: r.URL.Path, sig: r.Header.Get("Carlos-Signature"), body: body}) |
| + status, hold := h.status, h.hold |
| + h.mu.Unlock() |
| + select { |
| + case h.got <- struct{}{}: |
| + default: |
| + } |
| + if hold { |
| + <-r.Context().Done() |
| + return |
| + } |
| + w.WriteHeader(status) |
| +} |
| + |
| +func (h *hookRecorder) setStatus(code int) { |
| + h.mu.Lock() |
| + h.status = code |
| + h.mu.Unlock() |
| +} |
| + |
| +func (h *hookRecorder) requests() []hookReq { |
| + h.mu.Lock() |
| + defer h.mu.Unlock() |
| + return append([]hookReq(nil), h.reqs...) |
| +} |
| + |
| +func newNotifyFixture(t *testing.T) *notifyFixture { |
| + t.Helper() |
| + fx := newConsoleFixture(t) |
| + nf := ¬ifyFixture{consoleFixture: fx, mail: &fakeConsoleMail{ready: true}, now: alertT0, |
| + hook: &hookRecorder{status: http.StatusOK, got: make(chan struct{}, 1)}} |
| + fx.srv.consoleMail = nf.mail |
| + fx.srv.sendFederated = nil // straight to the mailer |
| + seal, _, err := openConnectorSeal(filepath.Join(t.TempDir(), "alert-connectors.key")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + nf.seal = seal |
| + fx.srv.alertSeal.Store(seal) |
| + srv := httptest.NewUnstartedServer(nf.hook) |
| + srv.Config.ErrorLog = log.New(io.Discard, "", 0) |
| + srv.StartTLS() |
| + t.Cleanup(srv.Close) |
| + nf.hookSrv = srv |
| + fx.srv.alertHTTP = pointAlertClientAt(t, srv, allowLoopback) |
| + fx.srv.alertClock = func() time.Time { return nf.now } |
| + return nf |
| +} |
| + |
| +func (nf *notifyFixture) addEmail(t *testing.T, scope, addr, owner string, confirmed bool) int64 { |
| + t.Helper() |
| + id, err := nf.st.AddAlertConnector(alertConnector{Scope: scope, Kind: alertConnectorEmail, Name: addr, |
| + OwnerAddress: owner, Confirmed: confirmed}, nil, addr) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return id |
| +} |
| + |
| +func (nf *notifyFixture) addHook(t *testing.T, kind, raw string, confirmed bool) int64 { |
| + t.Helper() |
| + sealed, err := nf.seal.Seal([]byte(raw)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + id, err := nf.st.AddAlertConnector(alertConnector{Scope: "fleet", Kind: kind, Name: kind, TargetHint: "…XYZ", |
| + Confirmed: confirmed}, sealed, "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return id |
| +} |
| + |
| +func (nf *notifyFixture) queue(t *testing.T, connector, incident int64, kind string, n alertNote) { |
| + t.Helper() |
| + b, err := json.Marshal(n) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := nf.st.CommitAlertStep(nil, nil, []alertOutboxRow{{IncidentID: incident, ConnectorID: connector, |
| + Kind: kind, Body: b, NextAt: nf.now}}); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func (nf *notifyFixture) drain(t *testing.T) { |
| + t.Helper() |
| + if err := nf.srv.alertDrainOutbox(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// outboxRow is what the outbox holds for one row, read by hand. |
| +type outboxState struct { |
| + kind string |
| + sent bool |
| + attempts int |
| + cat string |
| +} |
| + |
| +func (nf *notifyFixture) outbox(t *testing.T, connector int64) []outboxState { |
| + t.Helper() |
| + rows, err := nf.st.db.Query(`SELECT kind, sent_at IS NOT NULL, attempts, err_category FROM alert_outbox |
| + WHERE connector_id = ? ORDER BY id`, connector) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + var out []outboxState |
| + for rows.Next() { |
| + var o outboxState |
| + if err := rows.Scan(&o.kind, &o.sent, &o.attempts, &o.cat); err != nil { |
| + t.Fatal(err) |
| + } |
| + out = append(out, o) |
| + } |
| + return out |
| +} |
| + |
| +func (nf *notifyFixture) connector(t *testing.T, id int64) alertConnector { |
| + t.Helper() |
| + c, err := nf.st.AlertConnector(id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return c |
| +} |
| + |
| +// fireNote is the stored form of a fire: everything but the links |
| +// (ruling R-2), which the sender adds. |
| +func fireNote() alertNote { |
| + return alertNote{ |
| + Scope: "fleet", Rule: "disk_eta", Level: "warning", Kind: "fire", Subject: "box-1", |
| + What: "Disk on box-1 is filling up.", |
| + HowLong: "About 40 hours until it is full.", |
| + WhatToDo: "Free space on box-1 or give it a bigger disk.", |
| + Members: []string{"box-1", "box-2"}, |
| + At: alertT0, |
| + } |
| +} |
| + |
| +var alertLinkRE = regexp.MustCompile(`https?://[^\s|>"]+/alerts/(snooze|unsubscribe|confirm)/([A-Za-z0-9_-]+)`) |
| + |
| +// alertLinks is every token link in s, by action. |
| +func alertLinks(s string) map[string][]string { |
| + out := map[string][]string{} |
| + for _, m := range alertLinkRE.FindAllStringSubmatch(s, -1) { |
| + out[m[1]] = append(out[m[1]], m[2]) |
| + } |
| + return out |
| +} |
| + |
| +func TestRenderSlack(t *testing.T) { |
| + n := fireNote() |
| + n.Subject = "<!channel> box & co" |
| + n.IncidentURL = "https://console.example/fleet/alerts/history#incident-7" |
| + n.SnoozeURL = "https://console.example/alerts/snooze/tok-s" |
| + n.UnsubscribeURL = "https://console.example/alerts/unsubscribe/tok-u" |
| + var got struct { |
| + Text string `json:"text"` |
| + Blocks []json.RawMessage `json:"blocks"` |
| + } |
| + raw := renderSlack(n) |
| + if err := json.Unmarshal(raw, &got); err != nil { |
| + t.Fatalf("renderSlack is not JSON: %v\n%s", err, raw) |
| + } |
| + if got.Text == "" || len(got.Blocks) == 0 { |
| + t.Fatalf("renderSlack = %s, want text and blocks", raw) |
| + } |
| + // Decoded, so the escapes Slack reads are visible as written. |
| + var decoded strings.Builder |
| + for _, x := range got.Blocks { |
| + var v map[string]any |
| + if err := json.Unmarshal(x, &v); err != nil { |
| + t.Fatal(err) |
| + } |
| + collectText(v, &decoded) |
| + } |
| + text := got.Text + "\n" + decoded.String() |
| + for _, want := range []string{n.What, n.HowLong, n.WhatToDo, "box-2", |
| + "<" + n.IncidentURL + "|", "<" + n.SnoozeURL + "|", "<" + n.UnsubscribeURL + "|"} { |
| + if !strings.Contains(text, want) { |
| + t.Errorf("the Slack message lacks %q:\n%s", want, text) |
| + } |
| + } |
| + if strings.Contains(text, "<!channel>") || !strings.Contains(text, "<!channel> box & co") { |
| + t.Errorf("a subject is not escaped for Slack:\n%s", text) |
| + } |
| + if strings.Contains(string(raw), "\u2014") || strings.Contains(text, "\u2014") { |
| + t.Errorf("an em dash in the Slack message: %s", raw) |
| + } |
| +} |
| + |
| +// collectText appends every "text" string under v. |
| +func collectText(v any, b *strings.Builder) { |
| + switch x := v.(type) { |
| + case map[string]any: |
| + for k, e := range x { |
| + if s, ok := e.(string); ok && k == "text" { |
| + b.WriteString(s + "\n") |
| + continue |
| + } |
| + collectText(e, b) |
| + } |
| + case []any: |
| + for _, e := range x { |
| + collectText(e, b) |
| + } |
| + } |
| +} |
| + |
| +func TestRenderWebhookSignedV1(t *testing.T) { |
| + n := fireNote() |
| + n.DeliveryID = "d-1" |
| + var m map[string]any |
| + if err := json.Unmarshal(renderWebhook(n), &m); err != nil { |
| + t.Fatal(err) |
| + } |
| + keys := make([]string, 0, len(m)) |
| + for k := range m { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + want := []string{"at", "delivery_id", "how_long", "incident_url", "kind", "level", "members", "rule", |
| + "scope", "snooze_url", "subject", "v", "what", "what_to_do"} |
| + if !slices.Equal(keys, want) { |
| + t.Fatalf("webhook keys = %v, want %v", keys, want) |
| + } |
| + if m["v"] != float64(1) || m["delivery_id"] != "d-1" || m["at"] != "2026-10-30T12:00:00Z" { |
| + t.Errorf("webhook body = %v", m) |
| + } |
| + if !reflect.DeepEqual(m["members"], []any{"box-1", "box-2"}) { |
| + t.Errorf("members = %v", m["members"]) |
| + } |
| + // No members is an empty list, never null. |
| + n.Members = nil |
| + if !strings.Contains(string(renderWebhook(n)), `"members":[]`) { |
| + t.Errorf("no members renders as %s", renderWebhook(n)) |
| + } |
| + |
| + // Sent through the drain: signed with the alert key over the exact body. |
| + nf := newNotifyFixture(t) |
| + id := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", true) |
| + nf.queue(t, id, 0, "fire", fireNote()) |
| + nf.drain(t) |
| + reqs := nf.hook.requests() |
| + if len(reqs) != 1 { |
| + t.Fatalf("%d requests, want 1", len(reqs)) |
| + } |
| + key, err := nf.st.AlertSigningKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !verifyAlertHeader(t, alertPublicKey(key), reqs[0].sig, reqs[0].body) { |
| + t.Fatalf("signature %q does not verify over %s", reqs[0].sig, reqs[0].body) |
| + } |
| + if !strings.HasPrefix(reqs[0].sig, "t="+strconv.FormatInt(alertT0.Unix(), 10)+",") { |
| + t.Errorf("signature time %q, want the send time", reqs[0].sig) |
| + } |
| + var sent map[string]any |
| + if err := json.Unmarshal(reqs[0].body, &sent); err != nil || sent["v"] != float64(1) { |
| + t.Fatalf("sent body %s: %v", reqs[0].body, err) |
| + } |
| + var did string |
| + if err := nf.st.db.QueryRow(`SELECT delivery_id FROM alert_outbox WHERE connector_id = ?`, id).Scan(&did); err != nil { |
| + t.Fatal(err) |
| + } |
| + if sent["delivery_id"] != did { |
| + t.Errorf("delivery_id = %v, want the row's %s", sent["delivery_id"], did) |
| + } |
| +} |
| + |
| +func TestRenderEmailHasUnsubscribe(t *testing.T) { |
| + n := fireNote() |
| + n.IncidentURL = "https://console.example/fleet/alerts/history#incident-7" |
| + n.SnoozeURL = "https://console.example/alerts/snooze/tok-s" |
| + n.UnsubscribeURL = "https://console.example/alerts/unsubscribe/tok-u" |
| + subject, body := renderEmail(n) |
| + if subject == "" || !strings.Contains(subject, "box-1") { |
| + t.Errorf("subject = %q", subject) |
| + } |
| + if !strings.HasSuffix(strings.TrimRight(body, "\n"), n.UnsubscribeURL) { |
| + t.Errorf("the body does not end with the unsubscribe link:\n%s", body) |
| + } |
| + for _, want := range []string{n.What, n.HowLong, n.WhatToDo, n.IncidentURL, n.SnoozeURL, "box-2"} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("the body lacks %q:\n%s", want, body) |
| + } |
| + } |
| + if strings.Contains(subject+body, "\u2014") { |
| + t.Error("an em dash in the email") |
| + } |
| + for kind := range alertOutboxKinds { |
| + k := n |
| + k.Kind = kind |
| + if s, _ := renderEmail(k); strings.Contains(s, "%!") || !strings.Contains(s, "box-1") { |
| + t.Errorf("%s subject = %q", kind, s) |
| + } |
| + } |
| + for key, s := range alertCopy { |
| + if strings.Contains(s, "\u2014") { |
| + t.Errorf("alertCopy[%q] has an em dash", key) |
| + } |
| + } |
| + |
| + // Sent through the drain: the link is minted for this connector. |
| + nf := newNotifyFixture(t) |
| + id := nf.addEmail(t, "fleet", "ops@example.com", "", true) |
| + nf.queue(t, id, 0, "fire", fireNote()) |
| + nf.drain(t) |
| + sent := nf.mail.sentCopy() |
| + if len(sent) != 1 || !strings.HasPrefix(sent[0], "ops@example.com|") { |
| + t.Fatalf("sent = %q", sent) |
| + } |
| + links := alertLinks(sent[0]) |
| + if len(links["unsubscribe"]) != 1 { |
| + t.Fatalf("unsubscribe links in %q: %v", sent[0], links) |
| + } |
| + if !strings.HasSuffix(strings.TrimRight(sent[0], "\n"), links["unsubscribe"][0]) { |
| + t.Errorf("the sent body does not end with its unsubscribe link:\n%s", sent[0]) |
| + } |
| + tok, err := nf.st.UseAlertToken(links["unsubscribe"][0], alertTokenUnsubscribe, nf.now) |
| + if err != nil || tok.ConnectorID != id || tok.Scope != "fleet" || !tok.ExpiresAt.IsZero() { |
| + t.Errorf("unsubscribe token = %+v, %v; want bound to connector %d, no expiry", tok, err, id) |
| + } |
| +} |
| + |
| +func TestDrainRetriesThenSucceeds(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + id := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", true) |
| + nf.queue(t, id, 0, "fire", fireNote()) |
| + nf.hook.setStatus(http.StatusInternalServerError) |
| + nf.drain(t) |
| + if got := nf.outbox(t, id); len(got) != 1 || got[0].sent || got[0].attempts != 1 || got[0].cat != "status 500" { |
| + t.Fatalf("after a 500: %+v", got) |
| + } |
| + if c := nf.connector(t, id); !c.FailingSince.Equal(alertT0) { |
| + t.Errorf("failing since %v, want %v", c.FailingSince, alertT0) |
| + } |
| + nf.drain(t) // not due yet |
| + if n := len(nf.hook.requests()); n != 1 { |
| + t.Fatalf("%d sends before the retry was due, want 1", n) |
| + } |
| + nf.hook.setStatus(http.StatusOK) |
| + nf.now = alertT0.Add(time.Minute) |
| + nf.drain(t) |
| + if got := nf.outbox(t, id); !got[0].sent { |
| + t.Fatalf("after the retry: %+v", got) |
| + } |
| + if n := len(nf.hook.requests()); n != 2 { |
| + t.Errorf("%d sends, want 2", n) |
| + } |
| + if c := nf.connector(t, id); !c.FailingSince.IsZero() { |
| + t.Errorf("failing since %v after a success, want cleared", c.FailingSince) |
| + } |
| +} |
| + |
| +func TestDrainSuspendsAfter24hTellsOnce(t *testing.T) { |
| + t.Run("other connectors", func(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + hook := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", true) |
| + mail := nf.addEmail(t, "fleet", "ops@example.com", "", true) |
| + unconfirmed := nf.addEmail(t, "fleet", "new@example.com", "", false) |
| + nf.hook.setStatus(http.StatusServiceUnavailable) |
| + nf.queue(t, hook, 0, "fire", fireNote()) |
| + nf.drain(t) |
| + nf.now = alertT0.Add(25 * time.Hour) |
| + nf.drain(t) |
| + if c := nf.connector(t, hook); !c.Suspended { |
| + t.Fatal("not suspended after failing 25 hours") |
| + } |
| + got := nf.outbox(t, mail) |
| + if len(got) != 1 || got[0].kind != "suspended" { |
| + t.Fatalf("the other connector's outbox = %+v, want one suspended notice", got) |
| + } |
| + if got := nf.outbox(t, unconfirmed); len(got) != 0 { |
| + t.Errorf("an unconfirmed connector was queued a notice: %+v", got) |
| + } |
| + nf.drain(t) |
| + sent := nf.mail.sentCopy() |
| + if len(sent) != 1 || !strings.HasPrefix(sent[0], "ops@example.com|") || !strings.Contains(sent[0], "webhook") { |
| + t.Fatalf("sent = %q, want one notice naming the connector", sent) |
| + } |
| + // Suspended: nothing more is sent to it, and nobody is told again. |
| + hits := len(nf.hook.requests()) |
| + nf.queue(t, hook, 0, "fire", fireNote()) |
| + nf.now = nf.now.Add(48 * time.Hour) |
| + nf.drain(t) |
| + nf.drain(t) |
| + if n := len(nf.hook.requests()); n != hits { |
| + t.Errorf("%d sends to a suspended connector", n-hits) |
| + } |
| + if got := nf.outbox(t, mail); len(got) != 1 { |
| + t.Errorf("the owners were told %d times", len(got)) |
| + } |
| + }) |
| + t.Run("owner email", func(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + if err := nf.st.SetOperator("ops-a@example.com", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + hook := nf.addHook(t, alertConnectorSlack, "https://hooks.slack.com/services/T/B/x", true) |
| + nf.hook.setStatus(http.StatusNotFound) |
| + nf.queue(t, hook, 0, "fire", fireNote()) |
| + nf.drain(t) |
| + nf.now = alertT0.Add(25 * time.Hour) |
| + nf.drain(t) |
| + sent := nf.mail.sentCopy() |
| + if len(sent) != 1 || !strings.HasPrefix(sent[0], "ops-a@example.com|") { |
| + t.Fatalf("sent = %q, want the operator told by email", sent) |
| + } |
| + nf.now = nf.now.Add(48 * time.Hour) |
| + nf.drain(t) |
| + if n := len(nf.mail.sentCopy()); n != 1 { |
| + t.Errorf("told %d times", n) |
| + } |
| + }) |
| +} |
| + |
| +func TestDrainSkipsNeedsReentry(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + id := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", true) |
| + if _, err := nf.st.MarkSealedConnectorsNeedReentry(); err != nil { |
| + t.Fatal(err) |
| + } |
| + nf.queue(t, id, 0, "fire", fireNote()) |
| + nf.drain(t) |
| + if n := len(nf.hook.requests()); n != 0 { |
| + t.Fatalf("%d sends to a connector needing re-entry", n) |
| + } |
| + if got := nf.outbox(t, id); len(got) != 1 || got[0].sent { |
| + t.Errorf("outbox = %+v, want the row kept unsent", got) |
| + } |
| + if c := nf.connector(t, id); !c.FailingSince.IsZero() { |
| + t.Error("a skipped row counted against the connector's health") |
| + } |
| + // No seal at all (the engine has not read its key): the same. |
| + nf2 := newNotifyFixture(t) |
| + id2 := nf2.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", true) |
| + nf2.srv.alertSeal.Store(nil) |
| + nf2.queue(t, id2, 0, "fire", fireNote()) |
| + nf2.drain(t) |
| + if n := len(nf2.hook.requests()); n != 0 { |
| + t.Fatalf("%d sends with no seal", n) |
| + } |
| +} |
| + |
| +func TestDrainSkipsRevokedOperatorQueued(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + const op = "ops-a@example.com" |
| + if err := nf.st.SetOperator(op, true); err != nil { |
| + t.Fatal(err) |
| + } |
| + id := nf.addEmail(t, "fleet", op, op, true) |
| + nf.queue(t, id, 0, "fire", fireNote()) |
| + if err := nf.st.SetOperator(op, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + nf.drain(t) |
| + if sent := nf.mail.sentCopy(); len(sent) != 0 { |
| + t.Fatalf("a revoked operator was sent %q", sent) |
| + } |
| + if n := alertCount(t, nf.st, "alert_outbox"); n != 0 { |
| + t.Errorf("%d outbox rows left", n) |
| + } |
| + if _, err := nf.st.AlertConnector(id); !errors.Is(err, sql.ErrNoRows) { |
| + t.Errorf("the revoked operator's connector: %v, want deleted", err) |
| + } |
| +} |
| + |
| +func TestDrainUnconfirmedEmailGetsNothing(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + id := nf.addEmail(t, "fleet", "new@example.com", "", false) |
| + for _, kind := range []string{"fire", "clear", "update", "reminder", "suspended"} { |
| + n := fireNote() |
| + n.Kind = kind |
| + nf.queue(t, id, 0, kind, n) |
| + } |
| + for i := 0; i < 3; i++ { |
| + nf.drain(t) |
| + nf.now = nf.now.Add(13 * time.Hour) |
| + } |
| + if sent := nf.mail.sentCopy(); len(sent) != 0 { |
| + t.Fatalf("an unconfirmed address was sent %q", sent) |
| + } |
| + for _, o := range nf.outbox(t, id) { |
| + if o.sent { |
| + t.Errorf("row %+v marked sent", o) |
| + } |
| + } |
| + if c := nf.connector(t, id); !c.FailingSince.IsZero() { |
| + t.Error("withholding counted against the connector's health") |
| + } |
| + // Its confirmation is the one thing that goes. |
| + nf.queue(t, id, 0, "verify", alertNote{Scope: "fleet", Kind: "verify", Subject: "new@example.com", |
| + What: "Confirm", HowLong: "7 days", WhatToDo: "Open the link"}) |
| + nf.drain(t) |
| + sent := nf.mail.sentCopy() |
| + if len(sent) != 1 { |
| + t.Fatalf("sent = %q, want the confirmation only", sent) |
| + } |
| + links := alertLinks(sent[0]) |
| + if len(links["confirm"]) != 1 || len(links["unsubscribe"]) != 0 || len(links["snooze"]) != 0 { |
| + t.Errorf("the confirmation carries %v, want one confirm link only", links) |
| + } |
| + tok, err := nf.st.UseAlertToken(links["confirm"][0], alertTokenConfirm, nf.now) |
| + if err != nil || tok.ConnectorID != id || !tok.ExpiresAt.Equal(nf.now.Add(7*24*time.Hour)) { |
| + t.Errorf("confirm token = %+v, %v; want connector %d, 7 days", tok, err, id) |
| + } |
| +} |
| + |
| +func TestDrainUnconfirmedSlackSubscribedGetsNothing(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + id := nf.addHook(t, alertConnectorSlack, "https://hooks.slack.com/services/T/B/x", false) |
| + if err := nf.st.SetAlertRule("fleet", "disk_eta", alertRuleSetting{Enabled: true, ConnectorIDs: []int64{id}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + nf.queue(t, id, 0, "fire", fireNote()) |
| + // A queued retry: already tried once, due now. |
| + b, _ := json.Marshal(fireNote()) |
| + if err := nf.st.CommitAlertStep(nil, nil, []alertOutboxRow{{ConnectorID: id, Kind: "reminder", Body: b, |
| + Attempts: 1, NextAt: nf.now}}); err != nil { |
| + t.Fatal(err) |
| + } |
| + nf.drain(t) |
| + if n := len(nf.hook.requests()); n != 0 { |
| + t.Fatalf("%d sends to an unconfirmed Slack", n) |
| + } |
| + nf.queue(t, id, 0, "verify", alertNote{Scope: "fleet", Kind: "verify", Subject: "slack", |
| + What: "A test", HowLong: "7 days", WhatToDo: "Open the link"}) |
| + nf.drain(t) |
| + reqs := nf.hook.requests() |
| + if len(reqs) != 1 || reqs[0].path != "/services/T/B/x" { |
| + t.Fatalf("requests = %+v, want the verify only", reqs) |
| + } |
| + links := alertLinks(string(reqs[0].body)) |
| + if len(links["confirm"]) != 1 { |
| + t.Fatalf("the Slack test carries %v, want a confirm link", links) |
| + } |
| + if _, err := nf.st.UseAlertToken(links["confirm"][0], alertTokenConfirm, nf.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := nf.st.ConfirmAlertConnector(id); err != nil { |
| + t.Fatal(err) |
| + } |
| + nf.now = nf.now.Add(13 * time.Hour) |
| + nf.drain(t) |
| + if n := len(nf.hook.requests()); n != 3 { |
| + t.Errorf("%d sends after confirming, want the verify and both held rows", n) |
| + } |
| + for _, o := range nf.outbox(t, id) { |
| + if !o.sent { |
| + t.Errorf("row %+v unsent after confirming", o) |
| + } |
| + } |
| +} |
| + |
| +func TestRenderWebhookCarriesContent(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + id := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", true) |
| + inc := alertTestIncident("disk_eta", "box-1", "box-2") |
| + if err := nf.st.CommitAlertStep([]alertIncident{inc}, nil, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + n := fireNote() |
| + nf.queue(t, id, 1, "fire", n) |
| + nf.drain(t) |
| + reqs := nf.hook.requests() |
| + if len(reqs) != 1 { |
| + t.Fatalf("%d requests", len(reqs)) |
| + } |
| + key, _ := nf.st.AlertSigningKey() |
| + if !verifyAlertHeader(t, alertPublicKey(key), reqs[0].sig, reqs[0].body) { |
| + t.Fatal("the delivery is not signed") |
| + } |
| + var got map[string]any |
| + if err := json.Unmarshal(reqs[0].body, &got); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got["what"] != n.What || got["how_long"] != n.HowLong || got["what_to_do"] != n.WhatToDo { |
| + t.Errorf("content = %v", got) |
| + } |
| + origin := nf.srv.cfg.Origin |
| + if got["incident_url"] != origin+"/fleet/alerts/history#incident-1" { |
| + t.Errorf("incident_url = %v", got["incident_url"]) |
| + } |
| + snooze, _ := got["snooze_url"].(string) |
| + prefix := origin + "/alerts/snooze/" |
| + if !strings.HasPrefix(snooze, prefix) { |
| + t.Fatalf("snooze_url = %q", snooze) |
| + } |
| + raw, err := url.PathUnescape(strings.TrimPrefix(snooze, prefix)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tok, err := nf.st.UseAlertToken(raw, alertTokenSnooze, nf.now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if tok.Scope != "fleet" || tok.Rule != "disk_eta" || tok.Subject != "box-1" || !tok.ExpiresAt.Equal(nf.now.Add(30*24*time.Hour)) { |
| + t.Errorf("snooze token = %+v, want bound to (fleet, disk_eta, box-1) for 30 days", tok) |
| + } |
| + // A webhook has no unsubscribe link, so none is minted for it. |
| + var unsub int |
| + if err := nf.st.db.QueryRow(`SELECT COUNT(*) FROM alert_tokens WHERE action = 'unsubscribe'`).Scan(&unsub); err != nil { |
| + t.Fatal(err) |
| + } |
| + if unsub != 0 { |
| + t.Errorf("%d unsubscribe tokens minted for a webhook", unsub) |
| + } |
| +} |
| + |
| +func TestTestSendRefusedForUnconfirmedEmail(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + id := nf.addEmail(t, "fleet", "new@example.com", "", false) |
| + if err := nf.srv.sendTestAlert(context.Background(), "fleet", id); !errors.Is(err, errAlertTestUnconfirmed) { |
| + t.Fatalf("sendTestAlert = %v, want errAlertTestUnconfirmed", err) |
| + } |
| + if sent := nf.mail.sentCopy(); len(sent) != 0 { |
| + t.Errorf("sent %q", sent) |
| + } |
| + // Another scope's connector is not there at all. |
| + if err := nf.srv.sendTestAlert(context.Background(), "account:other", id); !errors.Is(err, sql.ErrNoRows) { |
| + t.Errorf("another scope's test = %v, want sql.ErrNoRows", err) |
| + } |
| + // Confirmed, it goes, ending with its unsubscribe link. |
| + ok := nf.addEmail(t, "fleet", "ops@example.com", "", true) |
| + if err := nf.srv.sendTestAlert(context.Background(), "fleet", ok); err != nil { |
| + t.Fatal(err) |
| + } |
| + sent := nf.mail.sentCopy() |
| + if len(sent) != 1 || len(alertLinks(sent[0])["unsubscribe"]) != 1 { |
| + t.Errorf("sent = %q", sent) |
| + } |
| +} |
| + |
| +func TestTestSendRateLimited(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + id := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", true) |
| + for i := 0; i < 10; i++ { |
| + nf.now = alertT0.Add(time.Duration(i) * time.Minute) |
| + if err := nf.srv.sendTestAlert(context.Background(), "fleet", id); err != nil { |
| + t.Fatalf("test %d: %v", i+1, err) |
| + } |
| + } |
| + if err := nf.srv.sendTestAlert(context.Background(), "fleet", id); !errors.Is(err, errAlertTestLimit) { |
| + t.Fatalf("the 11th test = %v, want errAlertTestLimit", err) |
| + } |
| + if n := len(nf.hook.requests()); n != 10 { |
| + t.Errorf("%d sends, want 10", n) |
| + } |
| + // Another connector has its own budget. |
| + other := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/other", true) |
| + if err := nf.srv.sendTestAlert(context.Background(), "fleet", other); err != nil { |
| + t.Errorf("another connector: %v", err) |
| + } |
| + nf.now = alertT0.Add(time.Hour + time.Second) |
| + if err := nf.srv.sendTestAlert(context.Background(), "fleet", id); err != nil { |
| + t.Errorf("an hour after the first: %v", err) |
| + } |
| +} |
| + |
| +// R2 #17 and ruling R-11: a Slack test carries a one-use confirm link, a |
| +// webhook test confirms on 2xx, and a test that gets through lifts a |
| +// suspension. |
| +func TestTestSendConfirmsAndResumes(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + slack := nf.addHook(t, alertConnectorSlack, "https://hooks.slack.com/services/T/B/x", false) |
| + if err := nf.srv.sendTestAlert(context.Background(), "fleet", slack); err != nil { |
| + t.Fatal(err) |
| + } |
| + reqs := nf.hook.requests() |
| + links := alertLinks(string(reqs[len(reqs)-1].body)) |
| + if len(links["confirm"]) != 1 { |
| + t.Fatalf("the Slack test carries %v", links) |
| + } |
| + if c := nf.connector(t, slack); c.Confirmed { |
| + t.Error("a Slack test confirmed without the link") |
| + } |
| + tok, err := nf.st.UseAlertToken(links["confirm"][0], alertTokenConfirm, nf.now) |
| + if err != nil || tok.ConnectorID != slack { |
| + t.Errorf("confirm token = %+v, %v", tok, err) |
| + } |
| + |
| + hook := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", false) |
| + nf.hook.setStatus(http.StatusInternalServerError) |
| + if err := nf.srv.sendTestAlert(context.Background(), "fleet", hook); err == nil || strings.Contains(err.Error(), "example.com") { |
| + t.Fatalf("a failed test = %v, want a URL-free error", err) |
| + } |
| + if c := nf.connector(t, hook); c.Confirmed { |
| + t.Fatal("a 500 confirmed the webhook") |
| + } |
| + nf.hook.setStatus(http.StatusNoContent) |
| + if err := nf.srv.sendTestAlert(context.Background(), "fleet", hook); err != nil { |
| + t.Fatal(err) |
| + } |
| + if c := nf.connector(t, hook); !c.Confirmed { |
| + t.Error("a 2xx test did not confirm the webhook") |
| + } |
| + |
| + // Suspend it, then a test that gets through lifts it. |
| + if _, err := nf.st.SetConnectorHealth(hook, false, alertT0); err != nil { |
| + t.Fatal(err) |
| + } |
| + if now, err := nf.st.SetConnectorHealth(hook, false, alertT0.Add(25*time.Hour)); err != nil || !now { |
| + t.Fatalf("suspend: %v, %v", now, err) |
| + } |
| + if err := nf.srv.sendTestAlert(context.Background(), "fleet", hook); err != nil { |
| + t.Fatal(err) |
| + } |
| + if c := nf.connector(t, hook); c.Suspended || !c.FailingSince.IsZero() { |
| + t.Errorf("after a good test: suspended %v, failing since %v", c.Suspended, c.FailingSince) |
| + } |
| +} |
| + |
| +func TestResumeAlertConnector(t *testing.T) { |
| + st := openTestStore(t) |
| + id := alertTestConnector(t, st, alertConnectorWebhook) |
| + if _, err := st.SetConnectorHealth(id, false, alertT0); err != nil { |
| + t.Fatal(err) |
| + } |
| + if now, err := st.SetConnectorHealth(id, false, alertT0.Add(alertSuspendAfter)); err != nil || !now { |
| + t.Fatalf("suspend: %v, %v", now, err) |
| + } |
| + if err := st.ResumeAlertConnector(id); err != nil { |
| + t.Fatal(err) |
| + } |
| + c, err := st.AlertConnector(id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if c.Suspended || !c.FailingSince.IsZero() { |
| + t.Errorf("resumed: suspended %v, failing since %v", c.Suspended, c.FailingSince) |
| + } |
| + // It can be suspended again, and is told about again. |
| + if _, err := st.SetConnectorHealth(id, false, alertT0.Add(48*time.Hour)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if now, err := st.SetConnectorHealth(id, false, alertT0.Add(72*time.Hour)); err != nil || !now { |
| + t.Errorf("second suspension: %v, %v", now, err) |
| + } |
| + if _, err := st.AlertConnector(id + 100); !errors.Is(err, sql.ErrNoRows) { |
| + t.Errorf("a missing connector: %v, want sql.ErrNoRows", err) |
| + } |
| +} |
| + |
| +func TestDrainErrorStoredHasNoSecret(t *testing.T) { |
| + var logs bytes.Buffer |
| + prev := log.Writer() |
| + log.SetOutput(&logs) |
| + t.Cleanup(func() { log.SetOutput(prev) }) |
| + nf := newNotifyFixture(t) |
| + slack := nf.addHook(t, alertConnectorSlack, "https://hooks.slack.com/services/T0/B0/sekrit-XYZ", true) |
| + hook := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/sekrit-XYZ?k=sekrit-XYZ", true) |
| + nf.hook.setStatus(http.StatusForbidden) |
| + nf.queue(t, slack, 0, "fire", fireNote()) |
| + nf.queue(t, hook, 0, "fire", fireNote()) |
| + nf.drain(t) |
| + // A refused dial too: the production guard, which refuses the loopback |
| + // address every name resolves to here. |
| + nf.srv.alertHTTP = pointAlertClientAt(t, nf.hookSrv, refusedAddr) |
| + nf.now = nf.now.Add(time.Hour) |
| + nf.drain(t) |
| + rows, err := nf.st.db.Query(`SELECT err_category FROM alert_outbox`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + var cats []string |
| + for rows.Next() { |
| + var c string |
| + if err := rows.Scan(&c); err != nil { |
| + t.Fatal(err) |
| + } |
| + cats = append(cats, c) |
| + } |
| + if len(cats) != 2 || cats[0] == "" { |
| + t.Fatalf("categories = %q", cats) |
| + } |
| + for _, c := range cats { |
| + if strings.Contains(c, "sekrit-XYZ") || strings.Contains(c, "example.com") { |
| + t.Errorf("err_category %q carries the URL", c) |
| + } |
| + } |
| + if strings.Contains(logs.String(), "sekrit-XYZ") { |
| + t.Errorf("the log carries the secret:\n%s", logs.String()) |
| + } |
| + if !strings.Contains(logs.String(), "status 403") { |
| + t.Errorf("the failure was not logged at all:\n%s", logs.String()) |
| + } |
| +} |
| + |
| +// Console shutdown is not a connector failure: a send cut short by the |
| +// drain's own context leaves the row due and the connector's health alone. |
| +func TestDrainCancelledLeavesRowDue(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + id := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", true) |
| + nf.queue(t, id, 0, "fire", fireNote()) |
| + nf.hook.mu.Lock() |
| + nf.hook.hold = true |
| + nf.hook.mu.Unlock() |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + go func() { |
| + <-nf.hook.got |
| + cancel() |
| + }() |
| + if err := nf.srv.alertDrainOutbox(ctx); !errors.Is(err, context.Canceled) { |
| + t.Errorf("drain = %v, want context.Canceled", err) |
| + } |
| + if got := nf.outbox(t, id); len(got) != 1 || got[0].sent || got[0].attempts != 0 || got[0].cat != "" { |
| + t.Errorf("outbox = %+v, want the row untouched", got) |
| + } |
| + if c := nf.connector(t, id); !c.FailingSince.IsZero() { |
| + t.Error("shutdown counted against the connector's health") |
| + } |
| +} |
| + |
| +// The drain reads at most 50 rows a pass. |
| +func TestDrainBatchOf50(t *testing.T) { |
| + nf := newNotifyFixture(t) |
| + id := nf.addHook(t, alertConnectorWebhook, "https://alerts.example.com/in", true) |
| + for i := 0; i < 51; i++ { |
| + nf.queue(t, id, 0, "fire", fireNote()) |
| + } |
| + nf.drain(t) |
| + if n := len(nf.hook.requests()); n != 50 { |
| + t.Errorf("%d sends in one pass, want 50", n) |
| + } |
| +} |
diff --git a/internal/console/alertstore.go b/internal/console/alertstore.go| index 7993401f0..a8253871b 100644 |
| --- a/internal/console/alertstore.go |
| +++ b/internal/console/alertstore.go |
| @@ -1,9 +1,7 @@ |
| package console |
| import ( |
| - "crypto/rand" |
| "database/sql" |
| - "encoding/hex" |
| "encoding/json" |
| "errors" |
| "fmt" |
| @@ -388,11 +386,11 @@ func insertAlertOutbox(tx *sql.Tx, r alertOutboxRow) error { |
| return fmt.Errorf("alert outbox: unknown kind %q", r.Kind) |
| } |
| if r.DeliveryID == "" { |
| - b := make([]byte, 16) |
| - if _, err := rand.Read(b); err != nil { |
| + id, err := newAlertDeliveryID() |
| + if err != nil { |
| return err |
| } |
| - r.DeliveryID = hex.EncodeToString(b) |
| + r.DeliveryID = id |
| } |
| body := r.Body |
| if body == nil { |
| @@ -484,6 +482,13 @@ func (s *Store) FinishOutbox(id int64, cat string, ok bool, now time.Time) error |
| return tx.Commit() |
| } |
| +// DropOutbox deletes unsent row id, one that can never be sent: its body |
| +// does not decode, or its connector is gone. |
| +func (s *Store) DropOutbox(id int64) error { |
| + _, err := s.db.Exec(`DELETE FROM alert_outbox WHERE id = ? AND sent_at IS NULL`, id) |
| + return err |
| +} |
| + |
| func alertRetryBackoff(attempts int) time.Duration { |
| d := alertRetryFirst |
| for i := 0; i < attempts && d < alertRetryCap; i++ { |
| @@ -494,28 +499,52 @@ func alertRetryBackoff(attempts int) time.Duration { |
| // ---- connectors -------------------------------------------------------------- |
| +const alertConnectorColumns = `id, scope, kind, name, target_hint, COALESCE(owner_address, ''), confirmed_at, |
| + suspended_at, needs_reentry, failing_since, created_by` |
| + |
| +func scanAlertConnector(row interface{ Scan(...any) error }) (alertConnector, error) { |
| + var c alertConnector |
| + var confirmed, suspended, failing int64 |
| + if err := row.Scan(&c.ID, &c.Scope, &c.Kind, &c.Name, &c.TargetHint, &c.OwnerAddress, &confirmed, |
| + &suspended, &c.NeedsReentry, &failing, &c.CreatedBy); err != nil { |
| + return alertConnector{}, err |
| + } |
| + c.Confirmed, c.Suspended, c.FailingSince = confirmed != 0, suspended != 0, alertTime(failing) |
| + return c, nil |
| +} |
| + |
| // 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) |
| + rows, err := s.db.Query(`SELECT `+alertConnectorColumns+` 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 { |
| + c, err := scanAlertConnector(rows) |
| + if 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() |
| } |
| +// AlertConnector is connector id, read fresh before each send. |
| +// sql.ErrNoRows: it has been deleted. |
| +func (s *Store) AlertConnector(id int64) (alertConnector, error) { |
| + return scanAlertConnector(s.db.QueryRow(`SELECT `+alertConnectorColumns+` FROM alert_connectors WHERE id = ?`, id)) |
| +} |
| + |
| +// ResumeAlertConnector lifts connector id's suspension and clears its |
| +// failing clock, after a test send got through (ruling R-11): the way back |
| +// for a suspended connector short of deleting and re-adding it. |
| +func (s *Store) ResumeAlertConnector(id int64) error { |
| + _, err := s.db.Exec(`UPDATE alert_connectors SET suspended_at = 0, failing_since = 0 WHERE id = ?`, id) |
| + return err |
| +} |
| + |
| // 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 |
diff --git a/internal/console/server.go b/internal/console/server.go| index 249d6a8a3..bfec2b1fc 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -998,6 +998,17 @@ type Server struct { |
| jobs *jobRegistry |
| // alertsNow is what the alert watcher last read as firing (alertnow.go). |
| alertsNow *alertNow |
| + // The alert senders (alertnotify.go). alertHTTP is built once, on first |
| + // use, as newAlertHTTPClient(refusedAddr); a test sets it first. |
| + // alertSeal opens connector targets once the engine has read its key; |
| + // nil until then, and every sealed target is unusable meanwhile. |
| + // alertTests is each connector's test sends in the last hour. |
| + // alertClock is time.Now outside tests. |
| + alertHTTP *http.Client |
| + alertHTTPOnce sync.Once |
| + alertSeal atomic.Pointer[connectorSeal] |
| + alertTests alertTestWindow |
| + alertClock func() time.Time |
| // perf records every request but /healthz; handler is the mux wrapped |
| // in its middleware, and is what serveAdmitted serves (NewServer). |
| perf *perf.Recorder |
diff --git a/internal/console/testdata/claim-authority-sites.txt b/internal/console/testdata/claim-authority-sites.txt| index fa8bfa35d..727d89055 100644 |
| --- a/internal/console/testdata/claim-authority-sites.txt |
| +++ b/internal/console/testdata/claim-authority-sites.txt |
| @@ -47,6 +47,7 @@ |
| ../mail/aws.go|NewAWSProvisioner|sesv2.NewFromConfig(cfg) |
| ../mail/aws.go|NewAWSProvisioner|sts.NewFromConfig(cfg) |
| ../mail/sessend.go|NewSESEmailSender|sesv2.NewFromConfig(cfg) |
| +alertnotify.go|alertTarget|seal.Open(sealed) |
| 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) |