tunnel: refuse a fleet tunnel stream with REFUSED_STREAM (#511 R26)
A fleet box's tunnel can now answer a stream with RST_STREAM REFUSED_STREAM (RFC 9113 §8.7, not processed), which the hub retries on another copy whatever the method. x/net's server has no handler API for that code: a handler that panics with http.ErrAbortHandler gets RST_STREAM INTERNAL_ERROR (handlerPanicRST). So the gate (streamGate, outermost on a fleet tunnel's streams) registers the stream's id, read from x/net's response writer by reflection, and panics; refusingConn, the connection the server writes to, follows frame boundaries and rewrites that one frame's code from INTERNAL_ERROR to REFUSED_STREAM. A stream is refused only by the gate once the drain has begun (replacing drainGate's INTERNAL_ERROR reset), or when its handler called tunnelclient.Refuse and wrote nothing at all (no status, 1xx, byte or flush). Every other reset passes through unchanged. Tests: the stream id against x/net's server, REFUSED_STREAM reaching a real ClientConn for a GET and a 100 KiB POST, no rewrite for a stream that wrote or reset on its own, the gate refusing before its handler, and the frame rewriter split at every byte.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/tunnelclient/drain_test.go+0 −22internal/tunnelclient/refuse.go+228 −0internal/tunnelclient/refuse_test.go+207 −0internal/tunnelclient/upgrade.go+11 −25
Intent
<task-notification> <task-id>a41c5fc02dcfea0c5</task-id> <tool-use-id>toolu_01BofsKmtaFcZvNwptf9ci8a</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/a41c5fc02dcfea0c5.output</output-file> <status>completed</status> <summary>Agent "Fix drill-3 hub routing gaps" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **Status: DONE.** R24 is built and witnessed through the real hub and box wiring. The tip is 03458374, not pushed. - **R24 commits:** ab6a7810 (box: once its edge starts shutting down, a fleet box refuses new tunnel streams and stops redialing), 1650e31c (hub: such a refusal counts as never-reached; single-copy rows on that box get a 503 with Retry-After instead of a bare 502), 03458374 (census re-proposal). Earlier commits: 83ea17bb, 8a629cd6, 214da4fc, 38b1f4b2, ab4cd5c3, be827bfd. - **Witness:** box-00 starts shutdown, and 20 new POSTs and GETs are served by box-01 with zero 503s; none reached box-00's edge. Of the requests box-00 had already accepted, one finishes there, a cut POST is not repeated (502) and a cut GET is retried. The control without the drain gets box-00's 503s, and with the box drain switched off the witness fails. - **Tests:** targeted edge (174 s), tunnelclient, host drain tests, a targeted `-race` run, grouproll, `TestRegionHA` (12 pass) and the three cross-compiles all pass. `make census-card` is clean (seal 8d1de8d6). - **Scope:** HA and fixed-box drains are unchanged. Only a fleet-named tunnel drains, no infra file sets a tunnel name, and nothing touches admission, leases, listeners or the ingress drain. - **Concerns:** - For about one hub-to-box round trip after a drain starts, streams already on the wire are refused by the box but still look possibly reached to the hub. GETs are retried; POSTs get 502. - systemd stops the app about 0.23 s before the edge gets its shutdown signal (region HA spec §25.1). Requests in that gap are accepted before any drain, as today. - Single-copy rows on a draining box now get the hub's "fleet unreachable" 503 instead of the box's own 503. - The box-side proof relies on x/net v0.62 internals; re-run the R22 boundary test and the drain tests on any bump. - `runAgent` has an authority disposition in the census, and Astra's census review is still owed. - **Report** (R24 section appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-4/.superpowers/sdd/2026-11-01-stateless-replicas-4-deploy-and-drill/task-drill3-report.md</result> <usage><subagent_tokens>480481</subagent_tokens><tool_uses>174</tool_uses><duration_ms>4503971</duration_ms></usage> </task-notification>
<task-notification> <task-id>bq8p7vqab</task-id> <tool-use-id>toolu_016ocS1nWX4iXK1RTnMbRJLr</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/bq8p7vqab.output</output-file> <status>completed</status> <summary>Background command "Astra census review of drill-3 card" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>boq6aff09</task-id> <tool-use-id>toolu_01RNd6v3q5JpRvtSvLgsoTv8</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/boq6aff09.output</output-file> <status>completed</status> <summary>Background command "Astra review of drill-3 fixes" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>bi1vf17x2</task-id> <tool-use-id>toolu_01EAKe3U8hJ3eqKHFUWFymYh</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/bi1vf17x2.output</output-file> <status>completed</status> <summary>Background command "Wait for CI on 03458374" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>brhlyivmc</task-id> <tool-use-id>toolu_01HdEhRNygHscdTvT6VVEqyu</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/brhlyivmc.output</output-file> <status>completed</status> <summary>Background command "Fable review of drill-3 fixes" completed (exit code 0)</summary> </task-notification>
diff --git a/internal/tunnelclient/drain_test.go b/internal/tunnelclient/drain_test.go| index b3d9045f2..6976c8824 100644 |
| --- a/internal/tunnelclient/drain_test.go |
| +++ b/internal/tunnelclient/drain_test.go |
| @@ -113,25 +113,3 @@ func TestLoopDrain(t *testing.T) { |
| t.Fatalf("a Loop drained before it started dialed: %d registrations", n) |
| } |
| } |
| - |
| -// TestDrainGateRefusesBeforeHandler: a stream whose handler starts after |
| -// the drain is reset (http.ErrAbortHandler) before the wrapped handler, |
| -// the upgrade shim, the edge, an activator or an app sees it. |
| -func TestDrainGateRefusesBeforeHandler(t *testing.T) { |
| - drain := make(chan struct{}) |
| - var calls atomic.Int32 |
| - g := drainGate{h: http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls.Add(1) }), drain: drain} |
| - g.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil)) |
| - close(drain) |
| - func() { |
| - defer func() { |
| - if r := recover(); r != http.ErrAbortHandler { |
| - t.Fatalf("drained stream: recovered %v, want http.ErrAbortHandler", r) |
| - } |
| - }() |
| - g.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("POST", "/", nil)) |
| - }() |
| - if calls.Load() != 1 { |
| - t.Fatalf("handler calls %d, want only the one before the drain", calls.Load()) |
| - } |
| -} |
diff --git a/internal/tunnelclient/refuse.go b/internal/tunnelclient/refuse.go| new file mode 100644 |
| index 000000000..d55911bfd |
| --- /dev/null |
| +++ b/internal/tunnelclient/refuse.go |
| @@ -0,0 +1,228 @@ |
| +package tunnelclient |
| + |
| +// Refusing a tunnel stream (#511 R26, R27). A fleet box's tunnel can answer |
| +// a stream with RST_STREAM REFUSED_STREAM, which RFC 9113 §8.7 defines as |
| +// "not processed in any way": the hub then sends the request to another |
| +// copy whatever its method. x/net's server has no handler API for that |
| +// code: a handler that panics with http.ErrAbortHandler gets RST_STREAM |
| +// INTERNAL_ERROR (handlerPanicRST, server.go:2329, v0.62.0). So a refused |
| +// stream is reset that way, and refusingConn, the connection the server |
| +// writes to, rewrites that one frame's error code to REFUSED_STREAM. Only |
| +// a stream whose id the gate registered, and whose handler wrote nothing |
| +// at all (no status, no 1xx, no byte, no flush), is ever rewritten. |
| + |
| +import ( |
| + "context" |
| + "encoding/binary" |
| + "net" |
| + "net/http" |
| + "reflect" |
| + "sync" |
| + "sync/atomic" |
| +) |
| + |
| +// HTTP/2 frame header fields (RFC 9113 §4.1) and the codes rewritten. |
| +const ( |
| + frameHeaderLen = 9 |
| + frameRSTStream = 0x3 |
| + codeInternalError = 0x2 |
| + codeRefusedStream = 0x7 |
| +) |
| + |
| +// refusingConn is the tunnel connection as the box's h2 server sees it. It |
| +// follows the frame boundaries of everything the server writes, and in the |
| +// RST_STREAM frame of a stream refuse registered, an INTERNAL_ERROR code |
| +// becomes REFUSED_STREAM. Every other byte passes through unchanged. A |
| +// frame's bytes may span Writes: the four code bytes of a frame being |
| +// rewritten are held until all four have arrived, which they do within the |
| +// same flush, since the server only flushes whole frames. |
| +type refusingConn struct { |
| + net.Conn |
| + mu sync.Mutex |
| + refused map[uint32]bool // stream ids whose RST is to be rewritten |
| + hdr [frameHeaderLen]byte |
| + hn int // header bytes collected for the current frame |
| + rem int // payload bytes left in the current frame |
| + rewrite bool // the current frame is a registered stream's RST_STREAM |
| + code []byte |
| +} |
| + |
| +func newRefusingConn(c net.Conn) *refusingConn { |
| + return &refusingConn{Conn: c, refused: map[uint32]bool{}} |
| +} |
| + |
| +// refuse registers id: its next RST_STREAM INTERNAL_ERROR is rewritten. |
| +func (c *refusingConn) refuse(id uint32) { |
| + c.mu.Lock() |
| + c.refused[id] = true |
| + c.mu.Unlock() |
| +} |
| + |
| +func (c *refusingConn) Write(p []byte) (int, error) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + out := make([]byte, 0, len(p)+4) |
| + for i := 0; i < len(p); { |
| + if c.rem == 0 { |
| + // Collecting a frame header. |
| + n := copy(c.hdr[c.hn:], p[i:]) |
| + out = append(out, p[i:i+n]...) |
| + c.hn += n |
| + i += n |
| + if c.hn < frameHeaderLen { |
| + break |
| + } |
| + c.hn = 0 |
| + length := int(c.hdr[0])<<16 | int(c.hdr[1])<<8 | int(c.hdr[2]) |
| + sid := binary.BigEndian.Uint32(c.hdr[5:9]) & 0x7fffffff |
| + c.rem = length |
| + c.rewrite = c.hdr[3] == frameRSTStream && length == 4 && c.refused[sid] |
| + if c.rewrite { |
| + delete(c.refused, sid) |
| + c.code = c.code[:0] |
| + } |
| + continue |
| + } |
| + n := min(c.rem, len(p)-i) |
| + if !c.rewrite { |
| + out = append(out, p[i:i+n]...) |
| + } else { |
| + c.code = append(c.code, p[i:i+n]...) |
| + if len(c.code) == 4 { |
| + if binary.BigEndian.Uint32(c.code) == codeInternalError { |
| + binary.BigEndian.PutUint32(c.code, codeRefusedStream) |
| + } |
| + out = append(out, c.code...) |
| + c.rewrite = false |
| + } |
| + } |
| + c.rem -= n |
| + i += n |
| + } |
| + if _, err := c.Conn.Write(out); err != nil { |
| + return 0, err |
| + } |
| + return len(p), nil |
| +} |
| + |
| +// refusal is one tunnel stream's refusal capability, on its request's |
| +// context (Refuse, Draining). |
| +type refusal struct { |
| + drain <-chan struct{} |
| + w *trackedWriter |
| + refused atomic.Bool |
| +} |
| + |
| +type refusalKey struct{} |
| + |
| +// Refuse asks the tunnel to refuse r's stream with REFUSED_STREAM, so the |
| +// hub may send the request to another copy whatever its method. It is for |
| +// a request no app has read: the caller must not have written anything |
| +// and must write nothing after a true answer, and return. It answers |
| +// false, and changes nothing, when r did not come over a refusing fleet |
| +// tunnel stream (a static tunnel, a link, the box's own listener) or |
| +// something was already written; the caller then answers as before. |
| +func Refuse(r *http.Request) bool { |
| + ref, _ := r.Context().Value(refusalKey{}).(*refusal) |
| + if ref == nil || ref.w.wrote.Load() { |
| + return false |
| + } |
| + ref.refused.Store(true) |
| + return true |
| +} |
| + |
| +// Draining reports whether ctx is a fleet tunnel stream's request on a box |
| +// whose tunnel has begun its drain (Config.Drain closed). |
| +func Draining(ctx context.Context) bool { |
| + ref, _ := ctx.Value(refusalKey{}).(*refusal) |
| + return ref != nil && closed(ref.drain) |
| +} |
| + |
| +// streamGate is the outermost handler of a fleet tunnel's streams. Once |
| +// the drain has begun, a stream whose handler starts is refused before |
| +// the wrapped handler (the upgrade shim, the box's edge, its activator, |
| +// an app) sees it. Otherwise it serves the stream with a refusal on its |
| +// context, and refuses it after all if the handler asked (Refuse) and |
| +// wrote nothing. |
| +type streamGate struct { |
| + h http.Handler |
| + drain <-chan struct{} |
| + conn *refusingConn |
| +} |
| + |
| +func (g streamGate) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + id, ok := h2StreamID(w) |
| + if !ok { |
| + // Not a stream this gate can name: never refused, served as ever. |
| + g.h.ServeHTTP(w, r) |
| + return |
| + } |
| + if closed(g.drain) { |
| + g.conn.refuse(id) |
| + panic(http.ErrAbortHandler) |
| + } |
| + tw := &trackedWriter{ResponseWriter: w} |
| + ref := &refusal{drain: g.drain, w: tw} |
| + g.h.ServeHTTP(tw, r.WithContext(context.WithValue(r.Context(), refusalKey{}, ref))) |
| + if ref.refused.Load() && !tw.wrote.Load() { |
| + g.conn.refuse(id) |
| + panic(http.ErrAbortHandler) |
| + } |
| +} |
| + |
| +// trackedWriter notes whether anything at all went to the stream: a |
| +// status (1xx included), a byte or a flush. |
| +type trackedWriter struct { |
| + http.ResponseWriter |
| + wrote atomic.Bool |
| +} |
| + |
| +func (t *trackedWriter) WriteHeader(code int) { |
| + t.wrote.Store(true) |
| + t.ResponseWriter.WriteHeader(code) |
| +} |
| + |
| +func (t *trackedWriter) Write(p []byte) (int, error) { |
| + t.wrote.Store(true) |
| + return t.ResponseWriter.Write(p) |
| +} |
| + |
| +func (t *trackedWriter) Flush() { _ = t.FlushError() } |
| + |
| +func (t *trackedWriter) FlushError() error { |
| + t.wrote.Store(true) |
| + return http.NewResponseController(t.ResponseWriter).Flush() |
| +} |
| + |
| +func (t *trackedWriter) Unwrap() http.ResponseWriter { return t.ResponseWriter } |
| + |
| +// h2StreamID is the HTTP/2 stream id behind w, x/net's server response |
| +// writer (v0.62.0: *http2.responseWriter{rws *responseWriterState{stream |
| +// *stream{id uint32}}}), read by reflection: the server exposes no other |
| +// way to name a stream. Any other shape answers false, and the stream is |
| +// then never refused (TestH2StreamIDReadsTheServersStream pins it). |
| +func h2StreamID(w http.ResponseWriter) (uint32, bool) { |
| + v := reflect.ValueOf(w) |
| + if v.Kind() != reflect.Pointer || v.IsNil() { |
| + return 0, false |
| + } |
| + v = v.Elem() |
| + if v.Kind() != reflect.Struct || v.Type().PkgPath() != "golang.org/x/net/http2" || v.Type().Name() != "responseWriter" { |
| + return 0, false |
| + } |
| + for _, name := range []string{"rws", "stream"} { |
| + f := v.FieldByName(name) |
| + if !f.IsValid() || f.Kind() != reflect.Pointer || f.IsNil() { |
| + return 0, false |
| + } |
| + v = f.Elem() |
| + if v.Kind() != reflect.Struct { |
| + return 0, false |
| + } |
| + } |
| + id := v.FieldByName("id") |
| + if !id.IsValid() || id.Kind() != reflect.Uint32 || id.Uint() == 0 { |
| + return 0, false |
| + } |
| + return uint32(id.Uint()), true |
| +} |
diff --git a/internal/tunnelclient/refuse_test.go b/internal/tunnelclient/refuse_test.go| new file mode 100644 |
| index 000000000..027c2e9f0 |
| --- /dev/null |
| +++ b/internal/tunnelclient/refuse_test.go |
| @@ -0,0 +1,207 @@ |
| +package tunnelclient |
| + |
| +import ( |
| + "bytes" |
| + "encoding/binary" |
| + "errors" |
| + "io" |
| + "net" |
| + "net/http" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "golang.org/x/net/http2" |
| +) |
| + |
| +// refuseRig is a box h2 server (serveConn with a drain) and the hub's |
| +// ClientConn on the other end of a pipe. |
| +func refuseRig(t *testing.T, handler http.Handler, drain <-chan struct{}) *http2.ClientConn { |
| + t.Helper() |
| + a, b := net.Pipe() |
| + done := make(chan struct{}) |
| + go func() { defer close(done); serveConn(b, handler, DefaultLimits, drain) }() |
| + cc, err := (&http2.Transport{}).NewClientConn(a) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { cc.Close(); b.Close(); <-done }) |
| + return cc |
| +} |
| + |
| +func refuseDo(t *testing.T, cc *http2.ClientConn, method, body string) (*http.Response, error) { |
| + t.Helper() |
| + var rd io.Reader |
| + if body != "" { |
| + rd = strings.NewReader(body) |
| + } |
| + req, _ := http.NewRequest(method, "https://shop.example.com/", rd) |
| + return cc.RoundTrip(req) |
| +} |
| + |
| +func refusedStream(err error) bool { |
| + var se http2.StreamError |
| + return errors.As(err, &se) && se.Code == http2.ErrCodeRefusedStream |
| +} |
| + |
| +// TestH2StreamIDReadsTheServersStream pins h2StreamID against x/net's own |
| +// server: client streams are 1, 3, 5. |
| +func TestH2StreamIDReadsTheServersStream(t *testing.T) { |
| + ids := make(chan uint32, 3) |
| + // A bare server: the handler gets x/net's own writer. |
| + cc := refuseRig(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + id, _ := h2StreamID(w) |
| + ids <- id |
| + }), nil) |
| + for i := 0; i < 3; i++ { |
| + resp, err := refuseDo(t, cc, "GET", "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + } |
| + for _, want := range []uint32{1, 3, 5} { |
| + if got := <-ids; got != want { |
| + t.Fatalf("stream id %d, want %d", got, want) |
| + } |
| + } |
| + if _, ok := h2StreamID(&trackedWriter{}); ok { |
| + t.Fatal("a writer that is not x/net's named a stream") |
| + } |
| +} |
| + |
| +// TestRefuseSendsRefusedStream (#511 R26, R27): a fleet tunnel stream whose |
| +// handler calls Refuse and writes nothing reaches the hub's ClientConn as |
| +// http2.StreamError{Code: REFUSED_STREAM}, its body included. A stream |
| +// that wrote first is not refused, and a handler's own ErrAbortHandler |
| +// stays INTERNAL_ERROR: only registered streams are rewritten. |
| +func TestRefuseSendsRefusedStream(t *testing.T) { |
| + var refusedAnswer atomic.Bool |
| + cc := refuseRig(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + switch r.Header.Get("X-Mode") { |
| + case "refuse": |
| + refusedAnswer.Store(Refuse(r)) |
| + case "wrote": |
| + w.WriteHeader(503) |
| + if Refuse(r) { |
| + t.Error("Refuse answered true after a status was written") |
| + } |
| + case "abort": |
| + panic(http.ErrAbortHandler) |
| + } |
| + }), make(chan struct{})) |
| + do := func(mode, method, body string) (*http.Response, error) { |
| + req, _ := http.NewRequest(method, "https://shop.example.com/", strings.NewReader(body)) |
| + if body == "" { |
| + req.Body = nil |
| + } |
| + req.Header.Set("X-Mode", mode) |
| + return cc.RoundTrip(req) |
| + } |
| + for _, c := range []struct{ method, body string }{{"GET", ""}, {"POST", strings.Repeat("x", 100<<10)}} { |
| + _, err := do("refuse", c.method, c.body) |
| + // TestRefuseSendsRefusedStream |
| + if !refusedStream(err) || !refusedAnswer.Load() { |
| + t.Fatalf("%s refused: %v (Refuse answered %v)", c.method, err, refusedAnswer.Load()) |
| + } |
| + } |
| + resp, err := do("wrote", "POST", "x") |
| + if err != nil || resp.StatusCode != 503 { |
| + t.Fatalf("a stream that wrote: %v %v", resp, err) |
| + } |
| + resp.Body.Close() |
| + var se http2.StreamError |
| + if _, err := do("abort", "POST", "x"); !errors.As(err, &se) || se.Code != http2.ErrCodeInternal { |
| + t.Fatalf("an unregistered reset: %v, want INTERNAL_ERROR", err) |
| + } |
| + if resp, err := do("", "GET", ""); err != nil || resp.StatusCode != 200 { |
| + t.Fatalf("the connection after refusals: %v %v", resp, err) |
| + } |
| +} |
| + |
| +// TestStreamGateRefusesOnceDraining: a stream whose handler starts after |
| +// the drain is refused with REFUSED_STREAM before the wrapped handler |
| +// runs (the gate alone, with no GOAWAY racing it). |
| +func TestStreamGateRefusesOnceDraining(t *testing.T) { |
| + a, b := net.Pipe() |
| + drain := make(chan struct{}) |
| + var calls atomic.Int32 |
| + rc := newRefusingConn(b) |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + (&http2.Server{}).ServeConn(rc, &http2.ServeConnOpts{Handler: streamGate{h: http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls.Add(1) }), drain: drain, conn: rc}}) |
| + }() |
| + cc, err := (&http2.Transport{}).NewClientConn(a) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer func() { cc.Close(); b.Close(); <-done }() |
| + if resp, err := refuseDo(t, cc, "POST", "before"); err != nil { |
| + t.Fatal(err) |
| + } else { |
| + resp.Body.Close() |
| + } |
| + close(drain) |
| + if _, err := refuseDo(t, cc, "POST", "after"); !refusedStream(err) { |
| + t.Fatalf("a stream after the drain: %v, want REFUSED_STREAM", err) |
| + } |
| + if calls.Load() != 1 { |
| + t.Fatalf("the wrapped handler ran %d times, want only before the drain", calls.Load()) |
| + } |
| +} |
| + |
| +// TestRefusingConnRewritesOnlyRegisteredRST feeds frames split at every |
| +// byte: only the registered stream's RST_STREAM INTERNAL_ERROR changes. |
| +func TestRefusingConnRewritesOnlyRegisteredRST(t *testing.T) { |
| + frame := func(typ byte, sid uint32, payload []byte) []byte { |
| + h := []byte{byte(len(payload) >> 16), byte(len(payload) >> 8), byte(len(payload)), typ, 0, 0, 0, 0, 0} |
| + binary.BigEndian.PutUint32(h[5:], sid) |
| + return append(h, payload...) |
| + } |
| + code := func(c uint32) []byte { b := make([]byte, 4); binary.BigEndian.PutUint32(b, c); return b } |
| + // A DATA frame whose payload looks like an RST header, an RST for an |
| + // unregistered stream, the registered stream's RST, a registered |
| + // stream's RST with another code, an empty frame. |
| + in := bytes.Join([][]byte{ |
| + frame(0x0, 3, frame(frameRSTStream, 5, code(codeInternalError))), |
| + frame(frameRSTStream, 7, code(codeInternalError)), |
| + frame(frameRSTStream, 5, code(codeInternalError)), |
| + frame(frameRSTStream, 9, code(0x8)), |
| + frame(0x4, 0, nil), |
| + }, nil) |
| + want := bytes.Join([][]byte{ |
| + frame(0x0, 3, frame(frameRSTStream, 5, code(codeInternalError))), |
| + frame(frameRSTStream, 7, code(codeInternalError)), |
| + frame(frameRSTStream, 5, code(codeRefusedStream)), |
| + frame(frameRSTStream, 9, code(0x8)), |
| + frame(0x4, 0, nil), |
| + }, nil) |
| + for split := 1; split < len(in); split++ { |
| + var out bytes.Buffer |
| + c := newRefusingConn(writerConn{&out}) |
| + c.refuse(5) |
| + c.refuse(9) |
| + for i := 0; i < len(in); i += split { |
| + end := min(i+split, len(in)) |
| + if n, err := c.Write(in[i:end]); err != nil || n != end-i { |
| + t.Fatalf("split %d: write %d %v", split, n, err) |
| + } |
| + } |
| + if !bytes.Equal(out.Bytes(), want) { |
| + t.Fatalf("split %d:\n got %x\nwant %x", split, out.Bytes(), want) |
| + } |
| + } |
| +} |
| + |
| +type writerConn struct{ w io.Writer } |
| + |
| +func (c writerConn) Write(p []byte) (int, error) { return c.w.Write(p) } |
| +func (writerConn) Read([]byte) (int, error) { return 0, io.EOF } |
| +func (writerConn) Close() error { return nil } |
| +func (writerConn) LocalAddr() net.Addr { return nil } |
| +func (writerConn) RemoteAddr() net.Addr { return nil } |
| +func (writerConn) SetDeadline(time.Time) error { return nil } |
| +func (writerConn) SetReadDeadline(time.Time) error { return nil } |
| +func (writerConn) SetWriteDeadline(time.Time) error { return nil } |
diff --git a/internal/tunnelclient/upgrade.go b/internal/tunnelclient/upgrade.go| index 4110bd4b5..4abf9ed5a 100644 |
| --- a/internal/tunnelclient/upgrade.go |
| +++ b/internal/tunnelclient/upgrade.go |
| @@ -94,20 +94,21 @@ func ServeWith(conn net.Conn, handler http.Handler, l Limits) { |
| serveConn(conn, handler, l, nil) |
| } |
| -// serveConn is ServeWith, refusing new streams once drain closes (#511 |
| -// R24). A nil drain never closes: the server is exactly ServeWith's. |
| +// serveConn is ServeWith for a fleet tunnel when drain is not nil: its |
| +// streams can be refused (refuse.go), and once drain closes it refuses new |
| +// streams (#511 R24, R26). A nil drain serves exactly as ServeWith did. |
| // |
| // Draining refuses at the tunnel, before any handler (the upgrade shim, |
| // the box's edge, its activator or an app) sees a new stream: |
| -// - drainGate: a stream whose handler starts once drain is closed is |
| -// reset (http.ErrAbortHandler, RST_STREAM) before it reaches handler; |
| +// - streamGate: a stream whose handler starts once drain is closed is |
| +// reset with REFUSED_STREAM before the handler it wraps runs; |
| // - a graceful GOAWAY: once the connection's serve goroutine runs |
| // goAway, x/net's processFrame (server.go:1464, v0.62.0) discards |
| // every frame of a stream above the last stream it saw, before |
| -// processHeaders, so no handler starts for it; and the hub's |
| -// ClientConn, once it has read the GOAWAY, refuses new streams |
| -// before writing their HEADERS, which the hub classifies as never |
| -// reached and retries on another copy whatever the method. |
| +// processHeaders, so no handler starts for it; the hub's ClientConn |
| +// aborts such a stream with its "graceful shutdown GOAWAY" error, and |
| +// once it has read the GOAWAY it refuses new streams before writing |
| +// them. The hub retries all three on another copy whatever the method. |
| // |
| // Streams already accepted run to their end: the server closes the |
| // connection only once they are done (goAwayTimeout after the last), or |
| @@ -150,23 +151,8 @@ func serveConn(conn net.Conn, handler http.Handler, l Limits, drain <-chan struc |
| // onShutdown hook (the GOAWAY) and returns. |
| _ = base.Shutdown(context.Background()) |
| }() |
| - srv.ServeConn(conn, &http2.ServeConnOpts{Handler: drainGate{h: handler, drain: drain}, BaseConfig: base}) |
| -} |
| - |
| -// drainGate resets a stream whose handler starts after drain has closed, |
| -// before the handler it wraps runs (serveConn). |
| -type drainGate struct { |
| - h http.Handler |
| - drain <-chan struct{} |
| -} |
| - |
| -func (g drainGate) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| - select { |
| - case <-g.drain: |
| - panic(http.ErrAbortHandler) |
| - default: |
| - } |
| - g.h.ServeHTTP(w, r) |
| + rc := newRefusingConn(conn) |
| + srv.ServeConn(rc, &http2.ServeConnOpts{Handler: streamGate{h: handler, drain: drain, conn: rc}, BaseConfig: base}) |
| } |
| // upgradeShim is the box half of an upgrade, applied by Mark. A request |