fix(tls): preserve early API rejection before forwarding upload bodies
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user