edge: bound a login body the HA front forward sends on
The region HA front forward runs before ServeHTTP reads a login body, and copyWholeBody then waited on it unbounded and outside the per-client count (O4 R1, H5-M5). bufferLoginBody is now the one read for every login POST sent to another box: backhaul, path hop and HA forward, before the hop is admitted. copyWholeBody grows with the bytes that arrive instead of allocating the claimed Content-Length up front.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+176
−15
internal/edge/edge.go+32 −3internal/edge/forwardha.go+15 −0internal/edge/hunt_H5-M5_test.go+87 −0internal/edge/pathhop.go+2 −10internal/edge/replay.go+11 −2internal/edge/replay_test.go+29 −0
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index b1d2b7f2a..967efc09c 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -2569,8 +2569,9 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| // it (e.backhaul, above), and that reverse-proxies this very 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 login's body is read by |
| - // backhaulTo itself, which hands it on whole with its length set. |
| + // 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 |
| + // length set. |
| // Placed before the meter so every step below, billing included, sees |
| // one settled up. |
| // |
| @@ -4268,7 +4269,7 @@ func isLoginPost(r *http.Request) bool { |
| // 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 backhauls it to another box (backhaulTo) call it, the second so |
| +// 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). |
| // |
| // The deadline is cleared once the body is in, so a login passed on is not |
| @@ -4312,6 +4313,34 @@ 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. |
| +// |
| +// 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 |
| + } |
| + r.Body = io.NopCloser(bytes.NewReader(b)) |
| + r.ContentLength = int64(len(b)) |
| + r.TransferEncoding = nil |
| + r.Header.Del("Expect") |
| + return true |
| +} |
| + |
| // loginReadShares is e.loginReads, built on first use. |
| func (e *Edge) loginReadShares() *ratelimit.Shares { |
| e.loginReadsOnce.Do(func() { e.loginReads = ratelimit.NewShares(loginReadsMaxKeys) }) |
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go| index 96d08804d..262d4207a 100644 |
| --- a/internal/edge/forwardha.go |
| +++ b/internal/edge/forwardha.go |
| @@ -385,6 +385,21 @@ 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. |
| + if at == nil || at.whole == nil { |
| + if !e.bufferLoginBody(w, r) { |
| + if r.Context().Err() != nil { |
| + res.Outcome = ForwardCanceled |
| + } |
| + return res |
| + } |
| + } |
| marked := false |
| if at != nil && !at.stream { |
| if n == 1 && at.whole == nil { |
diff --git a/internal/edge/hunt_H5-M5_test.go b/internal/edge/hunt_H5-M5_test.go| index 528385676..5c8c03da7 100644 |
| --- a/internal/edge/hunt_H5-M5_test.go |
| +++ b/internal/edge/hunt_H5-M5_test.go |
| @@ -17,8 +17,12 @@ package edge |
| import ( |
| "crypto/tls" |
| + "crypto/x509" |
| + "fmt" |
| "net" |
| "net/http" |
| + "net/url" |
| + "strings" |
| "sync/atomic" |
| "testing" |
| "time" |
| @@ -144,3 +148,86 @@ 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 { |
| + t.Helper() |
| + form := url.Values{"password": {fwPassword}, "next": {"/"}}.Encode() |
| + raw, err := net.Dial("tcp", addr) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + conn := tls.Client(raw, &tls.Config{ServerName: host, RootCAs: pool, MinVersion: tls.VersionTLS12, NextProtos: []string{"http/1.1"}}) |
| + t.Cleanup(func() { conn.Close() }) |
| + if err := conn.Handshake(); err != nil { |
| + 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]) |
| + 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. |
| +func TestStalledLoginForwardedToTheHAHolderIsBounded(t *testing.T) { |
| + old := loginBodyReadTimeout |
| + loginBodyReadTimeout = 300 * time.Millisecond |
| + t.Cleanup(func() { loginBodyReadTimeout = old }) |
| + x := newFwScene(t, fwOpts{}) |
| + |
| + 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) |
| + } |
| + }) |
| + |
| + 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) |
| + } |
| + }) |
| + |
| + 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) |
| + } |
| + 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) |
| + } |
| + }) |
| +} |
diff --git a/internal/edge/pathhop.go b/internal/edge/pathhop.go| index 5521da9a4..90435c122 100644 |
| --- a/internal/edge/pathhop.go |
| +++ b/internal/edge/pathhop.go |
| @@ -6,7 +6,6 @@ package edge |
| // respect but its wire Host and MAC, which stay H's. |
| import ( |
| - "bytes" |
| "context" |
| "fmt" |
| "io" |
| @@ -63,15 +62,8 @@ 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 isLoginPost(r) { |
| - b, ok := e.readLoginBody(w, r) |
| - if !ok { |
| - return true |
| - } |
| - r.Body = io.NopCloser(bytes.NewReader(b)) |
| - r.ContentLength = int64(len(b)) |
| - r.TransferEncoding = nil |
| - r.Header.Del("Expect") |
| + if !e.bufferLoginBody(w, r) { |
| + return true |
| } |
| eip, box = e.backhaulTarget(routeHost, eip, box, owner) |
| e.backhaulAttempt(w, withForwardAttempts(r), wireHost, routeHost, eip, box, key, owner, nil) |
diff --git a/internal/edge/replay.go b/internal/edge/replay.go| index f615c7de3..4a93e5e38 100644 |
| --- a/internal/edge/replay.go |
| +++ b/internal/edge/replay.go |
| @@ -71,6 +71,12 @@ type wholeBody struct{ b []byte } |
| // 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 |
| @@ -78,10 +84,13 @@ func copyWholeBody(r *http.Request) (*wholeBody, error) { |
| if r.ContentLength == 0 { |
| return &wholeBody{}, nil |
| } |
| - b := make([]byte, r.ContentLength) |
| - if _, err := io.ReadFull(r.Body, b); err != 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 |
| } |
diff --git a/internal/edge/replay_test.go b/internal/edge/replay_test.go| index e4c8d3751..49d6ae6da 100644 |
| --- a/internal/edge/replay_test.go |
| +++ b/internal/edge/replay_test.go |
| @@ -1092,3 +1092,32 @@ func TestEarlyAnswerRelaysASlowAnswerWhole(t *testing.T) { |
| slow(t, s.sender.tlsAddr, HAForwardHost, backhaulRootCAs) |
| }) |
| } |
| + |
| +// firstReadSize is a body that records the buffer its first Read is given |
| +// and then ends, having sent one byte of what its Content-Length promised. |
| +type firstReadSize struct{ first int } |
| + |
| +func (f *firstReadSize) Read(p []byte) (int, error) { |
| + if f.first == 0 { |
| + f.first = len(p) |
| + p[0] = 'x' |
| + return 1, nil |
| + } |
| + return 0, io.EOF |
| +} |
| + |
| +// The copy's memory follows the bytes that arrive, not the length the |
| +// client claims (O4 round 1, H5-M5's family): a client that promises |
| +// replayBodyLimit and sends nothing more did not make the edge hold |
| +// replayBodyLimit bytes for it while it waited. |
| +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 { |
| + t.Fatal("a short body copied") |
| + } |
| + if src.first > 4<<10 { |
| + t.Fatalf("the first read had a %d-byte buffer ready for a body that had sent nothing; want it to grow as bytes arrive", src.first) |
| + } |
| +} |