From 2b6f99284da37739e7b11fe0b28b1aefe5dda8c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D1=81=D0=BB=D0=BE=D0=B2?= Date: Sun, 22 Nov 2026 19:16:23 +0300 Subject: [PATCH] fix(tls): preserve early API rejection before forwarding upload bodies --- Dockerfile | 3 +- infra/tls/gateway.go | 25 +++++++++++---- infra/tls/gateway_test.go | 67 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 88 insertions(+), 7 deletions(-) diff --git a/Dockerfile b/Dockerfile index f0f15af..510ec64 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,8 @@ FROM library/golang:1.27.4-alpine@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 AS gateway WORKDIR /source COPY infra/tls/*.go ./ -RUN CGO_ENABLED=0 GOMAXPROCS=2 go build -trimpath -ldflags="-s -w" -o /out/tls-gateway gateway.go +RUN CGO_ENABLED=0 GOMAXPROCS=2 go test -count=1 gateway.go gateway_test.go \ + && CGO_ENABLED=0 GOMAXPROCS=2 go build -trimpath -ldflags="-s -w" -o /out/tls-gateway gateway.go FROM ghcr.io/astral-sh/uv:0.13.7@sha256:96f40d3904aad8d0bd010539001d36c8e2188b981e1334471a90c4a1d93bb490 AS uv FROM python:3.14.7-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d AS builder diff --git a/infra/tls/gateway.go b/infra/tls/gateway.go index 37eee74..e3dbbed 100644 --- a/infra/tls/gateway.go +++ b/infra/tls/gateway.go @@ -359,18 +359,31 @@ func (l *boundedListener) Accept() (net.Conn, error) { } } } -func runHTTP(c Config, b Boundary) error { - target, e := url.Parse("http://" + b.Target) - if e != nil { - return e - } +func loopbackProxy(c Config, target *url.URL) *httputil.ReverseProxy { proxy := httputil.NewSingleHostReverseProxy(target) - proxy.Transport = &http.Transport{MaxIdleConns: 32, MaxIdleConnsPerHost: 16, ResponseHeaderTimeout: 8 * time.Second, IdleConnTimeout: 30 * time.Second} + director := proxy.Director + proxy.Director = func(r *http.Request) { + director(r) + if c.Role == "api" && r.Body != nil && r.Body != http.NoBody { + // Uvicorn sends 100 only when ASGI receives the body. Preserve an + // early JSON 4xx without racing an unnecessary large body write. + r.Header.Set("Expect", "100-continue") + } + } + proxy.Transport = &http.Transport{MaxIdleConns: 32, MaxIdleConnsPerHost: 16, ResponseHeaderTimeout: 8 * time.Second, IdleConnTimeout: 30 * time.Second, ExpectContinueTimeout: time.Second} proxy.ErrorLog = log.New(io.Discard, "", 0) proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) { w.Header().Set("Connection", "close") http.Error(w, "Protected service unavailable", 503) } + return proxy +} +func runHTTP(c Config, b Boundary) error { + target, e := url.Parse("http://" + b.Target) + if e != nil { + return e + } + proxy := loopbackProxy(c, target) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Force a fresh handshake after each response: no indefinitely cached // certificate identity across rollover, expiry or serial revocation. diff --git a/infra/tls/gateway_test.go b/infra/tls/gateway_test.go index 86ebbc9..2910edb 100644 --- a/infra/tls/gateway_test.go +++ b/infra/tls/gateway_test.go @@ -9,14 +9,81 @@ import ( "crypto/x509/pkix" "encoding/json" "encoding/pem" + "io" "math/big" + "net/http" + "net/http/httptest" "net/url" "os" "path/filepath" + "strings" + "sync/atomic" "testing" "time" ) +type countedBody struct { + io.ReadCloser + bytes *atomic.Int64 +} + +func (b *countedBody) Read(data []byte) (int, error) { + n, err := b.ReadCloser.Read(data) + b.bytes.Add(int64(n)) + return n, err +} + +func TestEarlyRejectionDoesNotForwardBodyAndAcceptedBodyStillStreams(t *testing.T) { + for _, reject := range []bool{true, false} { + t.Run(map[bool]string{true: "early_413", false: "accepted_stream"}[reject], func(t *testing.T) { + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("X-Instance-Id", "synthetic-api") + if reject { + w.WriteHeader(413) + io.WriteString(w, `{"error":"payload_too_large"}`) + return + } + data, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + } + w.Write(data) + })) + defer backend.Close() + target, _ := url.Parse(backend.URL) + proxy := loopbackProxy(Config{Role: "api"}, target) + defer proxy.Transport.(*http.Transport).CloseIdleConnections() + var forwarded atomic.Int64 + director := proxy.Director + proxy.Director = func(r *http.Request) { + director(r) + r.Body = &countedBody{ReadCloser: r.Body, bytes: &forwarded} + } + frontend := httptest.NewServer(proxy) + defer frontend.Close() + 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)) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + body, err := io.ReadAll(response.Body) + if err != nil || response.Header.Get("X-Instance-Id") != "synthetic-api" { + t.Fatalf("incomplete application response: %v", err) + } + if reject { + if response.StatusCode != 413 || string(body) != `{"error":"payload_too_large"}` || forwarded.Load() != 0 { + t.Fatalf("early rejection lost: status=%d forwarded=%d", response.StatusCode, forwarded.Load()) + } + } else if response.StatusCode != 200 || string(body) != payload || forwarded.Load() != int64(len(payload)) { + t.Fatal("accepted body was not streamed intact") + } + }) + } +} + type authority struct { cert *x509.Certificate key *ecdsa.PrivateKey