console: an unsubscribe is lifted only by the recipient's confirm (R-37)
Unsubscribing clears the confirmation and drops unused confirm links, as well as suspending the connector. A test that gets through no longer lifts an unsubscribe: ResumeAlertConnector skips a connector with the unsubscribed marker. Confirming through a link sent afterwards confirms, resumes and clears the marker in one transaction. An unconfirmed email connector gets a "Send a new confirm link" action, on the add flow's confirmation limit; the drain lets its verify row through.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+355
−64
docs/superpowers/notes/copy-fleet-alerts-1.md+4 −2internal/console/alertnotify.go+16 −5internal/console/alertpages.go+63 −5internal/console/alertpages_test.go+198 −27internal/console/alertstore.go+50 −25internal/console/claim_invariant_fixtures_test.go+2 −0internal/console/claim_invariant_probes_nonapp_test.go+14 −0internal/console/server.go+1 −0internal/console/templates/ops_alerts.html+6 −0internal/console/testdata/claim-routes.txt+1 −0
Intent
Human
<task-notification> <task-id>b61zp34sm</task-id> <tool-use-id>toolu_01QLVBSPpZZ8FGWth4zwNdCv</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/b61zp34sm.output</output-file> <status>completed</status> <summary>Background command "Run the Luna docs pass" completed (exit code 0)</summary> </task-notification>
diff --git a/docs/superpowers/notes/copy-fleet-alerts-1.md b/docs/superpowers/notes/copy-fleet-alerts-1.md| index 43dc96d8d..f61b0f7d1 100644 |
| --- a/docs/superpowers/notes/copy-fleet-alerts-1.md |
| +++ b/docs/superpowers/notes/copy-fleet-alerts-1.md |
| @@ -364,9 +364,11 @@ The page is operator-only. Draft layout: page header, a Connectors section, a Ru |
| | `new:conn.status.unconfirmed` | `Waiting for confirmation` | Status cell | | |
| | `new:conn.status.suspended` | `Suspended. Sending has failed since %s.` | Status cell | `%s` is a time. A test that gets through turns it back on. | |
| | `new:conn.status.reentry` | `Enter the URL again` | Status cell | The key that opened it was lost. See `seal_key`. | |
| -| `conn.status.unsubscribed` | `The recipient turned these alerts off on %s. Send a test to turn them back on.` | Status cell, a connector turned off from its unsubscribe link | derived (R-35). `%s` is the time. A test that gets through turns it back on and drops this. | |
| +| `conn.status.unsubscribed` | `The recipient turned these alerts off on %s.` | Status cell, a connector turned off from its unsubscribe link | derived (R-37), from R-35's row with its second sentence dropped: a test no longer turns it back on. `%s` is the time. Only the recipient opening a confirm link sent after the unsubscribe turns it back on and drops this. | |
| | `new:conn.owner` | `Added for %s` | Note under the name of a seeded connector | `%s` is the operator's sign-in address. | |
| | `new:conn.btn.test` | `Send test` | Button on each row | | |
| +| `conn.btn.confirmlink` | `Send a new confirm link` | Button on an unconfirmed email connector's row, including one its recipient turned off | derived (R-37). | |
| +| `conn.confirmlink.sent` | `A confirm link is on its way to %s. Nothing else is sent there until it is clicked.` | Notice after "Send a new confirm link" | derived (R-37): `conn.added.email` without "Added.". `%s` is the address. | |
| | `new:conn.btn.delete` | `Delete` | Button on each row | | |
| | `new:conn.delete.confirm` | `Delete %s? Alerts stop going there.` | Confirmation before delete | `%s` is the connector's name. | |
| | `new:conn.add.heading` | `Add a connector` | Form heading | | |
| @@ -488,7 +490,7 @@ Reached from an emailed or posted link. Anyone holding the link can open the pag |
| | `new:door.confirm.btn` | `Confirm` | Button | | |
| | `new:door.confirm.done` | `Confirmed. Alerts now go to %s.` | After the POST | | |
| | `new:door.confirm.used` | `This link has been used already. Alerts to %s are on.` | Reusing a confirm link | One use. | |
| -| `door.confirm.paused` | `Confirmed. Alerts to %s are paused. An operator can turn them back on.` | After the confirm POST, when the connector is turned off | derived (R-35). Never says alerts go there. | |
| +| `door.confirm.paused` | `Confirmed. Alerts to %s are paused. An operator can turn them back on.` | After the confirm POST, when the connector is suspended because sending failed | derived (R-35). Never says alerts go there. A connector its recipient turned off is turned back on by the confirm (R-37) and gets `door.confirm.done`. | |
| | `door.confirm.failed` | `Confirming did not work. Ask an operator to send a new link from the Alerts page.` | A confirm POST that failed on the console's side; the link and the connector are left as they were | derived (Task 10), per the carry: on failure, ask for a new link. | |
| | `new:door.unsub.heading` | `Stop alerts to %s` | Unsubscribe page heading | | |
| | `new:door.unsub.body` | `This turns off this connector. Nothing more is sent to it. Other connectors are not changed. An operator can add it again from the Alerts page.` | Unsubscribe page | The link turns off the whole connector, not one rule. | |
diff --git a/internal/console/alertnotify.go b/internal/console/alertnotify.go| index 5c066c807..56c5711da 100644 |
| --- a/internal/console/alertnotify.go |
| +++ b/internal/console/alertnotify.go |
| @@ -589,9 +589,12 @@ func (s *Server) drainAlertRow(ctx context.Context, r alertOutboxRow) (alertRowO |
| // holdAlertRows puts c's due rows that hold applies to aside for |
| // alertHoldRecheck (ruling R-14): not an attempt, nothing against the |
| -// connector's health. An unconfirmed connector's verify rows are not held. |
| +// connector's health. An unconfirmed connector's verify rows are not held, |
| +// nor an unsubscribed one's: its confirm link is its way back (ruling |
| +// R-37). |
| func (s *Server) holdAlertRows(c alertConnector, hold string, now time.Time) error { |
| - return s.store.HoldConnectorOutbox(c.ID, hold, hold != "unconfirmed", now.Add(alertHoldRecheck)) |
| + verifyToo := hold != "unconfirmed" && !(hold == "suspended" && c.Unsubscribed) |
| + return s.store.HoldConnectorOutbox(c.ID, hold, verifyToo, now.Add(alertHoldRecheck)) |
| } |
| // alertOwnerRevoked reports whether c is an operator's seeded connector |
| @@ -614,11 +617,16 @@ func (s *Server) alertOwnerRevoked(c alertConnector) (bool, error) { |
| } |
| // alertWithheld is why a row of kind may not go to c now, "" when it may. |
| -// A withheld row is held (holdAlertRows), never counted as an attempt. |
| +// A withheld row is held (holdAlertRows), never counted as an attempt. A |
| +// connector its recipient unsubscribed is unconfirmed and suspended, and |
| +// takes only a verify row: the confirm link that can turn it back on |
| +// (ruling R-37). |
| func alertWithheld(c alertConnector, kind string) string { |
| switch { |
| case c.NeedsReentry: |
| return "needs re-entry" |
| + case c.Unsubscribed && !c.Confirmed && kind == "verify": |
| + return "" |
| case c.Suspended: |
| return "suspended" |
| case !c.Confirmed && kind != "verify": |
| @@ -861,8 +869,11 @@ func alertWhyText(code string) string { |
| // 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. |
| +// that gets through also lifts a suspension for failing (ruling R-11), but |
| +// never an unsubscribe (ruling R-37): an unsubscribed connector is |
| +// unconfirmed, so an email is refused, and a Slack channel's test carries |
| +// the confirm link that alone turns it back on. sql.ErrNoRows: no such |
| +// connector in scope. |
| func (s *Server) sendTestAlert(ctx context.Context, scope string, id int64) error { |
| now := s.alertClockNow() |
| c, err := s.store.AlertConnector(id) |
diff --git a/internal/console/alertpages.go b/internal/console/alertpages.go| index c60f1120f..604e0685c 100644 |
| --- a/internal/console/alertpages.go |
| +++ b/internal/console/alertpages.go |
| @@ -43,10 +43,15 @@ var alertPageCopy = map[string]string{ |
| "conn.status.unconfirmed": "Waiting for confirmation", |
| "conn.status.suspended": "Suspended since %s. Send a test to turn it back on.", |
| "conn.status.reentry": "Enter the URL again", |
| - // derived (R-35): a connector turned off from its unsubscribe link. |
| - "conn.status.unsubscribed": "The recipient turned these alerts off on %s. Send a test to turn them back on.", |
| - "conn.owner": "Added for %s", |
| - "conn.btn.test": "Send test", |
| + // derived (R-37): a connector turned off from its unsubscribe link. A |
| + // test no longer turns it back on, so the second sentence is gone. |
| + "conn.status.unsubscribed": "The recipient turned these alerts off on %s.", |
| + "conn.owner": "Added for %s", |
| + "conn.btn.test": "Send test", |
| + // derived (R-37): an unconfirmed email's way to ask again, and what the |
| + // page says once it is queued (conn.added.email without "Added."). |
| + "conn.btn.confirmlink": "Send a new confirm link", |
| + "conn.confirmlink.sent": "A confirm link is on its way to %s. Nothing else is sent there until it is clicked.", |
| "conn.btn.delete": "Delete", |
| "conn.delete.confirm": "Delete %s? Alerts stop going to this connector.", |
| "conn.add.heading": "Add a connector", |
| @@ -276,6 +281,10 @@ type alertsView struct { |
| type alertConnectorView struct { |
| ID int64 |
| Name, Owner, Kind, Target, Status, Tone, DeleteAsk string |
| + // ConfirmLink offers "Send a new confirm link": an email connector |
| + // waiting for confirmation, or turned off by its recipient (ruling |
| + // R-37). |
| + ConfirmLink bool |
| } |
| // alertKindForm is one kind's add form: one form per kind, so each has its |
| @@ -389,7 +398,7 @@ func (s *Server) alertsView() (*alertsView, error) { |
| func alertConnectorRow(c alertConnector, unsubscribedAt time.Time) alertConnectorView { |
| name := alertConnectorName(c) |
| v := alertConnectorView{ID: c.ID, Name: name, Kind: alertPageCopy["kind."+c.Kind], Target: c.TargetHint, |
| - DeleteAsk: fmt.Sprintf(alertPageCopy["conn.delete.confirm"], name)} |
| + DeleteAsk: fmt.Sprintf(alertPageCopy["conn.delete.confirm"], name), ConfirmLink: alertConfirmLinkable(c)} |
| if c.OwnerAddress != "" { |
| v.Owner = fmt.Sprintf(alertPageCopy["conn.owner"], c.OwnerAddress) |
| } |
| @@ -622,6 +631,55 @@ func (s *Server) handleAlertConnectorTest(w http.ResponseWriter, r *http.Request |
| } |
| } |
| +// alertConfirmLinkable reports whether c is offered "Send a new confirm |
| +// link": an unconfirmed email connector, including one its recipient |
| +// unsubscribed. Slack's test carries its own confirm link, and a webhook |
| +// is confirmed by answering. |
| +func alertConfirmLinkable(c alertConnector) bool { |
| + return c.Kind == alertConnectorEmail && !c.Confirmed |
| +} |
| + |
| +// handleAlertConnectorConfirmLink queues connector {id} a new confirm link, |
| +// through the add flow's path: a verify row the drain sends with a fresh |
| +// one-use link, counted against the scope's confirmation limit (spec |
| +// §5.3). For a connector its recipient unsubscribed it is the only way |
| +// back (ruling R-37); for one whose first link expired, the new link the |
| +// confirm door's refusal points to. Any other connector has no such |
| +// action: 404. |
| +func (s *Server) handleAlertConnectorConfirmLink(w http.ResponseWriter, r *http.Request) { |
| + addr, ok := s.alertOperatorForm(w, r) |
| + if !ok { |
| + return |
| + } |
| + c, ok := s.alertPathConnector(w, r) |
| + if !ok { |
| + return |
| + } |
| + if !alertConfirmLinkable(c) { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + anchor := fmt.Sprintf("connector-%d", c.ID) |
| + now := s.alertClockNow() |
| + verify, err := json.Marshal(alertTestNote(c, s.consoleName(), now)) |
| + if err != nil { |
| + log.Printf("console: alert connector %d: confirm link: %v", c.ID, err) |
| + s.alertsBack(w, r, anchor, "err", alertPageCopy["conn.err.failed"]) |
| + return |
| + } |
| + if !s.limits.alertConfirmSend(c.Scope) { |
| + s.alertsBack(w, r, anchor, "err", alertPageCopy["conn.err.confirmlimit"]) |
| + return |
| + } |
| + if err := s.store.CommitAlertStep(nil, nil, []alertOutboxRow{{ConnectorID: c.ID, Kind: "verify", Body: verify, NextAt: now}}); err != nil { |
| + log.Printf("console: alert connector %d: confirm link: %v", c.ID, err) |
| + s.alertsBack(w, r, anchor, "err", alertPageCopy["conn.err.failed"]) |
| + return |
| + } |
| + log.Printf("console: %s queued a new confirm link for alert connector %d", addr, c.ID) |
| + s.alertsBack(w, r, anchor, "ok", fmt.Sprintf(alertPageCopy["conn.confirmlink.sent"], c.TargetHint)) |
| +} |
| + |
| // handleAlertConnectorDelete deletes connector {id} with its queued rows and |
| // links. A seeded operator's connector stays deleted (ruling R-24). |
| func (s *Server) handleAlertConnectorDelete(w http.ResponseWriter, r *http.Request) { |
diff --git a/internal/console/alertpages_test.go b/internal/console/alertpages_test.go| index 4e9a8370a..5d621bc4a 100644 |
| --- a/internal/console/alertpages_test.go |
| +++ b/internal/console/alertpages_test.go |
| @@ -87,7 +87,7 @@ func TestFleetAlertsNotOperator404(t *testing.T) { |
| csrf := sessionToken(t, af.consoleFixture, notOperator) |
| gets := []string{"/fleet/alerts", "/fleet/alerts/history"} |
| posts := []string{"/fleet/alerts/connectors", "/fleet/alerts/connectors/1/test", "/fleet/alerts/connectors/1/delete", |
| - "/fleet/alerts/rules/box_silent"} |
| + "/fleet/alerts/connectors/1/confirm-link", "/fleet/alerts/rules/box_silent"} |
| for who, c := range map[string]*http.Client{"signed out": out, "not an operator": notOperator} { |
| for _, p := range gets { |
| if st, _, body := get(t, c, af.ts.URL+p); st != http.StatusNotFound || body != ghost { |
| @@ -359,8 +359,8 @@ func TestAlertDoorGetDoesNotAct(t *testing.T) { |
| } |
| } |
| c := af.connector(t, id) |
| - if !c.Confirmed || !c.Suspended { |
| - t.Fatalf("after the POSTs the connector is %+v, want confirmed and turned off", c) |
| + if c.Confirmed || !c.Suspended || !c.Unsubscribed { |
| + t.Fatalf("after the POSTs the connector is %+v, want turned off and asking for consent again (R-37)", c) |
| } |
| // Unsubscribing turns the connector off, keeps it, and is idempotent. |
| if st, _, body := postForm(t, door, af.ts.URL+"/alerts/unsubscribe/"+unsub, url.Values{}); st != http.StatusOK || |
| @@ -640,50 +640,221 @@ func TestAlertDoorRefusesLargeOrMultipartBody(t *testing.T) { |
| } |
| } |
| -// A connector its recipient turned off says so, and a test that gets |
| -// through turns it back on and clears that (ruling R-35). |
| -func TestFleetAlertsUnsubscribedStatus(t *testing.T) { |
| +// unsubscribeDoor turns connector id off from its unsubscribe link, as its |
| +// recipient would. |
| +func (af *alertsPageFixture) unsubscribeDoor(t *testing.T, id int64) { |
| + t.Helper() |
| + unsub, err := af.st.NewAlertToken(alertToken{Action: alertTokenUnsubscribe, Scope: alertScopeFleet, ConnectorID: id}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if st, _, body := postForm(t, newBrowser(t), af.ts.URL+"/alerts/unsubscribe/"+unsub, url.Values{}); st != http.StatusOK { |
| + t.Fatalf("unsubscribe = %d %s", st, body) |
| + } |
| +} |
| + |
| +// stillUnsubscribed fails unless connector id is off, unconfirmed and |
| +// carries its unsubscribed marker. |
| +func (af *alertsPageFixture) stillUnsubscribed(t *testing.T, id int64, after string) { |
| + t.Helper() |
| + if c := af.connector(t, id); !c.Suspended || c.Confirmed || !c.Unsubscribed { |
| + t.Fatalf("after %s the connector is %+v, want still turned off by its recipient", after, c) |
| + } |
| +} |
| + |
| +// Ruling R-37: an email its recipient turned off says so, a test is |
| +// refused as for any unconfirmed address, and the way back is a new |
| +// confirm link, which only the recipient opening turns it back on. |
| +func TestFleetAlertsUnsubscribedEmailOnlyConfirmResumes(t *testing.T) { |
| af := newAlertsPageFixture(t) |
| - id := af.addEmail(t, alertScopeFleet, "a@example.com", "", true) |
| - _, unsub, _ := doorTokens(t, af, id) |
| - if st, _, _ := postForm(t, newBrowser(t), af.ts.URL+"/alerts/unsubscribe/"+unsub, url.Values{}); st != http.StatusOK { |
| - t.Fatalf("unsubscribe = %d", st) |
| + af.addAndFlash(t, "kind", "email", "name", "on call", "target", "a@example.com") |
| + id := af.fleetConnectors(t)[0].ID |
| + af.drain(t) |
| + first := alertLinks(af.mail.sentCopy()[0])["confirm"] |
| + if len(first) != 1 { |
| + t.Fatal("the added address got no confirm link") |
| } |
| - want := "The recipient turned these alerts off on " + alertPageTime(af.now) + ". Send a test to turn them back on." |
| + if st, _, _ := postForm(t, newBrowser(t), af.ts.URL+"/alerts/confirm/"+first[0], url.Values{}); st != http.StatusOK { |
| + t.Fatalf("first confirm = %d", st) |
| + } |
| + before := len(af.mail.sentCopy()) // the first confirm link |
| + af.unsubscribeDoor(t, id) |
| + af.stillUnsubscribed(t, id, "the unsubscribe") |
| body := af.page(t, "/fleet/alerts") |
| - if !strings.Contains(body, want) || strings.Contains(body, "Suspended since") { |
| - t.Fatalf("the row does not say the recipient turned it off:\n%s", body) |
| + if want := "The recipient turned these alerts off on " + alertPageTime(af.now) + "."; !strings.Contains(body, want) || |
| + strings.Contains(body, "Suspended since") || strings.Contains(body, "Send a test to turn them back on") { |
| + t.Fatalf("the row does not say the recipient turned it off, or offers a test as the way back:\n%s", body) |
| + } |
| + if !strings.Contains(body, `action="/fleet/alerts/connectors/`+itoa(id)+`/confirm-link"`) || |
| + !strings.Contains(body, "Send a new confirm link") { |
| + t.Fatalf("no Send a new confirm link on the row:\n%s", body) |
| } |
| + |
| + // A test is refused, sends nothing and changes nothing. |
| if st, _ := af.post(t, "/fleet/alerts/connectors/"+itoa(id)+"/test"); st != http.StatusSeeOther { |
| t.Fatalf("test = %d", st) |
| } |
| - if c := af.connector(t, id); c.Suspended { |
| - t.Fatal("a test that got through left it off") |
| + if body := af.page(t, "/fleet/alerts"); !strings.Contains(body, "This address is not confirmed yet.") { |
| + t.Fatalf("the test was not refused in words:\n%s", body) |
| } |
| - var n int |
| - if err := af.st.db.QueryRow(`SELECT COUNT(*) FROM alert_meta WHERE k = ?`, alertUnsubscribedMarker(id)).Scan(&n); err != nil || n != 0 { |
| - t.Fatalf("the unsubscribed marker outlived the resume (%d, %v)", n, err) |
| + if n := len(af.mail.sentCopy()) - before; n != 0 { |
| + t.Fatalf("%d emails sent by a test to an unsubscribed address", n) |
| + } |
| + af.stillUnsubscribed(t, id, "a test") |
| + |
| + // An alert queued for it is held, not sent. |
| + af.queue(t, id, 0, "fire", fireNote()) |
| + af.drain(t) |
| + if n := len(af.mail.sentCopy()) - before; n != 0 { |
| + t.Fatalf("%d emails sent to an unsubscribed address by the drain", n) |
| + } |
| + |
| + // A new confirm link goes out, and the connector stays off until it is |
| + // opened. |
| + if st, _ := af.post(t, "/fleet/alerts/connectors/"+itoa(id)+"/confirm-link"); st != http.StatusSeeOther { |
| + t.Fatalf("confirm-link = %d", st) |
| + } |
| + if body := af.page(t, "/fleet/alerts"); !strings.Contains(body, "A confirm link is on its way to a@example.com.") { |
| + t.Fatalf("no notice for the new link:\n%s", body) |
| + } |
| + af.drain(t) |
| + mails := af.mail.sentCopy()[before:] |
| + if len(mails) != 1 { |
| + t.Fatalf("emails %v, want the confirm link alone", mails) |
| + } |
| + links := alertLinks(mails[0]) |
| + if len(links["confirm"]) != 1 || len(links["unsubscribe"]) != 0 || len(links["snooze"]) != 0 { |
| + t.Fatalf("the email carries %v, want one confirm link and nothing else", links) |
| + } |
| + af.stillUnsubscribed(t, id, "the confirm link was sent") |
| + |
| + st, _, body := postForm(t, newBrowser(t), af.ts.URL+"/alerts/confirm/"+links["confirm"][0], url.Values{}) |
| + if st != http.StatusOK || !strings.Contains(body, "Confirmed. Alerts now go to on call.") { |
| + t.Fatalf("confirm = %d %s", st, body) |
| + } |
| + if c := af.connector(t, id); !c.Confirmed || c.Suspended || c.Unsubscribed { |
| + t.Fatalf("after the recipient confirmed: %+v, want on", c) |
| + } |
| + if body := af.page(t, "/fleet/alerts"); strings.Contains(body, "The recipient turned these alerts off") || |
| + strings.Contains(body, "/confirm-link") { |
| + t.Fatal("the row still says the recipient turned it off, or offers a confirm link") |
| + } |
| + // The held alert goes now. |
| + af.now = af.now.Add(alertHoldRecheck) |
| + af.drain(t) |
| + if n := len(af.mail.sentCopy()) - before; n != 2 { |
| + t.Fatalf("%d emails after the resume, want the held fire too", n) |
| + } |
| +} |
| + |
| +// Ruling R-37: a Slack channel's recipient turned it off. A test still |
| +// posts, carrying a confirm link, but turns nothing back on; the link |
| +// does. |
| +func TestFleetAlertsUnsubscribedSlackTestCannotResubscribe(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + id := af.addHook(t, alertConnectorSlack, testSlackURL, true) |
| + af.unsubscribeDoor(t, id) |
| + if st, _ := af.post(t, "/fleet/alerts/connectors/"+itoa(id)+"/test"); st != http.StatusSeeOther { |
| + t.Fatalf("test = %d", st) |
| + } |
| + reqs := af.hook.requests() |
| + if len(reqs) != 1 { |
| + t.Fatalf("Slack got %d posts, want the test", len(reqs)) |
| + } |
| + links := alertLinks(string(reqs[0].body)) |
| + if len(links["confirm"]) != 1 || len(links["unsubscribe"]) != 0 { |
| + t.Fatalf("the test carries %v, want a confirm link only", links) |
| + } |
| + af.stillUnsubscribed(t, id, "a test that got through") |
| + if body := af.page(t, "/fleet/alerts"); strings.Contains(body, `/connectors/`+itoa(id)+`/confirm-link`) { |
| + t.Fatal("a Slack row offers Send a new confirm link; its test carries one") |
| + } |
| + // Alerts stay held. |
| + af.queue(t, id, 0, "fire", fireNote()) |
| + af.drain(t) |
| + if n := len(af.hook.requests()); n != 1 { |
| + t.Fatalf("%d Slack posts, want the alert held", n) |
| + } |
| + if st, _, body := postForm(t, newBrowser(t), af.ts.URL+"/alerts/confirm/"+links["confirm"][0], url.Values{}); st != http.StatusOK || |
| + !strings.Contains(body, "Alerts now go to") { |
| + t.Fatalf("confirm = %d %s", st, body) |
| } |
| - if body := af.page(t, "/fleet/alerts"); strings.Contains(body, "The recipient turned these alerts off") { |
| - t.Fatal("the row still says the recipient turned it off") |
| + if c := af.connector(t, id); !c.Confirmed || c.Suspended || c.Unsubscribed { |
| + t.Fatalf("after the confirm link: %+v, want on", c) |
| } |
| } |
| -// Confirming a connector its recipient has turned off does not say alerts |
| -// go there (ruling R-35). |
| +// Ruling R-37: unsubscribing drops the connector's unused confirm links, |
| +// so one sent before cannot undo it; a connector suspended for failing, |
| +// confirmed, keeps the "paused" answer (R-35). |
| func TestAlertDoorConfirmWhilePaused(t *testing.T) { |
| af := newAlertsPageFixture(t) |
| id := af.addEmail(t, alertScopeFleet, "a@example.com", "", false) |
| confirm, unsub, _ := doorTokens(t, af, id) |
| door := newBrowser(t) |
| postForm(t, door, af.ts.URL+"/alerts/unsubscribe/"+unsub, url.Values{}) |
| - st, _, body := postForm(t, door, af.ts.URL+"/alerts/confirm/"+confirm, url.Values{}) |
| - if st != http.StatusOK || !strings.Contains(body, "Confirmed. Alerts to a@example.com are paused. An operator can turn them back on.") || |
| + if st, _, body := postForm(t, door, af.ts.URL+"/alerts/confirm/"+confirm, url.Values{}); st != http.StatusNotFound || |
| + !strings.Contains(body, alertPageCopy["door.err.invalid"]) { |
| + t.Fatalf("a confirm link from before the unsubscribe = %d %s, want refused", st, body) |
| + } |
| + af.stillUnsubscribed(t, id, "an old confirm link") |
| + |
| + slack := af.addHook(t, alertConnectorSlack, testSlackURL, true) |
| + old, err := af.st.NewAlertToken(alertToken{Action: alertTokenConfirm, Scope: alertScopeFleet, ConnectorID: slack, |
| + ExpiresAt: af.now.Add(alertConfirmLinkTTL)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := af.st.SetConnectorHealth(slack, false, af.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if now, err := af.st.SetConnectorHealth(slack, false, af.now.Add(alertSuspendAfter)); err != nil || !now { |
| + t.Fatalf("suspend: %v, %v", now, err) |
| + } |
| + st, _, body := postForm(t, door, af.ts.URL+"/alerts/confirm/"+old, url.Values{}) |
| + if st != http.StatusOK || !strings.Contains(body, "Confirmed. Alerts to slack are paused. An operator can turn them back on.") || |
| strings.Contains(body, "Alerts now go to") { |
| - t.Fatalf("confirm while off = %d %s", st, body) |
| + t.Fatalf("confirm while suspended for failing = %d %s", st, body) |
| } |
| - if c := af.connector(t, id); !c.Confirmed || !c.Suspended { |
| - t.Fatalf("connector = %+v, want confirmed and still off", c) |
| + if c := af.connector(t, slack); !c.Confirmed || !c.Suspended { |
| + t.Fatalf("connector = %+v, want confirmed and still suspended", c) |
| + } |
| + // A test that gets through still lifts a suspension for failing. |
| + if st, _ := af.post(t, "/fleet/alerts/connectors/"+itoa(slack)+"/test"); st != http.StatusSeeOther { |
| + t.Fatalf("test = %d", st) |
| + } |
| + if c := af.connector(t, slack); c.Suspended { |
| + t.Fatal("a test that got through left a failing-suspended connector off (R-11)") |
| + } |
| +} |
| + |
| +// The confirm link a page sends is limited with the add flow's: 5 an hour |
| +// for the scope. A connector that is not an unconfirmed email has no such |
| +// action. |
| +func TestFleetAlertsConfirmLinkLimitedAndOnlyForUnconfirmedEmail(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + id := af.addEmail(t, alertScopeFleet, "a@example.com", "", false) |
| + for i := range 5 { |
| + if st, _ := af.post(t, "/fleet/alerts/connectors/"+itoa(id)+"/confirm-link"); st != http.StatusSeeOther { |
| + t.Fatalf("confirm-link %d = %d", i, st) |
| + } |
| + } |
| + af.post(t, "/fleet/alerts/connectors/"+itoa(id)+"/confirm-link") |
| + if body := af.page(t, "/fleet/alerts"); !strings.Contains(body, alertPageCopy["conn.err.confirmlimit"]) { |
| + t.Fatalf("a sixth link in the hour was not refused:\n%s", body) |
| + } |
| + if got := af.outbox(t, id); len(got) != 5 { |
| + t.Fatalf("outbox = %+v, want 5 verify rows", got) |
| + } |
| + confirmed := af.addEmail(t, alertScopeFleet, "b@example.com", "", true) |
| + slack := af.addHook(t, alertConnectorSlack, testSlackURL, false) |
| + for _, c := range []int64{confirmed, slack} { |
| + if st, _ := af.post(t, "/fleet/alerts/connectors/"+itoa(c)+"/confirm-link"); st != http.StatusNotFound { |
| + t.Errorf("confirm-link on connector %d = %d, want 404", c, st) |
| + } |
| + if got := af.outbox(t, c); len(got) != 0 { |
| + t.Errorf("connector %d outbox = %+v", c, got) |
| + } |
| } |
| } |
diff --git a/internal/console/alertstore.go b/internal/console/alertstore.go| index 595a3b159..fc59be369 100644 |
| --- a/internal/console/alertstore.go |
| +++ b/internal/console/alertstore.go |
| @@ -192,7 +192,11 @@ type alertConnector struct { |
| ID int64 |
| Scope, Kind, Name, TargetHint, OwnerAddress string |
| Confirmed, Suspended, NeedsReentry bool |
| - FailingSince, SuspendedAt time.Time |
| + // Unsubscribed is a connector its recipient turned off from an |
| + // unsubscribe link (the alert_meta unsubscribed:<id> marker). Only a |
| + // confirm link it is sent afterwards turns it back on (ruling R-37). |
| + Unsubscribed bool |
| + FailingSince, SuspendedAt time.Time |
| // CreatedBy is the address that added it, for the page. |
| CreatedBy string |
| } |
| @@ -653,13 +657,14 @@ 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` |
| + suspended_at, needs_reentry, failing_since, created_by, |
| + EXISTS (SELECT 1 FROM alert_meta WHERE k = 'unsubscribed:' || alert_connectors.id)` |
| 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 { |
| + &suspended, &c.NeedsReentry, &failing, &c.CreatedBy, &c.Unsubscribed); err != nil { |
| return alertConnector{}, err |
| } |
| c.Confirmed, c.Suspended, c.FailingSince, c.SuspendedAt = confirmed != 0, suspended != 0, alertTime(failing), alertTime(suspended) |
| @@ -692,24 +697,16 @@ func (s *Store) AlertConnector(id int64) (alertConnector, error) { |
| // ResumeAlertConnector lifts connector id's suspension and clears its |
| // failing clock, after a test send got through (ruling R-11): the way back |
| -// for a suspended connector short of deleting and re-adding it. |
| +// for a connector suspended because sending failed, short of deleting and |
| +// re-adding it. |
| // |
| -// It also clears the connector's unsubscribed:<id> marker in the same |
| -// transaction (ruling R-35): once a test has turned it back on, the page no |
| -// longer says the recipient turned it off. |
| +// A connector its recipient unsubscribed is left off (ruling R-37): an |
| +// operator's test is not the recipient's consent. Only a confirm link the |
| +// recipient opens turns it back on (ConfirmAlertConnectorByToken). |
| func (s *Store) ResumeAlertConnector(id int64) error { |
| - tx, err := s.db.Begin() |
| - if err != nil { |
| - return err |
| - } |
| - defer tx.Rollback() |
| - if _, err := tx.Exec(`UPDATE alert_connectors SET suspended_at = 0, failing_since = 0 WHERE id = ?`, id); err != nil { |
| - return err |
| - } |
| - if _, err := tx.Exec(`DELETE FROM alert_meta WHERE k = ?`, alertUnsubscribedMarker(id)); err != nil { |
| - return err |
| - } |
| - return tx.Commit() |
| + _, err := s.db.Exec(`UPDATE alert_connectors SET suspended_at = 0, failing_since = 0 |
| + WHERE id = ? AND NOT EXISTS (SELECT 1 FROM alert_meta WHERE k = ?)`, id, alertUnsubscribedMarker(id)) |
| + return err |
| } |
| // AlertUnsubscribes is when each connector carrying an unsubscribed:<id> |
| @@ -1160,6 +1157,12 @@ func spendAlertToken(tx *sql.Tx, raw string, t alertToken, now time.Time) (alert |
| // link on a connector still waiting. Refusals are UseAlertToken's; |
| // sql.ErrNoRows is a connector no longer there (its tokens go with it, so |
| // only a race reaches that), and leaves the token unspent. |
| +// |
| +// On a connector its recipient unsubscribed, the same transaction also |
| +// lifts the suspension and clears the unsubscribed:<id> marker (ruling |
| +// R-37): the recipient opening a link sent after they unsubscribed is the |
| +// one thing that turns it back on. A connector suspended because sending |
| +// failed stays suspended. |
| func (s *Store) ConfirmAlertConnectorByToken(raw string, now time.Time) (alertConnector, error) { |
| tx, err := s.db.Begin() |
| if err != nil { |
| @@ -1177,6 +1180,19 @@ func (s *Store) ConfirmAlertConnectorByToken(raw string, now time.Time) (alertCo |
| now.Unix(), t.ConnectorID, t.Scope); err != nil { |
| return alertConnector{}, err |
| } |
| + // A connector not in the token's scope fails the read below, and the |
| + // transaction with it. |
| + res, err := tx.Exec(`DELETE FROM alert_meta WHERE k = ?`, alertUnsubscribedMarker(t.ConnectorID)) |
| + if err != nil { |
| + return alertConnector{}, err |
| + } |
| + if n, err := res.RowsAffected(); err != nil { |
| + return alertConnector{}, err |
| + } else if n > 0 { |
| + if _, err := tx.Exec(`UPDATE alert_connectors SET suspended_at = 0, failing_since = 0 WHERE id = ?`, t.ConnectorID); err != nil { |
| + return alertConnector{}, err |
| + } |
| + } |
| c, err := scanAlertConnector(tx.QueryRow(`SELECT `+alertConnectorColumns+` FROM alert_connectors WHERE id = ? AND scope = ?`, |
| t.ConnectorID, t.Scope)) |
| if err != nil { |
| @@ -1190,10 +1206,15 @@ func (s *Store) ConfirmAlertConnectorByToken(raw string, now time.Time) (alertCo |
| // UnsubscribeAlertConnector redeems unsubscribe token raw and turns its |
| // connector off: suspended (spec §5.1), not deleted, so a seeded |
| -// operator's connector keeps its seeded marker (ruling R-24) and a test |
| -// that gets through can turn it back on (ruling R-11). The unsubscribe is |
| -// recorded as alert_meta unsubscribed:<id>, the first time kept. Using the |
| -// link again changes nothing. sql.ErrNoRows: the connector is gone. |
| +// operator's connector keeps its seeded marker (ruling R-24). The |
| +// unsubscribe is recorded as alert_meta unsubscribed:<id>, the first time |
| +// kept. Using the link again changes nothing. sql.ErrNoRows: the connector |
| +// is gone. |
| +// |
| +// It also clears the confirmation and drops the connector's unused confirm |
| +// links (ruling R-37), so the recipient's consent is asked again: nothing |
| +// but a confirm link sent from now on reaches it, and only opening that |
| +// turns it back on. A test that gets through does not. |
| func (s *Store) UnsubscribeAlertConnector(raw string, now time.Time) (alertConnector, error) { |
| tx, err := s.db.Begin() |
| if err != nil { |
| @@ -1204,8 +1225,8 @@ func (s *Store) UnsubscribeAlertConnector(raw string, now time.Time) (alertConne |
| if err != nil { |
| return alertConnector{}, err |
| } |
| - res, err := tx.Exec(`UPDATE alert_connectors SET suspended_at = CASE WHEN suspended_at = 0 THEN ? ELSE suspended_at END |
| - WHERE id = ? AND scope = ?`, now.Unix(), t.ConnectorID, t.Scope) |
| + res, err := tx.Exec(`UPDATE alert_connectors SET suspended_at = CASE WHEN suspended_at = 0 THEN ? ELSE suspended_at END, |
| + confirmed_at = 0 WHERE id = ? AND scope = ?`, now.Unix(), t.ConnectorID, t.Scope) |
| if err != nil { |
| return alertConnector{}, err |
| } |
| @@ -1218,6 +1239,10 @@ func (s *Store) UnsubscribeAlertConnector(raw string, now time.Time) (alertConne |
| alertUnsubscribedMarker(t.ConnectorID), now.UTC().Format(time.RFC3339)); err != nil { |
| return alertConnector{}, err |
| } |
| + if _, err := tx.Exec(`DELETE FROM alert_tokens WHERE connector_id = ? AND action = ? AND used_at IS NULL`, |
| + t.ConnectorID, alertTokenConfirm); err != nil { |
| + return alertConnector{}, err |
| + } |
| c, err := scanAlertConnector(tx.QueryRow(`SELECT `+alertConnectorColumns+` FROM alert_connectors WHERE id = ?`, t.ConnectorID)) |
| if err != nil { |
| return alertConnector{}, err |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index ebb0360d2..6e13b2a55 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -740,6 +740,8 @@ var claimFixtures = map[string]claimFixture{ |
| "route /fleet/economics/tier": claimNonApp("an account's economics tier: an account record, not an app"), |
| "route /fleet/alerts/connectors": claimNonApp("operator adds a fleet alert connector: its alert_connectors row, " + |
| "and a confirmation outbox row or a signed test; names no app"), |
| + "route /fleet/alerts/connectors/{id}/confirm-link": claimNonApp("operator queues an unconfirmed fleet email connector " + |
| + "a new confirm link: one verify outbox row"), |
| "route /fleet/alerts/connectors/{id}/delete": claimNonApp("operator deletes a fleet alert connector with its queued rows and links"), |
| "route /fleet/alerts/connectors/{id}/test": claimNonApp("operator sends a fleet alert connector a test; one that gets through " + |
| "confirms a webhook and lifts a suspension (alert_connectors)"), |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index b88216132..cb5893d76 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -353,6 +353,20 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return "" |
| }, |
| }, |
| + "route /fleet/alerts/connectors/{id}/confirm-link": { |
| + // The census connector is an unconfirmed email: a new confirm link |
| + // is one verify row queued for the drain. |
| + setup: claimWorldAlertLinks, |
| + do: claimFormReply("/fleet/alerts/connectors/<alertconn>/confirm-link"), |
| + status: http.StatusSeeOther, loc: "/fleet/alerts", |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + if cx.sqlCount(t, `SELECT COUNT(*) FROM alert_outbox WHERE connector_id = ? AND kind = 'verify' AND sent_at IS NULL`, |
| + cx.vars["alertconn"]) != 1 { |
| + return "no confirm link queued" |
| + } |
| + return "" |
| + }, |
| + }, |
| "route /fleet/alerts/connectors/{id}/delete": { |
| setup: claimWorldAlertLinks, |
| do: claimFormReply("/fleet/alerts/connectors/<alertconn>/delete"), |
diff --git a/internal/console/server.go b/internal/console/server.go| index ee57ba44a..261450f0b 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1788,6 +1788,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| s.registerRoute("GET /fleet/alerts/history", s.handleFleetAlertHistory) |
| s.registerRoute("/fleet/alerts/connectors", s.handleAlertConnectorAdd) |
| s.registerRoute("/fleet/alerts/connectors/{id}/test", s.handleAlertConnectorTest) |
| + s.registerRoute("/fleet/alerts/connectors/{id}/confirm-link", s.handleAlertConnectorConfirmLink) |
| s.registerRoute("/fleet/alerts/connectors/{id}/delete", s.handleAlertConnectorDelete) |
| s.registerRoute("/fleet/alerts/rules/{rule}", s.handleAlertRuleSave) |
| // The links alert messages carry, public: the token is the credential. |
diff --git a/internal/console/templates/ops_alerts.html b/internal/console/templates/ops_alerts.html| index 71c978a6c..4c4ee015e 100644 |
| --- a/internal/console/templates/ops_alerts.html |
| +++ b/internal/console/templates/ops_alerts.html |
| @@ -28,6 +28,12 @@ |
| <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| <button rst-btn type="submit">{{alertText "conn.btn.test"}}</button> |
| </form> |
| + {{if .ConfirmLink}} |
| + <form method="post" action="/fleet/alerts/connectors/{{.ID}}/confirm-link"> |
| + <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| + <button rst-btn type="submit">{{alertText "conn.btn.confirmlink"}}</button> |
| + </form> |
| + {{end}} |
| <details> |
| <summary rst-btn="danger">{{alertText "conn.btn.delete"}}</summary> |
| <form method="post" action="/fleet/alerts/connectors/{{.ID}}/delete"> |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index 70c810158..655139f28 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -1,6 +1,7 @@ |
| route /api/economics/backhaul |
| route /api/economics/bill |
| route /fleet/alerts/connectors |
| +route /fleet/alerts/connectors/{id}/confirm-link |
| route /fleet/alerts/connectors/{id}/delete |
| route /fleet/alerts/connectors/{id}/test |
| route /fleet/alerts/rules/{rule} |