console: /fleet/alerts pages and token doors
/fleet/alerts lists the fleet's connectors (host and last four characters only, never a URL), adds Slack, email and webhook connectors, sends tests, deletes, and sets each rule's state, connectors and, for box_silent and cert_expiring, threshold (R-29); box rules show their host.env variable read-only. /fleet/alerts/history shows the last 200 incidents, each at #incident-<id>. Operator writes are methodless POSTs behind operatorOnly and the session CSRF token. The public doors (confirm, unsubscribe, snooze) show a page on GET and act only on POST; snooze offers 1 hour, 1 day or 1 week and replaces, never extends (R-28). /alerts/signing-key serves the bare public key (R-30). Strings are the deck's groups 14 to 18 with Luna's rows; new ones are marked derived (Task 10) in the deck.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+1,713
−3
docs/superpowers/notes/copy-fleet-alerts-1.md+11 −3internal/console/alertpages.go+926 −0internal/console/alertpages_test.go+596 −0internal/console/opshell.go+1 −0internal/console/server.go+27 −0internal/console/templates/alert_door.html+21 −0internal/console/templates/ops_alerts.html+102 −0internal/console/templates/ops_alerts_history.html+29 −0
diff --git a/docs/superpowers/notes/copy-fleet-alerts-1.md b/docs/superpowers/notes/copy-fleet-alerts-1.md| index 0b4d9a853..01bd59b5c 100644 |
| --- a/docs/superpowers/notes/copy-fleet-alerts-1.md |
| +++ b/docs/superpowers/notes/copy-fleet-alerts-1.md |
| @@ -10,9 +10,10 @@ the code. A row ending "Final (Luna)" was rewritten by the Luna pass |
| (`LUNA-COPY-RESULT-fleet-alerts-1.md`); a row marked "derived (R-31)" was |
| added by the controller's ruling and is the approved string with its |
| subject clause dropped, or the box's own version of a group 3 line. Every |
| -other row is approved as the deck had it. Groups 14 to 18 are not built |
| -yet: they still show the draft, Luna's rows for them are in the result file, |
| -and Task 10 applies both. |
| +other row is approved as the deck had it. Groups 14 to 18 still show the |
| +draft in their `current` column; Task 10 built them with Luna's rows (in the |
| +result file) applied over the draft, and its new strings are the rows marked |
| +"derived (Task 10)". |
| How to read it (the `current` column is the text as the code has it, or, |
| for groups 14 to 18, the draft): |
| @@ -345,6 +346,8 @@ The page is operator-only. Draft layout: page header, a Connectors section, a Ru |
| | `new:nav.alerts` | `Alerts` | Operator nav, after Metrics | Fixed by the brief. | |
| | `new:page.title` | `Alerts` | Page `<title>` and heading | | |
| | `new:page.intro` | `Where fleet alerts go, which rules send them, and what has fired.` | Page header line | Matches the length and style of the other operator pages' header lines. | |
| +| `page.err` | `Alerts could not be read.` | Error page when the Alerts or History page cannot read its tables | derived (Task 10). | |
| +| `page.history` | `History` | Link from the page to History | derived (Task 10): the link text, the History page's own heading. | |
| | `new:conn.heading` | `Connectors` | Section heading | | |
| | `new:conn.help` | `A connector is a place alerts are sent. Add Slack, an email address or a webhook.` | Under the heading | | |
| | `new:conn.empty` | `No connectors. Alerts are recorded but sent nowhere. Add one to receive them.` | Empty state | Possible once an operator deletes their own. | |
| @@ -390,6 +393,7 @@ The page is operator-only. Draft layout: page header, a Connectors section, a Ru |
| | `new:conn.err.email` | `Enter a valid email address.` | Validation error | | |
| | `new:conn.err.kind` | `Choose Slack, email or webhook.` | Validation error | | |
| | `new:conn.err.confirmlimit` | `Too many confirmation emails. Try again later.` | Rate limit on adding email or retesting | Spec §5.3: 5 an hour and 20 a day. Say the numbers? | |
| +| `conn.err.failed` | `That did not work. Try again in a few minutes.` | Any add, test, delete or rule save that failed on the console's side | derived (Task 10). Never names the cause; the log does. | |
| | `new:conn.key.heading` | `Webhook signing key` | Section heading | | |
| | `new:conn.key.help` | `Each webhook alert carries a Carlos-Signature header, signed with the key below. Receivers check it with this public key. It is also served as plain text at %s.` | Help line | `%s` is the console's `/alerts/signing-key` URL. | |
| | `new:conn.key.label` | `Public key (Ed25519, base64)` | Label above the key | | |
| @@ -445,6 +449,7 @@ One row per rule on `/fleet/alerts`. Box rules show their thresholds read-only, |
| | `new:rules.state.offhelp` | `A rule that is off still records incidents in History but sends nothing.` | Help line | Matches the engine: a disabled rule queues nothing. | |
| | `new:rules.noise` | `Fired %d times. Cleared within 10 minutes %d times.` | Last 30 days cell | First `%d` is fires, second clears within 10 minutes. Spec §6.6, so a noisy rule is easy to spot. | |
| | `new:rules.saved.rule` | `Saved.` | Confirmation after changing connectors or state | | |
| +| `rules.err.connector` | `A connector you picked no longer exists. Reload the page and try again.` | A rule save naming a connector deleted since the page loaded | derived (Task 10). | |
| ## 16. History (new, drafts) |
| @@ -482,6 +487,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.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. | |
| | `new:door.unsub.btn` | `Stop alerts` | Button | | |
| @@ -492,6 +498,7 @@ Reached from an emailed or posted link. Anyone holding the link can open the pag |
| | `new:door.snooze.1d` | `1 day` | Length option | | |
| | `new:door.snooze.1w` | `1 week` | Length option | | |
| | `new:door.snooze.body` | `No messages about this for %s, counted from now. Using the link again starts the time from that moment. It does not add to it. The incident still shows in History.` | Snooze confirm page | `%s` is a length. | |
| +| `door.snooze.body` (as built) | `Counted from now. Using the link again starts the time from that moment. It does not add to it. The incident still shows in History.` | Snooze page, under the three buttons | derived (Task 10, ruling R-28): the row above without its length, since one page offers all three. | |
| | `new:door.snooze.btn` | `Snooze for %s` | Button | `%s` is a length. | |
| | `new:door.snooze.done` | `Snoozed until %s.` | After the POST | `%s` is a time. | |
| | `new:door.err.invalid` | `This link is not valid. It may be mistyped or cut off.` | Unknown or tampered token | | |
| @@ -500,6 +507,7 @@ Reached from an emailed or posted link. Anyone holding the link can open the pag |
| | `new:door.err.duration` | `That length is not offered. Choose 1 hour, 1 day or 1 week.` | Snooze `for` not 1h, 1d or 1w | | |
| | `new:door.err.rate` | `Too many tries. Wait a few minutes and try again.` | Rate-limited confirm | | |
| | `new:door.err.gone` | `The connector for this link no longer exists.` | Token for a deleted connector | | |
| +| `door.err.failed` | `That did not work. Try the link again in a few minutes.` | An unsubscribe or snooze that failed on the console's side | derived (Task 10). | |
| ## 18. Signing key page (new, drafts) |
diff --git a/internal/console/alertpages.go b/internal/console/alertpages.go| new file mode 100644 |
| index 000000000..9ffd2abac |
| --- /dev/null |
| +++ b/internal/console/alertpages.go |
| @@ -0,0 +1,926 @@ |
| +package console |
| + |
| +import ( |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net/http" |
| + "net/url" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "time" |
| + "unicode" |
| +) |
| + |
| +// alertPageCopy is every word of the Alerts pages and the token doors: the |
| +// copy deck's groups 14 to 18 (docs/superpowers/notes/copy-fleet-alerts-1.md) |
| +// with the Luna rows applied, approved by delegation. A key marked derived |
| +// was written for Task 10 in the same voice and is in the deck. Change the |
| +// deck first. |
| +var alertPageCopy = map[string]string{ |
| + // 14. The page and its connectors. |
| + "page.intro": "Where fleet alerts go, which rules send them, and what has fired.", |
| + "page.history": "History", |
| + // derived (Task 10): the page could not read its own tables. |
| + "page.err": "Alerts could not be read.", |
| + |
| + "conn.heading": "Connectors", |
| + "conn.help": "A connector is where alerts are sent. Add Slack, an email address or a webhook.", |
| + "conn.empty": "No connectors. Alerts are recorded but sent nowhere. Add one to receive them.", |
| + "conn.col.name": "Name", |
| + "conn.col.kind": "Kind", |
| + "conn.col.target": "Sent to", |
| + "conn.col.status": "Status", |
| + "kind.slack": "Slack", |
| + "kind.email": "Email", |
| + "kind.webhook": "Webhook", |
| + "conn.target.secret": "%s, ends in %s", |
| + "conn.status.on": "On", |
| + "conn.status.unconfirmed": "Waiting for confirmation", |
| + "conn.status.suspended": "Suspended since %s. Send a test to turn it back on.", |
| + "conn.status.reentry": "Enter the URL again", |
| + "conn.owner": "Added for %s", |
| + "conn.btn.test": "Send test", |
| + "conn.btn.delete": "Delete", |
| + "conn.delete.confirm": "Delete %s? Alerts stop going to this connector.", |
| + "conn.add.heading": "Add a connector", |
| + "conn.add.name": "Name", |
| + "conn.add.name.help": "It appears in alerts and on this page. For example, ops channel.", |
| + "conn.add.slack": "Slack webhook URL", |
| + "conn.add.slack.help": "An incoming-webhook URL from Slack, starting with https://hooks.slack.com/. It is stored encrypted and is not shown again.", |
| + "conn.add.webhook": "Webhook URL", |
| + "conn.add.webhook.help": "An HTTPS URL on port 443. It is stored encrypted and is not shown again. Each alert is sent as signed JSON, and the receiver must answer with a 2xx status.", |
| + "conn.add.email": "Email address", |
| + "conn.add.email.help": "We send a confirm link first. Nothing else goes to the address until it is clicked.", |
| + "conn.btn.add": "Add connector", |
| + "conn.added.slack": "Added. We sent a test message with a confirm link to Slack. Open the link to turn this connector on.", |
| + "conn.added.webhook": "Added. The signed test was sent and the webhook answered, so this connector is on.", |
| + "conn.added.webhook.failed": "Added, but the test did not get through (%s). Fix the connector, then send a test.", |
| + "conn.added.email": "Added. A confirm link is on its way to %s. Nothing else is sent there until it is clicked.", |
| + "conn.tested": "Test sent to %s.", |
| + "conn.test.unconfirmed": "This address is not confirmed yet. Open the confirm link we sent to %s.", |
| + "conn.test.limit": "At most 10 tests an hour for one connector. Try again later.", |
| + "conn.test.reentry": "Enter this connector's URL again before testing it.", |
| + "conn.deleted": "Deleted %s.", |
| + "conn.err.name": "Give the connector a name.", |
| + "conn.err.email": "Enter a valid email address.", |
| + "conn.err.kind": "Choose Slack, email or webhook.", |
| + "conn.err.confirmlimit": "Too many confirmation emails. The limit is 5 an hour and 20 a day. Try again later.", |
| + // derived (Task 10): a write on the page that failed on our side. |
| + "conn.err.failed": "That did not work. Try again in a few minutes.", |
| + "conn.key.heading": "Webhook signing key", |
| + "conn.key.help": "Each webhook alert carries a Carlos-Signature header. Receivers can check it with this public key. It is also served as plain text at %s.", |
| + "conn.key.label": "Public key (Ed25519, base64)", |
| + |
| + // 15. Rules. |
| + "rules.heading": "Rules", |
| + "rules.help": "Each rule watches one thing across the fleet. Pick where its messages go, or leave it on all confirmed connectors.", |
| + "rules.col.level": "Level", |
| + "rules.col.when": "Fires when", |
| + "rules.col.threshold": "Threshold", |
| + "rules.col.sendto": "Sent to", |
| + "rules.col.noise": "Last 30 days", |
| + "rules.col.state": "State", |
| + "rules.level.incident": "Incident", |
| + "rules.level.warning": "Warning", |
| + "rules.level.help": "Incident means something is broken now. Warning means something will break, or is degraded.", |
| + "rules.when.disk_eta": "A box's disk is on course to fill within the threshold, and has been for 2 hours.", |
| + "rules.when.disk": "A box's disk use is over the threshold.", |
| + "rules.when.mem": "A box's memory use is over the threshold for 10 minutes.", |
| + "rules.when.cpu": "A box's processor use is over the threshold for 15 minutes.", |
| + "rules.when.lag": "A box's mail relay is behind by more than the threshold.", |
| + "rules.when.geoip": "A box's location database is old, expiring, not loading or failing to update.", |
| + "rules.when.engine_silent": "The alert engine has not run for 10 minutes. Only the console box reports this.", |
| + "rules.when.box_silent": "A box has not reported for longer than the threshold.", |
| + "rules.when.service_down": "A platform service is reported down.", |
| + "rules.when.cert_expiring": "A served host's certificate expires within the threshold.", |
| + "rules.when.alert_delivery_broken": "A box has no place to send its own alerts.", |
| + "rules.when.seal_key": "The console cannot open the key for Slack and webhook connectors, or a connector needs its URL entered again.", |
| + "rules.th.disk": "Default: 90 percent. Each box can set CARLOS_ALERT_DISK_PCT in its host.env.", |
| + "rules.th.mem": "Default: 90 percent. Each box can set CARLOS_ALERT_MEM_PCT in its host.env.", |
| + "rules.th.cpu": "Default: 95 percent. Each box can set CARLOS_ALERT_CPU_PCT in its host.env.", |
| + "rules.th.disk_eta": "Default 72 hours. Each box can set CARLOS_ALERT_DISK_ETA_HOURS in its host.env.", |
| + "rules.th.lag": "Fixed at 900 seconds. Not configurable.", |
| + "rules.th.geoip": "Fixed. Not configurable.", |
| + "rules.th.engine_silent": "Fixed at 10 minutes. Not configurable.", |
| + "rules.th.readonly": "Set on each box, not here.", |
| + "rules.th.none": "No threshold.", |
| + "rules.th.box_silent": "Silent after (minutes)", |
| + "rules.th.cert_expiring": "Warn when a certificate expires within (days)", |
| + "rules.th.save": "Save", |
| + "rules.th.err": "Enter a whole number from %d to %d.", |
| + "rules.sendto.all": "All confirmed connectors", |
| + "rules.sendto.help": "Pick connectors, or leave all unticked to send to every confirmed connector.", |
| + "rules.state.on": "On", |
| + "rules.state.off": "Off", |
| + "rules.state.offhelp": "A rule that is off still records incidents in History but sends nothing.", |
| + "rules.noise": "Fired %d times. It cleared within 10 minutes %d times.", |
| + "rules.saved.rule": "Saved.", |
| + // derived (Task 10): a ticked connector was deleted before the save. |
| + "rules.err.connector": "A connector you picked no longer exists. Reload the page and try again.", |
| + |
| + // 16. History. |
| + "hist.heading": "History", |
| + "hist.intro": "The last 200 incidents, newest first.", |
| + "hist.empty": "No incidents yet. History starts when the first alert fires on this console.", |
| + "hist.col.rule": "Rule", |
| + "hist.col.affected": "Affected", |
| + "hist.col.level": "Level", |
| + "hist.col.opened": "Opened", |
| + "hist.col.state": "State", |
| + "hist.state.open": "Open for %s", |
| + "hist.state.flapping": "Open, fired and cleared 3 times in the last hour", |
| + "hist.state.cleared": "Cleared after %s", |
| + "hist.state.gone": "No further reports after %s", |
| + "hist.state.duplicate": "Closed as a duplicate", |
| + "hist.affected.many": "%d affected members: %s", |
| + "hist.limit": "Older incidents are not shown.", |
| + "hist.back": "Back to Alerts", |
| + |
| + // 17. The public doors. |
| + "door.title": "CARLOS alerts", |
| + "door.scanner": "Opening this link does nothing by itself. Press the button to go ahead.", |
| + "door.confirm.heading": "Confirm alerts to %s", |
| + "door.confirm.body": "Press Confirm to start receiving CARLOS alerts here. Until then, nothing is sent.", |
| + "door.confirm.btn": "Confirm", |
| + "door.confirm.done": "Confirmed. Alerts now go to %s.", |
| + "door.confirm.used": "This link has been used already. Alerts to %s are on.", |
| + // derived (Task 10): confirming failed; the link is left as it was. |
| + "door.confirm.failed": "Confirming did not work. Ask an operator to send a new link from the Alerts page.", |
| + "door.unsub.heading": "Stop alerts to %s", |
| + "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.", |
| + "door.unsub.btn": "Stop alerts", |
| + "door.unsub.done": "Stopped. Nothing more will be sent to %s.", |
| + "door.snooze.heading": "Snooze %s on %s", |
| + "door.snooze.choose": "How long should this stay quiet?", |
| + // derived (Task 10, ruling R-28): door.snooze.body without its length, |
| + // for the page that offers all three. |
| + "door.snooze.body": "Counted from now. Using the link again starts the time from that moment. It does not add to it. The incident still shows in History.", |
| + "door.snooze.1h": "1 hour", |
| + "door.snooze.1d": "1 day", |
| + "door.snooze.1w": "1 week", |
| + "door.snooze.btn": "Snooze for %s", |
| + "door.snooze.done": "Snoozed until %s.", |
| + "door.err.invalid": "This link is not valid. It may be mistyped or cut off.", |
| + "door.err.expired": "This link has expired. Ask an operator to send a new one from the Alerts page.", |
| + "door.err.action": "This link cannot be used on this page.", |
| + "door.err.duration": "That length is not offered. Choose 1 hour, 1 day or 1 week.", |
| + "door.err.gone": "The connector for this link no longer exists.", |
| + // derived (Task 10): an unsubscribe or snooze that failed on our side. |
| + "door.err.failed": "That did not work. Try the link again in a few minutes.", |
| +} |
| + |
| +// The operator Alerts pages (fleet alerts spec §5, plan 1 Task 10): |
| +// /fleet/alerts, the fleet's connectors, its rules and the webhook signing |
| +// key, and /fleet/alerts/history, the incidents. Every request goes through |
| +// operatorOnly, and every write is a POST carrying the session's CSRF token, |
| +// registered without a method so a wrong method answers the same 404 as an |
| +// unknown route (as the economics doors, server.go). |
| +// |
| +// And the public token doors the messages link to: /alerts/confirm, |
| +// /alerts/unsubscribe and /alerts/snooze. The token in the path is the only |
| +// credential; there is no session and no CSRF token. A GET only shows a |
| +// page with a button, and only the POST acts, so a mail scanner that opens |
| +// every link changes nothing. /alerts/signing-key serves the webhook |
| +// public key as bare text (ruling R-30). |
| + |
| +const ( |
| + // alertHistoryLimit is how many incidents History shows. |
| + alertHistoryLimit = 200 |
| + // alertNoiseWindow and alertQuickClear are each rule's noise count: how |
| + // often it fired, and cleared again within ten minutes, in the last 30 |
| + // days (spec §6.6). |
| + alertNoiseWindow = 30 * 24 * time.Hour |
| + alertQuickClear = 10 * time.Minute |
| +) |
| + |
| +// alertRuleOrder is the Rules section, top to bottom: the box rules, then |
| +// the console's. It names every rule in alertRuleLevels |
| +// (TestAlertRuleOrderCoversEveryRule). |
| +var alertRuleOrder = []string{"disk_eta", "disk", "mem", "cpu", "lag", "geoip", "engine_silent", |
| + "box_silent", "service_down", "cert_expiring", "alert_delivery_broken", "seal_key"} |
| + |
| +// alertThresholdBounds are the editable thresholds' whole-number bounds: |
| +// box_silent in minutes, cert_expiring in days (ruling R-29). |
| +var alertThresholdBounds = map[string][2]int{"box_silent": {5, 1440}, "cert_expiring": {1, 60}} |
| + |
| +// alertBoxEnvRules are the box rules whose threshold each box sets in its |
| +// host.env, shown read-only with the variable's name (spec §5.2). |
| +var alertBoxEnvRules = map[string]bool{"disk_eta": true, "disk": true, "mem": true, "cpu": true} |
| + |
| +// alertSnoozeLengths are the only snoozes a link offers (ruling R-28). |
| +var alertSnoozeLengths = []struct { |
| + For string |
| + D time.Duration |
| +}{{"1h", time.Hour}, {"1d", 24 * time.Hour}, {"1w", 7 * 24 * time.Hour}} |
| + |
| +// alertText is the template func for alertPageCopy. A key with no copy |
| +// fails the render rather than show nothing. |
| +func alertText(key string) (string, error) { |
| + if s, ok := alertPageCopy[key]; ok { |
| + return s, nil |
| + } |
| + return "", fmt.Errorf("alert page copy %q", key) |
| +} |
| + |
| +// alertPageTime is a time as the operator pages show one. |
| +func alertPageTime(t time.Time) string { return t.UTC().Format("2006-01-02 15:04 UTC") } |
| + |
| +// alertSpan is how long something lasted: minutes under an hour, then |
| +// hours, then days. |
| +func alertSpan(d time.Duration) string { |
| + if d < time.Hour { |
| + return alertUnits(max(int(d/time.Minute), 1), "minute") |
| + } |
| + return alertAge(d) |
| +} |
| + |
| +// alertConnectorName is what the pages and doors call c: its name, else |
| +// what it sends to, else its kind. |
| +func alertConnectorName(c alertConnector) string { |
| + switch { |
| + case c.Name != "": |
| + return c.Name |
| + case c.TargetHint != "": |
| + return c.TargetHint |
| + } |
| + return alertPageCopy["kind."+c.Kind] |
| +} |
| + |
| +// alertURLHint is what a Slack or webhook connector's page shows of the URL |
| +// typed: the host and the last four characters (spec §5.1). Never more: |
| +// the path is the secret. |
| +func alertURLHint(host, raw string) string { |
| + r := []rune(raw) |
| + return fmt.Sprintf(alertPageCopy["conn.target.secret"], host, string(r[max(len(r)-4, 0):])) |
| +} |
| + |
| +// ---- views ------------------------------------------------------------------- |
| + |
| +type alertsView struct { |
| + Connectors []alertConnectorView |
| + Kinds []alertKindForm |
| + Rules []alertRuleView |
| + // KeyHelp names the signing-key URL; PublicKey is the key. |
| + KeyHelp, PublicKey string |
| +} |
| + |
| +type alertConnectorView struct { |
| + ID int64 |
| + Name, Owner, Kind, Target, Status, Tone, DeleteAsk string |
| +} |
| + |
| +// alertKindForm is one kind's add form: one form per kind, so each has its |
| +// own label and help without a script. |
| +type alertKindForm struct{ Kind, Heading, Label, Help, InputType string } |
| + |
| +type alertRuleView struct { |
| + Rule, Title, Level, When, SendTo, Noise string |
| + // Threshold is a read-only threshold's text, and BoxEnv adds that each |
| + // box sets it. Editable rules have a whole-number field instead. |
| + Threshold string |
| + BoxEnv, Editable bool |
| + ThresholdLabel string |
| + ThresholdValue int |
| + ThresholdMin, ThresholdMax int |
| + Enabled bool |
| + Connectors []alertRuleConnectorView |
| +} |
| + |
| +type alertRuleConnectorView struct { |
| + ID int64 |
| + Label string |
| + Checked bool |
| +} |
| + |
| +type alertHistoryView struct { |
| + Rows []alertHistoryRow |
| + // Full is a page holding alertHistoryLimit rows, with older ones unshown. |
| + Full bool |
| +} |
| + |
| +type alertHistoryRow struct { |
| + ID int64 |
| + Rule, Affected, Level, Opened, State string |
| +} |
| + |
| +// alertDoorView is one door's page: a heading, what pressing the button |
| +// does and the buttons, or what was done, or why the link was refused. |
| +type alertDoorView struct { |
| + Heading, Body, Note, Action string |
| + Buttons []alertDoorButton |
| + Done, Error string |
| +} |
| + |
| +type alertDoorButton struct{ Label, For string } |
| + |
| +// ---- the Alerts page ----------------------------------------------------------- |
| + |
| +func (s *Server) handleFleetAlerts(w http.ResponseWriter, r *http.Request) { |
| + addr, raw, ok := s.operatorOnly(w, r) |
| + if !ok { |
| + return |
| + } |
| + v, err := s.alertsView() |
| + if err != nil { |
| + log.Printf("console: alerts page: %v", err) |
| + s.renderMessage(w, r, http.StatusInternalServerError, "Unavailable", alertPageCopy["page.err"]) |
| + return |
| + } |
| + p := s.opPage(addr, raw, "alerts") |
| + p.Flash, p.FlashErr = s.takeFlash(w, r) |
| + p.Alerts = v |
| + s.render(w, http.StatusOK, "ops_alerts", p) |
| +} |
| + |
| +// alertsView reads the fleet's connectors, rule settings and noise, and the |
| +// signing key (made on first use, as the first webhook would). |
| +func (s *Server) alertsView() (*alertsView, error) { |
| + conns, err := s.store.AlertConnectors(alertScopeFleet) |
| + if err != nil { |
| + return nil, err |
| + } |
| + settings, err := s.store.AlertRuleSettings(alertScopeFleet) |
| + if err != nil { |
| + return nil, err |
| + } |
| + noise, err := s.store.AlertRuleNoise(alertScopeFleet, s.alertClockNow().Add(-alertNoiseWindow), alertQuickClear) |
| + if err != nil { |
| + return nil, err |
| + } |
| + key, err := s.store.AlertSigningKey() |
| + if err != nil { |
| + return nil, err |
| + } |
| + v := &alertsView{ |
| + KeyHelp: fmt.Sprintf(alertPageCopy["conn.key.help"], s.cfg.Origin+"/alerts/signing-key"), |
| + PublicKey: alertPublicKey(key), |
| + } |
| + for _, c := range conns { |
| + v.Connectors = append(v.Connectors, alertConnectorRow(c)) |
| + } |
| + for _, k := range []struct{ kind, input string }{ |
| + {alertConnectorSlack, "url"}, {alertConnectorEmail, "email"}, {alertConnectorWebhook, "url"}, |
| + } { |
| + v.Kinds = append(v.Kinds, alertKindForm{Kind: k.kind, Heading: alertPageCopy["kind."+k.kind], |
| + Label: alertPageCopy["conn.add."+k.kind], Help: alertPageCopy["conn.add."+k.kind+".help"], InputType: k.input}) |
| + } |
| + for _, rule := range alertRuleOrder { |
| + v.Rules = append(v.Rules, alertRuleRow(rule, settings, conns, noise[rule])) |
| + } |
| + return v, nil |
| +} |
| + |
| +func alertConnectorRow(c alertConnector) 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)} |
| + if c.OwnerAddress != "" { |
| + v.Owner = fmt.Sprintf(alertPageCopy["conn.owner"], c.OwnerAddress) |
| + } |
| + switch { |
| + case c.NeedsReentry: |
| + v.Status, v.Tone = alertPageCopy["conn.status.reentry"], "negative" |
| + case c.Suspended: |
| + v.Status, v.Tone = fmt.Sprintf(alertPageCopy["conn.status.suspended"], alertPageTime(c.SuspendedAt)), "negative" |
| + case !c.Confirmed: |
| + v.Status, v.Tone = alertPageCopy["conn.status.unconfirmed"], "neutral" |
| + default: |
| + v.Status, v.Tone = alertPageCopy["conn.status.on"], "positive" |
| + } |
| + return v |
| +} |
| + |
| +func alertRuleRow(rule string, settings map[string]alertRuleSetting, conns []alertConnector, noise alertNoise) alertRuleView { |
| + st, set := settings[rule] |
| + v := alertRuleView{Rule: rule, Title: alertRuleTitle(rule), Level: alertPageCopy["rules.level."+alertRuleLevel(rule)], |
| + When: alertPageCopy["rules.when."+rule], Enabled: !set || st.Enabled, |
| + Noise: fmt.Sprintf(alertPageCopy["rules.noise"], noise.Fired, noise.QuickClears)} |
| + if b, ok := alertThresholdBounds[rule]; ok { |
| + v.Editable, v.ThresholdLabel = true, alertPageCopy["rules.th."+rule] |
| + v.ThresholdValue, v.ThresholdMin, v.ThresholdMax = int(alertThreshold(settings, rule)), b[0], b[1] |
| + } else if th, ok := alertPageCopy["rules.th."+rule]; ok { |
| + v.Threshold, v.BoxEnv = th, alertBoxEnvRules[rule] |
| + } else { |
| + v.Threshold = alertPageCopy["rules.th.none"] |
| + } |
| + var to []string |
| + for _, c := range conns { |
| + picked := slices.Contains(st.ConnectorIDs, c.ID) |
| + if picked { |
| + to = append(to, alertConnectorName(c)) |
| + } |
| + v.Connectors = append(v.Connectors, alertRuleConnectorView{ID: c.ID, Label: alertConnectorName(c), Checked: picked}) |
| + } |
| + v.SendTo = alertPageCopy["rules.sendto.all"] |
| + if len(to) > 0 { |
| + v.SendTo = strings.Join(to, ", ") |
| + } |
| + return v |
| +} |
| + |
| +// ---- the operator writes ------------------------------------------------------- |
| + |
| +// alertOperatorForm admits an operator's POST to one of the Alerts page's |
| +// doors: the method first, so a GET is the unknown route's 404 to anyone, |
| +// then operatorOnly, then the form and its CSRF token. |
| +func (s *Server) alertOperatorForm(w http.ResponseWriter, r *http.Request) (addr string, ok bool) { |
| + if r.Method != http.MethodPost { |
| + http.NotFound(w, r) |
| + return "", false |
| + } |
| + addr, raw, ok := s.operatorOnly(w, r) |
| + if !ok { |
| + return "", false |
| + } |
| + if !s.storeFormCSRF(w, r, raw) { |
| + return "", false |
| + } |
| + return addr, true |
| +} |
| + |
| +// alertsBack sends the operator back to the Alerts page at anchor, with |
| +// msg as its notice (kind "ok" or "err"). |
| +func (s *Server) alertsBack(w http.ResponseWriter, r *http.Request, anchor, kind, msg string) { |
| + s.setFlash(w, kind, msg) |
| + http.Redirect(w, r, "/fleet/alerts#"+anchor, http.StatusSeeOther) |
| +} |
| + |
| +// alertPathConnector is the fleet connector the path's {id} names; false |
| +// (after a 404) for an id that is malformed, gone or another scope's. |
| +func (s *Server) alertPathConnector(w http.ResponseWriter, r *http.Request) (alertConnector, bool) { |
| + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) |
| + if err != nil || id <= 0 { |
| + http.NotFound(w, r) |
| + return alertConnector{}, false |
| + } |
| + c, err := s.store.AlertConnector(id) |
| + if errors.Is(err, sql.ErrNoRows) || (err == nil && c.Scope != alertScopeFleet) { |
| + http.NotFound(w, r) |
| + return alertConnector{}, false |
| + } |
| + if err != nil { |
| + log.Printf("console: alert connector %d: %v", id, err) |
| + s.alertsBack(w, r, "connectors", "err", alertPageCopy["conn.err.failed"]) |
| + return alertConnector{}, false |
| + } |
| + return c, true |
| +} |
| + |
| +// handleAlertConnectorAdd adds a Slack, email or webhook connector to the |
| +// fleet (spec §5.1). Slack and email are stored unconfirmed with their |
| +// confirmation queued in the same transaction, both counted against the |
| +// scope's confirmation limit (spec §5.3); the drain sends it within a |
| +// minute. A webhook is sent its signed test at once, and an answer of 2xx |
| +// confirms it. A URL is checked (validConnectorURL) and sealed before it is |
| +// stored, and nothing about it but the host and its last four characters is |
| +// ever shown again; a refused URL is never echoed back. |
| +func (s *Server) handleAlertConnectorAdd(w http.ResponseWriter, r *http.Request) { |
| + addr, ok := s.alertOperatorForm(w, r) |
| + if !ok { |
| + return |
| + } |
| + fail := func(msg string) { s.alertsBack(w, r, "connectors", "err", msg) } |
| + kind, name, target := r.PostFormValue("kind"), strings.TrimSpace(r.PostFormValue("name")), strings.TrimSpace(r.PostFormValue("target")) |
| + switch kind { |
| + case alertConnectorSlack, alertConnectorEmail, alertConnectorWebhook: |
| + default: |
| + fail(alertPageCopy["conn.err.kind"]) |
| + return |
| + } |
| + if name == "" || strings.ContainsFunc(name, unicode.IsControl) { |
| + fail(alertPageCopy["conn.err.name"]) |
| + return |
| + } |
| + now := s.alertClockNow() |
| + c := alertConnector{Scope: alertScopeFleet, Kind: kind, Name: name, CreatedBy: addr} |
| + var sealed []byte |
| + var plain string |
| + if kind == alertConnectorEmail { |
| + a, ok := canonicalAddress(target) |
| + if !ok { |
| + fail(alertPageCopy["conn.err.email"]) |
| + return |
| + } |
| + c.TargetHint, plain = a, a |
| + } else { |
| + u, err := validConnectorURL(kind, target) |
| + if err != nil { |
| + fail(err.Error()) // names the rule broken, never the URL |
| + return |
| + } |
| + seal := s.alertSeal.Load() |
| + if seal == nil { |
| + fail(alertCopy["hold.no_seal_key"]) |
| + return |
| + } |
| + if sealed, err = seal.Seal([]byte(target)); err != nil { |
| + log.Printf("console: alert connector add: seal: %v", err) |
| + fail(alertPageCopy["conn.err.failed"]) |
| + return |
| + } |
| + c.TargetHint = alertURLHint(u.Hostname(), target) |
| + } |
| + if kind == alertConnectorWebhook { |
| + id, err := s.store.AddAlertConnector(c, sealed, "") |
| + if err != nil { |
| + log.Printf("console: alert connector add: %v", err) |
| + fail(alertPageCopy["conn.err.failed"]) |
| + return |
| + } |
| + log.Printf("console: %s added webhook alert connector %d", addr, id) |
| + var f alertTestFailure |
| + switch err := s.sendTestAlert(r.Context(), alertScopeFleet, id); { |
| + case err == nil: |
| + s.alertsBack(w, r, "connectors", "ok", alertPageCopy["conn.added.webhook"]) |
| + case errors.As(err, &f): |
| + fail(fmt.Sprintf(alertPageCopy["conn.added.webhook.failed"], f.Reason())) |
| + default: |
| + // The console's own trouble (its signing key, its database): the |
| + // connector is there, unconfirmed, for a test from its row. |
| + log.Printf("console: alert connector %d: first test: %v", id, err) |
| + fail(alertPageCopy["conn.err.failed"]) |
| + } |
| + return |
| + } |
| + // Slack and email: a confirmation, limited per scope. |
| + verify, err := json.Marshal(alertTestNote(c, s.consoleName(), now)) |
| + if err != nil { |
| + log.Printf("console: alert connector add: %v", err) |
| + fail(alertPageCopy["conn.err.failed"]) |
| + return |
| + } |
| + if !s.limits.alertConfirmSend(alertScopeFleet) { |
| + fail(alertPageCopy["conn.err.confirmlimit"]) |
| + return |
| + } |
| + id, err := s.store.AddAlertConnectorVerify(c, sealed, plain, verify, now) |
| + if err != nil { |
| + log.Printf("console: alert connector add: %v", err) |
| + fail(alertPageCopy["conn.err.failed"]) |
| + return |
| + } |
| + log.Printf("console: %s added %s alert connector %d", addr, kind, id) |
| + msg := alertPageCopy["conn.added.slack"] |
| + if kind == alertConnectorEmail { |
| + msg = fmt.Sprintf(alertPageCopy["conn.added.email"], plain) |
| + } |
| + s.alertsBack(w, r, "connectors", "ok", msg) |
| +} |
| + |
| +// handleAlertConnectorTest sends connector {id} a test now (sendTestAlert). |
| +// An unconfirmed Slack connector's test carries a confirm link, so it |
| +// counts against the scope's confirmation limit first. |
| +func (s *Server) handleAlertConnectorTest(w http.ResponseWriter, r *http.Request) { |
| + if _, ok := s.alertOperatorForm(w, r); !ok { |
| + return |
| + } |
| + c, ok := s.alertPathConnector(w, r) |
| + if !ok { |
| + return |
| + } |
| + anchor := fmt.Sprintf("connector-%d", c.ID) |
| + if c.Kind == alertConnectorSlack && !c.Confirmed && !c.NeedsReentry && !s.limits.alertConfirmSend(c.Scope) { |
| + s.alertsBack(w, r, anchor, "err", alertPageCopy["conn.err.confirmlimit"]) |
| + return |
| + } |
| + err := s.sendTestAlert(r.Context(), alertScopeFleet, c.ID) |
| + var f alertTestFailure |
| + switch { |
| + case err == nil: |
| + s.alertsBack(w, r, anchor, "ok", fmt.Sprintf(alertPageCopy["conn.tested"], alertConnectorName(c))) |
| + case errors.Is(err, sql.ErrNoRows): |
| + http.NotFound(w, r) // deleted since, or its owner is no operator now |
| + case errors.Is(err, errAlertTestUnconfirmed): |
| + s.alertsBack(w, r, anchor, "err", fmt.Sprintf(alertPageCopy["conn.test.unconfirmed"], c.TargetHint)) |
| + case errors.Is(err, errAlertTestLimit): |
| + s.alertsBack(w, r, anchor, "err", alertPageCopy["conn.test.limit"]) |
| + case errors.Is(err, errAlertTestReentry): |
| + s.alertsBack(w, r, anchor, "err", alertPageCopy["conn.test.reentry"]) |
| + case errors.As(err, &f): |
| + s.alertsBack(w, r, anchor, "err", f.Error()) |
| + default: |
| + log.Printf("console: alert connector %d: test: %v", c.ID, err) |
| + s.alertsBack(w, r, anchor, "err", alertPageCopy["conn.err.failed"]) |
| + } |
| +} |
| + |
| +// 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) { |
| + addr, ok := s.alertOperatorForm(w, r) |
| + if !ok { |
| + return |
| + } |
| + c, ok := s.alertPathConnector(w, r) |
| + if !ok { |
| + return |
| + } |
| + switch err := s.store.DeleteAlertConnector(alertScopeFleet, c.ID); { |
| + case errors.Is(err, sql.ErrNoRows): |
| + http.NotFound(w, r) |
| + case err != nil: |
| + log.Printf("console: alert connector %d: delete: %v", c.ID, err) |
| + s.alertsBack(w, r, "connectors", "err", alertPageCopy["conn.err.failed"]) |
| + default: |
| + log.Printf("console: %s deleted alert connector %d", addr, c.ID) |
| + s.alertsBack(w, r, "connectors", "ok", fmt.Sprintf(alertPageCopy["conn.deleted"], alertConnectorName(c))) |
| + } |
| +} |
| + |
| +// handleAlertRuleSave sets rule {rule}'s state, connectors and, for the |
| +// console's own rules, threshold. A box rule's threshold is each box's |
| +// host.env setting (spec §5.2): one posted for it is not kept. |
| +func (s *Server) handleAlertRuleSave(w http.ResponseWriter, r *http.Request) { |
| + if _, ok := s.alertOperatorForm(w, r); !ok { |
| + return |
| + } |
| + rule := r.PathValue("rule") |
| + if _, known := alertRuleLevels[rule]; !known { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + anchor := "rule-" + rule |
| + fail := func(msg string) { s.alertsBack(w, r, anchor, "err", msg) } |
| + st := alertRuleSetting{Enabled: r.PostFormValue("enabled") == "on"} |
| + conns, err := s.store.AlertConnectors(alertScopeFleet) |
| + if err != nil { |
| + log.Printf("console: alert rule %s: %v", rule, err) |
| + fail(alertPageCopy["conn.err.failed"]) |
| + return |
| + } |
| + for _, v := range r.PostForm["connector"] { |
| + id, err := strconv.ParseInt(v, 10, 64) |
| + if err != nil || !slices.ContainsFunc(conns, func(c alertConnector) bool { return c.ID == id }) { |
| + fail(alertPageCopy["rules.err.connector"]) |
| + return |
| + } |
| + st.ConnectorIDs = append(st.ConnectorIDs, id) |
| + } |
| + if b, ok := alertThresholdBounds[rule]; ok { |
| + if raw := strings.TrimSpace(r.PostFormValue("threshold")); raw != "" { |
| + n, err := strconv.Atoi(raw) |
| + if err != nil || n < b[0] || n > b[1] { |
| + fail(fmt.Sprintf(alertPageCopy["rules.th.err"], b[0], b[1])) |
| + return |
| + } |
| + th := float64(n) |
| + st.Threshold = &th |
| + } |
| + } |
| + if err := s.store.SetAlertRule(alertScopeFleet, rule, st); err != nil { |
| + log.Printf("console: alert rule %s: %v", rule, err) |
| + fail(alertPageCopy["conn.err.failed"]) |
| + return |
| + } |
| + s.alertsBack(w, r, anchor, "ok", alertPageCopy["rules.saved.rule"]) |
| +} |
| + |
| +// ---- History ------------------------------------------------------------------- |
| + |
| +// handleFleetAlertHistory is the fleet's last alertHistoryLimit incidents, |
| +// each at #incident-<id>, where a message's incident link lands. |
| +func (s *Server) handleFleetAlertHistory(w http.ResponseWriter, r *http.Request) { |
| + addr, raw, ok := s.operatorOnly(w, r) |
| + if !ok { |
| + return |
| + } |
| + ins, err := s.store.RecentAlertIncidents(alertScopeFleet, alertHistoryLimit) |
| + if err != nil { |
| + log.Printf("console: alert history: %v", err) |
| + s.renderMessage(w, r, http.StatusInternalServerError, "Unavailable", alertPageCopy["page.err"]) |
| + return |
| + } |
| + now := s.alertClockNow() |
| + v := &alertHistoryView{Full: len(ins) >= alertHistoryLimit} |
| + for _, in := range ins { |
| + v.Rows = append(v.Rows, alertHistoryRowOf(in, now)) |
| + } |
| + p := s.opPage(addr, raw, "alerts") |
| + p.Title = alertPageCopy["hist.heading"] |
| + p.AlertHistory = v |
| + s.render(w, http.StatusOK, "ops_alerts_history", p) |
| +} |
| + |
| +func alertHistoryRowOf(in alertIncident, now time.Time) alertHistoryRow { |
| + row := alertHistoryRow{ID: in.ID, Rule: alertRuleTitle(in.Rule), Level: alertPageCopy["rules.level."+in.Level], |
| + Opened: alertPageTime(in.OpenedAt)} |
| + switch len(in.Members) { |
| + case 0: |
| + case 1: |
| + row.Affected = in.Members[0] |
| + default: |
| + row.Affected = fmt.Sprintf(alertPageCopy["hist.affected.many"], len(in.Members), strings.Join(in.Members, ", ")) |
| + } |
| + lasted := in.ClosedAt.Sub(in.OpenedAt) |
| + switch { |
| + case in.ClosedAt.IsZero() && in.Flapping: |
| + row.State = alertPageCopy["hist.state.flapping"] |
| + case in.ClosedAt.IsZero(): |
| + row.State = fmt.Sprintf(alertPageCopy["hist.state.open"], alertSpan(now.Sub(in.OpenedAt))) |
| + case in.CloseReason == alertCloseDuplicate: |
| + row.State = alertPageCopy["hist.state.duplicate"] |
| + case in.CloseReason == alertCloseGone: |
| + row.State = fmt.Sprintf(alertPageCopy["hist.state.gone"], alertSpan(lasted)) |
| + default: |
| + row.State = fmt.Sprintf(alertPageCopy["hist.state.cleared"], alertSpan(lasted)) |
| + } |
| + return row |
| +} |
| + |
| +// ---- the public doors ---------------------------------------------------------- |
| + |
| +// renderAlertDoor renders a door's page. The token is in the page's own |
| +// URL, so no Referer carries it anywhere. |
| +func (s *Server) renderAlertDoor(w http.ResponseWriter, status int, v alertDoorView) { |
| + w.Header().Set("Referrer-Policy", "no-referrer") |
| + s.render(w, status, "alert_door", page{Title: alertPageCopy["door.title"], AlertDoor: &v}) |
| +} |
| + |
| +// alertDoorRefused renders why a token was refused: unknown, for another |
| +// door, expired, or its connector gone. Anything else is a failure of the |
| +// console's own, said as failed. |
| +func (s *Server) alertDoorRefused(w http.ResponseWriter, door string, err error, failed string) { |
| + status, key := http.StatusInternalServerError, "" |
| + switch { |
| + case errors.Is(err, errAlertTokenExpired): |
| + status, key = http.StatusGone, "door.err.expired" |
| + case errors.Is(err, errAlertTokenAction): |
| + status, key = http.StatusBadRequest, "door.err.action" |
| + case errors.Is(err, errAlertTokenInvalid): |
| + status, key = http.StatusNotFound, "door.err.invalid" |
| + case errors.Is(err, sql.ErrNoRows): |
| + status, key = http.StatusNotFound, "door.err.gone" |
| + default: |
| + log.Printf("console: alert %s door: %v", door, err) |
| + key = failed |
| + } |
| + s.renderAlertDoor(w, status, alertDoorView{Error: alertPageCopy[key]}) |
| +} |
| + |
| +// alertDoorConnector is the connector token t is bound to; sql.ErrNoRows |
| +// when it is gone or not in the token's scope. |
| +func (s *Server) alertDoorConnector(t alertToken) (alertConnector, error) { |
| + c, err := s.store.AlertConnector(t.ConnectorID) |
| + if err == nil && c.Scope != t.Scope { |
| + return alertConnector{}, sql.ErrNoRows |
| + } |
| + return c, err |
| +} |
| + |
| +// handleAlertConfirmPage is a confirm link's page: whose alerts, and a |
| +// button. Opening it confirms nothing and spends nothing. |
| +func (s *Server) handleAlertConfirmPage(w http.ResponseWriter, r *http.Request) { |
| + raw := r.PathValue("token") |
| + t, err := s.store.PeekAlertToken(raw, alertTokenConfirm, s.alertClockNow()) |
| + if errors.Is(err, errAlertTokenUsed) { |
| + s.alertConfirmUsed(w, t) |
| + return |
| + } |
| + var c alertConnector |
| + if err == nil { |
| + c, err = s.alertDoorConnector(t) |
| + } |
| + if err != nil { |
| + s.alertDoorRefused(w, "confirm", err, "door.confirm.failed") |
| + return |
| + } |
| + s.renderAlertDoor(w, http.StatusOK, alertDoorView{ |
| + Heading: fmt.Sprintf(alertPageCopy["door.confirm.heading"], alertConnectorName(c)), |
| + Body: alertPageCopy["door.confirm.body"], |
| + Action: "/alerts/confirm/" + url.PathEscape(raw), |
| + Buttons: []alertDoorButton{{Label: alertPageCopy["door.confirm.btn"]}}, |
| + }) |
| +} |
| + |
| +// handleAlertConfirm spends a confirm link and confirms its connector, in |
| +// one transaction (ConfirmAlertConnectorByToken): a failure leaves both as |
| +// they were, and the page says to ask for a new link. |
| +func (s *Server) handleAlertConfirm(w http.ResponseWriter, r *http.Request) { |
| + raw := r.PathValue("token") |
| + now := s.alertClockNow() |
| + c, err := s.store.ConfirmAlertConnectorByToken(raw, now) |
| + if errors.Is(err, errAlertTokenUsed) { |
| + t, perr := s.store.PeekAlertToken(raw, alertTokenConfirm, now) |
| + if errors.Is(perr, errAlertTokenUsed) { |
| + s.alertConfirmUsed(w, t) |
| + return |
| + } |
| + } |
| + if err != nil { |
| + s.alertDoorRefused(w, "confirm", err, "door.confirm.failed") |
| + return |
| + } |
| + log.Printf("console: alert connector %d confirmed from its link", c.ID) |
| + s.renderAlertDoor(w, http.StatusOK, alertDoorView{Done: fmt.Sprintf(alertPageCopy["door.confirm.done"], alertConnectorName(c))}) |
| +} |
| + |
| +// alertConfirmUsed answers a confirm link already used: alerts there are |
| +// on, when they are; otherwise the link is simply not valid any more. |
| +func (s *Server) alertConfirmUsed(w http.ResponseWriter, t alertToken) { |
| + c, err := s.alertDoorConnector(t) |
| + if err != nil || !c.Confirmed || c.Suspended { |
| + s.alertDoorRefused(w, "confirm", errAlertTokenInvalid, "door.confirm.failed") |
| + return |
| + } |
| + s.renderAlertDoor(w, http.StatusOK, alertDoorView{Done: fmt.Sprintf(alertPageCopy["door.confirm.used"], alertConnectorName(c))}) |
| +} |
| + |
| +// handleAlertUnsubscribePage is an unsubscribe link's page. |
| +func (s *Server) handleAlertUnsubscribePage(w http.ResponseWriter, r *http.Request) { |
| + raw := r.PathValue("token") |
| + t, err := s.store.PeekAlertToken(raw, alertTokenUnsubscribe, s.alertClockNow()) |
| + var c alertConnector |
| + if err == nil { |
| + c, err = s.alertDoorConnector(t) |
| + } |
| + if err != nil { |
| + s.alertDoorRefused(w, "unsubscribe", err, "door.err.failed") |
| + return |
| + } |
| + s.renderAlertDoor(w, http.StatusOK, alertDoorView{ |
| + Heading: fmt.Sprintf(alertPageCopy["door.unsub.heading"], alertConnectorName(c)), |
| + Body: alertPageCopy["door.unsub.body"], |
| + Action: "/alerts/unsubscribe/" + url.PathEscape(raw), |
| + Buttons: []alertDoorButton{{Label: alertPageCopy["door.unsub.btn"]}}, |
| + }) |
| +} |
| + |
| +// handleAlertUnsubscribe turns the link's connector off |
| +// (UnsubscribeAlertConnector). Again is the same answer. |
| +func (s *Server) handleAlertUnsubscribe(w http.ResponseWriter, r *http.Request) { |
| + c, err := s.store.UnsubscribeAlertConnector(r.PathValue("token"), s.alertClockNow()) |
| + if err != nil { |
| + s.alertDoorRefused(w, "unsubscribe", err, "door.err.failed") |
| + return |
| + } |
| + log.Printf("console: alert connector %d turned off from its unsubscribe link", c.ID) |
| + s.renderAlertDoor(w, http.StatusOK, alertDoorView{Done: fmt.Sprintf(alertPageCopy["door.unsub.done"], alertConnectorName(c))}) |
| +} |
| + |
| +// handleAlertSnoozePage is a snooze link's page: the rule and subject, and |
| +// one button per length (ruling R-28). A for in the link is not read here. |
| +func (s *Server) handleAlertSnoozePage(w http.ResponseWriter, r *http.Request) { |
| + raw := r.PathValue("token") |
| + t, err := s.store.PeekAlertToken(raw, alertTokenSnooze, s.alertClockNow()) |
| + if err != nil { |
| + s.alertDoorRefused(w, "snooze", err, "door.err.failed") |
| + return |
| + } |
| + v := alertDoorView{ |
| + Heading: fmt.Sprintf(alertPageCopy["door.snooze.heading"], alertMidSentence(alertRuleTitle(t.Rule)), t.Subject), |
| + Body: alertPageCopy["door.snooze.choose"], |
| + Note: alertPageCopy["door.snooze.body"], |
| + Action: "/alerts/snooze/" + url.PathEscape(raw), |
| + } |
| + for _, l := range alertSnoozeLengths { |
| + v.Buttons = append(v.Buttons, alertDoorButton{ |
| + Label: fmt.Sprintf(alertPageCopy["door.snooze.btn"], alertPageCopy["door.snooze."+l.For]), For: l.For}) |
| + } |
| + s.renderAlertDoor(w, http.StatusOK, v) |
| +} |
| + |
| +// handleAlertSnooze snoozes the link's (scope, rule, subject) for one of |
| +// the offered lengths, from now: a later use replaces the snooze and never |
| +// adds to it (Store.Snooze). Any other length is refused. |
| +func (s *Server) handleAlertSnooze(w http.ResponseWriter, r *http.Request) { |
| + now := s.alertClockNow() |
| + t, err := s.store.UseAlertToken(r.PathValue("token"), alertTokenSnooze, now) |
| + if err != nil { |
| + s.alertDoorRefused(w, "snooze", err, "door.err.failed") |
| + return |
| + } |
| + var d time.Duration |
| + for _, l := range alertSnoozeLengths { |
| + if r.FormValue("for") == l.For { |
| + d = l.D |
| + } |
| + } |
| + if d == 0 { |
| + s.renderAlertDoor(w, http.StatusBadRequest, alertDoorView{Error: alertPageCopy["door.err.duration"]}) |
| + return |
| + } |
| + until := now.Add(d) |
| + if err := s.store.Snooze(t.Scope, t.Rule, t.Subject, until); err != nil { |
| + s.alertDoorRefused(w, "snooze", err, "door.err.failed") |
| + return |
| + } |
| + s.renderAlertDoor(w, http.StatusOK, alertDoorView{Done: fmt.Sprintf(alertPageCopy["door.snooze.done"], alertPageTime(until))}) |
| +} |
| + |
| +// handleAlertSigningKey serves the webhook signing key's public half as one |
| +// line of standard base64, for receivers to fetch (ruling R-30). |
| +func (s *Server) handleAlertSigningKey(w http.ResponseWriter, r *http.Request) { |
| + key, err := s.store.AlertSigningKey() |
| + if err != nil { |
| + log.Printf("console: alert signing key: %v", err) |
| + http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable) |
| + return |
| + } |
| + w.Header().Set("Content-Type", "text/plain; charset=utf-8") |
| + io.WriteString(w, alertPublicKey(key)+"\n") |
| +} |
diff --git a/internal/console/alertpages_test.go b/internal/console/alertpages_test.go| new file mode 100644 |
| index 000000000..f232b8c01 |
| --- /dev/null |
| +++ b/internal/console/alertpages_test.go |
| @@ -0,0 +1,596 @@ |
| +package console |
| + |
| +import ( |
| + "html" |
| + "io" |
| + "maps" |
| + "net/http" |
| + "net/url" |
| + "regexp" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// alertsPageFixture is an operator signed in to a console whose alert |
| +// senders reach notifyFixture's recorders, with the confirmation limit on |
| +// the same clock as the senders. |
| +type alertsPageFixture struct { |
| + *notifyFixture |
| + c *http.Client |
| + csrf string |
| +} |
| + |
| +func newAlertsPageFixture(t *testing.T) *alertsPageFixture { |
| + t.Helper() |
| + nf := newNotifyFixture(t) |
| + c := signInOperator(t, nf.consoleFixture) |
| + af := &alertsPageFixture{notifyFixture: nf, c: c, csrf: sessionToken(t, nf.consoleFixture, c)} |
| + nf.srv.limits.now = func() time.Time { return af.now } |
| + return af |
| +} |
| + |
| +// post sends an operator form with the session's CSRF token. |
| +func (af *alertsPageFixture) post(t *testing.T, path string, kv ...string) (int, string) { |
| + t.Helper() |
| + v := url.Values{"csrf": {af.csrf}} |
| + for i := 0; i+1 < len(kv); i += 2 { |
| + v.Add(kv[i], kv[i+1]) |
| + } |
| + status, loc, _ := postForm(t, af.c, af.ts.URL+path, v) |
| + return status, loc |
| +} |
| + |
| +// page is /fleet/alerts as the operator sees it, flash included. |
| +func (af *alertsPageFixture) page(t *testing.T, path string) string { |
| + t.Helper() |
| + status, _, body := get(t, af.c, af.ts.URL+path) |
| + if status != http.StatusOK { |
| + t.Fatalf("%s = %d: %s", path, status, body) |
| + } |
| + return body |
| +} |
| + |
| +// addAndFlash posts an add and returns the page it redirects to. |
| +func (af *alertsPageFixture) addAndFlash(t *testing.T, kv ...string) string { |
| + t.Helper() |
| + status, loc := af.post(t, "/fleet/alerts/connectors", kv...) |
| + if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/fleet/alerts") { |
| + t.Fatalf("add %v = %d %q", kv, status, loc) |
| + } |
| + return af.page(t, "/fleet/alerts") |
| +} |
| + |
| +func (af *alertsPageFixture) fleetConnectors(t *testing.T) []alertConnector { |
| + t.Helper() |
| + cs, err := af.st.AlertConnectors(alertScopeFleet) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return cs |
| +} |
| + |
| +const testSlackURL = "https://hooks.slack.com/services/T0SECRET/B0SECRET/xoxSecretPathTail" |
| + |
| +var confirmLinkRE = regexp.MustCompile(`/alerts/confirm/([A-Za-z0-9_-]+)`) |
| + |
| +func TestFleetAlertsNotOperator404(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + out := newBrowser(t) |
| + _, _, ghost := get(t, out, af.ts.URL+"/this-route-does-not-exist") |
| + notOperator := signInPaul(t, af.consoleFixture) |
| + if err := af.st.SetOperator("paul@keymail.dev", false); err != nil { |
| + t.Fatal(err) |
| + } |
| + 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"} |
| + 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 { |
| + t.Errorf("GET %s %s = %d %q, want the missing-route 404", p, who, st, body) |
| + } |
| + } |
| + for _, p := range posts { |
| + v := url.Values{"csrf": {csrf}, "kind": {"email"}, "name": {"x"}, "target": {"x@example.com"}, "threshold": {"30"}} |
| + if st, _, body := postForm(t, c, af.ts.URL+p, v); st != http.StatusNotFound || body != ghost { |
| + t.Errorf("POST %s %s = %d %q, want the missing-route 404", p, who, st, body) |
| + } |
| + } |
| + } |
| + if len(af.fleetConnectors(t)) != 0 { |
| + t.Fatal("a refused request added a connector") |
| + } |
| + // A wrong method answers what an unknown route does, even to an |
| + // operator: the POST doors do not announce themselves. |
| + if err := af.st.SetOperator("paul@keymail.dev", true); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, p := range posts { |
| + if st, _, body := get(t, af.c, af.ts.URL+p); st != http.StatusNotFound || body != ghost { |
| + t.Errorf("GET %s as an operator = %d %q, want the missing-route 404", p, st, body) |
| + } |
| + } |
| +} |
| + |
| +func TestFleetAlertsAddSlackSendsTestWithConfirm(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + body := af.addAndFlash(t, "kind", "slack", "name", "ops channel", "target", testSlackURL) |
| + if !strings.Contains(body, alertPageCopy["conn.added.slack"]) { |
| + t.Errorf("no added notice on the page") |
| + } |
| + cs := af.fleetConnectors(t) |
| + if len(cs) != 1 || cs[0].Kind != alertConnectorSlack || cs[0].Confirmed || cs[0].Name != "ops channel" { |
| + t.Fatalf("connectors = %+v", cs) |
| + } |
| + if !strings.Contains(body, alertPageCopy["conn.status.unconfirmed"]) { |
| + t.Error("the new connector does not read as waiting for confirmation") |
| + } |
| + // The stored target is sealed: what it opens to is the URL typed. |
| + sealed, plain, err := af.st.AlertConnectorTarget(cs[0].ID) |
| + if err != nil || plain != "" { |
| + t.Fatalf("target: plain %q err %v", plain, err) |
| + } |
| + if p, err := af.seal.Open(sealed); err != nil || string(p) != testSlackURL { |
| + t.Fatalf("sealed target opens to %q (%v)", p, err) |
| + } |
| + if got := af.outbox(t, cs[0].ID); len(got) != 1 || got[0].kind != "verify" { |
| + t.Fatalf("outbox = %+v, want one verify row", got) |
| + } |
| + af.drain(t) |
| + reqs := af.hook.requests() |
| + if len(reqs) != 1 { |
| + t.Fatalf("Slack got %d posts, want the test", len(reqs)) |
| + } |
| + m := confirmLinkRE.FindStringSubmatch(string(reqs[0].body)) |
| + if m == nil { |
| + t.Fatalf("the Slack test carries no confirm link: %s", reqs[0].body) |
| + } |
| + if af.connector(t, cs[0].ID).Confirmed { |
| + t.Fatal("sending the test confirmed the connector") |
| + } |
| + door := newBrowser(t) |
| + if st, _, _ := postForm(t, door, af.ts.URL+"/alerts/confirm/"+m[1], url.Values{}); st != http.StatusOK { |
| + t.Fatalf("confirm POST = %d", st) |
| + } |
| + if !af.connector(t, cs[0].ID).Confirmed { |
| + t.Fatal("the confirm link did not confirm the connector") |
| + } |
| + // One use. |
| + if _, err := af.st.PeekAlertToken(m[1], alertTokenConfirm, af.now); err != errAlertTokenUsed { |
| + t.Fatalf("the confirm token after use: %v", err) |
| + } |
| +} |
| + |
| +func TestFleetAlertsAddSlackRefusesNonSlackHost(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + for _, target := range []string{"https://example.com/services/T/B/x", "https://hooks.slack.com.example.com/x", |
| + "http://hooks.slack.com/services/x", "https://hooks.slack.com:8443/services/x"} { |
| + body := af.addAndFlash(t, "kind", "slack", "name", "ops", "target", target) |
| + if !strings.Contains(body, `rst-tone="negative"`) { |
| + t.Errorf("%s: no error on the page", target) |
| + } |
| + if strings.Contains(body, target) { |
| + t.Errorf("%s: the refused URL is echoed back", target) |
| + } |
| + } |
| + body := af.addAndFlash(t, "kind", "slack", "name", "ops", "target", "https://example.com/services/T/B/x") |
| + if !strings.Contains(body, alertCopy["url.slack"]) { |
| + t.Errorf("the refusal does not say why") |
| + } |
| + if cs := af.fleetConnectors(t); len(cs) != 0 { |
| + t.Fatalf("a refused URL was stored: %+v", cs) |
| + } |
| + af.drain(t) |
| + if n := len(af.hook.requests()); n != 0 { |
| + t.Fatalf("%d sends after a refused add", n) |
| + } |
| +} |
| + |
| +func TestFleetAlertsSecretNeverRendered(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + af.addAndFlash(t, "kind", "slack", "name", "ops channel", "target", testSlackURL) |
| + af.hook.setStatus(http.StatusInternalServerError) |
| + af.addAndFlash(t, "kind", "webhook", "name", "pager", "target", "https://hooks.example.net/in/WebhookSecretTail") |
| + for _, path := range []string{"/fleet/alerts", "/fleet/alerts/history"} { |
| + body := af.page(t, path) |
| + for _, secret := range []string{"T0SECRET", "B0SECRET", "xoxSecretPathTail", "/services/", "WebhookSecret", "/in/"} { |
| + if strings.Contains(body, secret) { |
| + t.Errorf("%s renders %q", path, secret) |
| + } |
| + } |
| + } |
| + body := af.page(t, "/fleet/alerts") |
| + for _, want := range []string{"hooks.slack.com, ends in Tail", "hooks.example.net, ends in Tail"} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("/fleet/alerts lacks the hint %q", want) |
| + } |
| + } |
| +} |
| + |
| +func TestFleetAlertsRepeatedTestOnUnconfirmedEmailRefused(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + body := af.addAndFlash(t, "kind", "email", "name", "on call", "target", "Oncall@Example.com") |
| + if !strings.Contains(body, "A confirm link is on its way to oncall@example.com.") { |
| + t.Errorf("no added notice naming the address") |
| + } |
| + cs := af.fleetConnectors(t) |
| + if len(cs) != 1 || cs[0].Confirmed || cs[0].Kind != alertConnectorEmail { |
| + t.Fatalf("connectors = %+v", cs) |
| + } |
| + if _, plain, err := af.st.AlertConnectorTarget(cs[0].ID); err != nil || plain != "oncall@example.com" { |
| + t.Fatalf("stored address %q (%v)", plain, err) |
| + } |
| + if got := af.outbox(t, cs[0].ID); len(got) != 1 || got[0].kind != "verify" { |
| + t.Fatalf("outbox = %+v, want the confirmation", got) |
| + } |
| + for i := 0; i < 2; i++ { |
| + status, _ := af.post(t, "/fleet/alerts/connectors/"+itoa(cs[0].ID)+"/test") |
| + if status != http.StatusSeeOther { |
| + t.Fatalf("test = %d", status) |
| + } |
| + body = af.page(t, "/fleet/alerts") |
| + if !strings.Contains(body, "This address is not confirmed yet. Open the confirm link we sent to oncall@example.com.") { |
| + t.Errorf("try %d: the test was not refused in words", i) |
| + } |
| + } |
| + if got := af.outbox(t, cs[0].ID); len(got) != 1 { |
| + t.Fatalf("outbox = %+v: a refused test queued something", got) |
| + } |
| + if n := len(af.mail.sentCopy()); n != 0 { |
| + t.Fatalf("%d emails sent to an unconfirmed address by a test", n) |
| + } |
| +} |
| + |
| +func TestFleetAlertsBoxRuleThresholdReadOnly(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + body := af.page(t, "/fleet/alerts") |
| + disk := ruleSection(t, body, "disk") |
| + if !strings.Contains(disk, "CARLOS_ALERT_DISK_PCT") || !strings.Contains(disk, alertPageCopy["rules.th.readonly"]) { |
| + t.Errorf("the disk rule does not name its host.env variable read-only:\n%s", disk) |
| + } |
| + if strings.Contains(disk, `name="threshold"`) { |
| + t.Errorf("the disk rule has a threshold control:\n%s", disk) |
| + } |
| + if !strings.Contains(ruleSection(t, body, "box_silent"), `name="threshold"`) { |
| + t.Error("box_silent has no threshold control") |
| + } |
| + // A threshold posted for a box rule is not kept. |
| + if st, _ := af.post(t, "/fleet/alerts/rules/disk", "enabled", "on", "threshold", "50"); st != http.StatusSeeOther { |
| + t.Fatalf("disk rule save = %d", st) |
| + } |
| + settings, err := af.st.AlertRuleSettings(alertScopeFleet) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if st := settings["disk"]; !st.Enabled || st.Threshold != nil { |
| + t.Fatalf("disk settings = %+v, want on with no threshold", st) |
| + } |
| + // box_silent: whole minutes from 5 to 1440 (ruling R-29). |
| + for _, bad := range []string{"4", "1441", "2.5", "x", "-10"} { |
| + af.post(t, "/fleet/alerts/rules/box_silent", "enabled", "on", "threshold", bad) |
| + if body := af.page(t, "/fleet/alerts"); !strings.Contains(body, "Enter a whole number from 5 to 1440.") { |
| + t.Errorf("threshold %q not refused in words", bad) |
| + } |
| + } |
| + settings, _ = af.st.AlertRuleSettings(alertScopeFleet) |
| + if _, set := settings["box_silent"]; set { |
| + t.Fatalf("a refused threshold was stored: %+v", settings["box_silent"]) |
| + } |
| + af.post(t, "/fleet/alerts/rules/box_silent", "enabled", "on", "threshold", "30") |
| + settings, _ = af.st.AlertRuleSettings(alertScopeFleet) |
| + if th := settings["box_silent"].Threshold; th == nil || *th != 30 { |
| + t.Fatalf("box_silent threshold = %v, want 30", th) |
| + } |
| + if st, _ := af.post(t, "/fleet/alerts/rules/no_such_rule", "enabled", "on"); st != http.StatusNotFound { |
| + t.Fatalf("an unknown rule = %d, want 404", st) |
| + } |
| +} |
| + |
| +// ruleSection is the page's markup for one rule, from its anchor to the |
| +// next rule's. |
| +func ruleSection(t *testing.T, body, rule string) string { |
| + t.Helper() |
| + i := strings.Index(body, `id="rule-`+rule+`"`) |
| + if i < 0 { |
| + t.Fatalf("no rule-%s on the page", rule) |
| + } |
| + rest := body[i+1:] |
| + if j := strings.Index(rest, `id="rule-`); j >= 0 { |
| + rest = rest[:j] |
| + } |
| + return rest |
| +} |
| + |
| +// doorTokens mints one of each token for connector c, and a snooze for |
| +// disk on box-1. |
| +func doorTokens(t *testing.T, af *alertsPageFixture, c int64) (confirm, unsub, snooze string) { |
| + t.Helper() |
| + var err error |
| + if confirm, err = af.st.NewAlertToken(alertToken{Action: alertTokenConfirm, Scope: alertScopeFleet, ConnectorID: c, |
| + ExpiresAt: af.now.Add(alertConfirmLinkTTL)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if unsub, err = af.st.NewAlertToken(alertToken{Action: alertTokenUnsubscribe, Scope: alertScopeFleet, ConnectorID: c}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if snooze, err = af.st.NewAlertToken(alertToken{Action: alertTokenSnooze, Scope: alertScopeFleet, Rule: "disk", Subject: "box-1", |
| + ExpiresAt: af.now.Add(alertSnoozeLinkTTL)}); err != nil { |
| + t.Fatal(err) |
| + } |
| + return confirm, unsub, snooze |
| +} |
| + |
| +func (af *alertsPageFixture) snoozeUntil(t *testing.T) (time.Time, bool) { |
| + t.Helper() |
| + var until int64 |
| + err := af.st.db.QueryRow(`SELECT until FROM alert_snoozes WHERE scope = 'fleet' AND rule = 'disk' AND subject = 'box-1'`).Scan(&until) |
| + if err != nil { |
| + return time.Time{}, false |
| + } |
| + return time.Unix(until, 0).UTC(), true |
| +} |
| + |
| +func TestAlertDoorGetDoesNotAct(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + id := af.addEmail(t, alertScopeFleet, "a@example.com", "", false) |
| + confirm, unsub, snooze := doorTokens(t, af, id) |
| + door := newBrowser(t) |
| + for _, p := range []string{"/alerts/confirm/" + confirm, "/alerts/unsubscribe/" + unsub, "/alerts/snooze/" + snooze, |
| + "/alerts/snooze/" + snooze + "?for=1h"} { |
| + status, _, body := get(t, door, af.ts.URL+p) |
| + if status != http.StatusOK || !strings.Contains(body, `method="post"`) || !strings.Contains(body, alertPageCopy["door.scanner"]) { |
| + t.Errorf("GET %s = %d, want a page with a button: %s", p, status, body) |
| + } |
| + } |
| + if c := af.connector(t, id); c.Confirmed || c.Suspended { |
| + t.Fatalf("a GET acted on the connector: %+v", c) |
| + } |
| + if _, ok := af.snoozeUntil(t); ok { |
| + t.Fatal("a GET snoozed") |
| + } |
| + // The POSTs act, and the confirm link was not spent by its GET. |
| + for _, p := range []string{"/alerts/confirm/" + confirm, "/alerts/unsubscribe/" + unsub} { |
| + if st, _, body := postForm(t, door, af.ts.URL+p, url.Values{}); st != http.StatusOK { |
| + t.Fatalf("POST %s = %d %s", p, st, body) |
| + } |
| + } |
| + 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) |
| + } |
| + // 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 || |
| + !strings.Contains(body, "Stopped. Nothing more will be sent to a@example.com.") { |
| + t.Fatalf("a second unsubscribe = %d %s", st, body) |
| + } |
| + var n int |
| + if err := af.st.db.QueryRow(`SELECT COUNT(*) FROM alert_meta WHERE k = ?`, alertUnsubscribedMarker(id)).Scan(&n); err != nil || n != 1 { |
| + t.Fatalf("unsubscribe recorded %d times (%v)", n, err) |
| + } |
| +} |
| + |
| +func TestAlertDoorWrongActionRefused(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + id := af.addEmail(t, alertScopeFleet, "a@example.com", "", false) |
| + confirm, unsub, snooze := doorTokens(t, af, id) |
| + door := newBrowser(t) |
| + for _, c := range []struct{ path, tok string }{ |
| + {"/alerts/confirm/", unsub}, {"/alerts/confirm/", snooze}, |
| + {"/alerts/unsubscribe/", confirm}, {"/alerts/unsubscribe/", snooze}, |
| + {"/alerts/snooze/", confirm}, {"/alerts/snooze/", unsub}, |
| + } { |
| + for _, method := range []string{http.MethodGet, http.MethodPost} { |
| + var status int |
| + var body string |
| + if method == http.MethodGet { |
| + status, _, body = get(t, door, af.ts.URL+c.path+c.tok) |
| + } else { |
| + status, _, body = postForm(t, door, af.ts.URL+c.path+c.tok, url.Values{"for": {"1h"}}) |
| + } |
| + if status != http.StatusBadRequest || !strings.Contains(body, alertPageCopy["door.err.action"]) { |
| + t.Errorf("%s %s<%s token> = %d, want refused", method, c.path, c.tok[:4], status) |
| + } |
| + } |
| + } |
| + if st, _, body := postForm(t, door, af.ts.URL+"/alerts/confirm/not-a-token", url.Values{}); st != http.StatusNotFound || |
| + !strings.Contains(body, alertPageCopy["door.err.invalid"]) { |
| + t.Errorf("an unknown token = %d", st) |
| + } |
| + if c := af.connector(t, id); c.Confirmed || c.Suspended { |
| + t.Fatalf("a refused token acted: %+v", c) |
| + } |
| + if _, ok := af.snoozeUntil(t); ok { |
| + t.Fatal("a refused token snoozed") |
| + } |
| + // The right links still work: a refusal spent nothing. |
| + if _, err := af.st.PeekAlertToken(confirm, alertTokenConfirm, af.now); err != nil { |
| + t.Fatalf("the confirm token after the refusals: %v", err) |
| + } |
| + // An expired confirm link says so. |
| + af.now = af.now.Add(alertConfirmLinkTTL) |
| + if st, _, body := postForm(t, door, af.ts.URL+"/alerts/confirm/"+confirm, url.Values{}); st != http.StatusGone || |
| + !strings.Contains(body, alertPageCopy["door.err.expired"]) { |
| + t.Errorf("an expired confirm = %d %s", st, body) |
| + } |
| +} |
| + |
| +func TestAlertDoorSnoozeInvalidDuration(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + _, _, snooze := doorTokens(t, af, af.addEmail(t, alertScopeFleet, "a@example.com", "", true)) |
| + door := newBrowser(t) |
| + for _, d := range []string{"", "2h", "1h1", "60m", "1W", "-1h", "168h"} { |
| + status, _, body := postForm(t, door, af.ts.URL+"/alerts/snooze/"+snooze, url.Values{"for": {d}}) |
| + if status != http.StatusBadRequest || !strings.Contains(body, alertPageCopy["door.err.duration"]) { |
| + t.Errorf("for=%q = %d, want refused", d, status) |
| + } |
| + } |
| + // A for in the query is no different. |
| + if st, _, _ := postForm(t, door, af.ts.URL+"/alerts/snooze/"+snooze+"?for=2h", url.Values{}); st != http.StatusBadRequest { |
| + t.Errorf("?for=2h = %d", st) |
| + } |
| + if _, ok := af.snoozeUntil(t); ok { |
| + t.Fatal("a refused length snoozed") |
| + } |
| +} |
| + |
| +func TestAlertDoorSnoozeNotCumulative(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + _, _, snooze := doorTokens(t, af, af.addEmail(t, alertScopeFleet, "a@example.com", "", true)) |
| + door := newBrowser(t) |
| + use := func(d string) time.Time { |
| + t.Helper() |
| + if st, _, body := postForm(t, door, af.ts.URL+"/alerts/snooze/"+snooze, url.Values{"for": {d}}); st != http.StatusOK { |
| + t.Fatalf("for=%s = %d %s", d, st, body) |
| + } |
| + until, ok := af.snoozeUntil(t) |
| + if !ok { |
| + t.Fatalf("for=%s snoozed nothing", d) |
| + } |
| + return until |
| + } |
| + if got, want := use("1w"), af.now.Add(7*24*time.Hour); !got.Equal(want) { |
| + t.Fatalf("1w: until %v, want %v", got, want) |
| + } |
| + // A shorter length later replaces it: from now, never added on. |
| + af.now = af.now.Add(time.Hour) |
| + if got, want := use("1h"), af.now.Add(time.Hour); !got.Equal(want) { |
| + t.Fatalf("1h after 1w: until %v, want %v", got, want) |
| + } |
| + if got, want := use("1d"), af.now.Add(24*time.Hour); !got.Equal(want) { |
| + t.Fatalf("1d: until %v, want %v", got, want) |
| + } |
| + if got, want := use("1d"), af.now.Add(24*time.Hour); !got.Equal(want) { |
| + t.Fatalf("1d twice: until %v, want %v", got, want) |
| + } |
| +} |
| + |
| +func TestAlertsConfirmRateLimit(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + limit := alertPageCopy["conn.err.confirmlimit"] |
| + for i := 0; i < 4; i++ { |
| + if body := af.addAndFlash(t, "kind", "email", "name", "e", "target", "e"+itoa(int64(i))+"@example.com"); strings.Contains(body, limit) { |
| + t.Fatalf("email %d refused", i) |
| + } |
| + } |
| + // A Slack connector's test carries a confirm link, so it counts too. |
| + af.addAndFlash(t, "kind", "slack", "name", "ops", "target", testSlackURL) |
| + if n := len(af.fleetConnectors(t)); n != 5 { |
| + t.Fatalf("%d connectors after five confirmations", n) |
| + } |
| + if body := af.addAndFlash(t, "kind", "email", "name", "e", "target", "six@example.com"); !strings.Contains(body, limit) { |
| + t.Fatal("a sixth confirmation in the hour was not refused") |
| + } |
| + if n := len(af.fleetConnectors(t)); n != 5 { |
| + t.Fatalf("a refused add stored a connector: %d", n) |
| + } |
| + var slack int64 |
| + for _, c := range af.fleetConnectors(t) { |
| + if c.Kind == alertConnectorSlack { |
| + slack = c.ID |
| + } |
| + } |
| + af.post(t, "/fleet/alerts/connectors/"+itoa(slack)+"/test") |
| + if body := af.page(t, "/fleet/alerts"); !strings.Contains(body, limit) { |
| + t.Fatal("a test to an unconfirmed Slack connector over the limit was not refused") |
| + } |
| + af.drain(t) |
| + if n := len(af.hook.requests()); n != 1 { |
| + t.Fatalf("Slack got %d posts, want only the one queued when it was added", n) |
| + } |
| + // An hour on, five more; twenty in the day is the end of it. |
| + for hour := 1; hour < 4; hour++ { |
| + af.now = af.now.Add(time.Hour + time.Second) |
| + for i := 0; i < 5; i++ { |
| + if body := af.addAndFlash(t, "kind", "email", "name", "e", "target", "h"+itoa(int64(hour*10+i))+"@example.com"); strings.Contains(body, limit) { |
| + t.Fatalf("hour %d email %d refused", hour, i) |
| + } |
| + } |
| + } |
| + af.now = af.now.Add(time.Hour + time.Second) |
| + if body := af.addAndFlash(t, "kind", "email", "name", "e", "target", "late@example.com"); !strings.Contains(body, limit) { |
| + t.Fatal("a twenty-first confirmation in a day was not refused") |
| + } |
| + if n := len(af.fleetConnectors(t)); n != 20 { |
| + t.Fatalf("%d connectors, want 20", n) |
| + } |
| +} |
| + |
| +func TestAlertsSigningKeyServed(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + res, err := newBrowser(t).Get(af.ts.URL + "/alerts/signing-key") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer res.Body.Close() |
| + b := new(strings.Builder) |
| + if _, err := io.Copy(b, res.Body); err != nil { |
| + t.Fatal(err) |
| + } |
| + key, err := af.st.AlertSigningKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := alertPublicKey(key) + "\n" |
| + if res.StatusCode != http.StatusOK || !strings.HasPrefix(res.Header.Get("Content-Type"), "text/plain") || b.String() != want { |
| + t.Fatalf("signing key = %d %q %q, want 200 text/plain %q", res.StatusCode, res.Header.Get("Content-Type"), b.String(), want) |
| + } |
| + if body := html.UnescapeString(af.page(t, "/fleet/alerts")); !strings.Contains(body, alertPublicKey(key)) || |
| + !strings.Contains(body, af.srv.cfg.Origin+"/alerts/signing-key") { |
| + t.Error("the Alerts page does not show the key and where it is served") |
| + } |
| +} |
| + |
| +func TestAlertRuleOrderCoversEveryRule(t *testing.T) { |
| + got := slices.Sorted(slices.Values(alertRuleOrder)) |
| + want := slices.Sorted(maps.Keys(alertRuleLevels)) |
| + if !slices.Equal(got, want) { |
| + t.Fatalf("alertRuleOrder = %v, want every rule in alertRuleLevels %v", got, want) |
| + } |
| + for _, rule := range alertRuleOrder { |
| + if _, ok := alertPageCopy["rules.when."+rule]; !ok { |
| + t.Errorf("%s has no rules.when copy", rule) |
| + } |
| + } |
| +} |
| + |
| +// The page copy keeps the voice: no em or en dashes, and no number then a |
| +// percent sign (TestAppPageOwnerMetricsBoundary reads one as a reading). |
| +func TestAlertPageCopyVoice(t *testing.T) { |
| + digitPct := regexp.MustCompile(`[0-9]%`) |
| + for key, s := range alertPageCopy { |
| + if strings.ContainsAny(s, "—–") || digitPct.MatchString(s) { |
| + t.Errorf("%s: %q", key, s) |
| + } |
| + } |
| +} |
| + |
| +func TestFleetAlertsHistoryAnchors(t *testing.T) { |
| + af := newAlertsPageFixture(t) |
| + now := af.now |
| + open := alertIncident{Scope: alertScopeFleet, Rule: "disk", Level: "incident", OpenedAt: now.Add(-90 * time.Minute), |
| + NotifyAt: now, Members: []string{"box-1", "box-2"}} |
| + cleared := alertIncident{Scope: alertScopeFleet, Rule: "box_silent", Level: "incident", OpenedAt: now.Add(-3 * time.Hour), |
| + NotifyAt: now, ClosedAt: now.Add(-150 * time.Minute), CloseReason: alertCloseCleared, Members: []string{"box-3"}} |
| + gone := alertIncident{Scope: alertScopeFleet, Rule: "cpu", Level: "warning", OpenedAt: now.Add(-50 * time.Hour), |
| + NotifyAt: now, ClosedAt: now.Add(-2 * time.Hour), CloseReason: alertCloseGone, Members: []string{"box-4"}} |
| + if err := af.st.CommitAlertStep([]alertIncident{cleared, gone, open}, nil, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + body := af.page(t, "/fleet/alerts/history") |
| + for _, want := range []string{ |
| + `id="incident-1"`, `id="incident-2"`, `id="incident-3"`, |
| + "Cleared after 30 minutes", "No further reports after 2 days", "Open for 1 hour", |
| + "2 affected members: box-1, box-2", |
| + } { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("history lacks %q", want) |
| + } |
| + } |
| + // Newest first. |
| + if strings.Index(body, `id="incident-3"`) > strings.Index(body, `id="incident-1"`) { |
| + t.Error("history is not newest first") |
| + } |
| +} |
diff --git a/internal/console/opshell.go b/internal/console/opshell.go| index 5e27fe3aa..a3c346536 100644 |
| --- a/internal/console/opshell.go |
| +++ b/internal/console/opshell.go |
| @@ -33,6 +33,7 @@ var opRail = []opRailItem{ |
| {Key: "activity", Href: "/fleet/activity", Label: "Activity"}, |
| {Key: "boxes", Href: "/fleet/boxes", Label: "Boxes"}, |
| {Key: "metrics", Href: "/fleet/metrics", Label: "Metrics"}, |
| + {Key: "alerts", Href: "/fleet/alerts", Label: "Alerts"}, |
| {Key: "store", Href: "/fleet/store", Label: "Storage requests", StoreOnly: true}, |
| {Key: "economics", Href: "/fleet/economics", Label: "Economics"}, |
| {Key: "architecture", Href: "/fleet/architecture", Label: "Architecture"}, |
diff --git a/internal/console/server.go b/internal/console/server.go| index f87a46037..ee57ba44a 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -74,6 +74,8 @@ var templates = template.Must(template.New("").Funcs(template.FuncMap{ |
| "fmtTime": func(t time.Time) string { return t.UTC().Format("2006-01-02 15:04 UTC") }, |
| // billingText is a billing page string (billingpage_copy.go). |
| "billingText": func(key string) string { return billingCopy[key] }, |
| + // alertText is an Alerts page or alert door string (alertpages.go). |
| + "alertText": alertText, |
| // until renders a future horizon the way the cards speak: "~4h", never a |
| // timestamp — the safety-delay strip's "goes live ~4h" and Task 6's |
| // summary strip both read it this way. |
| @@ -1778,6 +1780,26 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| s.registerRoute("POST /fleet/store/{account}/{decision}", s.handleStoreDecisionPage) |
| s.registerRoute("POST /a/{sqid}/store/apply", s.handleStoreApplyPage) |
| s.registerRoute("GET /fleet/metrics", s.handleFleetMetrics) |
| + // Fleet alerts (alertpages.go): the operator pages, same gate. Their |
| + // writes are registered without a method, as the economics doors below |
| + // are and for the same reason: a wrong method answers the unknown |
| + // route's 404, never a 405 that says the door is there. |
| + s.registerRoute("GET /fleet/alerts", s.handleFleetAlerts) |
| + 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}/delete", s.handleAlertConnectorDelete) |
| + s.registerRoute("/fleet/alerts/rules/{rule}", s.handleAlertRuleSave) |
| + // The links alert messages carry, public: the token is the credential. |
| + // Each GET shows a page and acts on nothing; only the POST acts, so a |
| + // scanner that opens every link in a mail changes nothing. |
| + s.registerRoute("GET /alerts/confirm/{token}", s.handleAlertConfirmPage) |
| + s.registerRoute("POST /alerts/confirm/{token}", s.handleAlertConfirm) |
| + s.registerRoute("GET /alerts/unsubscribe/{token}", s.handleAlertUnsubscribePage) |
| + s.registerRoute("POST /alerts/unsubscribe/{token}", s.handleAlertUnsubscribe) |
| + s.registerRoute("GET /alerts/snooze/{token}", s.handleAlertSnoozePage) |
| + s.registerRoute("POST /alerts/snooze/{token}", s.handleAlertSnooze) |
| + s.registerRoute("GET /alerts/signing-key", s.handleAlertSigningKey) |
| s.registerRoute("GET /fleet/economics", s.handleEconomics) |
| // The deployment's map (archpage.go), same operatorOnly gate. BOTH are |
| // registered WITHOUT a method prefix, for the reason spelled out below |
| @@ -2443,6 +2465,11 @@ type page struct { |
| Metrics []BoxMetricsView |
| MetricAlerts []AlertRow |
| + // The Alerts pages and the alert token doors (alertpages.go). |
| + Alerts *alertsView |
| + AlertHistory *alertHistoryView |
| + AlertDoor *alertDoorView |
| + |
| // The Console speed tables on /fleet/metrics (perfspeed.go): pages |
| // (GET and HEAD) and changes (every other method). Then the S3 |
| // requests made since the console started that neither a page request |
diff --git a/internal/console/templates/alert_door.html b/internal/console/templates/alert_door.html| new file mode 100644 |
| index 000000000..11d70b2fd |
| --- /dev/null |
| +++ b/internal/console/templates/alert_door.html |
| @@ -0,0 +1,21 @@ |
| +{{/* An alert link's page (/alerts/confirm, /alerts/unsubscribe, |
| + /alerts/snooze; alertpages.go), for whoever holds the link: no |
| + operator chrome. Before anything is done it is a heading and a button |
| + that POSTs back to the same link; after, what was done; or why the link |
| + was refused. */}} |
| +{{define "alert_door"}}{{template "top" .}} |
| +{{with .AlertDoor}} |
| +{{if .Error}}<h1>{{alertText "door.title"}}</h1> |
| +<p>{{.Error}}</p> |
| +{{else if .Done}}<h1>{{alertText "door.title"}}</h1> |
| +<p>{{.Done}}</p> |
| +{{else}}<p class="small">{{alertText "door.title"}}</p> |
| +<h1>{{.Heading}}</h1> |
| +<p>{{.Body}}</p> |
| +{{with .Note}}<p>{{.}}</p> |
| +{{end}}<form method="post" action="{{.Action}}"> |
| +{{range .Buttons}}<button type="submit"{{with .For}} name="for" value="{{.}}"{{end}}>{{.Label}}</button> |
| +{{end}}</form> |
| +<p class="small">{{alertText "door.scanner"}}</p> |
| +{{end}}{{end}} |
| +{{template "bottom" .}}{{end}} |
diff --git a/internal/console/templates/ops_alerts.html b/internal/console/templates/ops_alerts.html| new file mode 100644 |
| index 000000000..71c978a6c |
| --- /dev/null |
| +++ b/internal/console/templates/ops_alerts.html |
| @@ -0,0 +1,102 @@ |
| +{{/* Alerts (/fleet/alerts, alertpages.go): the fleet's connectors, how to |
| + add one, the webhook signing key, and the rules, on Rastrillo's |
| + components as Boxes is. Every word is alertPageCopy's. A connector's |
| + URL is never on this page: only the host and its last four |
| + characters. */}} |
| +{{define "ops_alerts"}}{{template "op_top" .}} |
| +{{template "op_page_header" (opHeader .Title (alertText "page.intro"))}} |
| +{{template "op_flash" .}} |
| +<p><a href="/fleet/alerts/history">{{alertText "page.history"}}</a></p> |
| +{{with .Alerts}} |
| +<div rst-box-head id="connectors"><h2>{{alertText "conn.heading"}}</h2></div> |
| +<p co-note>{{alertText "conn.help"}}</p> |
| +{{if .Connectors}} |
| +<div rst-card class="co-table-wrap"> |
| +<table co-table> |
| + <tr> |
| + <th>{{alertText "conn.col.name"}}</th><th>{{alertText "conn.col.kind"}}</th> |
| + <th>{{alertText "conn.col.target"}}</th><th>{{alertText "conn.col.status"}}</th><th></th> |
| + </tr> |
| + {{range .Connectors}} |
| + <tr id="connector-{{.ID}}"> |
| + <td>{{.Name}}{{with .Owner}} <span co-note>{{.}}</span>{{end}}</td> |
| + <td>{{.Kind}}</td> |
| + <td>{{emptyOrDash .Target}}</td> |
| + <td>{{template "op_status" (opPill .Status .Tone)}}</td> |
| + <td><div co-actions> |
| + <form method="post" action="/fleet/alerts/connectors/{{.ID}}/test"> |
| + <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| + <button rst-btn type="submit">{{alertText "conn.btn.test"}}</button> |
| + </form> |
| + <details> |
| + <summary rst-btn="danger">{{alertText "conn.btn.delete"}}</summary> |
| + <form method="post" action="/fleet/alerts/connectors/{{.ID}}/delete"> |
| + <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| + <p>{{.DeleteAsk}}</p> |
| + <button rst-btn="danger" type="submit">{{alertText "conn.btn.delete"}}</button> |
| + </form> |
| + </details> |
| + </div></td> |
| + </tr> |
| + {{end}} |
| +</table> |
| +</div> |
| +{{else}}{{template "op_empty" (opEmpty "" (alertText "conn.empty"))}}{{end}} |
| + |
| +<div rst-box-head id="add"><h2>{{alertText "conn.add.heading"}}</h2></div> |
| +{{range .Kinds}} |
| +<section rst-card co-pad> |
| +<h3>{{.Heading}}</h3> |
| +<div co-actions> |
| +<form method="post" action="/fleet/alerts/connectors"> |
| + <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| + <input type="hidden" name="kind" value="{{.Kind}}"> |
| + <label>{{alertText "conn.add.name"}} <input rst-input type="text" name="name" required></label> |
| + <label>{{.Label}} <input rst-input type="{{.InputType}}" name="target" required autocomplete="off"></label> |
| + <button rst-btn="primary" type="submit">{{alertText "conn.btn.add"}}</button> |
| +</form> |
| +</div> |
| +<p co-note>{{alertText "conn.add.name.help"}}</p> |
| +<p co-note>{{.Help}}</p> |
| +</section> |
| +{{end}} |
| + |
| +<div rst-box-head id="signing-key"><h2>{{alertText "conn.key.heading"}}</h2></div> |
| +<div rst-card co-pad> |
| +<p>{{.KeyHelp}}</p> |
| +<p co-note>{{alertText "conn.key.label"}}</p> |
| +<pre><code>{{.PublicKey}}</code></pre> |
| +</div> |
| + |
| +<div rst-box-head id="rules"><h2>{{alertText "rules.heading"}}</h2></div> |
| +<p co-note>{{alertText "rules.help"}}</p> |
| +<p co-note>{{alertText "rules.level.help"}} {{alertText "rules.state.offhelp"}}</p> |
| +{{range .Rules}} |
| +<section rst-card co-pad id="rule-{{.Rule}}"> |
| +<h3>{{.Title}}</h3> |
| +<dl> |
| + <dt>{{alertText "rules.col.level"}}</dt><dd>{{.Level}}</dd> |
| + <dt>{{alertText "rules.col.when"}}</dt><dd>{{.When}}</dd> |
| + <dt>{{alertText "rules.col.threshold"}}</dt> |
| + <dd>{{if .Editable}}{{.ThresholdValue}}{{else}}{{.Threshold}}{{if .BoxEnv}} <span co-note>{{alertText "rules.th.readonly"}}</span>{{end}}{{end}}</dd> |
| + <dt>{{alertText "rules.col.sendto"}}</dt><dd>{{.SendTo}}</dd> |
| + <dt>{{alertText "rules.col.noise"}}</dt><dd>{{.Noise}}</dd> |
| + <dt>{{alertText "rules.col.state"}}</dt><dd>{{if .Enabled}}{{alertText "rules.state.on"}}{{else}}{{alertText "rules.state.off"}}{{end}}</dd> |
| +</dl> |
| +<div co-actions> |
| +<form method="post" action="/fleet/alerts/rules/{{.Rule}}"> |
| + <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| + {{if .Editable}}<label>{{.ThresholdLabel}} <input rst-input type="number" name="threshold" min="{{.ThresholdMin}}" max="{{.ThresholdMax}}" step="1" value="{{.ThresholdValue}}"></label>{{end}} |
| + <label><span><input type="checkbox" name="enabled" value="on"{{if .Enabled}} checked{{end}}> {{alertText "rules.state.on"}}</span></label> |
| + {{if .Connectors}}<fieldset> |
| + <legend>{{alertText "rules.col.sendto"}}</legend> |
| + {{range .Connectors}}<label><span><input type="checkbox" name="connector" value="{{.ID}}"{{if .Checked}} checked{{end}}> {{.Label}}</span></label> |
| + {{end}}<p co-note>{{alertText "rules.sendto.help"}}</p> |
| + </fieldset>{{end}} |
| + <button rst-btn type="submit">{{alertText "rules.th.save"}}</button> |
| +</form> |
| +</div> |
| +</section> |
| +{{end}} |
| +{{end}} |
| +{{template "op_bottom" .}}{{end}} |
diff --git a/internal/console/templates/ops_alerts_history.html b/internal/console/templates/ops_alerts_history.html| new file mode 100644 |
| index 000000000..e9e2128a2 |
| --- /dev/null |
| +++ b/internal/console/templates/ops_alerts_history.html |
| @@ -0,0 +1,29 @@ |
| +{{/* Alert history (/fleet/alerts/history, alertpages.go): the fleet's last |
| + 200 incidents, newest first. Each row is #incident-<id>, which a |
| + message's incident link opens. */}} |
| +{{define "ops_alerts_history"}}{{template "op_top" .}} |
| +{{template "op_page_header" (opHeader .Title (alertText "hist.intro"))}} |
| +<p><a href="/fleet/alerts">{{alertText "hist.back"}}</a></p> |
| +{{with .AlertHistory}} |
| +{{if .Rows}} |
| +<div rst-card class="co-table-wrap"> |
| +<table co-table> |
| + <tr> |
| + <th>{{alertText "hist.col.rule"}}</th><th>{{alertText "hist.col.affected"}}</th><th>{{alertText "hist.col.level"}}</th> |
| + <th>{{alertText "hist.col.opened"}}</th><th>{{alertText "hist.col.state"}}</th> |
| + </tr> |
| + {{range .Rows}} |
| + <tr id="incident-{{.ID}}"> |
| + <td>{{.Rule}}</td> |
| + <td>{{emptyOrDash .Affected}}</td> |
| + <td>{{.Level}}</td> |
| + <td>{{.Opened}}</td> |
| + <td>{{.State}}</td> |
| + </tr> |
| + {{end}} |
| +</table> |
| +</div> |
| +{{if .Full}}<p co-note>{{alertText "hist.limit"}}</p>{{end}} |
| +{{else}}{{template "op_empty" (opEmpty "" (alertText "hist.empty"))}}{{end}} |
| +{{end}} |
| +{{template "op_bottom" .}}{{end}} |