console: alert client fix round 1 (no keep-alives, wider refusals, shared Ed25519 signing)
- Transport: DisableKeepAlives (no idle connection to a tenant-chosen host, HTTP/2 included) and MaxResponseHeaderBytes 16 KiB. - refusedAddr also refuses NAT64 (64:ff9b::/96, 64:ff9b:1::/48), IPv4-compatible ::/96, 6to4, Teredo, 240/4, 198.18/15 and fec0::/10. - validConnectorURL rejects a numeric or 0x last label (127.1, 2130706433, 0x7f000001) and compares the Slack host as ASCII only, so a long s or Kelvin sign cannot fold into hooks.slack.com. - postAlert sends the validated *url.URL itself. - Store.ed25519Key, signLabelled and labelledBytes are shared by the mail-event and alert schemes; names, signatures and output unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/console/alertdial.go+67 −10internal/console/alertdial_test.go+73 −1internal/console/alertsign.go+1 −13internal/console/alertsign_test.go+42 −0internal/console/mailpush.go+18 −45internal/console/store.go+13 −6
CI failed — run details
Intent
<task-notification> <task-id>af261fb5bed9a187e</task-id> <tool-use-id>toolu_01TF3JhvP3XwPFTeDTcXwfQ9</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/af261fb5bed9a187e.output</output-file> <status>completed</status> <summary>Agent "Implement Task 5: guarded client and signing" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **Status:** DONE - **Commit:** `b1d38187` console: guarded alert client, URL-free errors, alert signing (5 files, +674 lines; not pushed). - **Tests:** all 9 new tests pass (the 8 from the brief plus `TestPostAlertCategories`), along with the console census tests and the mail-event signature test. RED was a build failure before the code existed. After GREEN, each of 8 deliberate breaks to `alertdial.go` made a test fail: proxy from env, `Control` not refusing, following redirects, no read limit, no `Unmap`, returning the raw URL error, no Slack host check, and TLS errors reported as connect. The file was restored after each one. `go vet` is clean for linux, darwin and windows. - **Concerns (all minor):** 1. A cancelled context (`context.Canceled`) maps to `"connect"`, so a send cut off by console shutdown records a failure. Task 8 might skip recording it. 2. TLS errors are recognised by type. An untyped handshake error maps to `"connect"`. Only the label is wrong; the URL still never appears. 3. NAT64 (`64:ff9b::/96`) isn't in the brief's refuse list, so it isn't refused. It's a one-line addition if wanted. 4. `MailEventsSigningKey` is in `mailpush.go`, not `store.go` as the brief said. I put `AlertSigningKey` in `store.go`, as the file list asks. 5. The error messages from `validConnectorURL` will be shown to users and still need the Task 9 copy review. - **Report:** `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-alerts/.superpowers/sdd/2026-10-30-fleet-alerts-1-engine-connectors/task-5-report.md`</result> <usage><subagent_tokens>102062</subagent_tokens><tool_uses>33</tool_uses><duration_ms>614010</duration_ms></usage> </task-notification>
<task-notification> <task-id>aa9089bdda4212d1a</task-id> <tool-use-id>toolu_01B6goQuRHtpaN5VjGjH46nn</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6112a34e-476e-4b5e-8e07-f93a46fc6d50/tasks/aa9089bdda4212d1a.output</output-file> <status>completed</status> <summary>Agent "Review Task 5 (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 interface in the brief is in the diff with the stated values: - `validConnectorURL` at alertdial.go:50-77. - `refusedAddr` at alertdial.go:92-101. It calls `Unmap` first and covers every class the brief lists. - The transport at alertdial.go:127-135: `Proxy: nil`, Dialer 5 s with `Control`, `TLSHandshakeTimeout` 5 s, `ForceAttemptHTTP2`, `CheckRedirect` returning `ErrUseLastResponse`, client `Timeout` 5 s. - `sendErr` categories at alertdial.go:172-192. - `postAlert` revalidates on every send (alertdial.go:146) and reads through a 1 KiB `LimitReader` (alertdial.go:163). - The signing API is at alertsign.go:20-42 and `AlertSigningKey` at store.go:3005. - All 8 named tests are present. - ⚠️ NAT64 `64:ff9b::/96` and `64:ff9b:1::/48` are still missing from `refusedAddr` (alertdial.go:97-100). This is expected under R-12, which applies in the fix round. The controller should confirm the fix round adds both prefixes and a row for each in `TestRefusedAddrTable`. - ⚠️ The diff alone can't confirm that production builds the client once and passes `refusedAddr` itself. There are no callers yet; Task 8 owns that. The same goes for the Important idle-connection finding below. ### Strengths - `Control` is the right hook for the dial check: - Go calls it for every socket, so each Happy Eyeballs attempt and each fallback address is checked. - The resolver's own DNS dials use a separate `Dialer`, so a local stub resolver such as 127.0.0.53 is not refused by mistake. - Zoned addresses (`[fe80::1%eth0]:443`) parse with `netip.ParseAddr`, keep their zone, and are refused as link-local. - If `Control` fails to parse an address, it refuses it (alertdial.go:115-121). - I found no path from the URL, query or response body into a returned category: - `sendErrOf` returns only fixed strings, and `"status %d"` carries only the number (alertdial.go:164-165). - The `*url.Error` is never wrapped or formatted. - `validConnectorURL`'s errors name the rule that failed, never the URL. - The only `%q` in those errors is the internal `kind`. - The response body is handled correctly. At most 1 KiB is read, then `defer Close`. A partly read HTTP/1 body closes the connection rather than reusing it, and HTTP/2 resets the stream. Nothing leaks per request. - The signing is sound: - The key is distinct: row `'alert-sign'` against `'mail-events-sign'` (mailpush.go:143). - The race-safe pattern holds: `keys.name` is `TEXT PRIMARY KEY` (store.go:174-178), so `INSERT OR IGNORE` plus a re-load converges on one key. - Concatenation can't be ambiguous. The label is followed by `\n`, and the timestamp is decimal with no `\n` in it, so the first two newlines split the message unambiguously. The two labels `carlos-alert\n` and `carlos-mail-event\n` cannot be confused with each other. - The test checks cross-label rejection both ways (alertsign_test.go:68-74) and verifies by hand from the spec rather than with the code under test. - The mutation table (M1-M8) shows each guard has a test that fails without it. `Proxy == nil` is also asserted directly, which covers the cached `ProxyFromEnvironment` problem. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) 1. **alertdial.go:127-132: idle connections to tenant-chosen hosts never expire.** - The `http.Transport` sets no `IdleConnTimeout` and no `MaxIdleConns`. Unlike `DefaultTransport`, the zero values mean no idle timeout and no limit on the total idle pool. - A reply of 1 KiB or less is read to EOF, so the connection goes back to the pool. Up to 2 connections per distinct host then stay open, with a read goroutine each, until the far end closes them. - A tenant with wildcard DNS (`a1.evil.example`, `a2.evil.example`, ...) and a server that never closes idle connections makes the console's file descriptors grow with every host it has ever sent to. Deleting connectors doesn't release them. - This is the connection-leak half of named risk 3. The client is long-lived and its URLs come from customers. - Fix: set `DisableKeepAlives: true`. Alerts are rare, so keep-alive gains nothing, and this also removes HTTP/2 reuse from the threat model. Otherwise set `IdleConnTimeout: 30*time.Second` with a small `MaxIdleConns`. 2. **store.go:3005-3046 and alertsign.go:23-42 duplicate mailpush.go:140-199 almost verbatim (plan-mandated).** - `AlertSigningKey` is `MailEventsSigningKey` with the row name and error strings swapped. I diffed the two: only those lines differ. - `signAlert`, `alertSignedBytes` and `alertPublicKey` are `signMailEvent`, `mailEventSignedBytes` and `mailEventsPublicKey` with a different label constant. - This is about 60 lines of security-relevant logic in two copies. A future fix to one (key-type checks, encoding) will miss the other. - The brief says "copying `MailEventsSigningKey`", so this is plan-mandated. Under the rubric it is still Important. - Fix: add `(s *Store) ed25519Key(name string)`, `signLabelled(label, priv, t, body)` and `labelledBytes(label, ts, body)`, and have both kinds call them. The human decides whether to do this now. #### Minor (Nice to Have) 1. **alertdial.go:97-100: a few address forms that carry an IPv4 address are not refused.** None of these is reachable from a console box without a tunnel interface, so this is defence in depth only. The fix is the same one-line edit as R-12. - **IPv4-compatible `::/96`.** I checked that `netip` leaves `::10.0.0.1` and `::127.0.0.1` alone: `Unmap` is a no-op, and they are neither private nor loopback, so both are allowed. Linux routes these through `sit0` if it is up. - **6to4 `2002::/16`** and **Teredo `2001::/32`** (named risk 1). They need a tunnel or relay to reach anything. - Unroutable `240.0.0.0/4`, `255.255.255.255`, `198.18.0.0/15`, and the deprecated site-local `fec0::/10`. - Suggest adding `::/96`, `2002::/16` and `2001::/32` with the NAT64 prefixes, with rows in `TestRefusedAddrTable`. 2. **alertdial.go:71: the IP-literal rule misses numeric forms that `inet_aton` accepts.** - I checked that `https://127.1/`, `https://2130706433/` and `https://0x7f000001/` all parse, and `netip.ParseAddr` rejects each host, so `validConnectorURL` treats them as DNS names. - It isn't exploitable. If cgo's `getaddrinfo` turns one into an address, `Control` still judges the real address, and TLS fails because no CA issues a certificate for the name `2130706433`. - But the stored-URL rule ("name a host, not an IP address") doesn't hold to the letter. - Fix: also reject a host whose last label is all digits or starts with `0x`. No real top-level domain is numeric. 3. **alertdial.go:74 and :150: the Slack host check uses Unicode case folding, and the request is built from a re-serialised URL.** - `strings.EqualFold` accepts `hooks.ſlack.com` (U+017F) and the Kelvin sign `hoo\u212As.slack.com` as `hooks.slack.com`. - I checked that `http.Transport`'s IDNA mapping then dials the real `hooks.slack.com:443` in both cases, so the destination is still Slack. The allowlist is only safe because UTS46 maps these characters the same way. - Separately, `u.String()` is parsed a second time inside `NewRequestWithContext`, so the URL that was checked is not the exact object that gets sent. - Fix: compare ASCII only (`host == slackHookHost` after an ASCII lowercase) and reject non-ASCII Slack hosts. Assign the checked `u` to `req.URL`. 4. **alertdial.go:127: response headers are not limited.** - `MaxResponseHeaderBytes` is unset, so the 10 MB default applies. A hostile endpoint can make each send allocate up to that much within 5 s, despite the 1 KiB body limit. - Fix: set it to about 16 KiB. 5. **Report concern 1: `context.Canceled` maps to `"connect"` (alertdial.go:191).** - When the console shuts down, the send is recorded as a connector failure. - Task 8 should skip recording when its own context was cancelled. Otherwise add a category. 6. **Copy: `validConnectorURL`'s error strings will be user-facing (alertdial.go:56-75).** - They still need the Task 9 copy pass. The implementer flags this too. ### Checks - **Named risk 1, HTTP/2 reuse across hosts:** Go's `net/http` and its bundled HTTP/2 pool connections by `host:port` and never coalesce across hosts by certificate SAN. A pooled connection was already checked when it was dialled, so a later DNS rebind can't redirect it. - **Named risk 1, redirects:** `CheckRedirect` returns `ErrUseLastResponse` (alertdial.go:133), so a 3xx comes back as `"status 3xx"` and no second request is made. `TestAlertClientNoRedirect` asserts one hit. - **Named risk 2, revalidation and encodings:** - `postAlert` calls `validConnectorURL` before any I/O (alertdial.go:146). - `HTTPS://` is lowercased by `url.Parse`. - `hooks%2eslack.com` fails to parse; Go rejects `%`-escapes of ASCII in hosts. - `hooks.slack.com.` (trailing dot) is rejected for Slack. - `https://@host` gives a non-nil `User` and is rejected. - The `:` with no port maps to 443. - I verified the encodings with a scratch Go program in `$TMPDIR`, since deleted. - **Named risk 5, signing:** row name `'alert-sign'` against mailpush.go:143, the `PRIMARY KEY` at store.go:174-178, and the label and separator layout at alertsign.go:29-36 against mailpush.go:195-201. ### Assessment **Task quality:** Needs fixes **Reasoning:** The dial-time guard, the URL-free error categories and the signing all hold against the attacks named in the brief. I found no way to reach a refused address or leak a URL. But the client keeps idle connections to tenant-chosen hosts forever (`IdleConnTimeout` and `MaxIdleConns` unset), so a customer can make the console's file descriptors grow without limit. The signing-key code is also duplicated from mailpush, which the plan mandated but is still worth a decision now.</result> <usage><subagent_tokens>80134</subagent_tokens><tool_uses>8</tool_uses><duration_ms>199038</duration_ms></usage> </task-notification>
Attributed to this commit: 19.4 g CO₂e (2,421,593 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| index c76bd0dd0..5ef99f2d1 100644 |
| --- a/internal/console/alertdial.go |
| +++ b/internal/console/alertdial.go |
| @@ -14,7 +14,8 @@ package console |
| // 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 |
| +// - redirects are not followed, no connection is kept for the next send, |
| +// at most 1 KiB of a response body (and 16 KiB of headers) 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 |
| @@ -68,21 +69,63 @@ func validConnectorURL(kind, raw string) (*url.URL, error) { |
| if host == "" { |
| return nil, errors.New("alert connector: the URL has no host") |
| } |
| - if _, err := netip.ParseAddr(host); err == nil { |
| + if _, err := netip.ParseAddr(host); err == nil || numericLastLabel(host) { |
| return nil, errors.New("alert connector: the URL must name a host, not an IP address") |
| } |
| - if kind == alertConnectorSlack && !strings.EqualFold(host, slackHookHost) { |
| + // ASCII only, then an ASCII comparison: strings.EqualFold would let |
| + // "hooks.\u017flack.com" (long s) or a Kelvin sign stand in for the |
| + // Slack host. |
| + if kind == alertConnectorSlack && (!isASCII(host) || strings.ToLower(host) != slackHookHost) { |
| return nil, errors.New("alert connector: a Slack URL must be on hooks.slack.com") |
| } |
| return u, nil |
| } |
| +// numericLastLabel is true for a host some resolvers read as an IPv4 |
| +// address though netip does not: 127.1, 2130706433, 0x7f000001. A DNS name's |
| +// last label is never all digits, nor hex. |
| +func numericLastLabel(host string) bool { |
| + host = strings.TrimSuffix(host, ".") |
| + last := host[strings.LastIndexByte(host, '.')+1:] |
| + if strings.HasPrefix(strings.ToLower(last), "0x") { |
| + return true |
| + } |
| + for i := 0; i < len(last); i++ { |
| + if last[i] < '0' || last[i] > '9' { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func isASCII(s string) bool { |
| + for i := 0; i < len(s); i++ { |
| + if s[i] >= 0x80 { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| 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") |
| + // refusedPrefixes are the ranges netip has no predicate for. The v6 |
| + // ones carry, or translate to, a v4 address the v4 checks never see: |
| + // NAT64 (well-known and local-use), IPv4-compatible, 6to4 and Teredo. |
| + refusedPrefixes = []netip.Prefix{ |
| + netip.MustParsePrefix("0.0.0.0/8"), // this network |
| + netip.MustParsePrefix("100.64.0.0/10"), // CGNAT, Tailscale |
| + netip.MustParsePrefix("192.0.0.0/24"), // IETF protocol assignments |
| + netip.MustParsePrefix("198.18.0.0/15"), // benchmarking |
| + netip.MustParsePrefix("240.0.0.0/4"), // reserved, and broadcast |
| + netip.MustParsePrefix("64:ff9b::/96"), // NAT64 |
| + netip.MustParsePrefix("64:ff9b:1::/48"), // local-use NAT64 |
| + netip.MustParsePrefix("::/96"), // IPv4-compatible |
| + netip.MustParsePrefix("2002::/16"), // 6to4 |
| + netip.MustParsePrefix("2001::/32"), // Teredo |
| + netip.MustParsePrefix("fec0::/10"), // site-local |
| + } |
| ) |
| // refusedAddr is true for an address no alert may be sent to: anything not |
| @@ -94,10 +137,17 @@ func refusedAddr(ip netip.Addr) bool { |
| if !ip.IsValid() { |
| return true |
| } |
| - return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || |
| + if 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 |
| + ip.IsUnspecified() || ip == awsMetadata4 || ip == awsMetadata6 { |
| + return true |
| + } |
| + for _, p := range refusedPrefixes { |
| + if p.Contains(ip) { |
| + return true |
| + } |
| + } |
| + return false |
| } |
| // errRefusedAddr is the dialler's refusal; postAlert reports it as |
| @@ -129,6 +179,11 @@ func newAlertHTTPClient(refused func(netip.Addr) bool) *http.Client { |
| DialContext: dialer.DialContext, |
| TLSHandshakeTimeout: alertSendTimeout, |
| ForceAttemptHTTP2: true, |
| + // No idle connection to a host a tenant chose outlives its send, |
| + // HTTP/2 included. Alerts are rare; a fresh dial each time also |
| + // means every send passes Control again. |
| + DisableKeepAlives: true, |
| + MaxResponseHeaderBytes: 16 << 10, |
| }, |
| CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| Timeout: alertSendTimeout, |
| @@ -147,10 +202,12 @@ func postAlert(ctx context.Context, c *http.Client, kind, raw string, body []byt |
| if err != nil { |
| return "invalid" |
| } |
| - req, err := http.NewRequestWithContext(ctx, http.MethodPost, u.String(), bytes.NewReader(body)) |
| + // The request carries the URL that was validated, not a re-parse of it. |
| + req, err := http.NewRequestWithContext(ctx, http.MethodPost, "", bytes.NewReader(body)) |
| if err != nil { |
| return "invalid" |
| } |
| + req.URL = u |
| req.Header.Set("Content-Type", "application/json") |
| for k, v := range hdr { |
| req.Header.Set(k, v) |
diff --git a/internal/console/alertdial_test.go b/internal/console/alertdial_test.go| index e35baf2c8..14460b15d 100644 |
| --- a/internal/console/alertdial_test.go |
| +++ b/internal/console/alertdial_test.go |
| @@ -11,6 +11,7 @@ import ( |
| "net/http/httptest" |
| "net/netip" |
| "strings" |
| + "sync" |
| "sync/atomic" |
| "testing" |
| "time" |
| @@ -31,6 +32,14 @@ func TestRefusedAddrTable(t *testing.T) { |
| "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", |
| + "64:ff9b::a00:1", "64:ff9b::7f00:1", // NAT64 of 10.0.0.1, 127.0.0.1 |
| + "64:ff9b:1::a00:1", // local-use NAT64 |
| + "::10.0.0.1", "::127.0.0.1", // IPv4-compatible |
| + "2002:a00:1::1", "2002:7f00:1::", // 6to4 of 10.0.0.1, 127.0.0.1 |
| + "2001:0:4136:e378::1", // Teredo |
| + "240.0.0.1", "255.255.255.255", // reserved, broadcast |
| + "198.18.0.1", "198.19.255.254", // benchmarking |
| + "fec0::1", // site-local |
| } |
| for _, s := range refused { |
| if !refusedAddr(netip.MustParseAddr(s)) { |
| @@ -40,7 +49,8 @@ func TestRefusedAddrTable(t *testing.T) { |
| 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"} { |
| + for _, s := range []string{"1.1.1.1", "2606:4700::1111", "::ffff:1.1.1.1", "100.128.0.1", "192.0.1.1", |
| + "198.20.0.1", "223.255.255.254", "2001:4860:4860::8888"} { |
| if refusedAddr(netip.MustParseAddr(s)) { |
| t.Errorf("%s was refused", s) |
| } |
| @@ -54,6 +64,8 @@ func TestValidConnectorURL(t *testing.T) { |
| {alertConnectorSlack, "HTTPS://Hooks.Slack.com/services/T0/B0/xyz"}, |
| {alertConnectorWebhook, "https://alerts.example.com/carlos?k=1"}, |
| {alertConnectorWebhook, "https://alerts.example.com:443/"}, |
| + {alertConnectorWebhook, "https://1password.example.com/"}, |
| + {alertConnectorWebhook, "https://10.example.com./"}, |
| } |
| for _, c := range good { |
| if _, err := validConnectorURL(c.kind, c.raw); err != nil { |
| @@ -80,6 +92,14 @@ func TestValidConnectorURL(t *testing.T) { |
| {alertConnectorSlack, "https://hooks.slack.com.evil.example/services/x"}, |
| {alertConnectorSlack, "https://evilhooks.slack.com/services/x"}, |
| {alertConnectorSlack, "http://hooks.slack.com/services/x"}, |
| + {alertConnectorSlack, "https://hooks.\u017flack.com/services/x"}, // long s folds to s |
| + {alertConnectorSlack, "https://hoo\u212as.slack.com/services/x"}, // Kelvin sign folds to k |
| + {alertConnectorWebhook, "https://127.1/"}, |
| + {alertConnectorWebhook, "https://2130706433/"}, |
| + {alertConnectorWebhook, "https://0x7f000001/"}, |
| + {alertConnectorWebhook, "https://0X7F000001/"}, |
| + {alertConnectorWebhook, "https://alerts.example.0x1/"}, |
| + {alertConnectorWebhook, "https://10.0.0.1./"}, |
| {alertConnectorEmail, "https://alerts.example.com/"}, |
| {"sms", "https://alerts.example.com/"}, |
| } |
| @@ -199,6 +219,49 @@ func TestAlertClientNoRedirect(t *testing.T) { |
| } |
| } |
| +// No connection to a host a tenant chose is kept between sends: each |
| +// postAlert dials afresh, over HTTP/1.1 and over HTTP/2 alike, so an idle |
| +// connection never outlives its send and every send passes Control. |
| +func TestAlertClientNewConnectionPerSend(t *testing.T) { |
| + for _, h2 := range []bool{false, true} { |
| + var accepts atomic.Int32 |
| + var mu sync.Mutex |
| + var protos []int |
| + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + mu.Lock() |
| + protos = append(protos, r.ProtoMajor) |
| + mu.Unlock() |
| + w.WriteHeader(http.StatusOK) |
| + })) |
| + srv.EnableHTTP2 = h2 |
| + srv.Config.ConnState = func(_ net.Conn, s http.ConnState) { |
| + if s == http.StateNew { |
| + accepts.Add(1) |
| + } |
| + } |
| + srv.StartTLS() |
| + t.Cleanup(srv.Close) |
| + c := pointAlertClientAt(t, srv, allowLoopback) |
| + for i := 0; i < 2; i++ { |
| + if got := postAlert(context.Background(), c, alertConnectorWebhook, "https://alerts.example.com/hook", []byte(`{"v":1}`), nil); got != "" { |
| + t.Fatalf("h2=%v send %d = %q", h2, i, got) |
| + } |
| + } |
| + mu.Lock() |
| + defer mu.Unlock() |
| + want := 1 |
| + if h2 { |
| + want = 2 |
| + } |
| + if len(protos) != 2 || protos[0] != want || protos[1] != want { |
| + t.Fatalf("h2=%v: requests arrived as HTTP/%v, want HTTP/%d", h2, protos, want) |
| + } |
| + if n := accepts.Load(); n != 2 { |
| + t.Fatalf("h2=%v: two sends opened %d connections, want 2", h2, 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 } |
| @@ -290,6 +353,15 @@ func TestPostAlertCategories(t *testing.T) { |
| t.Errorf("a 502 = %q", got) |
| } |
| + // Headers past 16 KiB are not read. |
| + bloated, _ := countingServer(t, func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("X-Bloat", strings.Repeat("x", 32<<10)) |
| + w.WriteHeader(http.StatusOK) |
| + }) |
| + if got := postAlert(context.Background(), pointAlertClientAt(t, bloated, allowLoopback), alertConnectorWebhook, url, body, nil); got != "connect" { |
| + t.Errorf("32 KiB of response headers = %q, want connect", got) |
| + } |
| + |
| // A certificate nobody vouches for. |
| untrusted := pointAlertClientAt(t, ok, allowLoopback) |
| untrusted.Transport.(*http.Transport).TLSClientConfig.RootCAs = x509.NewCertPool() |
diff --git a/internal/console/alertsign.go b/internal/console/alertsign.go| index e64f80d16..9a6165332 100644 |
| --- a/internal/console/alertsign.go |
| +++ b/internal/console/alertsign.go |
| @@ -13,7 +13,6 @@ package console |
| import ( |
| "crypto/ed25519" |
| "encoding/base64" |
| - "strconv" |
| "time" |
| ) |
| @@ -21,18 +20,7 @@ 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...) |
| + return signLabelled(alertSignatureLabel, priv, t, body) |
| } |
| // alertPublicKey is the verifying half, as shown on the connector page and |
diff --git a/internal/console/alertsign_test.go b/internal/console/alertsign_test.go| index 5887f2a6d..664f3c80b 100644 |
| --- a/internal/console/alertsign_test.go |
| +++ b/internal/console/alertsign_test.go |
| @@ -2,6 +2,7 @@ package console |
| import ( |
| "crypto/ed25519" |
| + "crypto/x509" |
| "encoding/base64" |
| "strconv" |
| "strings" |
| @@ -73,3 +74,44 @@ func TestSignAlertVerifies(t *testing.T) { |
| t.Fatal("an alert signature verified as a mail event") |
| } |
| } |
| + |
| +// The shared helpers keep each scheme's bytes exactly as they were: a |
| +// signature is the label's own definition, reconstructed here by hand, and |
| +// each key lives in its own keys row. |
| +func TestSignLabelledKeepsEachScheme(t *testing.T) { |
| + st := openTestStore(t) |
| + key := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize)) |
| + now := time.Date(2026, 10, 30, 9, 0, 0, 0, time.UTC) |
| + body := []byte(`{"v":1}`) |
| + ts := strconv.FormatInt(now.Unix(), 10) |
| + for label, got := range map[string]string{ |
| + "carlos-mail-event": signMailEvent(key, now, body), |
| + "carlos-alert": signAlert(key, now, body), |
| + } { |
| + want := "t=" + ts + ",ed25519=" + base64.StdEncoding.EncodeToString( |
| + ed25519.Sign(key, []byte(label+"\n"+ts+"\n"+string(body)))) |
| + if got != want { |
| + t.Errorf("%s: header = %q, want %q", label, got, want) |
| + } |
| + } |
| + |
| + mailKey, err := st.MailEventsSigningKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + alertKey, err := st.AlertSigningKey() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, k := range map[string]ed25519.PrivateKey{"mail-events-sign": mailKey, "alert-sign": alertKey} { |
| + var b64 string |
| + if err := st.db.QueryRow(`SELECT pkcs8 FROM keys WHERE name = ?`, name).Scan(&b64); err != nil { |
| + t.Fatalf("keys row %s: %v", name, err) |
| + } |
| + der, _ := base64.StdEncoding.DecodeString(b64) |
| + stored, err := x509.ParsePKCS8PrivateKey(der) |
| + if err != nil || !k.Equal(stored) { |
| + t.Fatalf("keys row %s does not hold the key returned for it", name) |
| + } |
| + } |
| +} |
diff --git a/internal/console/mailpush.go b/internal/console/mailpush.go| index 4c809cd49..1adef91c7 100644 |
| --- a/internal/console/mailpush.go |
| +++ b/internal/console/mailpush.go |
| @@ -53,8 +53,6 @@ import ( |
| "bytes" |
| "context" |
| "crypto/ed25519" |
| - "crypto/rand" |
| - "crypto/x509" |
| "database/sql" |
| "encoding/base64" |
| "encoding/json" |
| @@ -138,45 +136,7 @@ var mailPushedTypes = map[string]bool{ |
| // that signs two kinds of thing is one whose signatures can be carried from |
| // one to the other. |
| func (s *Store) MailEventsSigningKey() (ed25519.PrivateKey, error) { |
| - load := func() (ed25519.PrivateKey, error) { |
| - var b64 string |
| - if err := s.db.QueryRow(`SELECT pkcs8 FROM keys WHERE name = 'mail-events-sign'`).Scan(&b64); err != nil { |
| - return nil, err |
| - } |
| - der, err := base64.StdEncoding.DecodeString(b64) |
| - if err != nil { |
| - return nil, fmt.Errorf("console: stored mail events key: %v", err) |
| - } |
| - key, err := x509.ParsePKCS8PrivateKey(der) |
| - if err != nil { |
| - return nil, fmt.Errorf("console: stored mail events key: %v", err) |
| - } |
| - ed, ok := key.(ed25519.PrivateKey) |
| - if !ok { |
| - return nil, fmt.Errorf("console: stored mail events 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 ('mail-events-sign', ?, ?)`, |
| - base64.StdEncoding.EncodeToString(der), time.Now().Unix()); err != nil { |
| - return nil, err |
| - } |
| - return load() |
| + return s.ed25519Key("mail-events-sign") |
| } |
| // mailEventsPublicKey is the verifying half, as delivered to an app: the 32 |
| @@ -187,14 +147,27 @@ func mailEventsPublicKey(priv ed25519.PrivateKey) string { |
| // signMailEvent is the Carlos-Signature header value for body at t. |
| func signMailEvent(priv ed25519.PrivateKey, t time.Time, body []byte) string { |
| + return signLabelled(mailEventSignatureLabel, priv, t, body) |
| +} |
| + |
| +func mailEventSignedBytes(ts string, body []byte) []byte { |
| + return labelledBytes(mailEventSignatureLabel, ts, body) |
| +} |
| + |
| +// signLabelled is a Carlos-Signature header value, t=<unix>,ed25519=<std |
| +// base64>, over labelledBytes. Mail events and alerts share the scheme and |
| +// differ only in the label (and the key). |
| +func signLabelled(label string, priv ed25519.PrivateKey, t time.Time, body []byte) string { |
| ts := strconv.FormatInt(t.Unix(), 10) |
| - sig := ed25519.Sign(priv, mailEventSignedBytes(ts, body)) |
| + sig := ed25519.Sign(priv, labelledBytes(label, ts, body)) |
| return "t=" + ts + ",ed25519=" + base64.StdEncoding.EncodeToString(sig) |
| } |
| -func mailEventSignedBytes(ts string, body []byte) []byte { |
| - msg := make([]byte, 0, len(mailEventSignatureLabel)+len(ts)+len(body)+2) |
| - msg = append(msg, mailEventSignatureLabel...) |
| +// labelledBytes is what a Carlos-Signature signs: label, "\n", ts, "\n", |
| +// body. |
| +func labelledBytes(label, ts string, body []byte) []byte { |
| + msg := make([]byte, 0, len(label)+len(ts)+len(body)+2) |
| + msg = append(msg, label...) |
| msg = append(msg, '\n') |
| msg = append(msg, ts...) |
| msg = append(msg, '\n') |
diff --git a/internal/console/store.go b/internal/console/store.go| index 8b24b6b6c..1da9979f8 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -3003,22 +3003,29 @@ func (s *Store) SigningKey() (*ecdsa.PrivateKey, error) { |
| // 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) { |
| + return s.ed25519Key("alert-sign") |
| +} |
| + |
| +// ed25519Key returns the Ed25519 key kept in the keys row name, generating |
| +// and persisting it on first use. Each caller names its own row: one key, |
| +// one kind of thing signed. |
| +func (s *Store) ed25519Key(name string) (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 { |
| + if err := s.db.QueryRow(`SELECT pkcs8 FROM keys WHERE name = ?`, name).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) |
| + return nil, fmt.Errorf("console: stored %s key: %v", name, err) |
| } |
| key, err := x509.ParsePKCS8PrivateKey(der) |
| if err != nil { |
| - return nil, fmt.Errorf("console: stored alert signing key: %v", err) |
| + return nil, fmt.Errorf("console: stored %s key: %v", name, err) |
| } |
| ed, ok := key.(ed25519.PrivateKey) |
| if !ok { |
| - return nil, fmt.Errorf("console: stored alert signing key is not Ed25519") |
| + return nil, fmt.Errorf("console: stored %s key is not Ed25519", name) |
| } |
| return ed, nil |
| } |
| @@ -3037,8 +3044,8 @@ func (s *Store) AlertSigningKey() (ed25519.PrivateKey, error) { |
| } |
| // 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 { |
| + if _, err := s.db.Exec(`INSERT OR IGNORE INTO keys (name, pkcs8, created_at) VALUES (?, ?, ?)`, |
| + name, base64.StdEncoding.EncodeToString(der), time.Now().Unix()); err != nil { |
| return nil, err |
| } |
| return load() |