carlos / platform Public

console: guarded alert client, URL-free errors, alert signing

The console's own client for Slack and webhook connectors (spec 5.3):
validConnectorURL (https, 443, no userinfo, no IP literal, Slack on
hooks.slack.com only), revalidated on every send; refusedAddr checked in
Dialer.Control on the dialled address after Unmap, with Proxy nil; no
redirects, 1 KiB read limit, 5 s timeout; failures reduced to sendErr
categories so the URL never reaches a log or a row.

Webhook alerts are signed with their own Ed25519 key (keys row
'alert-sign') under the label "carlos-alert", so a mail event and an
alert can never stand in for each other.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev b1d38187e9058092c10a07570e63eccadb3f85a1 parent 9ee8752
5 files changed, +674 −0
  • internal/console/alertdial.go +192 −0
  • internal/console/alertdial_test.go +317 −0
  • internal/console/alertsign.go +42 −0
  • internal/console/alertsign_test.go +75 −0
  • internal/console/store.go +48 −0

Intent

Human

<task-notification> <task-id>aba2d26b14f647383</task-id> <tool-use-id>toolu_01RkLeSnXCNTo46uSGfqtiCL</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/aba2d26b14f647383.output</output-file> <status>completed</status> <summary>Agent "Implement Task 4: alert store and seal" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **Status:** DONE_WITH_CONCERNS - **Commit:** `9ee87528` "console: alert store, transactional step, connector seal". git printed the usual packed-refs.lock warning, and `git log` shows the commit landed. - **Tests:** all 16 tests from the brief pass, plus `TestAlertConnectorLifecycle` and `TestAlertCutoverOnce`, which I added. The existing classification test (`TestClaimSQLTableCensus`) passes and fails when two of the new entries are removed. The wider claim, census and gate runs pass, `TestPlan9B8RecordWriteCensus` passes, and `go vet` is clean. - **Concerns:** 1. I added a `CreatedBy string` field to `alertConnector`, because the brief's struct had no way to fill the `created_by` column. 2. `AddAlertConnector` and `ConfirmAlertConnector` use `time.Now()`, because their signatures take no `now`. 3. A new incident has no ID until it is inserted, so an outbox row in the same step can't point to it. Task 7 never emits for a new incident, so this doesn't bite today. `incident_id = 0` means "no incident". 4. Nothing prunes sent outbox rows, closed incidents or used tokens. 5. A successful send does not lift a suspension, and there is no accessor to lift one. 6. Fires older than an hour are pruned inside `AlertStepInputs`, the per-pass read that takes `now`. 7. The authority census test lists every call named `Open`, and it caught the seal's two (the AES-GCM open and the key directory's fsync open). Neither touches claim state, so I added both to `testdata/claim-authority-sites.txt` and named them in the commit body. - **Report:** `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-4-report.md`</result> <usage><subagent_tokens>165415</subagent_tokens><tool_uses>51</tool_uses><duration_ms>1009024</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a96c895bec617a84b</task-id> <tool-use-id>toolu_01KzVwRMwjqdqPF3CLa4ou9t</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/a96c895bec617a84b.output</output-file> <status>completed</status> <summary>Agent "Review Task 4 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>### Spec Compliance - ✅ Spec compliant. Every file the brief names has its hunk: `alertstore.go` and `alertseal.go` are new with their tests, `store.go:645-779` calls `migrateAlerts()` after `migrateOperatorPages()`, and `store_gate.go:1805-1815` adds one `NonApp` entry for each of the nine tables. All nine tables exist with the columns and nullability the brief gives (diff 336-442). Every accessor signature the brief lists is present, and all 16 brief tests exist in `alertstore_test.go` and `alertseal_test.go`. - Deviations, both acceptable: - `alertConnector.CreatedBy` (diff 496-497) is an extra field. It is the only way to fill the brief's `created_by` column, and it is additive. - `Config.AlertSealKeyPath` defaults in `cmd/console/main.go:35-37` and not inside the console package. The brief names that default, and nothing opens the seal until Task 8. - ⚠️ Cannot verify from the diff: the caller's use of `openConnectorSeal`'s `created` result. Task 8 must call `MarkSealedConnectorsNeedReentry` and raise `seal_key` when it is true. Check this in Task 8. ### Strengths - **Seal (risk 1):** - Each seal draws a fresh 12-byte nonce from `crypto/rand` (diff 159-163). - The key file is created with `O_CREATE|O_EXCL` at 0600, then pinned with `Chmod` (diff 131-136). - A key is created only when the read fails with `IsNotExist`. A lost `O_EXCL` race reads the winner's key and does not overwrite it (diff 94-104). - A 0000 key, a wrong-length key or an unlistable directory gives an error and leaves the file untouched. The tests cover all three (diff 253-300). - A dangling symlink at the path also fails safely: `O_EXCL` refuses it, and the reread returns ENOENT as an error. - Errors carry the path and the length, never key bytes (diff 106, 109, 171). - **Tokens (risk 2):** - The store keeps only the SHA-256 hex of a 32-byte base64url token (`store.go:2731-2742`, diff 1093-1096). - Lookup is by hash equality in SQL, so raw values are never compared. - The action is checked (diff 1129). Expiry uses `&gt;=`, with the boundary tested (diff 1624-1629). - A confirm is marked used inside the same transaction as the read (diff 1136-1138). - Two concurrent confirms can't both succeed. I checked `store.go:103`: `SetMaxOpenConns(1)` puts every transaction on one connection, the same guarantee `authstore.go:302` relies on. - **`CommitAlertStep` (risk 3):** - Incidents, fires and outbox rows all go through one `tx`, with `defer tx.Rollback()` (diff 635-658). - An update to a missing incident ID fails the whole step (diff 683-685). - `delivery_id` is `TEXT NOT NULL UNIQUE` (diff 408). Minted IDs are 128-bit random hex. - The atomicity test is real. A trigger forces the outbox insert to fail, and the test asserts that the changed incident is unchanged, the new incident is absent, and no fires or outbox rows remain (diff 1230-1271). - **SQL (risk 4):** every production statement is a constant string with `?` placeholders. `scope`, `rule`, `subject`, `cat` and `body` are always bound arguments. The only string concatenation is the test helper `alertCount` (diff 1194), which takes constant table names. - **Single-connection safety:** `AlertStepInputs` and `AlertRuleSettings` close the first row set before running the second query (diff 611, 988). Without that, the single connection would deadlock. - **Scope checks:** `SetAlertRule` refuses a connector from another scope (diff 1030-1037), and the lifecycle test covers it. - **Census fixture (risk 5):** `claim-authority-sites.txt` gains exactly the two new `Open` call sites, each with its literal expression (diff 1841-1842). Neither is broader than its call. - **Real wiring:** `TestClaimSQLTablesClassified` runs on `openGatedStore`, not a fixture. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) None. #### Minor (Nice to Have) 1. **`store_gate.go:1811-1814`: the census reasons say less than the code stores.** `alert_outbox` ("names no app") and `alert_tokens` ("names no app") can hold app names in `body_json` and in the snooze token's `subject`. `alert_fires` and `alert_snoozes` ("no app state") are keyed by a subject that can be an app. The block comment at 1805-1806 admits this, but the per-table reasons don't. One consequence is real: a snooze keyed `(account, rule, app)` outlives the app and applies to a new app with the same name in the same account. It never crosses accounts. - Fix: reword the four reasons to "subject may name an app as text; no lifecycle authority", as `alert_incidents` already does. Optionally, note snooze cleanup for a later sweep. 2. **`alertstore.go`, diff 1136-1138: single use is not checked at the row.** `UseAlertToken` ignores `RowsAffected` on `UPDATE ... AND used_at IS NULL`. Single use is correct today only because of `SetMaxOpenConns(1)`. - Fix: require `n == 1` and return `errAlertTokenInvalid` otherwise. The guarantee then survives a change to the pool setting. 3. **Diff 683-684: the not-found error is malformed.** When no row matches, `fmt.Errorf("alert incident %d: not found (%v)", in.ID, err)` prints "not found (&lt;nil&gt;)". - Fix: split the `err != nil` case from the `n != 1` case. 4. **`writeAlertIncident`, diff 669-675: the store doesn't enforce `notify_at`.** The brief says `notify_at` is `opened_at + 5 min`, but the store writes whatever the caller passes. An insert with a zero `NotifyAt` stores 0 and is due at once. That would break the noise rule's 5-minute hold if Task 7 ever omits the field. - Fix: default to `OpenedAt + 5m` on insert when `NotifyAt` is zero, or refuse the insert. 5. **No store-level guard against two open incidents for one group.** Spec §6.2 allows one open incident per (scope, rule), but `alert_incidents_open` (diff 390) is a plain index. A partial UNIQUE index would enforce the invariant. A step that closes one incident and opens its successor would then have to write the close first. 6. **Burning a confirm token and confirming the connector are separate calls.** `UseAlertToken` commits the burn before the caller runs `ConfirmAlertConnector`. If the second call fails, the token is spent and the connector stays unconfirmed. The user can recover by requesting a new link. Task 10 should be aware of this. 7. **Diff 1564-1568: the hash-only check is weak.** `TestAlertTokenActionBound` only asserts that no row's hash equals the raw token. It does not assert that the stored hash equals `hashToken(raw)`. ### Assessment **Task quality:** Approved **Reasoning:** The step transaction, the seal's key handling and the token store all hold up under the five named risks. I verified single-use confirm concurrency against the store's single-connection pool (`store.go:103`). What remains is census wording and defensive hardening, none of which makes the task untrustworthy.</result> <usage><subagent_tokens>107193</subagent_tokens><tool_uses>10</tool_uses><duration_ms>132542</duration_ms></usage> </task-notification>

Attributed to this commit: 15.9 g CO₂e (1,966,805 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-fleet-alerts, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/alertdial.go b/internal/console/alertdial.go
new file mode 100644
index 000000000..c76bd0dd0
--- /dev/null
+++ b/internal/console/alertdial.go
@@ -0,0 +1,192 @@
+package console
+
+// The console's own outbound client for Slack and webhook connectors (spec
+// §5.3). Unlike mailpush, which only ever POSTs to platform hosts it built
+// itself, these URLs are typed in by operators and, later, customers, so
+// everything about where a POST may go is checked here:
+//
+// - the URL is https on 443 with a DNS name and no userinfo, and a Slack
+// connector's host is hooks.slack.com. It is checked when saved and again
+// on every send, so a stored row is never trusted on its own.
+// - the address actually dialled is checked in the dialler's Control hook,
+// after Unmap, so a name that resolves (or rebinds) to loopback, a
+// private or CGNAT range, or the metadata service is refused at the
+// socket, whatever DNS said at save time.
+// - there is no proxy. With one, the dial check would vouch for the proxy
+// and the destination would never be looked at.
+// - redirects are not followed, at most 1 KiB of a response is read, and
+// the whole exchange has 5 seconds.
+// - a failure is reduced to a category (sendErr) here, before anything can
+// store or log it. A *url.Error names the URL, and a Slack or webhook
+// URL's path is its secret.
+
+import (
+ "bytes"
+ "context"
+ "crypto/tls"
+ "crypto/x509"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/netip"
+ "net/url"
+ "strings"
+ "syscall"
+ "time"
+)
+
+const (
+ alertSendTimeout = 5 * time.Second
+ // alertReadLimit is the most of a response read: enough to drain a
+ // short reply, never enough to be a cost.
+ alertReadLimit = 1 << 10
+ slackHookHost = "hooks.slack.com"
+)
+
+// validConnectorURL parses raw as a kind connector's target. Its errors name
+// the rule broken and never the URL.
+func validConnectorURL(kind, raw string) (*url.URL, error) {
+ if kind != alertConnectorSlack && kind != alertConnectorWebhook {
+ return nil, fmt.Errorf("alert connector: %q has no URL", kind)
+ }
+ u, err := url.Parse(raw)
+ if err != nil {
+ return nil, errors.New("alert connector: the URL does not parse")
+ }
+ if u.Scheme != "https" || u.Opaque != "" {
+ return nil, errors.New("alert connector: the URL must start with https://")
+ }
+ if u.User != nil {
+ return nil, errors.New("alert connector: the URL must not carry a user name or password")
+ }
+ if p := u.Port(); p != "" && p != "443" {
+ return nil, errors.New("alert connector: the URL must use port 443")
+ }
+ host := u.Hostname()
+ if host == "" {
+ return nil, errors.New("alert connector: the URL has no host")
+ }
+ if _, err := netip.ParseAddr(host); err == nil {
+ return nil, errors.New("alert connector: the URL must name a host, not an IP address")
+ }
+ if kind == alertConnectorSlack && !strings.EqualFold(host, slackHookHost) {
+ return nil, errors.New("alert connector: a Slack URL must be on hooks.slack.com")
+ }
+ return u, nil
+}
+
+var (
+ cgnatPrefix = netip.MustParsePrefix("100.64.0.0/10")
+ thisNetwork = netip.MustParsePrefix("0.0.0.0/8")
+ ietfProtocol = netip.MustParsePrefix("192.0.0.0/24")
+ awsMetadata4 = netip.MustParseAddr("169.254.169.254")
+ awsMetadata6 = netip.MustParseAddr("fd00:ec2::254")
+)
+
+// refusedAddr is true for an address no alert may be sent to: anything not
+// on the public internet, Tailscale's CGNAT range and the metadata service.
+// The metadata addresses already fall in link-local and ULA; they are named
+// so that no later narrowing of those classes can let them through.
+func refusedAddr(ip netip.Addr) bool {
+ ip = ip.Unmap()
+ if !ip.IsValid() {
+ return true
+ }
+ return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() ||
+ ip.IsLinkLocalMulticast() || ip.IsInterfaceLocalMulticast() || ip.IsMulticast() ||
+ ip.IsUnspecified() || cgnatPrefix.Contains(ip) || thisNetwork.Contains(ip) ||
+ ietfProtocol.Contains(ip) || ip == awsMetadata4 || ip == awsMetadata6
+}
+
+// errRefusedAddr is the dialler's refusal; postAlert reports it as
+// "refused".
+var errRefusedAddr = errors.New("alert dial: address refused")
+
+// newAlertHTTPClient is the client every Slack and webhook send goes
+// through. Production passes refusedAddr; only a test passes anything else.
+func newAlertHTTPClient(refused func(netip.Addr) bool) *http.Client {
+ dialer := &net.Dialer{
+ Timeout: alertSendTimeout,
+ // Control runs on the address being connected to, after any DNS
+ // answer, so a name that rebinds between save and send is caught.
+ Control: func(network, address string, _ syscall.RawConn) error {
+ host, _, err := net.SplitHostPort(address)
+ if err != nil {
+ return errRefusedAddr
+ }
+ ip, err := netip.ParseAddr(host)
+ if err != nil || refused(ip.Unmap()) {
+ return errRefusedAddr
+ }
+ return nil
+ },
+ }
+ return &http.Client{
+ Transport: &http.Transport{
+ Proxy: nil,
+ DialContext: dialer.DialContext,
+ TLSHandshakeTimeout: alertSendTimeout,
+ ForceAttemptHTTP2: true,
+ },
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+ Timeout: alertSendTimeout,
+ }
+}
+
+// sendErr is a failed send reduced to something safe to store and show:
+// "refused", "timeout", "connect", "tls", "status <N>" or "invalid". The
+// empty sendErr is success.
+type sendErr string
+
+// postAlert POSTs body to raw with hdr set (Content-Type defaults to JSON).
+// It does not wrap, return or log the client's error, which names the URL.
+func postAlert(ctx context.Context, c *http.Client, kind, raw string, body []byte, hdr map[string]string) sendErr {
+ u, err := validConnectorURL(kind, raw)
+ if err != nil {
+ return "invalid"
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(body))
+ if err != nil {
+ return "invalid"
+ }
+ req.Header.Set("Content-Type", "application/json")
+ for k, v := range hdr {
+ req.Header.Set(k, v)
+ }
+ resp, err := c.Do(req)
+ if err != nil {
+ return sendErrOf(err)
+ }
+ defer resp.Body.Close()
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, alertReadLimit))
+ if resp.StatusCode < 200 || resp.StatusCode > 299 {
+ return sendErr(fmt.Sprintf("status %d", resp.StatusCode))
+ }
+ return ""
+}
+
+// sendErrOf maps a client error to its category. The refusal is checked
+// first: it is a dial error, and must not read as an ordinary "connect".
+func sendErrOf(err error) sendErr {
+ var (
+ netErr net.Error
+ recordErr tls.RecordHeaderError
+ alertErr tls.AlertError
+ verifyErr *tls.CertificateVerificationError
+ authErr x509.UnknownAuthorityError
+ hostErr x509.HostnameError
+ certErr x509.CertificateInvalidError
+ )
+ switch {
+ case errors.Is(err, errRefusedAddr):
+ return "refused"
+ case errors.Is(err, context.DeadlineExceeded), errors.As(err, &netErr) && netErr.Timeout():
+ return "timeout"
+ case errors.As(err, &verifyErr), errors.As(err, &recordErr), errors.As(err, &alertErr),
+ errors.As(err, &authErr), errors.As(err, &hostErr), errors.As(err, &certErr):
+ return "tls"
+ }
+ return "connect"
+}
diff --git a/internal/console/alertdial_test.go b/internal/console/alertdial_test.go
new file mode 100644
index 000000000..e35baf2c8
--- /dev/null
+++ b/internal/console/alertdial_test.go
@@ -0,0 +1,317 @@
+package console
+
+import (
+ "context"
+ "crypto/tls"
+ "crypto/x509"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// Every class the guard refuses, and two public addresses it lets through.
+// The IPv4-mapped forms are the ones a v6 socket reports for a v4 peer: they
+// must be judged as the v4 address they carry (spec §5.3).
+func TestRefusedAddrTable(t *testing.T) {
+ refused := []string{
+ "127.0.0.1", "127.1.2.3", "::1", // loopback
+ "10.0.0.1", "172.16.5.4", "192.168.1.1", "fc00::1", "fd12:3456::1", // RFC 1918, ULA
+ "169.254.1.1", "fe80::1", // link-local
+ "100.64.0.1", "100.100.1.1", "100.127.255.254", // CGNAT, Tailscale
+ "0.0.0.0", "::", // unspecified
+ "224.0.0.1", "239.1.2.3", "ff02::1", // multicast
+ "169.254.169.254", "fd00:ec2::254", // metadata
+ "0.1.2.3", // 0.0.0.0/8
+ "192.0.0.1", "192.0.0.170", // 192.0.0.0/24
+ "::ffff:10.0.0.1", "::ffff:127.0.0.1", "::ffff:169.254.169.254", "::ffff:100.100.1.1",
+ }
+ for _, s := range refused {
+ if !refusedAddr(netip.MustParseAddr(s)) {
+ t.Errorf("%s was allowed", s)
+ }
+ }
+ if !refusedAddr(netip.Addr{}) {
+ t.Error("the zero Addr was allowed")
+ }
+ for _, s := range []string{"1.1.1.1", "2606:4700::1111", "::ffff:1.1.1.1", "100.128.0.1", "192.0.1.1"} {
+ if refusedAddr(netip.MustParseAddr(s)) {
+ t.Errorf("%s was refused", s)
+ }
+ }
+}
+
+func TestValidConnectorURL(t *testing.T) {
+ good := []struct{ kind, raw string }{
+ {alertConnectorSlack, "https://hooks.slack.com/services/T0/B0/xyz"},
+ {alertConnectorSlack, "https://hooks.slack.com:443/services/T0/B0/xyz"},
+ {alertConnectorSlack, "HTTPS://Hooks.Slack.com/services/T0/B0/xyz"},
+ {alertConnectorWebhook, "https://alerts.example.com/carlos?k=1"},
+ {alertConnectorWebhook, "https://alerts.example.com:443/"},
+ }
+ for _, c := range good {
+ if _, err := validConnectorURL(c.kind, c.raw); err != nil {
+ t.Errorf("%s %s: %v", c.kind, c.raw, err)
+ }
+ }
+ bad := []struct{ kind, raw string }{
+ {alertConnectorWebhook, "http://alerts.example.com/"},
+ {alertConnectorWebhook, "ftp://alerts.example.com/"},
+ {alertConnectorWebhook, "https://user:pw@alerts.example.com/"},
+ {alertConnectorWebhook, "https://user@alerts.example.com/"},
+ {alertConnectorWebhook, "https://alerts.example.com:8443/"},
+ {alertConnectorWebhook, "https://alerts.example.com:80/"},
+ {alertConnectorWebhook, "https://1.1.1.1/"},
+ {alertConnectorWebhook, "https://127.0.0.1/"},
+ {alertConnectorWebhook, "https://[::1]/"},
+ {alertConnectorWebhook, "https://[2606:4700::1111]/"},
+ {alertConnectorWebhook, "https:///path"},
+ {alertConnectorWebhook, "https:opaque"},
+ {alertConnectorWebhook, "/relative"},
+ {alertConnectorWebhook, ""},
+ {alertConnectorWebhook, "https://alerts.example.com/\x7f"},
+ {alertConnectorSlack, "https://alerts.example.com/services/T0/B0/xyz"},
+ {alertConnectorSlack, "https://hooks.slack.com.evil.example/services/x"},
+ {alertConnectorSlack, "https://evilhooks.slack.com/services/x"},
+ {alertConnectorSlack, "http://hooks.slack.com/services/x"},
+ {alertConnectorEmail, "https://alerts.example.com/"},
+ {"sms", "https://alerts.example.com/"},
+ }
+ for _, c := range bad {
+ if _, err := validConnectorURL(c.kind, c.raw); err == nil {
+ t.Errorf("%s %q was accepted", c.kind, c.raw)
+ }
+ }
+}
+
+// allowLoopback is the test-only relaxation: a guard that refuses all the
+// production guard does except loopback, where the test servers live.
+func allowLoopback(ip netip.Addr) bool {
+ return !ip.Unmap().IsLoopback() && refusedAddr(ip)
+}
+
+// pointAlertClientAt returns the client newAlertHTTPClient builds, with its
+// dialler fronted by a stand-in resolver that answers every name with srv's
+// loopback address. The real dialler, and with it Control, still runs on
+// that address, which is what a rebinding name does to it in production.
+// srv's certificate is trusted for every name.
+func pointAlertClientAt(t *testing.T, srv *httptest.Server, refused func(netip.Addr) bool) *http.Client {
+ t.Helper()
+ c := newAlertHTTPClient(refused)
+ tr := c.Transport.(*http.Transport)
+ dial := tr.DialContext
+ target := srv.Listener.Addr().String()
+ tr.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
+ return dial(ctx, network, target)
+ }
+ pool := x509.NewCertPool()
+ pool.AddCert(srv.Certificate())
+ tr.TLSClientConfig = &tls.Config{RootCAs: pool, ServerName: "example.com"}
+ return c
+}
+
+func countingServer(t *testing.T, h http.HandlerFunc) (*httptest.Server, *atomic.Int32) {
+ t.Helper()
+ var n atomic.Int32
+ srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ n.Add(1)
+ if h != nil {
+ h(w, r)
+ }
+ }))
+ // The untrusted-certificate case makes the server log a handshake error.
+ srv.Config.ErrorLog = log.New(io.Discard, "", 0)
+ srv.StartTLS()
+ t.Cleanup(srv.Close)
+ return srv, &n
+}
+
+// A public name that resolves to loopback at send time is refused in the
+// dialler, on the address being connected to, and the far end never sees a
+// request.
+func TestAlertClientRefusesRebind(t *testing.T) {
+ srv, hits := countingServer(t, nil)
+ c := pointAlertClientAt(t, srv, refusedAddr)
+ got := postAlert(context.Background(), c, alertConnectorWebhook, "https://alerts.example.com/hook", []byte(`{"v":1}`), nil)
+ if got != "refused" {
+ t.Fatalf("postAlert = %q, want refused", got)
+ }
+ if n := hits.Load(); n != 0 {
+ t.Fatalf("the loopback server saw %d requests", n)
+ }
+}
+
+// HTTPS_PROXY in the console's environment is never used: a proxy would be
+// dialled instead of the destination, and the dial check would vouch for
+// the proxy rather than where the POST goes.
+func TestAlertClientIgnoresProxyEnv(t *testing.T) {
+ var proxied atomic.Int32
+ proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ proxied.Add(1)
+ w.WriteHeader(http.StatusOK)
+ }))
+ t.Cleanup(proxy.Close)
+ for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY"} {
+ t.Setenv(k, proxy.URL)
+ }
+ t.Setenv("NO_PROXY", "")
+ t.Setenv("no_proxy", "")
+
+ srv, hits := countingServer(t, nil)
+ c := pointAlertClientAt(t, srv, allowLoopback)
+ if tr := c.Transport.(*http.Transport); tr.Proxy != nil {
+ t.Fatal("the alert transport has a Proxy func")
+ }
+ if got := postAlert(context.Background(), c, alertConnectorWebhook, "https://alerts.example.com/hook", []byte(`{"v":1}`), nil); got != "" {
+ t.Fatalf("postAlert = %q, want success", got)
+ }
+ if n := proxied.Load(); n != 0 {
+ t.Fatalf("the proxy saw %d requests", n)
+ }
+ if n := hits.Load(); n != 1 {
+ t.Fatalf("the destination saw %d requests, want 1", n)
+ }
+}
+
+// A redirect is the far end's answer, not somewhere to go: following it
+// would POST the alert to a host nobody validated.
+func TestAlertClientNoRedirect(t *testing.T) {
+ srv, hits := countingServer(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/hook" {
+ http.Redirect(w, r, "https://alerts.example.com/elsewhere", http.StatusTemporaryRedirect)
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ })
+ c := pointAlertClientAt(t, srv, allowLoopback)
+ got := postAlert(context.Background(), c, alertConnectorWebhook, "https://alerts.example.com/hook", []byte(`{"v":1}`), nil)
+ if got != "status 307" {
+ t.Fatalf("postAlert = %q, want status 307", got)
+ }
+ if n := hits.Load(); n != 1 {
+ t.Fatalf("the server saw %d requests, want 1 (the redirect was followed)", n)
+ }
+}
+
+// bigAlertBody is a 1 MiB response body that counts what was read. Finite,
+// so a reader with no limit fails the test rather than hanging it.
+type bigAlertBody struct{ n int64 }
+
+func (b *bigAlertBody) Read(p []byte) (int, error) {
+ if b.n >= 1<<20 {
+ return 0, io.EOF
+ }
+ p = p[:min(int64(len(p)), 1<<20-b.n)]
+ for i := range p {
+ p[i] = 'x'
+ }
+ b.n += int64(len(p))
+ return len(p), nil
+}
+func (b *bigAlertBody) Close() error { return nil }
+
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func TestPostAlertReadsAtMost1KiB(t *testing.T) {
+ for _, code := range []int{http.StatusOK, http.StatusInternalServerError} {
+ body := &bigAlertBody{}
+ c := &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ return &http.Response{StatusCode: code, Body: body, Header: http.Header{}, Request: r}, nil
+ })}
+ got := postAlert(context.Background(), c, alertConnectorWebhook, "https://alerts.example.com/hook", []byte(`{"v":1}`), nil)
+ if code == http.StatusOK && got != "" {
+ t.Fatalf("postAlert = %q on 200", got)
+ }
+ if code != http.StatusOK && got != "status 500" {
+ t.Fatalf("postAlert = %q on 500", got)
+ }
+ if body.n > 1024 {
+ t.Fatalf("read %d bytes of a %d response, want at most 1024", body.n, code)
+ }
+ }
+}
+
+// A failed send is reduced to a category before anyone sees it: the URL,
+// whose path is the Slack or webhook secret, is in none of them.
+func TestPostAlertErrorHasNoURL(t *testing.T) {
+ release := make(chan struct{})
+ srv, _ := countingServer(t, func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-release:
+ case <-r.Context().Done():
+ }
+ })
+ t.Cleanup(func() { close(release) })
+ c := pointAlertClientAt(t, srv, allowLoopback)
+ ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
+ defer cancel()
+ raw := "https://alerts.example.com/hooks/sekrit-XYZ?token=sekrit-XYZ"
+ got := postAlert(ctx, c, alertConnectorWebhook, raw, []byte(`{"v":1}`), nil)
+ if got != "timeout" {
+ t.Fatalf("postAlert = %q, want timeout", got)
+ }
+ if strings.Contains(string(got), "sekrit-XYZ") || strings.Contains(string(got), "example.com") {
+ t.Fatalf("the category %q carries the URL", got)
+ }
+}
+
+// The categories other than refused and timeout, each from the failure that
+// produces it.
+func TestPostAlertCategories(t *testing.T) {
+ ok, _ := countingServer(t, func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Content-Type") != "application/json" || r.Header.Get("Carlos-Signature") != "t=1,ed25519=x" {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ b, _ := io.ReadAll(r.Body)
+ if string(b) != `{"v":1}` {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+ })
+ hdr := map[string]string{"Carlos-Signature": "t=1,ed25519=x"}
+ body := []byte(`{"v":1}`)
+ url := "https://alerts.example.com/hook"
+ if got := postAlert(context.Background(), pointAlertClientAt(t, ok, allowLoopback), alertConnectorWebhook, url, body, hdr); got != "" {
+ t.Errorf("a 204 with the headers and body = %q, want success", got)
+ }
+
+ failing, _ := countingServer(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadGateway) })
+ if got := postAlert(context.Background(), pointAlertClientAt(t, failing, allowLoopback), alertConnectorWebhook, url, body, nil); got != "status 502" {
+ t.Errorf("a 502 = %q", got)
+ }
+
+ // A certificate nobody vouches for.
+ untrusted := pointAlertClientAt(t, ok, allowLoopback)
+ untrusted.Transport.(*http.Transport).TLSClientConfig.RootCAs = x509.NewCertPool()
+ if got := postAlert(context.Background(), untrusted, alertConnectorWebhook, url, body, nil); got != "tls" {
+ t.Errorf("an untrusted certificate = %q, want tls", got)
+ }
+
+ // Nothing listening.
+ closed, _ := countingServer(t, nil)
+ nobody := pointAlertClientAt(t, closed, allowLoopback)
+ closed.Close()
+ if got := postAlert(context.Background(), nobody, alertConnectorWebhook, url, body, nil); got != "connect" {
+ t.Errorf("a closed port = %q, want connect", got)
+ }
+
+ // Revalidated on every send, whatever was stored.
+ for _, raw := range []string{"http://alerts.example.com/hook", "https://alerts.example.com:8443/hook", "https://127.0.0.1/hook"} {
+ if got := postAlert(context.Background(), pointAlertClientAt(t, ok, allowLoopback), alertConnectorWebhook, raw, body, nil); got != "invalid" {
+ t.Errorf("%s = %q, want invalid", raw, got)
+ }
+ }
+ if got := postAlert(context.Background(), pointAlertClientAt(t, ok, allowLoopback), alertConnectorSlack, url, body, nil); got != "invalid" {
+ t.Errorf("a slack send to another host = %q, want invalid", got)
+ }
+}
diff --git a/internal/console/alertsign.go b/internal/console/alertsign.go
new file mode 100644
index 000000000..e64f80d16
--- /dev/null
+++ b/internal/console/alertsign.go
@@ -0,0 +1,42 @@
+package console
+
+// Signing webhook alerts (spec §5.1). The scheme is mailpush's, with its own
+// key (Store.AlertSigningKey) and its own label:
+//
+// Carlos-Signature: t=<unix seconds>,ed25519=<base64 signature>
+// signed bytes: "carlos-alert\n" + t + "\n" + body
+//
+// The label is what keeps the two kinds apart: a mail event can never be
+// passed off as an alert, or an alert as a mail event, even were the keys
+// ever the same.
+
+import (
+ "crypto/ed25519"
+ "encoding/base64"
+ "strconv"
+ "time"
+)
+
+const alertSignatureLabel = "carlos-alert"
+
+// signAlert is the Carlos-Signature header value for body at t.
+func signAlert(priv ed25519.PrivateKey, t time.Time, body []byte) string {
+ ts := strconv.FormatInt(t.Unix(), 10)
+ sig := ed25519.Sign(priv, alertSignedBytes(ts, body))
+ return "t=" + ts + ",ed25519=" + base64.StdEncoding.EncodeToString(sig)
+}
+
+func alertSignedBytes(ts string, body []byte) []byte {
+ msg := make([]byte, 0, len(alertSignatureLabel)+len(ts)+len(body)+2)
+ msg = append(msg, alertSignatureLabel...)
+ msg = append(msg, '\n')
+ msg = append(msg, ts...)
+ msg = append(msg, '\n')
+ return append(msg, body...)
+}
+
+// alertPublicKey is the verifying half, as shown on the connector page and
+// served to receivers: the 32 raw bytes, standard base64.
+func alertPublicKey(priv ed25519.PrivateKey) string {
+ return base64.StdEncoding.EncodeToString(priv.Public().(ed25519.PublicKey))
+}
diff --git a/internal/console/alertsign_test.go b/internal/console/alertsign_test.go
new file mode 100644
index 000000000..5887f2a6d
--- /dev/null
+++ b/internal/console/alertsign_test.go
@@ -0,0 +1,75 @@
+package console
+
+import (
+ "crypto/ed25519"
+ "encoding/base64"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+// verifyAlertHeader is a receiver's check, done by hand from the spec's
+// definition (§5.1) rather than with the code under test.
+func verifyAlertHeader(t *testing.T, pubB64, header string, body []byte) bool {
+ t.Helper()
+ pub, err := base64.StdEncoding.DecodeString(pubB64)
+ if err != nil || len(pub) != ed25519.PublicKeySize {
+ t.Fatalf("public key %q is not 32 raw bytes in standard base64", pubB64)
+ }
+ ts, sig, ok := strings.Cut(header, ",ed25519=")
+ if !ok || !strings.HasPrefix(ts, "t=") {
+ t.Fatalf("header %q is not t=<unix>,ed25519=<sig>", header)
+ }
+ raw, err := base64.StdEncoding.DecodeString(sig)
+ if err != nil {
+ t.Fatalf("signature in %q is not standard base64", header)
+ }
+ msg := "carlos-alert\n" + strings.TrimPrefix(ts, "t=") + "\n" + string(body)
+ return ed25519.Verify(pub, []byte(msg), raw)
+}
+
+func TestSignAlertVerifies(t *testing.T) {
+ st := openTestStore(t)
+ key, err := st.AlertSigningKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ again, err := st.AlertSigningKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if alertPublicKey(again) != alertPublicKey(key) {
+ t.Fatal("the alert key changed between reads; every receiver's copy would stop verifying")
+ }
+ mailKey, err := st.MailEventsSigningKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if mailEventsPublicKey(mailKey) == alertPublicKey(key) {
+ t.Fatal("alerts are signed with the mail-events key")
+ }
+
+ now := time.Date(2026, 10, 30, 9, 0, 0, 0, time.UTC)
+ body := []byte(`{"v":1,"delivery_id":"d1","rule":"disk_eta"}`)
+ header := signAlert(key, now, body)
+ if !strings.HasPrefix(header, "t="+strconv.FormatInt(now.Unix(), 10)+",ed25519=") {
+ t.Fatalf("header = %q", header)
+ }
+ pub := alertPublicKey(key)
+ if !verifyAlertHeader(t, pub, header, body) {
+ t.Fatal("a genuine alert did not verify")
+ }
+ if verifyAlertHeader(t, pub, header, []byte(strings.Replace(string(body), "d1", "d2", 1))) {
+ t.Fatal("a changed body verified")
+ }
+
+ // The same key and bytes under the mail-event label is not an alert, and
+ // an alert is not a mail event: the labels keep the two apart.
+ if verifyAlertHeader(t, pub, signMailEvent(key, now, body), body) {
+ t.Fatal("a mail-event signature verified as an alert")
+ }
+ if err := VerifyMailEvent(pub, header, body, now, 5*time.Minute); err == nil {
+ t.Fatal("an alert signature verified as a mail event")
+ }
+}
diff --git a/internal/console/store.go b/internal/console/store.go
index 3953fe5ae..8b24b6b6c 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -8,6 +8,7 @@ package console
import (
"context"
"crypto/ecdsa"
+ "crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
@@ -2995,6 +2996,53 @@ func (s *Store) SigningKey() (*ecdsa.PrivateKey, error) {
}
return load()
}
+
+// AlertSigningKey returns the Ed25519 key webhook alerts are signed with
+// (spec §5.1), generating and persisting it on first use. It is its own key,
+// not MailEventsSigningKey's, for the reason that one is not SigningKey's: a
+// key that signs two kinds of thing is one whose signatures can be carried
+// from one to the other.
+func (s *Store) AlertSigningKey() (ed25519.PrivateKey, error) {
+ load := func() (ed25519.PrivateKey, error) {
+ var b64 string
+ if err := s.db.QueryRow(`SELECT pkcs8 FROM keys WHERE name = 'alert-sign'`).Scan(&b64); err != nil {
+ return nil, err
+ }
+ der, err := base64.StdEncoding.DecodeString(b64)
+ if err != nil {
+ return nil, fmt.Errorf("console: stored alert signing key: %v", err)
+ }
+ key, err := x509.ParsePKCS8PrivateKey(der)
+ if err != nil {
+ return nil, fmt.Errorf("console: stored alert signing key: %v", err)
+ }
+ ed, ok := key.(ed25519.PrivateKey)
+ if !ok {
+ return nil, fmt.Errorf("console: stored alert signing key is not Ed25519")
+ }
+ return ed, nil
+ }
+ if k, err := load(); err == nil {
+ return k, nil
+ } else if err != sql.ErrNoRows {
+ return nil, err
+ }
+ _, priv, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ return nil, err
+ }
+ der, err := x509.MarshalPKCS8PrivateKey(priv)
+ if err != nil {
+ return nil, err
+ }
+ // INSERT OR IGNORE + re-load, as SigningKey: a racing opener's row wins
+ // and everyone converges on it.
+ if _, err := s.db.Exec(`INSERT OR IGNORE INTO keys (name, pkcs8, created_at) VALUES ('alert-sign', ?, ?)`,
+ base64.StdEncoding.EncodeToString(der), time.Now().Unix()); err != nil {
+ return nil, err
+ }
+ return load()
+}
func (s *Store) RecordActivity(accountID int64, app, address string, activity Activity, now time.Time) (claimResult0 error) {
return s.RecordActivityContext(context.Background(), accountID, app, address, activity, now)
}