fix(tls): flush early API responses before request body teardown

This commit is contained in:
2026-11-22 19:37:57 +03:00
parent 87d71cba8f
commit 3c8db323c4
4 changed files with 50 additions and 5 deletions
+5
View File
@@ -361,6 +361,11 @@ func (l *boundedListener) Accept() (net.Conn, error) {
}
func loopbackProxy(c Config, target *url.URL) *httputil.ReverseProxy {
proxy := httputil.NewSingleHostReverseProxy(target)
if c.Role == "api" {
// Deliver the application's early error before request-body teardown.
// Otherwise a large upload can close the hop before buffered JSON drains.
proxy.FlushInterval = -1
}
director := proxy.Director
proxy.Director = func(r *http.Request) {
director(r)
+29 -4
View File
@@ -17,6 +17,7 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
@@ -24,7 +25,15 @@ import (
type countedBody struct {
io.ReadCloser
bytes *atomic.Int64
bytes *atomic.Int64
release <-chan struct{}
}
func (b *countedBody) Close() error {
if b.release != nil {
<-b.release
}
return b.ReadCloser.Close()
}
func (b *countedBody) Read(data []byte) (int, error) {
@@ -55,21 +64,37 @@ func TestEarlyRejectionDoesNotForwardBodyAndAcceptedBodyStillStreams(t *testing.
proxy := loopbackProxy(Config{Role: "api"}, target)
defer proxy.Transport.(*http.Transport).CloseIdleConnections()
var forwarded atomic.Int64
release := make(chan struct{})
var released sync.Once
unhold := func() { released.Do(func() { close(release) }) }
director := proxy.Director
proxy.Director = func(r *http.Request) {
director(r)
r.Body = &countedBody{ReadCloser: r.Body, bytes: &forwarded}
body := &countedBody{ReadCloser: r.Body, bytes: &forwarded}
if reject {
body.release = release
}
r.Body = body
}
frontend := httptest.NewServer(proxy)
frontend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Connection", "close")
proxy.ServeHTTP(w, r)
}))
defer frontend.Close()
defer unhold()
payload := strings.Repeat("x", 10*1024*1024+1)
client := &http.Client{Timeout: 5 * time.Second}
response, err := client.Post(frontend.URL, "image/png", strings.NewReader(payload))
request, _ := http.NewRequest("POST", frontend.URL, strings.NewReader(payload))
request.Header.Set("Content-Type", "image/png")
request.Close = true
response, err := client.Do(request)
if err != nil {
unhold()
t.Fatal(err)
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
unhold()
if err != nil || response.Header.Get("X-Instance-Id") != "synthetic-api" {
t.Fatalf("incomplete application response: %v", err)
}