carlos / platform Public

edge: one bounded read for every body an edge buffers to hand on

The HA front forward's replay copy of a non-login body up to 64 KiB still
waited on the client unbounded in time and outside any per-client count
(O4 R2, H5-M5). readBoundedBody is now the one read (size, time, per
client) for every body this edge buffers before a hop: bufferBody admits
a login POST on backhaul, path hop and both HA forwards, and the replay
copy on a front forward's first attempt. copyWholeBody is gone; its
eligibility is replayable. The witness covers each path, including a
non-login POST with a withheld tail.

The H5-M5 tests wait on a read seam (bodyReadHook) instead of polling
with time.Sleep, which the code-health ratchet refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev d17fa61970f17f2cec5b70a6324bebb7fef406c7 parent 124471a
8 files changed, +388 −248
  • internal/edge/edge.go +125 −67
  • internal/edge/forwardha.go +33 −42
  • internal/edge/hunt_H5-M5_test.go +191 −80
  • internal/edge/login_body_test.go +14 −16
  • internal/edge/pathhop.go +1 −1
  • internal/edge/replay.go +8 −28
  • internal/edge/replay_test.go +8 −6
  • internal/edge/tunnel_login_test.go +8 −8
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index 967efc09c..d2f67442b 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -444,11 +444,11 @@ type Edge struct {
// holds, for the fair share in backhaulAcquire. Keyed by box for the
// reason backhaulInflight is; each Shares bounds its own client keys.
backhaulShares sync.Map // box → *ratelimit.Shares
- // loginReads counts, per client, the login POST bodies this edge is
- // still waiting on (readLoginBody), built on first use. Its own Shares,
- // not a box's: the wait happens before any hop is chosen.
- loginReadsOnce sync.Once
- loginReads *ratelimit.Shares
+ // bodyReads counts, per client, the request bodies this edge is still
+ // waiting on (readBoundedBody), built on first use. Its own Shares, not
+ // a box's: the wait happens before any hop is admitted.
+ bodyReadsOnce sync.Once
+ bodyReads *ratelimit.Shares
// The edge-local door (door.go, #175 P7). doorPath and doorAddr come from
// WithEdgeDoor: the socket to listen on ("" = no door, the default) and
// the box's public address, which every door request presents as its
@@ -2570,7 +2570,7 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// draining its body here would send the home box a ContentLength it
// cannot fill, and the hop would 502. Nothing is read here until the
// host is known to be ours; a backhauled or HA-forwarded login's body is
- // read by the sender (bufferLoginBody), which hands it on whole with its
+ // read by the sender (bufferBody), which hands it on whole with its
// length set.
// Placed before the meter so every step below, billing included, sees
// one settled up.
@@ -4237,61 +4237,79 @@ func tunnelProxy(name string, hub *TunnelHub) *httputil.ReverseProxy {
}
}
-// loginBodyTimeout bounds how long the hub waits for the body of a login
-// POST it keeps to pass down a -tunnel row (#471, Task 6 fix round 3). The
+// bodyTimeout bounds how long this edge waits for a request body it reads
+// whole before handing the request on (readBoundedBody): a login POST it
+// judges or sends to another box, and the replay copy of an HA forward. The
// read comes before any rate admission and the production listeners set
// only ReadHeaderTimeout, so without it a client that sends the headers and
-// holds the body back would hold a handler for as long as it liked. The
-// gate has no body timeout of its own to reuse. loginBodyReadTimeout is
-// the value in force; a test shortens it.
-const loginBodyTimeout = 10 * time.Second
+// holds the body back would hold a handler (and whatever it holds in
+// memory) for as long as it liked. The gate has no body timeout of its own
+// to reuse. bodyReadTimeout is the value in force; a test shortens it.
+const bodyTimeout = 10 * time.Second
-var loginBodyReadTimeout = loginBodyTimeout
+var bodyReadTimeout = bodyTimeout
-// loginReadsPerClient is the most login POST bodies one client may have this
-// edge waiting on at once. A real visitor sends a form a few hundred bytes
-// long in the packets behind its headers, so it is waited on for
+// bodyReadsPerClient is the most request bodies one client may have this
+// edge waiting on at once (readBoundedBody). A real visitor sends a form or
+// a small POST in the packets behind its headers, so it is waited on for
// milliseconds and holds one of these at most; only a client holding bodies
// back holds several. The same number as backhaulClientShare, the fair
-// share of a hop. loginReadsMaxKeys bounds the clients tracked, as
+// share of a hop. bodyReadsMaxKeys bounds the clients tracked, as
// backhaulSharesMaxKeys does; past it a new client is let through
-// untracked, still under the time bound.
+// untracked, still under the time and size bounds.
const (
- loginReadsPerClient = 8
- loginReadsMaxKeys = 10_000
+ bodyReadsPerClient = 8
+ bodyReadsMaxKeys = 10_000
)
+// bodyReadHook is a test seam: called with the client key once a body
+// read is admitted (its share held) and before its deadline is set. nil in
+// production.
+var bodyReadHook atomic.Pointer[func(key string)]
+
// isLoginPost reports whether r is a password gate's login POST.
func isLoginPost(r *http.Request) bool {
return r.Method == http.MethodPost && r.URL.Path == gate.LoginPath
}
-// readLoginBody reads a login POST's body whole, bounded in size
-// (gate.MaxFormBody) and in time (loginBodyReadTimeout), or answers on w and
-// reports false. Both the edge that judges the login (ServeHTTP) and an
-// edge that sends it to another box (bufferLoginBody) call it, the second so
-// that no hop slot is held while a client keeps its body back (hunt H5-M5).
+// readBoundedBody is the one way this edge reads a request body whole into
+// memory before it judges the request or hands it to another box or hop
+// (hunt H5-M5, O4 rounds 1 and 2). Every such read is bounded three ways:
+//
+// - in size, by limit (a longer body is answered 413);
+// - in time, by bodyReadTimeout from when the read is admitted;
+// - per client, by bodyReadsPerClient reads waiting at once
+// (bodyClientKey), past which the rate limit's 429 answers at once.
+//
+// The copy grows as the bytes arrive (io.ReadAll), never sized up front
+// from Content-Length, which is only the client's claim (O4 round 1).
+//
+// It reads the body or answers on w and reports false. A body that did not
+// arrive whole in time, or broke off, is answered unreadable (413 for a
+// login, as every unreadable login body has been; 408 for the rest). Its
+// callers are readLoginBody, which ServeHTTP judges a login by, and
+// bufferBody, which every hand-on that buffers goes through. Nothing else
+// in this package reads a client's body whole before sending it on.
//
-// The deadline is cleared once the body is in, so a login passed on is not
-// cut off while the box answers. A writer that cannot set deadlines
+// The deadline is cleared once the body is in, so a request passed on is
+// not cut off while the box answers. A writer that cannot set deadlines
// (ErrNotSupported) reads as before: every listener this edge serves on is a
// net/http server, whose HTTP/1 and HTTP/2 writers both support it, and the
-// wrappers in front of ServeHTTP (the ACME fallback, the door) hand that
-// writer on; what is left is a writer with neither SetReadDeadline nor
-// Unwrap, such as a test's httptest.ResponseRecorder. This per-request
-// deadline is the bound, not a server-wide ReadTimeout, which would also cut
-// long uploads (publicServers).
+// wrappers in front of ServeHTTP (the ACME fallback, the door, a handover
+// exit) hand that writer on; what is left is a writer with neither
+// SetReadDeadline nor Unwrap, such as a test's httptest.ResponseRecorder.
+// This per-request deadline is the bound, not a server-wide ReadTimeout,
+// which would also cut long uploads (publicServers).
//
// On a failed read, and on a refusal before any read, the deadline is left
// in the past: net/http tries to drain an unread body before it writes the
// answer, and that drain must fail at once rather than wait on the client
-// again. The connection is closed after the answer. A failed read is the
-// 413 every unreadable login body has had; a client already holding
-// loginReadsPerClient bodies back gets the rate limit's 429.
-func (e *Edge) readLoginBody(w http.ResponseWriter, r *http.Request) ([]byte, bool) {
+// again. The connection is closed after the answer.
+func (e *Edge) readBoundedBody(w http.ResponseWriter, r *http.Request, limit int64, unreadable int) ([]byte, bool) {
rc := http.NewResponseController(w)
- if key := loginClientKey(r); key != "" {
- release, ok := e.loginReadShares().Acquire(key, true, loginReadsPerClient)
+ key := bodyClientKey(r)
+ if key != "" {
+ release, ok := e.bodyReadShares().Acquire(key, true, bodyReadsPerClient)
if !ok {
_ = rc.SetReadDeadline(time.Now())
w.Header().Set("Connection", "close")
@@ -4300,11 +4318,20 @@ func (e *Edge) readLoginBody(w http.ResponseWriter, r *http.Request) ([]byte, bo
}
defer release()
}
- bounded := rc.SetReadDeadline(time.Now().Add(loginBodyReadTimeout)) == nil
- b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, gate.MaxFormBody))
+ if h := bodyReadHook.Load(); h != nil {
+ (*h)(key)
+ }
+ bounded := rc.SetReadDeadline(time.Now().Add(bodyReadTimeout)) == nil
+ b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, limit))
if err != nil {
+ _ = rc.SetReadDeadline(time.Now())
w.Header().Set("Connection", "close")
- http.Error(w, http.StatusText(http.StatusRequestEntityTooLarge), http.StatusRequestEntityTooLarge)
+ status := unreadable
+ var tooLarge *http.MaxBytesError
+ if errors.As(err, &tooLarge) {
+ status = http.StatusRequestEntityTooLarge
+ }
+ http.Error(w, http.StatusText(status), status)
return nil, false
}
if bounded {
@@ -4313,47 +4340,78 @@ func (e *Edge) readLoginBody(w http.ResponseWriter, r *http.Request) ([]byte, bo
return b, true
}
-// bufferLoginBody is readLoginBody for a login POST this edge passes on to
-// another box rather than judges: the body is read whole under the same
-// bounds, then put back as a copy with its length known, so whatever sends
-// it on (a hop's proxy, the HA forward's replay copy) sends it at once and
-// never waits on the client. Any other request is left untouched. It
-// reports false when it answered on w.
+// readLoginBody is readBoundedBody for a login POST's form, which ServeHTTP
+// judges: at most gate.MaxFormBody, and 413 for any body it cannot read.
+func (e *Edge) readLoginBody(w http.ResponseWriter, r *http.Request) ([]byte, bool) {
+ return e.readBoundedBody(w, r, gate.MaxFormBody, http.StatusRequestEntityTooLarge)
+}
+
+// bufferBody is the body admission of every request this edge hands to
+// another box or hop: whatever body it will hold in memory for that, it
+// reads here, through readBoundedBody, before the hop is admitted and
+// before anything is dialled, and puts back as a copy with its length
+// known, so whatever sends it on sends it at once and never waits on the
+// client. It buffers
//
-// Every edge that sends a login POST to another box calls it before that
-// box's hop is admitted: a backhaul or a path hop (backhaulRouteTo) and a
-// region HA forward (forwardHAObserved). Otherwise a client that sent the
-// headers and held the body back waited there unbounded, outside
-// loginReadsPerClient, and a backhaul held a slot toward the box shared by
-// every host on it while it did (hunt H5-M5, O4 round 1).
-func (e *Edge) bufferLoginBody(w http.ResponseWriter, r *http.Request) bool {
- if !isLoginPost(r) {
- return true
- }
- b, ok := e.readLoginBody(w, r)
- if !ok {
- return false
+// - a login POST, always (readLoginBody's bounds): the receiving edge
+// judges it, and a client holding its body back must hold no slot
+// toward that box meanwhile;
+// - with replay, a body the HA forward copies whole to send again
+// (replayable: none, or a known length up to replayBodyLimit), under
+// its own Content-Length.
+//
+// Any other body is left to stream as it always has, and bufferBody answers
+// nil. Otherwise it answers the copy (empty for no body), which replay
+// sends from. ok is false when it answered on w.
+//
+// Its callers are every hand-on that may buffer: a backhaul and a path hop
+// (backhaulRouteTo, replay false) and both region HA forwards
+// (forwardHAObserved: the front forward with replay on its first attempt,
+// the draining box's streaming release without).
+func (e *Edge) bufferBody(w http.ResponseWriter, r *http.Request, replay bool) (*wholeBody, bool) {
+ var b []byte
+ switch {
+ case isLoginPost(r):
+ var ok bool
+ if b, ok = e.readLoginBody(w, r); !ok {
+ return nil, false
+ }
+ case !replay || !replayable(r):
+ return nil, true
+ case r.ContentLength == 0:
+ return &wholeBody{}, true
+ default:
+ var ok bool
+ if b, ok = e.readBoundedBody(w, r, r.ContentLength, http.StatusRequestTimeout); !ok {
+ return nil, false
+ }
+ if int64(len(b)) < r.ContentLength {
+ // A body shorter than it said: it broke off.
+ w.Header().Set("Connection", "close")
+ http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+ return nil, false
+ }
}
r.Body = io.NopCloser(bytes.NewReader(b))
r.ContentLength = int64(len(b))
r.TransferEncoding = nil
r.Header.Del("Expect")
- return true
+ return &wholeBody{b: b}, true
}
-// loginReadShares is e.loginReads, built on first use.
-func (e *Edge) loginReadShares() *ratelimit.Shares {
- e.loginReadsOnce.Do(func() { e.loginReads = ratelimit.NewShares(loginReadsMaxKeys) })
- return e.loginReads
+// bodyReadShares is e.bodyReads, built on first use.
+func (e *Edge) bodyReadShares() *ratelimit.Shares {
+ e.bodyReadsOnce.Do(func() { e.bodyReads = ratelimit.NewShares(bodyReadsMaxKeys) })
+ return e.bodyReads
}
-// loginClientKey is the client readLoginBody counts r under: the verified
+// bodyClientKey is the client readBoundedBody counts r under: the verified
// client (clientIP: a proven hop's forwarded client, else the connection's
// address) in ratelimit.ClientKey's form, an IPv6 client by its /64. ""
// counts nothing, as backhaulClientKey's "" does and for its reasons: a door
// caller is this box, and a request over a fleet tunnel carries the hub's
// address, shared by every visitor behind it.
-func loginClientKey(r *http.Request) string {
+func bodyClientKey(r *http.Request) string {
if _, door := doorCallerFrom(r.Context()); door || fromTunnel(r.Context()) {
return ""
}
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go
index 262d4207a..07ffae123 100644
--- a/internal/edge/forwardha.go
+++ b/internal/edge/forwardha.go
@@ -256,10 +256,13 @@ func (e *Edge) forwardHAAndNote(w http.ResponseWriter, r *http.Request, host str
return res
}
-// forwardHAStreaming is forwardHAAndNote with the body streamed as today,
-// never copied, marked or replayed: the draining box's release of a
-// client's request to the confirmed holder (§25.5 "Release"), whose
-// every exit must answer without waiting for a body (R3.3).
+// forwardHAStreaming is forwardHAAndNote with the body never copied,
+// marked or replayed: the draining box's release of a client's request to
+// the confirmed holder (§25.5 "Release"). Its exits answer without waiting
+// for a body (R3.3), with one bounded exception: a login POST's body is
+// read first, as on every hand-on (bufferBody), so a released login may
+// wait up to bodyReadTimeout for its form before the hop; any other body
+// streams as today.
func (e *Edge) forwardHAStreaming(w http.ResponseWriter, r *http.Request, host string, rt registry.Route, fw HAForwarder, d ForwardDecision) ForwardResult {
return e.forwardHANoted(w, withForwardAttempts(r), host, rt, fw, d, &forwardAttempt{rt: rt, stream: true})
}
@@ -344,7 +347,7 @@ func (e *Edge) forwardHA(w http.ResponseWriter, r *http.Request, host string, d
// forwardHAObserved is one attempt. With at, it spends one of r's attempts
// (nextForwardAttempt): on the first it copies the body whole when it can
-// (copyWholeBody) and marks the hop replayable, on the second it sends the
+// (bufferBody with replay) and marks the hop replayable, on the second it sends the
// copy unmarked, and it never makes a third. A handover answer to a marked
// first attempt is consumed before the proxy writes anything and, when its
// ref checks out (handoverInRegion), recorded in at.next for the caller to
@@ -385,51 +388,39 @@ func (e *Edge) forwardHAObserved(w http.ResponseWriter, r *http.Request, host st
answerHolderUnreachable(w, r)
return res
}
- // A login POST's body, before anything below sends or copies it and
- // before the hop is admitted (hopTo): read whole under the bounds
- // ServeHTTP's own login read has (bufferLoginBody), which this forward
- // comes before. Once per request: a second attempt sends the copy the
- // first made, and a buffered login is always copied (gate.MaxFormBody
- // is under replayBodyLimit). Refused, it ends as copyWholeBody's
- // failure does, answered before any dial.
+ // The body admission (bufferBody), once per request, before anything
+ // below sends it and before the hop is admitted (hopTo): a login POST's
+ // body always, and on a front forward's first attempt any body it can
+ // copy whole to send again (replayable), read under the one bound
+ // (readBoundedBody: size, time, per client). A second attempt sends the
+ // copy the first made. Refused, it is answered before any dial. Any
+ // other body streams as today.
+ marked := false
if at == nil || at.whole == nil {
- if !e.bufferLoginBody(w, r) {
+ replay := at != nil && !at.stream && n == 1
+ whole, ok := e.bufferBody(w, r, replay)
+ if !ok {
if r.Context().Err() != nil {
res.Outcome = ForwardCanceled
}
+ e.logThrottled("forward-error "+ref, fmt.Sprintf("forward %s → %s: the request body was refused before the hop", name, ref))
return res
}
- }
- marked := false
- if at != nil && !at.stream {
- if n == 1 && at.whole == nil {
- whole, err := copyWholeBody(r)
- if err != nil {
- // The body broke off before it was all here, as it would
- // have while being proxied: the same answer, before any dial.
- if r.Context().Err() != nil {
- res.Outcome = ForwardCanceled
- }
- e.logThrottled("forward-error "+ref, fmt.Sprintf("forward %s → %s: reading the request body: %v", name, ref, err))
- w.WriteHeader(http.StatusBadGateway)
- return res
- }
- if whole != nil {
- at.whole = whole
- if at.orig != nil {
- // For local service, should a handover name this box:
- // the body is the copy again, and its Expect is already
- // met (net/http sent the 100 Continue when the copy was
- // read), so no second interim answer reaches the client.
- at.orig.Body = whole.reader()
- at.orig.Header.Del("Expect")
- }
+ if replay && whole != nil {
+ at.whole = whole
+ if at.orig != nil {
+ // For local service, should a handover name this box:
+ // the body is the copy again, and its Expect is already
+ // met (net/http sent the 100 Continue when the copy was
+ // read), so no second interim answer reaches the client.
+ at.orig.Body = whole.reader()
+ at.orig.Header.Del("Expect")
}
}
- if at.whole != nil {
- marked = n == 1
- r = at.whole.request(r, marked)
- }
+ }
+ if at != nil && !at.stream && at.whole != nil {
+ marked = n == 1
+ r = at.whole.request(r, marked)
}
stopObservation := func() {}
if d.Kind == Holder && note != nil {
diff --git a/internal/edge/hunt_H5-M5_test.go b/internal/edge/hunt_H5-M5_test.go
index 5c8c03da7..ff1bbe279 100644
--- a/internal/edge/hunt_H5-M5_test.go
+++ b/internal/edge/hunt_H5-M5_test.go
@@ -23,6 +23,7 @@ import (
"net/http"
"net/url"
"strings"
+ "sync"
"sync/atomic"
"testing"
"time"
@@ -89,6 +90,7 @@ func TestHunt_H5_M5_StalledGatePostsBlockEveryHost(t *testing.T) {
backhaulMaxInflight.Store(capN)
t.Cleanup(func() { backhaulMaxInflight.Store(old) })
+ reads := watchBodyReads(t)
s := huntBackhaulScene(t, []string{huntM5GatedHost, huntM5OtherHost})
h, err := gate.Hash("correct horse")
if err != nil {
@@ -107,25 +109,10 @@ func TestHunt_H5_M5_StalledGatePostsBlockEveryHost(t *testing.T) {
}
// Wait until all the stalls are open at the sending edge: on the code
- // this test was written against, each then held a backhaul slot (the
- // hunt waited for backhaulInflight to reach the cap); since the fix,
- // each waits for its body in readLoginBody and holds no slot, so wait
- // on whichever comes first.
- deadline := time.Now().Add(5 * time.Second)
- for {
- inflight := int64(0)
- if v, ok := s.b.edge.backhaulInflight.Load("annie"); ok {
- inflight = v.(*atomic.Int64).Load()
- }
- reading := s.b.edge.loginReadShares().Held(huntM5StallKey(t))
- if inflight >= capN || reading >= capN {
- break
- }
- if time.Now().After(deadline) {
- t.Fatalf("stalled POSTs never reached the edge (slots %d, body reads %d of %d)", inflight, reading, capN)
- }
- time.Sleep(20 * time.Millisecond)
- }
+ // this test was written against, each then held a backhaul slot; since
+ // the fix, each waits for its body in readBoundedBody and holds no
+ // slot, and the read seam signals it there.
+ reads.await(t, capN)
if v, ok := s.b.edge.backhaulInflight.Load("annie"); ok && v.(*atomic.Int64).Load() != 0 {
t.Errorf("H5-M5: %d backhaul slots toward annie held by bodies that never arrived", v.(*atomic.Int64).Load())
}
@@ -149,11 +136,72 @@ func huntM5StallKey(t *testing.T) string {
return p.String()
}
-// stallTLSLogin opens a TLS connection to addr for host and writes a login
-// POST whose Content-Length promises the whole form but sends five bytes.
-func stallTLSLogin(t *testing.T, addr, host string, pool *x509.CertPool) net.Conn {
+// bodyReadWatch watches readBoundedBody through bodyReadHook: each admitted
+// read signals arrived, then waits while reads are held.
+type bodyReadWatch struct {
+ arrived chan string
+ mu sync.Mutex
+ hold chan struct{} // nil: reads go on
+}
+
+// watchBodyReads installs the watch for the test's lifetime. Install it
+// before the scene starts serving.
+func watchBodyReads(t *testing.T) *bodyReadWatch {
+ t.Helper()
+ w := &bodyReadWatch{arrived: make(chan string, 1024)}
+ f := func(key string) {
+ w.arrived <- key
+ w.mu.Lock()
+ h := w.hold
+ w.mu.Unlock()
+ if h != nil {
+ <-h
+ }
+ }
+ old := bodyReadHook.Swap(&f)
+ t.Cleanup(func() {
+ w.release()
+ bodyReadHook.Store(old)
+ })
+ return w
+}
+
+// holdReads keeps every read admitted from now on waiting, its share held,
+// until release.
+func (w *bodyReadWatch) holdReads() {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.hold == nil {
+ w.hold = make(chan struct{})
+ }
+}
+
+func (w *bodyReadWatch) release() {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.hold != nil {
+ close(w.hold)
+ w.hold = nil
+ }
+}
+
+// await waits for n more admitted reads.
+func (w *bodyReadWatch) await(t *testing.T, n int) {
+ t.Helper()
+ timeout := time.After(5 * time.Second)
+ for i := 0; i < n; i++ {
+ select {
+ case <-w.arrived:
+ case <-timeout:
+ t.Fatalf("only %d of %d bodies reached the bounded read (readBoundedBody)", i, n)
+ }
+ }
+}
+
+// stallTLSPost opens a TLS connection to addr for host and writes a POST to
+// path whose Content-Length promises body but sends its first five bytes.
+func stallTLSPost(t *testing.T, addr, host string, pool *x509.CertPool, path, body string) net.Conn {
t.Helper()
- form := url.Values{"password": {fwPassword}, "next": {"/"}}.Encode()
raw, err := net.Dial("tcp", addr)
if err != nil {
t.Fatal(err)
@@ -164,70 +212,133 @@ func stallTLSLogin(t *testing.T, addr, host string, pool *x509.CertPool) net.Con
t.Fatalf("handshake: %v", err)
}
fmt.Fprintf(conn, "POST %s HTTP/1.1\r\nHost: %s\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: %d\r\n\r\n%s",
- gate.LoginPath, host, len(form), form[:5])
+ path, host, len(body), body[:5])
return conn
}
-// The front forward's half of hunt H5-M5 (O4 round 1): a login POST for an
-// HA host whose lease another box holds is forwarded before ServeHTTP's
-// own login read, so it must pass the same bounds there: read whole within
-// loginBodyReadTimeout, at most loginReadsPerClient waiting per client,
-// before the hop is admitted. Before, copyWholeBody waited on the body for
-// as long as the client liked, with no per-client count. Through the
-// production wiring: two real edges over a real TLS hop, annie forwarding
-// to betty, the holder.
+// stallTLSLogin is stallTLSPost of a whole login form.
+func stallTLSLogin(t *testing.T, addr, host string, pool *x509.CertPool) net.Conn {
+ t.Helper()
+ return stallTLSPost(t, addr, host, pool, gate.LoginPath, url.Values{"password": {fwPassword}, "next": {"/"}}.Encode())
+}
+
+// huntM5Upload is a non-login POST body: small enough for an HA forward to
+// copy whole (replayBodyLimit).
+var huntM5Upload = strings.Repeat("x", 4<<10)
+
+// A forwarded login still reaches the holder whole once it is buffered.
func TestStalledLoginForwardedToTheHAHolderIsBounded(t *testing.T) {
- old := loginBodyReadTimeout
- loginBodyReadTimeout = 300 * time.Millisecond
- t.Cleanup(func() { loginBodyReadTimeout = old })
x := newFwScene(t, fwOpts{})
+ req, err := http.NewRequest(http.MethodPost, "https://"+fwGatedHost+gate.LoginPath,
+ strings.NewReader(url.Values{"password": {fwPassword}, "next": {"/"}}.Encode()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ c := *x.a.client
+ c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ resp, err := c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusSeeOther || !strings.Contains(resp.Header.Get("Set-Cookie"), gate.CookieName) {
+ t.Fatalf("a whole login: %d %q, want the holder's 303 with the gate cookie", resp.StatusCode, resp.Header.Get("Set-Cookie"))
+ }
+ if got := x.bAct.asked.Load(); got != 0 {
+ t.Fatalf("betty asked its activator %d times; the login should have arrived as a hop", got)
+ }
+}
- t.Run("a whole login still reaches the holder", func(t *testing.T) {
- req, err := http.NewRequest(http.MethodPost, "https://"+fwGatedHost+gate.LoginPath,
- strings.NewReader(url.Values{"password": {fwPassword}, "next": {"/"}}.Encode()))
- if err != nil {
- t.Fatal(err)
- }
- req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- c := *x.a.client
- c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
- resp, err := c.Do(req)
- if err != nil {
- t.Fatal(err)
- }
- resp.Body.Close()
- if resp.StatusCode != http.StatusSeeOther || !strings.Contains(resp.Header.Get("Set-Cookie"), gate.CookieName) {
- t.Fatalf("a whole login: %d %q, want the holder's 303 with the gate cookie", resp.StatusCode, resp.Header.Get("Set-Cookie"))
- }
- if got := x.bAct.asked.Load(); got != 0 {
- t.Fatalf("betty asked its activator %d times; the login should have arrived as a hop", got)
- }
- })
+// bodyBoundCase is one way a client's body is buffered by an edge before
+// that edge hands the request to another box: scene builds it and answers
+// the edge that buffers and how to open a request there whose body never
+// finishes; want is the answer to that request once the time bound passes.
+type bodyBoundCase struct {
+ name string
+ want int
+ scene func(t *testing.T) (*Edge, func(t *testing.T) net.Conn)
+}
- t.Run("a stalled body is answered within the bound", func(t *testing.T) {
- resp, elapsed := readAnswer(t, stallTLSLogin(t, x.a.tlsAddr, fwGatedHost, x.ca.pool), 5*time.Second)
- if resp.StatusCode != http.StatusRequestEntityTooLarge || elapsed > 2*time.Second {
- t.Fatalf("a stalled forwarded login: %d after %s, want 413 within the bound (%s)", resp.StatusCode, elapsed, loginBodyReadTimeout)
- }
- })
+// The body-admission invariant (hunt H5-M5, O4 round 2): every request
+// body an edge buffers before handing the request to another box or hop,
+// login or not, is bounded in time and per client by the one read
+// (readBoundedBody), before any hop is admitted. One witness per path that
+// buffers: a backhaul, an in-region HA front forward (a login, and a
+// non-login POST it copies whole to replay), the same forward for a path
+// route's target, and a draining box's streaming release to the holder.
+// Before round 2 the HA forward's replay copy of a non-login body waited
+// for as long as the client liked, with no per-client count. Every scene is
+// the production wiring: real edges, real TLS, real signed hops.
+func TestEveryBufferedBodyIsBounded(t *testing.T) {
+ cases := []bodyBoundCase{
+ {"backhaul, a login", http.StatusRequestEntityTooLarge, func(t *testing.T) (*Edge, func(*testing.T) net.Conn) {
+ s := huntBackhaulScene(t, []string{huntM5GatedHost, huntM5OtherHost})
+ h, err := gate.Hash(fwPassword)
+ if err != nil {
+ t.Fatal(err)
+ }
+ gateHostOnAnnie(t, s, huntM5GatedHost, h)
+ return s.b.edge, func(t *testing.T) net.Conn { return stallTLSLogin(t, s.b.tlsAddr, huntM5GatedHost, s.ca.pool) }
+ }},
+ {"HA front forward, a login", http.StatusRequestEntityTooLarge, func(t *testing.T) (*Edge, func(*testing.T) net.Conn) {
+ x := newFwScene(t, fwOpts{})
+ return x.a.edge, func(t *testing.T) net.Conn { return stallTLSLogin(t, x.a.tlsAddr, fwGatedHost, x.ca.pool) }
+ }},
+ {"HA front forward, a non-login POST", http.StatusRequestTimeout, func(t *testing.T) (*Edge, func(*testing.T) net.Conn) {
+ x := newFwScene(t, fwOpts{})
+ return x.a.edge, func(t *testing.T) net.Conn {
+ return stallTLSPost(t, x.a.tlsAddr, fwHost, x.ca.pool, "/upload", huntM5Upload)
+ }
+ }},
+ {"path hop to an HA target, a non-login POST", http.StatusRequestTimeout, func(t *testing.T) (*Edge, func(*testing.T) net.Conn) {
+ // C serves T, held by B: a request for H's prefix is
+ // front-forwarded to B under T (TestPathAcrossHATargetFromThirdBox).
+ s := newPathAcrossHAScene(t, acrossHAOpts{target: true, tHolder: "betty", hub: true, hubHolder: "annie"})
+ return s.third.edge, func(t *testing.T) net.Conn {
+ return stallTLSPost(t, s.third.tlsAddr, acrossHub, s.ca.pool, "/acme/upload", huntM5Upload)
+ }
+ }},
+ {"draining box's streaming release, a login", http.StatusRequestEntityTooLarge, func(t *testing.T) (*Edge, func(*testing.T) net.Conn) {
+ x := newHoScene(t)
+ x.mv.mu.Lock()
+ x.mv.phase, x.mv.holder, x.mv.gen = MoveTaken, "betty", 9
+ x.mv.confirm = MoveDecision{Phase: MoveTaken, Holder: "betty", Gen: 9}
+ x.mv.mu.Unlock()
+ return x.a.edge, func(t *testing.T) net.Conn { return stallTLSLogin(t, x.a.tlsAddr, fwGatedHost, x.ca.pool) }
+ }},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ old := bodyReadTimeout
+ bodyReadTimeout = 300 * time.Millisecond
+ t.Cleanup(func() { bodyReadTimeout = old })
+ reads := watchBodyReads(t)
+ e, stall := tc.scene(t)
- t.Run("stalled bodies are bounded per client", func(t *testing.T) {
- loginBodyReadTimeout = time.Minute
- k := huntM5StallKey(t)
- for i := 0; i < loginReadsPerClient; i++ {
- stallTLSLogin(t, x.a.tlsAddr, fwGatedHost, x.ca.pool)
- }
- deadline := time.Now().Add(5 * time.Second)
- for x.a.edge.loginReadShares().Held(k) < loginReadsPerClient {
- if time.Now().After(deadline) {
- t.Fatalf("only %d of %d stalled forwarded logins are counted against their client",
- x.a.edge.loginReadShares().Held(k), loginReadsPerClient)
+ // In time: answered once the bound passes, not held open.
+ resp, elapsed := readAnswer(t, stall(t), 5*time.Second)
+ if resp.StatusCode != tc.want || elapsed > 2*time.Second {
+ t.Fatalf("a body that never finishes: %d after %s, want %d within the bound (%s)", resp.StatusCode, elapsed, tc.want, bodyReadTimeout)
}
- time.Sleep(10 * time.Millisecond)
- }
- resp, elapsed := readAnswer(t, stallTLSLogin(t, x.a.tlsAddr, fwGatedHost, x.ca.pool), 5*time.Second)
- if resp.StatusCode != http.StatusTooManyRequests || elapsed > 2*time.Second {
- t.Fatalf("forwarded login %d from one client: %d after %s, want 429 at once", loginReadsPerClient+1, resp.StatusCode, elapsed)
- }
- })
+ reads.await(t, 1)
+
+ // Per client: with bodyReadsPerClient reads waiting, the next is
+ // refused at once and never read.
+ reads.holdReads()
+ for i := 0; i < bodyReadsPerClient; i++ {
+ stall(t)
+ }
+ reads.await(t, bodyReadsPerClient)
+ k := huntM5StallKey(t)
+ if got := e.bodyReadShares().Held(k); got != bodyReadsPerClient {
+ t.Fatalf("%d bodies counted against their client, want %d", got, bodyReadsPerClient)
+ }
+ resp, elapsed = readAnswer(t, stall(t), 5*time.Second)
+ if resp.StatusCode != http.StatusTooManyRequests || elapsed > 2*time.Second {
+ t.Fatalf("body %d from one client: %d after %s, want 429 at once", bodyReadsPerClient+1, resp.StatusCode, elapsed)
+ }
+ reads.release()
+ })
+ }
}
diff --git a/internal/edge/login_body_test.go b/internal/edge/login_body_test.go
index 46af1f228..3a674fb97 100644
--- a/internal/edge/login_body_test.go
+++ b/internal/edge/login_body_test.go
@@ -73,43 +73,41 @@ func readAnswer(t *testing.T, c net.Conn, within time.Duration) (*http.Response,
}
// Hunt H5-M5, the judging edge's half: a login POST to a gated route whose
-// body never arrives is answered 413 within loginBodyReadTimeout, as the
+// body never arrives is answered 413 within bodyReadTimeout, as the
// -tunnel branch's always was, rather than holding its handler (and, when
// it came over a hop, the sending edge's slot) for as long as the client
// likes.
func TestStalledGatedLoginBodyEndsWithinTheBound(t *testing.T) {
- old := loginBodyReadTimeout
- loginBodyReadTimeout = 300 * time.Millisecond
- t.Cleanup(func() { loginBodyReadTimeout = old })
+ old := bodyReadTimeout
+ bodyReadTimeout = 300 * time.Millisecond
+ t.Cleanup(func() { bodyReadTimeout = old })
_, srv := loginBodyScene(t)
resp, elapsed := readAnswer(t, stalledLogin(t, srv), 5*time.Second)
if resp.StatusCode != http.StatusRequestEntityTooLarge || elapsed > 2*time.Second {
- t.Fatalf("the stalled login: %d after %s, want 413 within the bound (%s)", resp.StatusCode, elapsed, loginBodyReadTimeout)
+ t.Fatalf("the stalled login: %d after %s, want 413 within the bound (%s)", resp.StatusCode, elapsed, bodyReadTimeout)
}
}
// Hunt H5-M5, the per-client bound: a client already holding
-// loginReadsPerClient login bodies back is refused the next one at once,
+// bodyReadsPerClient login bodies back is refused the next one at once,
// with the rate limit's 429, while the time bound is still far off.
func TestLoginBodyReadsAreBoundedPerClient(t *testing.T) {
+ reads := watchBodyReads(t)
e, srv := loginBodyScene(t)
- for i := 0; i < loginReadsPerClient; i++ {
+ for i := 0; i < bodyReadsPerClient; i++ {
stalledLogin(t, srv)
}
k := huntM5StallKey(t)
- deadline := time.Now().Add(5 * time.Second)
- for e.loginReadShares().Held(k) < loginReadsPerClient {
- if time.Now().After(deadline) {
- t.Fatalf("only %d of %d stalled logins reached the edge", e.loginReadShares().Held(k), loginReadsPerClient)
- }
- time.Sleep(10 * time.Millisecond)
+ reads.await(t, bodyReadsPerClient)
+ if got := e.bodyReadShares().Held(k); got != bodyReadsPerClient {
+ t.Fatalf("%d of %d stalled logins are counted against their client", got, bodyReadsPerClient)
}
resp, elapsed := readAnswer(t, stalledLogin(t, srv), 5*time.Second)
if resp.StatusCode != http.StatusTooManyRequests || elapsed > 2*time.Second {
- t.Fatalf("login %d from one client: %d after %s, want 429 at once", loginReadsPerClient+1, resp.StatusCode, elapsed)
+ t.Fatalf("login %d from one client: %d after %s, want 429 at once", bodyReadsPerClient+1, resp.StatusCode, elapsed)
}
- if got := e.loginReadShares().Held(k); got != loginReadsPerClient {
- t.Fatalf("the refused login left %d reads counted, want %d", got, loginReadsPerClient)
+ if got := e.bodyReadShares().Held(k); got != bodyReadsPerClient {
+ t.Fatalf("the refused login left %d reads counted, want %d", got, bodyReadsPerClient)
}
}
diff --git a/internal/edge/pathhop.go b/internal/edge/pathhop.go
index 90435c122..b8bb809bd 100644
--- a/internal/edge/pathhop.go
+++ b/internal/edge/pathhop.go
@@ -62,7 +62,7 @@ func (e *Edge) backhaulRouteTo(w http.ResponseWriter, r *http.Request, wireHost,
// liked, and the box's cap of them (backhaulMaxInflight) is shared by
// every host on that box: a few unfinished forms answered 503 for all
// of them (hunt H5-M5).
- if !e.bufferLoginBody(w, r) {
+ if _, ok := e.bufferBody(w, r, false); !ok {
return true
}
eip, box = e.backhaulTarget(routeHost, eip, box, owner)
diff --git a/internal/edge/replay.go b/internal/edge/replay.go
index 4a93e5e38..a4065ebd3 100644
--- a/internal/edge/replay.go
+++ b/internal/edge/replay.go
@@ -6,8 +6,9 @@ package edge
// time only from a whole copy of its body, and the attempts it makes are
// counted in one place.
//
-// - H2, the copy: copyWholeBody, called once, before the first send. A
-// body is copied whole only when that changes nothing for a request
+// - H2, the copy: bufferBody with replay (edge.go), called once, before
+// the first send, and read under the one body bound (readBoundedBody).
+// A body is copied whole only when that changes nothing for a request
// that is not replayable: no body, or a known Content-Length of at
// most replayBodyLimit. Chunked and unknown-length bodies of any size
// are never read here; they stream as today and are never replayed.
@@ -66,32 +67,11 @@ func nextForwardAttempt(r *http.Request) (n int, ok bool) {
// send.
type wholeBody struct{ b []byte }
-// copyWholeBody is H2's one body preparation. It reads r's body whole
-// when r has no body or a known Content-Length of at most replayBodyLimit,
-// and answers nil, reading nothing, for anything else. An error is a body
-// that could not be read in full (the client left or broke off), and r
-// cannot be sent.
-//
-// The copy grows as the bytes arrive rather than being sized up front from
-// Content-Length, which is only the client's claim: one that promised
-// replayBodyLimit and sent nothing more held that much memory here while
-// the copy waited (O4 round 1). A login POST's body is already in memory
-// when it gets here, read under its own bounds (bufferLoginBody).
-func copyWholeBody(r *http.Request) (*wholeBody, error) {
- if len(r.TransferEncoding) > 0 || r.ContentLength < 0 || r.ContentLength > replayBodyLimit {
- return nil, nil
- }
- if r.ContentLength == 0 {
- return &wholeBody{}, nil
- }
- b, err := io.ReadAll(io.LimitReader(r.Body, r.ContentLength))
- if err != nil {
- return nil, err
- }
- if int64(len(b)) < r.ContentLength {
- return nil, io.ErrUnexpectedEOF
- }
- return &wholeBody{b: b}, nil
+// replayable reports whether r's body may be copied whole to send again:
+// none, or a known Content-Length of at most replayBodyLimit. Chunked and
+// unknown-length bodies of any size never are.
+func replayable(r *http.Request) bool {
+ return len(r.TransferEncoding) == 0 && r.ContentLength >= 0 && r.ContentLength <= replayBodyLimit
}
// reader is a fresh reader over the copy.
diff --git a/internal/edge/replay_test.go b/internal/edge/replay_test.go
index 49d6ae6da..1a315d6af 100644
--- a/internal/edge/replay_test.go
+++ b/internal/edge/replay_test.go
@@ -754,9 +754,11 @@ func TestForwardAttemptsBudget(t *testing.T) {
}
}
-// H2: only no body, or a known length of at most 64 KiB, is copied; an
-// unreadable body is an error; nothing else is read at all.
+// H2: only no body, or a known length of at most 64 KiB, is copied
+// (bufferBody with replay); an unreadable body is refused; nothing else is
+// read at all.
func TestCopyWholeBody(t *testing.T) {
+ e := &Edge{}
for _, tc := range []struct {
name string
n int64
@@ -779,9 +781,9 @@ func TestCopyWholeBody(t *testing.T) {
}
r := httptest.NewRequest(http.MethodPost, "https://"+fwHost+"/", nil)
r.Body, r.ContentLength, r.TransferEncoding = io.NopCloser(src), tc.n, tc.te
- c, err := copyWholeBody(r)
- if (err != nil) != tc.wantErr || (c != nil) != tc.want {
- t.Fatalf("copy %v err %v", c != nil, err)
+ c, ok := e.bufferBody(httptest.NewRecorder(), r, true)
+ if ok == tc.wantErr || (c != nil) != tc.want {
+ t.Fatalf("copy %v refused %v", c != nil, !ok)
}
if !tc.want && !tc.wantErr && src.n != 0 {
t.Fatalf("read %d bytes of a body that is not replayable", src.n)
@@ -1114,7 +1116,7 @@ func TestCopyWholeBodyGrowsWithTheBody(t *testing.T) {
src := &firstReadSize{}
r := httptest.NewRequest(http.MethodPost, "https://"+fwHost+"/", nil)
r.Body, r.ContentLength = io.NopCloser(src), replayBodyLimit
- if _, err := copyWholeBody(r); err == nil {
+ if _, ok := (&Edge{}).bufferBody(httptest.NewRecorder(), r, true); ok {
t.Fatal("a short body copied")
}
if src.first > 4<<10 {
diff --git a/internal/edge/tunnel_login_test.go b/internal/edge/tunnel_login_test.go
index de23adf0f..e9037ffe0 100644
--- a/internal/edge/tunnel_login_test.go
+++ b/internal/edge/tunnel_login_test.go
@@ -226,9 +226,9 @@ func rawLogin(t *testing.T, srv *httptest.Server, host string, sent int) (net.Co
// handler returns (the whole answer arrives and the connection ends);
// nothing reaches the box. The bound is shortened here.
func TestStalledTunnelLoginBodyEndsWithinTheBound(t *testing.T) {
- old := loginBodyReadTimeout
- loginBodyReadTimeout = 300 * time.Millisecond
- t.Cleanup(func() { loginBodyReadTimeout = old })
+ old := bodyReadTimeout
+ bodyReadTimeout = 300 * time.Millisecond
+ t.Cleanup(func() { bodyReadTimeout = old })
srv, _, _, box, _ := tunnelLoginScene(t, false)
c, form := rawLogin(t, srv, tlFront, 5)
@@ -245,7 +245,7 @@ func TestStalledTunnelLoginBodyEndsWithinTheBound(t *testing.T) {
t.Fatalf("the answer did not complete: %v", err)
}
if elapsed := time.Since(start); resp.StatusCode != http.StatusRequestEntityTooLarge || elapsed > 2*time.Second {
- t.Fatalf("the stalled login: %d after %s, want 413 within the bound (%s) and well inside 2 s", resp.StatusCode, elapsed, loginBodyReadTimeout)
+ t.Fatalf("the stalled login: %d after %s, want 413 within the bound (%s) and well inside 2 s", resp.StatusCode, elapsed, bodyReadTimeout)
}
if got := box.take(); len(got) != 0 {
t.Fatalf("the box saw %q", got)
@@ -288,9 +288,9 @@ func TestStalledTunnelLoginBodyEndsWithinTheBound(t *testing.T) {
// tunnel whose box answers well after the bound is still answered, and
// the connection serves a second request.
func TestPassedLoginOutlivesTheBodyDeadline(t *testing.T) {
- old := loginBodyReadTimeout
- loginBodyReadTimeout = 200 * time.Millisecond
- t.Cleanup(func() { loginBodyReadTimeout = old })
+ old := bodyReadTimeout
+ bodyReadTimeout = 200 * time.Millisecond
+ t.Cleanup(func() { bodyReadTimeout = old })
srv, _, _, box, _ := tunnelLoginScene(t, false)
hold := make(chan struct{})
box.mu.Lock()
@@ -301,7 +301,7 @@ func TestPassedLoginOutlivesTheBodyDeadline(t *testing.T) {
// The one wall-clock wait: the box holds its answer until well past
// the bound, which is what a deadline left set would cut off. The
// deadline is the subject, so time has to pass.
- time.Sleep(3 * loginBodyReadTimeout)
+ time.Sleep(3 * bodyReadTimeout)
close(hold)
c.SetReadDeadline(time.Now().Add(5 * time.Second))
br := bufio.NewReader(c)