carlos / platform Public

console: bound SNS cert fetches on a cache miss (H5-M12 review 1)

Astra: any path on the pinned host was a fresh outbound fetch, failures
were never remembered and concurrent misses fetched apart. Now the path
must be /SimpleNotificationService-<hex>.pem (no port), identical misses
share one fetch, a failed URL backs off 30 s doubling to 15 min, and the
door makes at most 2 fetches at once and 10 a minute, refusing beyond.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev ff961d58cada72529ce59af5642ac8e3e7f6869d parent 5a5642d
2 files changed, +327 −12
  • internal/console/sesevents.go +178 −11
  • internal/console/sesevents_test.go +149 −1
diff --git a/internal/console/sesevents.go b/internal/console/sesevents.go
index 49b24295e..b27786cd7 100644
--- a/internal/console/sesevents.go
+++ b/internal/console/sesevents.go
@@ -725,17 +725,72 @@ func (s *Server) confirmSNSSubscription(ctx context.Context, subscribeURL string
// certificate at a time and rotates rarely; a handful of slots is plenty,
// and the oldest entry makes room when they are full.
//
+// A cache only bounds hits; a miss is outbound work an unsigned request can
+// ask for (H5-M12 review 1). So, before any fetch: the path must have the
+// shape of an SNS signing certificate (validSigningCertPath); identical
+// misses in flight share one fetch; a failed URL is not fetched again until
+// its backoff (snsCertBackoff, doubling per failure to a ceiling) runs out,
+// and the failures remembered are bounded too; and the door as a whole
+// starts at most snsCertFetchesPerMinute fetches a minute and holds at most
+// snsCertFetchesInFlight at once, refusing past either without fetching.
+// A genuine message whose certificate is cached never fetches, so an
+// attacker filling these windows delays only a certificate rotation, and
+// SNS retries a refused delivery.
+//
// A value type with a nil-safe zero value on purpose: Server embeds one
// directly (no constructor call needed), the same way ceClientOnce
// (server.go) needs no init.
type snsCertCache struct {
mu sync.Mutex
+ now func() time.Time // nil: time.Now
keys map[string]*rsa.PublicKey
order []string // insertion order of keys, oldest first
+
+ fails map[string]snsCertFailure // failed fetches, by canonical URL
+ failOrder []string // insertion order of fails, oldest first
+ inflight map[string]*snsCertCall // fetches in flight, by canonical URL
+ started []time.Time // fetch starts in the last minute
}
-// snsCertCacheMax bounds snsCertCache.
-const snsCertCacheMax = 8
+// snsCertFailure is a URL's failed fetches: how many in a row, the last
+// error, and when it may be fetched again.
+type snsCertFailure struct {
+ n int
+ err error
+ until time.Time
+}
+
+// snsCertCall is one fetch in flight; done closes when pub and err are set.
+type snsCertCall struct {
+ done chan struct{}
+ pub *rsa.PublicKey
+ err error
+}
+
+const (
+ // snsCertCacheMax bounds the verified keys, and snsCertFailMax the
+ // failures, snsCertCache remembers.
+ snsCertCacheMax = 8
+ snsCertFailMax = 64
+ // snsCertFetchesInFlight and snsCertFetchesPerMinute bound the
+ // certificate fetches the whole door makes.
+ snsCertFetchesInFlight = 2
+ snsCertFetchesPerMinute = 10
+ // A failed URL waits snsCertBackoffBase, doubling per failure in a row,
+ // up to snsCertBackoffMax, before it is fetched again.
+ snsCertBackoffBase = 30 * time.Second
+ snsCertBackoffMax = 15 * time.Minute
+)
+
+// errSNSCertBusy refuses a miss past the door's fetch limits, unfetched.
+var errSNSCertBusy = errors.New("sns: signing cert fetches over their limit; not fetched")
+
+func (c *snsCertCache) clock() time.Time {
+ if c.now != nil {
+ return c.now()
+ }
+ return time.Now()
+}
func (c *snsCertCache) get(certURL string) (*rsa.PublicKey, bool) {
c.mu.Lock()
@@ -747,6 +802,10 @@ func (c *snsCertCache) get(certURL string) (*rsa.PublicKey, bool) {
func (c *snsCertCache) put(certURL string, pub *rsa.PublicKey) {
c.mu.Lock()
defer c.mu.Unlock()
+ c.putLocked(certURL, pub)
+}
+
+func (c *snsCertCache) putLocked(certURL string, pub *rsa.PublicKey) {
if c.keys == nil {
c.keys = map[string]*rsa.PublicKey{}
}
@@ -760,6 +819,118 @@ func (c *snsCertCache) put(certURL string, pub *rsa.PublicKey) {
c.keys[certURL] = pub
}
+// snsCertBackoff is how long a URL waits after its nth failure in a row.
+func snsCertBackoff(n int) time.Duration {
+ d := snsCertBackoffBase
+ for i := 1; i < n && d < snsCertBackoffMax; i++ {
+ d *= 2
+ }
+ return min(d, snsCertBackoffMax)
+}
+
+// failLocked records a failed fetch of certURL.
+func (c *snsCertCache) failLocked(certURL string, err error, now time.Time) {
+ if c.fails == nil {
+ c.fails = map[string]snsCertFailure{}
+ }
+ f, ok := c.fails[certURL]
+ if !ok {
+ for len(c.failOrder) >= snsCertFailMax {
+ delete(c.fails, c.failOrder[0])
+ c.failOrder = c.failOrder[1:]
+ }
+ c.failOrder = append(c.failOrder, certURL)
+ }
+ f.n++
+ f.err = err
+ f.until = now.Add(snsCertBackoff(f.n))
+ c.fails[certURL] = f
+}
+
+// key returns certURL's verified key: cached, the answer of a fetch already
+// in flight for it, a remembered failure still in its backoff, a refusal
+// past the door's fetch limits, or else the result of fetching it now with
+// fetch. certURL is canonical and shape-checked.
+func (c *snsCertCache) key(ctx context.Context, certURL string, fetch func(context.Context, string) (*rsa.PublicKey, error)) (*rsa.PublicKey, error) {
+ c.mu.Lock()
+ if pub, ok := c.keys[certURL]; ok {
+ c.mu.Unlock()
+ return pub, nil
+ }
+ now := c.clock()
+ if f, ok := c.fails[certURL]; ok && now.Before(f.until) {
+ c.mu.Unlock()
+ return nil, f.err
+ }
+ if call, ok := c.inflight[certURL]; ok {
+ c.mu.Unlock()
+ select {
+ case <-call.done:
+ return call.pub, call.err
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+ kept := c.started[:0]
+ for _, t := range c.started {
+ if t.After(now.Add(-time.Minute)) {
+ kept = append(kept, t)
+ }
+ }
+ c.started = kept
+ if len(c.inflight) >= snsCertFetchesInFlight || len(c.started) >= snsCertFetchesPerMinute {
+ c.mu.Unlock()
+ return nil, errSNSCertBusy
+ }
+ if c.inflight == nil {
+ c.inflight = map[string]*snsCertCall{}
+ }
+ call := &snsCertCall{done: make(chan struct{})}
+ c.inflight[certURL] = call
+ c.started = append(c.started, now)
+ c.mu.Unlock()
+
+ // The fetch is the door's, not this request's: a caller that gives up
+ // must not fail the others waiting on it.
+ call.pub, call.err = fetch(context.WithoutCancel(ctx), certURL)
+
+ c.mu.Lock()
+ delete(c.inflight, certURL)
+ if call.err != nil {
+ c.failLocked(certURL, call.err, c.clock())
+ } else {
+ c.putLocked(certURL, call.pub)
+ delete(c.fails, certURL) // its failOrder slot ages out
+ }
+ c.mu.Unlock()
+ close(call.done)
+ return call.pub, call.err
+}
+
+// snsCertPathPattern is the path of an SNS signing certificate:
+// /SimpleNotificationService-<hex>.pem, as every SigningCertURL AWS
+// documents and sends (the hex is 32 digits today; any length up to 64 is
+// let through so a change of digest does not stop mail).
+var snsCertPathPattern = regexp.MustCompile(`^/SimpleNotificationService-[0-9a-fA-F]{1,64}\.pem$`)
+
+// validSigningCertPath refuses a canonical SigningCertURL whose path is not
+// an SNS signing certificate's, or that names a port other than https's:
+// nothing else on the pinned host is worth a fetch (H5-M12 review 1). It is
+// for SigningCertURL only; SubscribeURL is a query on "/".
+func validSigningCertPath(certURL string) error {
+ u, err := url.Parse(certURL)
+ if err != nil {
+ return fmt.Errorf("sns: unparseable SigningCertURL")
+ }
+ if u.Port() != "" {
+ return fmt.Errorf("sns: SigningCertURL names a port")
+ }
+ if !snsCertPathPattern.MatchString(u.EscapedPath()) {
+ return fmt.Errorf("sns: SigningCertURL path %q is not an SNS signing certificate", u.EscapedPath())
+ }
+ return nil
+}
+
// canonicalSigningCertURL is the one URL a SigningCertURL names, for both
// the cache key and the fetch: https, the lowercased host (default port
// dropped), the path as given, and nothing else. A fragment never reaches
@@ -779,22 +950,18 @@ func canonicalSigningCertURL(raw string) (string, error) {
// verifiedCertKey returns the RSA public key for a signing certificate URL
// — already pinned to an SNS host by the caller (validSigningCertURL) —
-// using the cache on a hit, and fetching plus fully verifying the
-// certificate on a miss. Both use the canonical URL.
+// canonical and shape-checked first, then through snsCertCache.key: the
+// cache on a hit, and on a miss, within the door's fetch limits, fetching
+// plus fully verifying the certificate.
func (s *Server) verifiedCertKey(ctx context.Context, certURL string) (*rsa.PublicKey, error) {
certURL, err := canonicalSigningCertURL(certURL)
if err != nil {
return nil, err
}
- if pub, ok := s.snsCerts.get(certURL); ok {
- return pub, nil
- }
- pub, err := fetchVerifiedCertKey(ctx, certURL)
- if err != nil {
+ if err := validSigningCertPath(certURL); err != nil {
return nil, err
}
- s.snsCerts.put(certURL, pub)
- return pub, nil
+ return s.snsCerts.key(ctx, certURL, fetchVerifiedCertKey)
}
// snsCertDNSName is the hostname a genuine SNS message-signing certificate
diff --git a/internal/console/sesevents_test.go b/internal/console/sesevents_test.go
index 46432da21..1fea8107b 100644
--- a/internal/console/sesevents_test.go
+++ b/internal/console/sesevents_test.go
@@ -23,6 +23,7 @@ import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
+ "encoding/json"
"encoding/pem"
"errors"
"fmt"
@@ -34,6 +35,8 @@ import (
"os"
"reflect"
"strings"
+ "sync"
+ "sync/atomic"
"testing"
"time"
@@ -692,7 +695,7 @@ func TestVerifiedCertKeyServesFromCache(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- const certURL = "https://sns.eu-west-1.amazonaws.com/nothing-listens-here.pem"
+ const certURL = "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-0badc0de.pem" // nothing listens
fx.srv.snsCerts.put(certURL, &key.PublicKey)
pub, err := fx.srv.verifiedCertKey(context.Background(), certURL)
@@ -744,6 +747,151 @@ func TestCanonicalSigningCertURL(t *testing.T) {
}
}
+// snsCertServer is a local TLS stand-in for the pinned regional SNS host,
+// hijacked under snsFetchClient. Each fetch is counted; status answers it
+// (200 serves a valid signing cert), and gate, when not nil, holds every
+// fetch until it closes.
+func snsCertServer(t *testing.T, status int, gate chan struct{}) *atomic.Int64 {
+ t.Helper()
+ tlsDER, tlsLeaf, tlsKey := genLeafCert(t, "sns.eu-west-1.amazonaws.com")
+ pemDER, _, _ := genLeafCert(t, snsCertDNSName)
+ certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: pemDER})
+ var fetches atomic.Int64
+ ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fetches.Add(1)
+ if gate != nil {
+ <-gate
+ }
+ w.WriteHeader(status)
+ if status == http.StatusOK {
+ w.Write(certPEM)
+ }
+ }))
+ ts.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{tlsDER}, PrivateKey: tlsKey}}}
+ ts.StartTLS()
+ t.Cleanup(ts.Close)
+ hijackFetchClient(t, ts.Listener.Addr().String(), tlsLeaf)
+ return &fetches
+}
+
+func snsCertPath(i int) string {
+ return fmt.Sprintf("https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-%032x.pem", i)
+}
+
+// H5-M12 review 1: N unsigned requests, each naming a distinct valid-shaped
+// certificate path on the pinned host, cost at most the door's per-minute
+// fetches, through the real route.
+func TestSNSCertFetchesAreCapped(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.MailDeployment.SNSTopicARN = "arn:aws:sns:eu-west-1:1:carlos-mail"
+ fx.srv.cfg.MailDeployment.Region = "eu-west-1"
+ fetches := snsCertServer(t, http.StatusOK, nil)
+ const n = 50
+ for i := 0; i < n; i++ {
+ env, _ := json.Marshal(map[string]string{
+ "Type": "Notification", "MessageId": "m", "TopicArn": fx.srv.cfg.MailDeployment.SNSTopicARN,
+ "Message": "{}", "Timestamp": "2026-10-25T00:00:00Z", "SignatureVersion": "1",
+ "Signature": "Ym9ndXM=", "SigningCertURL": snsCertPath(i),
+ })
+ resp := sesPost(t, fx, string(env))
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusForbidden {
+ t.Fatalf("request %d = %d, want 403", i, resp.StatusCode)
+ }
+ }
+ if got := fetches.Load(); got > snsCertFetchesPerMinute {
+ t.Fatalf("%d unsigned requests with distinct certificate paths made %d fetches; want at most %d", n, got, snsCertFetchesPerMinute)
+ }
+}
+
+// A path that is not an SNS signing certificate's, or a port, is refused
+// before any fetch.
+func TestSNSCertPathShapeRefusedUnfetched(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fetches := snsCertServer(t, http.StatusOK, nil)
+ for _, u := range []string{
+ "https://sns.eu-west-1.amazonaws.com/x.pem",
+ "https://sns.eu-west-1.amazonaws.com/",
+ "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-abc.pem/x",
+ "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-.pem",
+ "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-%61bc.pem",
+ "https://sns.eu-west-1.amazonaws.com:8443/SimpleNotificationService-abc.pem",
+ } {
+ if _, err := fx.srv.verifiedCertKey(context.Background(), u); err == nil {
+ t.Errorf("verifiedCertKey(%q) accepted", u)
+ }
+ }
+ if got := fetches.Load(); got != 0 {
+ t.Fatalf("%d fetches for refused shapes, want 0", got)
+ }
+ if _, err := fx.srv.verifiedCertKey(context.Background(), snsCertPath(1)+"#frag"); err != nil {
+ t.Fatalf("a genuine shape was refused: %v", err)
+ }
+}
+
+// A failed URL is not fetched again until its backoff runs out, and the
+// backoff doubles to a ceiling.
+func TestSNSCertFailureIsBackedOff(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fetches := snsCertServer(t, http.StatusNotFound, nil)
+ var off atomic.Int64
+ fx.srv.snsCerts.now = func() time.Time { return time.Now().Add(time.Duration(off.Load())) }
+ for i := 0; i < 5; i++ {
+ if _, err := fx.srv.verifiedCertKey(context.Background(), snsCertPath(7)); err == nil {
+ t.Fatal("a 404 certificate was accepted")
+ }
+ }
+ if got := fetches.Load(); got != 1 {
+ t.Fatalf("five tries of one failing URL made %d fetches, want 1", got)
+ }
+ off.Add(int64(snsCertBackoffBase + time.Second))
+ fx.srv.verifiedCertKey(context.Background(), snsCertPath(7))
+ if got := fetches.Load(); got != 2 {
+ t.Fatalf("after the backoff, %d fetches, want 2", got)
+ }
+ off.Add(int64(snsCertBackoffBase + time.Second)) // the second backoff is twice the first
+ fx.srv.verifiedCertKey(context.Background(), snsCertPath(7))
+ if got := fetches.Load(); got != 2 {
+ t.Fatalf("inside the doubled backoff, %d fetches, want 2", got)
+ }
+ if d := snsCertBackoff(100); d != snsCertBackoffMax {
+ t.Fatalf("backoff after 100 failures = %v, want the ceiling %v", d, snsCertBackoffMax)
+ }
+}
+
+// Identical misses in flight share one fetch, and every caller gets its key.
+func TestSNSCertMissesCoalesce(t *testing.T) {
+ fx := newConsoleFixture(t)
+ gate := make(chan struct{})
+ fetches := snsCertServer(t, http.StatusOK, gate)
+ const n = 8
+ var wg sync.WaitGroup
+ errs := make(chan error, n)
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ _, err := fx.srv.verifiedCertKey(context.Background(), snsCertPath(3))
+ errs <- err
+ }()
+ }
+ for fetches.Load() == 0 {
+ time.Sleep(time.Millisecond)
+ }
+ time.Sleep(20 * time.Millisecond) // let the rest arrive and wait on it
+ close(gate)
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ if err != nil {
+ t.Fatalf("a coalesced caller failed: %v", err)
+ }
+ }
+ if got := fetches.Load(); got != 1 {
+ t.Fatalf("%d identical concurrent misses made %d fetches, want 1", n, got)
+ }
+}
+
// ---- event-to-domain attribution (I6, review follow-up) --------------------
//
// ParseEvent attributes an event by the domain of mail.source. If SES