carlos / platform Public

edge: bound gate-form body waits so stalls cannot block a home box

A backhauled POST /.carlos/gate held a slot toward its home box while
the home edge waited, with no deadline, for a body the client never
sent; 64 of them answered 503 for every host on that box (hunt H5-M5).

- readLoginBody reads every login body bounded in size and, per request,
  in time (loginBodyTimeout, 10 s), on the judging edge as the -tunnel
  branch already did, and on a sending edge before it takes a slot.
- A client may have at most 8 login bodies outstanding; the next is 429.
- The public servers get IdleTimeout 120 s. No ReadTimeout/WriteTimeout:
  they would cut uploads, held streams and WebSockets.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev b4bbc496aabde03f38f479170b7b2b4bb7ce9822 parent 149a3b8
4 files changed, +413 −40
  • internal/edge/edge.go +129 −36
  • internal/edge/hunt_H5-M5_test.go +146 −0
  • internal/edge/ingressdrain.go +23 −4
  • internal/edge/login_body_test.go +115 −0
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index ca153c571..079112ed1 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -427,6 +427,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
// 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
@@ -2636,9 +2641,11 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// host this box does not serve may be backhauled to the box that homes
// 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 until the host is
- // known to be ours. Placed before the meter so every step below,
- // billing included, sees one settled up.
+ // 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.
+ // Placed before the meter so every step below, billing included, sees
+ // one settled up.
//
// A body that will not parse — over gate.MaxFormBody, or malformed — is
// answered 413 here and never reaches Admit, so it spends no limiter
@@ -2665,39 +2672,21 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
!up.route.IsForward()
if loginPost {
front := up
+ // Read whole, bounded in size and in time (readLoginBody), whoever
+ // judges it. The time bound was once only on the -tunnel branch
+ // below; every other login POST waited on its body for as long as
+ // the client liked, and a backhauled one held a slot toward this
+ // box while it did, so a few unfinished forms shut the hop for
+ // every host this box serves (hunt H5-M5).
+ b, ok := e.readLoginBody(w, r)
+ if !ok {
+ return
+ }
var kept []byte
if front.tenancy.Arm == ArmTunnel && front.route.Gate == "" {
- // The read is bounded in time as well as size
- // (loginBodyTimeout), and 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 (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.
- //
- // On a failed 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.
- rc := http.NewResponseController(w)
- bounded := rc.SetReadDeadline(time.Now().Add(loginBodyReadTimeout)) == nil
- b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, gate.MaxFormBody))
- if err != nil {
- w.Header().Set("Connection", "close")
- http.Error(w, http.StatusText(http.StatusRequestEntityTooLarge), http.StatusRequestEntityTooLarge)
- return
- }
- if bounded {
- rc.SetReadDeadline(time.Time{})
- }
kept = b
- r.Body = io.NopCloser(bytes.NewReader(b))
- } else {
- r.Body = http.MaxBytesReader(w, r.Body, gate.MaxFormBody)
}
+ r.Body = io.NopCloser(bytes.NewReader(b))
if err := r.ParseForm(); err != nil {
http.Error(w, http.StatusText(http.StatusRequestEntityTooLarge), http.StatusRequestEntityTooLarge)
return
@@ -4337,6 +4326,93 @@ const loginBodyTimeout = 10 * time.Second
var loginBodyReadTimeout = loginBodyTimeout
+// 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
+// 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
+// backhaulSharesMaxKeys does; past it a new client is let through
+// untracked, still under the time bound.
+const (
+ loginReadsPerClient = 8
+ loginReadsMaxKeys = 10_000
+)
+
+// 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 backhauls it to another box (backhaulTo) 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
+// 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).
+//
+// 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) {
+ rc := http.NewResponseController(w)
+ if key := loginClientKey(r); key != "" {
+ release, ok := e.loginReadShares().Acquire(key, true, loginReadsPerClient)
+ if !ok {
+ _ = rc.SetReadDeadline(time.Now())
+ w.Header().Set("Connection", "close")
+ writeRateLimited(w, time.Second)
+ return nil, false
+ }
+ defer release()
+ }
+ bounded := rc.SetReadDeadline(time.Now().Add(loginBodyReadTimeout)) == nil
+ b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, gate.MaxFormBody))
+ if err != nil {
+ w.Header().Set("Connection", "close")
+ http.Error(w, http.StatusText(http.StatusRequestEntityTooLarge), http.StatusRequestEntityTooLarge)
+ return nil, false
+ }
+ if bounded {
+ rc.SetReadDeadline(time.Time{})
+ }
+ return 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
+}
+
+// loginClientKey is the client readLoginBody 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 {
+ if _, door := doorCallerFrom(r.Context()); door || fromTunnel(r.Context()) {
+ return ""
+ }
+ if p, ok := ratelimit.ClientKey(clientIP(r)); ok {
+ return p.String()
+ }
+ return ""
+}
+
// loginPassesThrough reports whether a login POST that arrived on front, an
// ungated static -tunnel row, and whose `next` selected target, goes down
// front's tunnel to the box that holds the gate (#471 spec §4.5): only when
@@ -4811,6 +4887,23 @@ func (e *Edge) backhaulTo(w http.ResponseWriter, r *http.Request, host, eip, box
e.logThrottled("backhaul-no-mesh-key", fmt.Sprintf("%s is homed on %s but no mesh key is mirrored — not dialling (the request gets the unknown-host answer until the key lands)", host, box))
return false
}
+ // A login POST's body is read here, before a slot toward the home box
+ // is taken (hopTo), and goes on whole: the home edge reads it the same
+ // way (readLoginBody) and judges it. Streamed instead, a client that
+ // sent the headers and held the body back held a slot for as long as it
+ // 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")
+ }
eip, box = e.backhaulTarget(host, eip, box, owner)
e.backhaulAttempt(w, withForwardAttempts(r), host, eip, box, key, owner, nil)
return true
@@ -5213,10 +5306,10 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
if e.doorPath != "" {
log.Printf("edge: edge-local door off in dev mode")
}
- // ReadHeaderTimeout guards against Slowloris-style slow-header
- // connection exhaustion. No ReadTimeout/WriteTimeout — those would
- // break long-lived proxied WebSockets.
- srv := &http.Server{Addr: *httpAddr, Handler: e, ReadHeaderTimeout: 10 * time.Second}
+ // ReadHeaderTimeout and IdleTimeout as on the public servers, and
+ // for their reasons (publicServers). No ReadTimeout/WriteTimeout —
+ // those would break long-lived proxied WebSockets.
+ srv := &http.Server{Addr: *httpAddr, Handler: e, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: publicIdleTimeout}
// Bound here, on this goroutine, as ListenAndServe would; the line
// below means the bind succeeded.
ln, err := listen("http", *httpAddr, ":http")
diff --git a/internal/edge/hunt_H5-M5_test.go b/internal/edge/hunt_H5-M5_test.go
new file mode 100644
index 000000000..528385676
--- /dev/null
+++ b/internal/edge/hunt_H5-M5_test.go
@@ -0,0 +1,146 @@
+package edge
+
+// Hunt H5-M5 (verifier: opus). A request for a host the sending edge does not
+// serve reserves one per-home-box in-flight slot (backhaulTo ->
+// backhaulAcquire, default cap 64) and holds it until the hop's ServeHTTP
+// returns. The sending edge backhauls a POST /.carlos/gate before any local
+// form parse (the !ok branch runs ahead of the loginPost ParseForm), and the
+// home edge then runs ParseForm before any gate decision, blocking on a body
+// that never arrives. With no body read deadline on either public server,
+// slots stay held. Once the cap is reached, every OTHER hostname homed on
+// that box answers 503 through that edge.
+//
+// Production wiring: two real edges over a real TLS hop. The cap is lowered
+// (the same backhaulMaxInflight seam homemap_test.go uses) so the proof
+// needs a handful of stalled connections, not 64. The secure assertion: a
+// second, unrelated host stays reachable while the stalls are open.
+
+import (
+ "crypto/tls"
+ "net"
+ "net/http"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/gate"
+ "github.com/carlosframework/platform/internal/ratelimit"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+const (
+ huntM5GatedHost = e2eHomedHost // reused name, gated below
+ huntM5OtherHost = e2eMovedHost // a second host homed on the same box
+)
+
+func gateHostOnAnnie(t *testing.T, s *backhaulScene, host, hash string) {
+ t.Helper()
+ routes, err := s.a.edge.reg.List()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var addr string
+ for _, rt := range routes {
+ if rt.Host == host {
+ addr = rt.Addr
+ }
+ }
+ if addr == "" {
+ t.Fatalf("test bug: %s is not a route on annie", host)
+ }
+ if err := s.a.edge.reg.Upsert(registry.Route{Host: host, Kind: "service", Addr: addr, Status: "ready", Gate: hash}); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.a.edge.Reload(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// stallGatePost opens a raw TLS connection to the sending edge, writes a gate
+// POST with a Content-Length it never fulfils, and returns the open conn. The
+// sending edge backhauls it and blocks holding a slot.
+func stallGatePost(t *testing.T, s *backhaulScene, host string) net.Conn {
+ t.Helper()
+ raw, err := net.Dial("tcp", s.b.tlsAddr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ conn := tls.Client(raw, &tls.Config{ServerName: host, RootCAs: s.ca.pool, MinVersion: tls.VersionTLS12})
+ if err := conn.Handshake(); err != nil {
+ raw.Close()
+ t.Fatalf("handshake: %v", err)
+ }
+ req := "POST /.carlos/gate HTTP/1.1\r\nHost: " + host +
+ "\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 4096\r\n\r\npa"
+ if _, err := conn.Write([]byte(req)); err != nil {
+ conn.Close()
+ t.Fatalf("write: %v", err)
+ }
+ return conn
+}
+
+func TestHunt_H5_M5_StalledGatePostsBlockEveryHost(t *testing.T) {
+ const capN = 3
+ old := backhaulMaxInflight.Load()
+ backhaulMaxInflight.Store(capN)
+ t.Cleanup(func() { backhaulMaxInflight.Store(old) })
+
+ s := huntBackhaulScene(t, []string{huntM5GatedHost, huntM5OtherHost})
+ h, err := gate.Hash("correct horse")
+ if err != nil {
+ t.Fatal(err)
+ }
+ gateHostOnAnnie(t, s, huntM5GatedHost, h)
+
+ var conns []net.Conn
+ t.Cleanup(func() {
+ for _, c := range conns {
+ c.Close()
+ }
+ })
+ for i := 0; i < capN; i++ {
+ conns = append(conns, stallGatePost(t, s, huntM5GatedHost))
+ }
+
+ // 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)
+ }
+ 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())
+ }
+
+ resp, _ := s.get(t, s.b, "https://"+huntM5OtherHost+"/", nil, false)
+ if resp.StatusCode == http.StatusServiceUnavailable {
+ t.Fatalf("H5-M5: %d stalled unauthenticated gate POSTs to %s made the unrelated host %s answer %d through the sending edge "+
+ "— a few connections disable an ingress-to-home path for every tenant on that box",
+ capN, huntM5GatedHost, huntM5OtherHost, resp.StatusCode)
+ }
+}
+
+// huntM5StallKey is loginClientKey for stallGatePost's connections, which
+// dial from the default source address.
+func huntM5StallKey(t *testing.T) string {
+ t.Helper()
+ p, ok := ratelimit.ClientKey("127.0.0.1")
+ if !ok {
+ t.Fatal("test bug: no client key for 127.0.0.1")
+ }
+ return p.String()
+}
diff --git a/internal/edge/ingressdrain.go b/internal/edge/ingressdrain.go
index 54370928f..2fbc3f9a3 100644
--- a/internal/edge/ingressdrain.go
+++ b/internal/edge/ingressdrain.go
@@ -89,14 +89,33 @@ func (e *Edge) plainTracked(h http.Handler) http.Handler {
// address :80's health check never reaches plainTracked or the challenge.
//
// ReadHeaderTimeout guards the public front door against Slowloris-style
-// slow-header connection exhaustion. No ReadTimeout/WriteTimeout: those
-// would break long-lived proxied WebSockets.
+// slow-header connection exhaustion. IdleTimeout closes a keep-alive
+// connection that has sat between requests (an HTTP/2 connection with no
+// stream open) for publicIdleTimeout; with none set, Go falls back to
+// ReadTimeout, and with that unset too an idle connection was held for
+// ever. Neither touches a request in progress: a held stream is an open
+// stream, and a WebSocket is a hijacked connection the server no longer
+// times at all.
+//
+// No ReadTimeout/WriteTimeout: they bound a whole request, so they would
+// cut long uploads, edge-held streams and proxied WebSockets. A request
+// whose body the edge must wait on before it can act gets its own deadline
+// instead, on that request alone: the gate's login form (readLoginBody),
+// the burst notice and the HA control paths.
func (e *Edge) publicServers(https, challenge http.Handler, tlsCfg *tls.Config, httpAddr, httpsAddr string) (httpsSrv, httpSrv *http.Server) {
- httpSrv = &http.Server{Addr: httpAddr, Handler: e.plainTracked(challenge), ReadHeaderTimeout: 10 * time.Second}
- httpsSrv = &http.Server{Addr: httpsAddr, Handler: https, TLSConfig: tlsCfg, ReadHeaderTimeout: 10 * time.Second}
+ httpSrv = &http.Server{Addr: httpAddr, Handler: e.plainTracked(challenge), ReadHeaderTimeout: 10 * time.Second, IdleTimeout: publicIdleTimeout}
+ httpsSrv = &http.Server{Addr: httpsAddr, Handler: https, TLSConfig: tlsCfg, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: publicIdleTimeout}
return httpsSrv, httpSrv
}
+// publicIdleTimeout is how long the public servers keep an idle keep-alive
+// connection. Longer than every client transport this deployment points
+// at another edge's public port (the backhaul's, the HA forward's: 90 s
+// IdleConnTimeout), so a sibling edge always retires a pooled connection
+// before this server closes it under a request it has just sent. Browsers
+// reconnect on a closed idle connection as a matter of course.
+const publicIdleTimeout = 120 * time.Second
+
// CloseIngress is step 3's edge half: close the public listeners
// gracefully, waiting up to wait (the connection wait).
//
diff --git a/internal/edge/login_body_test.go b/internal/edge/login_body_test.go
new file mode 100644
index 000000000..46af1f228
--- /dev/null
+++ b/internal/edge/login_body_test.go
@@ -0,0 +1,115 @@
+package edge
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/gate"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// loginBodyScene is one edge serving one gated route, gated.test, on a
+// real net/http server, so per-request read deadlines apply.
+func loginBodyScene(t *testing.T) (*Edge, *httptest.Server) {
+ t.Helper()
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ io.WriteString(w, "the app")
+ }))
+ t.Cleanup(backend.Close)
+ hash, err := gate.Hash("correct horse")
+ if err != nil {
+ t.Fatal(err)
+ }
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: "gated.test", Kind: "service", Status: "ready",
+ Addr: backend.Listener.Addr().String(), Gate: hash}); err != nil {
+ t.Fatal(err)
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ srv := httptest.NewServer(e)
+ t.Cleanup(srv.Close)
+ return e, srv
+}
+
+// stalledLogin sends a login POST to srv whose Content-Length promises the
+// whole form but writes only its first five bytes, and returns the open
+// connection.
+func stalledLogin(t *testing.T, srv *httptest.Server) net.Conn {
+ t.Helper()
+ form := url.Values{"password": {"correct horse"}, "next": {"/"}}.Encode()
+ c, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { c.Close() })
+ fmt.Fprintf(c, "POST %s HTTP/1.1\r\nHost: gated.test\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: %d\r\n\r\n%s",
+ gate.LoginPath, len(form), form[:5])
+ return c
+}
+
+func readAnswer(t *testing.T, c net.Conn, within time.Duration) (*http.Response, time.Duration) {
+ t.Helper()
+ start := time.Now()
+ c.SetReadDeadline(start.Add(within))
+ resp, err := http.ReadResponse(bufio.NewReader(c), nil)
+ if err != nil {
+ t.Fatalf("no answer within %s: %v", within, err)
+ }
+ io.ReadAll(resp.Body)
+ resp.Body.Close()
+ return resp, time.Since(start)
+}
+
+// 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
+// -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 })
+ _, 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)
+ }
+}
+
+// Hunt H5-M5, the per-client bound: a client already holding
+// loginReadsPerClient 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) {
+ e, srv := loginBodyScene(t)
+ for i := 0; i < loginReadsPerClient; 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)
+ }
+ 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)
+ }
+ if got := e.loginReadShares().Held(k); got != loginReadsPerClient {
+ t.Fatalf("the refused login left %d reads counted, want %d", got, loginReadsPerClient)
+ }
+}