carlos / platform Public

edge: burst fix round 1 (bounded read before every refusal, replay set, rotation test)

The no-key refusal answered before reading the body, so net/http drained
an unread body with no deadline and a stalled sender could hold the
connection on a fleet box or a box without a loaded key. The bounded
body read now comes before every refusal. An exact copy of a taken
notice (same timestamp and body, so the same MAC) is refused as a replay
before it takes an acceptance slot or a log line, through a seen set of
at most 600 signatures kept for twice hopSkew. A rotation test takes
sealed notices under the current and the next key.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 0fa5f59c730b5d8ea31aadc33f383ca87bcc2846 parent d1ab27c
2 files changed, +233 −38
  • internal/edge/burst_notice.go +66 −10
  • internal/edge/burst_notice_test.go +167 −28
diff --git a/internal/edge/burst_notice.go b/internal/edge/burst_notice.go
index ed88a6861..a5a518d75 100644
--- a/internal/edge/burst_notice.go
+++ b/internal/edge/burst_notice.go
@@ -107,6 +107,7 @@ type burstNoticeStats struct {
RefusedNotice int64 // malformed, or the client not a canonical /32 or /64
RefusedUntil int64 // expiry passed or more than a cool-down ahead
RefusedCap int64 // over burstNoticeAcceptPerMinute
+ RefusedReplay int64 // an exact copy of a notice already taken
}
// burstTarget is one peer as its edges file publishes it: where to dial and
@@ -131,6 +132,7 @@ type burstPeer struct {
type burstNotices struct {
budget burstWindowCap
accept burstWindowCap
+ seen burstSeen
mu sync.Mutex
peers map[string]*burstPeer
@@ -149,6 +151,7 @@ func newBurstNotices() *burstNotices {
return &burstNotices{
budget: burstWindowCap{n: burstNoticeSendPerMinute},
accept: burstWindowCap{n: burstNoticeAcceptPerMinute},
+ seen: burstSeen{n: burstNoticeAcceptPerMinute, keys: make(map[string]int64)},
peers: make(map[string]*burstPeer),
}
}
@@ -195,6 +198,45 @@ func (c *burstWindowCap) take(clock func() time.Time) (ok bool, now, next time.T
return true, now, time.Time{}
}
+// burstSeen remembers the signatures of recently taken notices, so an exact
+// copy is refused. A signature is only good within hopSkew of its
+// timestamp, so an entry is kept for twice that, which covers a copy
+// arriving at either edge of the skew. It holds at most n, the acceptance
+// cap's worth; at that bound the oldest goes first.
+type burstSeen struct {
+ n int
+ mu sync.Mutex
+ keys map[string]int64 // signature → when it was taken (unix nanos)
+ order []burstSeenEntry // in the order taken, oldest first
+}
+
+type burstSeenEntry struct {
+ key string
+ at int64
+}
+
+// add records key at now and reports whether it was new.
+func (c *burstSeen) add(key string, now time.Time) bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ t := now.UnixNano()
+ if at, ok := c.keys[key]; ok && t-at < int64(2*hopSkew) {
+ return false
+ }
+ // Expired entries come off the front, and at the bound the oldest. An
+ // entry whose key was taken again since is only dropped from the order.
+ for len(c.order) > 0 && (t-c.order[0].at >= int64(2*hopSkew) || len(c.order) >= c.n) {
+ old := c.order[0]
+ c.order = c.order[1:]
+ if c.keys[old.key] == old.at {
+ delete(c.keys, old.key)
+ }
+ }
+ c.keys[key] = t
+ c.order = append(c.order, burstSeenEntry{key: key, at: t})
+ return true
+}
+
// burstNow is the probe-burst clock: the limiter's, so a notice's age, its
// expiry and its signature's timestamp are read on the clock that set them.
func (e *Edge) burstNow() time.Time {
@@ -439,6 +481,7 @@ const (
burstRefusedNotice = "notice"
burstRefusedUntil = "until"
burstRefusedCap = "cap"
+ burstRefusedReplay = "replay"
)
// serveBurstNotice answers a notice from another edge, and reports whether
@@ -457,16 +500,13 @@ func (e *Edge) serveBurstNotice(w http.ResponseWriter, r *http.Request) bool {
if len(auth) == 0 {
return false
}
- n := e.notices
- current, next := e.homes.Load().meshKeys()
- if n == nil || e.burst == nil || e.box == "" || (len(current) == 0 && len(next) == 0) {
- e.refuseBurstNotice(w, r, burstRefusedNoKey)
- return true
- }
- // Bounded in time as well as size, as the login body is (edge.go): a
- // sender that stalls its body must not hold the connection. On a failed
- // read the deadline is left where it is, past for a stall, and the
- // connection is closed after the answer.
+ // The body is read first, bounded in time as well as size as the login
+ // body is (edge.go), before any answer, refusals included: net/http
+ // drains an unread body before it writes the answer, so a refusal that
+ // left it unread would wait on the sender with no deadline at all (the
+ // listeners set only ReadHeaderTimeout). On a failed read the deadline
+ // is left where it is, past for a stall, and the connection is closed
+ // after the answer.
rc := http.NewResponseController(w)
bounded := rc.SetReadDeadline(time.Now().Add(burstNoticeReadTimeout)) == nil
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, burstNoticeMaxBody))
@@ -478,6 +518,12 @@ func (e *Edge) serveBurstNotice(w http.ResponseWriter, r *http.Request) bool {
if bounded {
rc.SetReadDeadline(time.Time{})
}
+ n := e.notices
+ current, next := e.homes.Load().meshKeys()
+ if n == nil || e.burst == nil || e.box == "" || (len(current) == 0 && len(next) == 0) {
+ e.refuseBurstNotice(w, r, burstRefusedNoKey)
+ return true
+ }
now := e.burstNow()
if len(auth) != 1 || !verifyBurstNoticeEitherKey(current, next, e.box, auth[0], body, now) {
e.refuseBurstNotice(w, r, burstRefusedAuth)
@@ -506,6 +552,14 @@ func (e *Edge) serveBurstNotice(w http.ResponseWriter, r *http.Request) bool {
e.refuseBurstNotice(w, r, burstRefusedUntil)
return true
}
+ // An exact copy of a notice already taken (same timestamp, same body,
+ // so the same MAC) is a replay: refused before it takes an acceptance
+ // slot or a log line. The header is lower-cased so a copy with its hex
+ // in capitals is the same copy.
+ if !n.seen.add(strings.ToLower(auth[0]), now) {
+ e.refuseBurstNotice(w, r, burstRefusedReplay)
+ return true
+ }
if ok, _, _ := n.accept.take(e.burstNow); !ok {
e.refuseBurstNotice(w, r, burstRefusedCap)
return true
@@ -541,6 +595,8 @@ func (e *Edge) refuseBurstNotice(w http.ResponseWriter, r *http.Request, reason
s.RefusedUntil++
case burstRefusedCap:
s.RefusedCap++
+ case burstRefusedReplay:
+ s.RefusedReplay++
}
})
}
diff --git a/internal/edge/burst_notice_test.go b/internal/edge/burst_notice_test.go
index a40ca3482..2f578afae 100644
--- a/internal/edge/burst_notice_test.go
+++ b/internal/edge/burst_notice_test.go
@@ -7,6 +7,7 @@ import (
"crypto/rand"
"crypto/tls"
"encoding/base64"
+ "encoding/hex"
"errors"
"fmt"
"io"
@@ -621,34 +622,7 @@ func TestBurstNoticeStalledBodyBounded(t *testing.T) {
s.publish(t)
now := s.clock.now()
auth, body := seal(t, s.key, "betty", now, noticeBody("203.0.113.7/32", now.Add(burstCooldown), "annie", "x"))
-
- conn, err := tls.Dial("tcp", net.JoinHostPort(b.file.ip, s.port), &tls.Config{ServerName: b.file.host, RootCAs: s.ca.pool, NextProtos: []string{"http/1.1"}})
- if err != nil {
- t.Fatal(err)
- }
- defer conn.Close()
- start := time.Now()
- fmt.Fprintf(conn, "POST %s HTTP/1.1\r\nHost: %s\r\n%s: %s\r\nContent-Type: application/octet-stream\r\nContent-Length: %d\r\n\r\n%s",
- burstNoticePath, b.file.host, burstNoticeAuthHeader, auth, len(body), body[:10])
- conn.SetReadDeadline(time.Now().Add(10 * time.Second))
- br := bufio.NewReader(conn)
- resp, err := http.ReadResponse(br, nil)
- if err != nil {
- t.Fatalf("no answer to a stalled body: %v", err)
- }
- io.Copy(io.Discard, resp.Body)
- resp.Body.Close()
- took := time.Since(start)
- if resp.StatusCode != http.StatusNotFound {
- t.Fatalf("a stalled body answered %d, want 404", resp.StatusCode)
- }
- if took < burstNoticeReadTimeout-200*time.Millisecond || took > burstNoticeReadTimeout+time.Second {
- t.Fatalf("answered after %v, want about %v", took, burstNoticeReadTimeout)
- }
- conn.SetReadDeadline(time.Now().Add(time.Second))
- if _, err := br.ReadByte(); !errors.Is(err, io.EOF) {
- t.Fatalf("connection still open after the refusal: %v", err)
- }
+ s.stall(t, b, auth, body)
if _, _, ok := b.edge().burst.cooling(noticePrefix(t, "203.0.113.7")); ok {
t.Fatal("a stalled notice applied")
}
@@ -776,6 +750,164 @@ func TestBurstNoticeRefusesWhatDoesNotOpen(t *testing.T) {
}
}
+// The same on a box without the mesh key (a fleet box, or an edge whose key
+// has not loaded): its refusal still waits no longer than the body deadline.
+func TestBurstNoticeStalledBodyBoundedWithoutAKey(t *testing.T) {
+ s := newNoticeScene(t, false)
+ b := s.add(t, "betty", "127.0.0.12", "blog.example.com", "bab", "blog", true)
+ s.publish(t)
+ key := make([]byte, 32)
+ rand.Read(key)
+ now := s.clock.now()
+ auth, body := seal(t, key, "betty", now, noticeBody("203.0.113.7/32", now.Add(burstCooldown), "annie", strings.Repeat("x", 200)))
+ s.stall(t, b, auth, body)
+ if st := b.edge().notices.stats(); st.RefusedBody != 1 || st.Accepted != 0 {
+ t.Fatalf("betty's counts %+v, want one body refusal", st)
+ }
+}
+
+// stall sends x a notice over a real connection, declaring the whole body
+// and sending ten bytes of it, and checks the answer is a 404 at the body
+// deadline and the connection is closed after it.
+func (s *noticeScene) stall(t *testing.T, x *noticeEdge, auth, body string) {
+ t.Helper()
+ conn, err := tls.Dial("tcp", net.JoinHostPort(x.file.ip, s.port), &tls.Config{ServerName: x.file.host, RootCAs: s.ca.pool, NextProtos: []string{"http/1.1"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ start := time.Now()
+ fmt.Fprintf(conn, "POST %s HTTP/1.1\r\nHost: %s\r\n%s: %s\r\nContent-Type: application/octet-stream\r\nContent-Length: %d\r\n\r\n%s",
+ burstNoticePath, x.file.host, burstNoticeAuthHeader, auth, len(body), body[:10])
+ conn.SetReadDeadline(time.Now().Add(10 * time.Second))
+ br := bufio.NewReader(conn)
+ resp, err := http.ReadResponse(br, nil)
+ if err != nil {
+ t.Fatalf("no answer to a stalled body: %v", err)
+ }
+ io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ took := time.Since(start)
+ if resp.StatusCode != http.StatusNotFound {
+ t.Fatalf("a stalled body answered %d, want 404", resp.StatusCode)
+ }
+ if took < burstNoticeReadTimeout-200*time.Millisecond || took > burstNoticeReadTimeout+time.Second {
+ t.Fatalf("answered after %v, want about %v", took, burstNoticeReadTimeout)
+ }
+ conn.SetReadDeadline(time.Now().Add(time.Second))
+ if _, err := br.ReadByte(); !errors.Is(err, io.EOF) {
+ t.Fatalf("connection still open after the refusal: %v", err)
+ }
+}
+
+// A delivered notice delivered again, byte for byte, is a replay: refused
+// and counted, taking no acceptance slot, leaving the cool-down as it was
+// and sending nothing on.
+func TestBurstNoticeReplayRefused(t *testing.T) {
+ s := newNoticeScene(t, true)
+ s.add(t, "annie", "127.0.0.11", "shop.example.com", "bdk", "shop", true)
+ b := s.add(t, "betty", "127.0.0.12", "blog.example.com", "bab", "blog", true)
+ s.publish(t)
+ now := s.clock.now()
+ until := now.Add(burstCooldown)
+ auth, body := seal(t, s.key, "betty", now, noticeBody("203.0.113.7/32", until, "annie", "x"))
+ if w := b.post(auth, body); w.Code != http.StatusNoContent {
+ t.Fatalf("first delivery answered %d, want 204", w.Code)
+ }
+ s.clock.advance(10 * time.Second)
+ ts, sig, _ := strings.Cut(auth, ":")
+ for name, a := range map[string]string{"the same bytes": auth, "its hex in capitals": ts + ":" + strings.ToUpper(sig)} {
+ if w := b.post(a, body); w.Code != http.StatusNotFound {
+ t.Errorf("%s again: answered %d, want 404", name, w.Code)
+ }
+ }
+ got, _, ok := b.edge().burst.cooling(noticePrefix(t, "203.0.113.7"))
+ if !ok || !got.Equal(until) {
+ t.Fatalf("after the replays the client cools until %v (%v), want %v unchanged", got, ok, until)
+ }
+ if st := b.edge().notices.stats(); st.Accepted != 1 || st.RefusedReplay != 2 || st.RefusedCap != 0 {
+ t.Fatalf("betty's counts %+v, want one accepted and two replays", st)
+ }
+ if n := transmitted(b); n != 0 || b.edge().notices.peerCount() != 0 {
+ t.Fatalf("betty sent %d notices on after a replay", n)
+ }
+ // The window holds one: the replays took no slot.
+ if b.edge().notices.accept.count() != 1 {
+ t.Fatalf("the acceptance window holds %d, want 1", b.edge().notices.accept.count())
+ }
+}
+
+// The seen set stays within its bound and forgets after twice hopSkew.
+func TestBurstNoticeSeenBounded(t *testing.T) {
+ c := burstSeen{n: burstNoticeAcceptPerMinute, keys: make(map[string]int64)}
+ now := time.Date(2026, 10, 31, 12, 0, 0, 0, time.UTC)
+ for i := range burstNoticeAcceptPerMinute + 1 {
+ if !c.add(fmt.Sprint(i), now) {
+ t.Fatalf("key %d refused as seen", i)
+ }
+ }
+ if len(c.keys) != burstNoticeAcceptPerMinute || len(c.order) != burstNoticeAcceptPerMinute {
+ t.Fatalf("holds %d keys, %d in order, want %d", len(c.keys), len(c.order), burstNoticeAcceptPerMinute)
+ }
+ if c.add("600", now) {
+ t.Fatal("the newest key was not remembered")
+ }
+ if !c.add("0", now) {
+ t.Fatal("the oldest key was not the one evicted at the bound")
+ }
+ if c.add("5", now.Add(2*hopSkew-time.Nanosecond)) {
+ t.Fatal("a key was forgotten inside twice hopSkew")
+ }
+ if !c.add("5", now.Add(2*hopSkew)) {
+ t.Fatal("a key was remembered past twice hopSkew")
+ }
+ if len(c.keys) > burstNoticeAcceptPerMinute || len(c.order) > burstNoticeAcceptPerMinute {
+ t.Fatalf("holds %d keys after expiry", len(c.keys))
+ }
+}
+
+// A rotation: with .next mirrored, the receiver takes notices sealed and
+// signed under either key, and a trip's notice (now under .next, as
+// signingKey prefers) still applies.
+func TestBurstNoticeRotation(t *testing.T) {
+ s := newNoticeScene(t, true)
+ a := s.add(t, "annie", "127.0.0.11", "shop.example.com", "bdk", "shop", true)
+ b := s.add(t, "betty", "127.0.0.12", "blog.example.com", "bab", "blog", true)
+ next := make([]byte, meshKeyBytes)
+ rand.Read(next)
+ putJSON(t, s.seed, meshKeyNextKey, hex.EncodeToString(next))
+ s.publish(t)
+ cur, gotNext := b.be.homes.meshKeys()
+ if len(cur) == 0 || !bytes.Equal(gotNext, next) {
+ t.Fatal("test bug: betty does not mirror both keys")
+ }
+ now := s.clock.now()
+ other := make([]byte, meshKeyBytes)
+ rand.Read(other)
+ for i, c := range []struct {
+ name string
+ key []byte
+ want int
+ }{{"current", cur, http.StatusNoContent}, {"next", next, http.StatusNoContent}, {"unknown", other, http.StatusNotFound}} {
+ client := fmt.Sprintf("203.0.113.%d", i+1)
+ if w := b.post(seal(t, c.key, "betty", now, noticeBody(client+"/32", now.Add(burstCooldown), "annie", "x"))); w.Code != c.want {
+ t.Errorf("sealed and signed under the %s key: answered %d, want %d", c.name, w.Code, c.want)
+ }
+ }
+ s.trip(t, a, "203.0.113.9")
+ waitFor(t, 5*time.Second, "betty applies a notice sent under .next", func() bool {
+ _, _, ok := b.edge().burst.cooling(noticePrefix(t, "203.0.113.9"))
+ return ok
+ })
+ wire := b.wireBodies()
+ if len(wire) != 1 {
+ t.Fatalf("betty saw %d notices over the wire, want 1", len(wire))
+ }
+ if _, ok := openBurstNotice(nil, next, "betty", fmt.Sprint(now.Unix()), wire[0]); !ok {
+ t.Fatal("the trip's notice was not sealed under .next")
+ }
+}
+
// The path alone is not a notice: without the header it is the app's.
func TestBurstNoticePathWithoutAuthReachesApp(t *testing.T) {
s := newNoticeScene(t, true)
@@ -901,3 +1033,10 @@ func (n *burstNotices) peerCount() int {
defer n.mu.Unlock()
return len(n.peers)
}
+
+// count is how many admissions the window holds.
+func (c *burstWindowCap) count() int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return len(c.at)
+}