From 5b60b6026401c674c0244d3219ae1953430dc870 Mon Sep 17 00:00:00 2001 From: Twiink Date: Wed, 2 Dec 2026 18:36:45 +0800 Subject: [PATCH 1/5] =?UTF-8?q?fix(proxy):=20=E9=87=8D=E8=AF=95=E6=97=B6?= =?UTF-8?q?=E9=87=8D=E5=BB=BA=E5=8F=AF=E5=9B=9E=E6=94=BE=E7=9A=84=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E6=AD=A3=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/proxy.go | 7 +++++ middleware/proxy_test.go | 59 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/middleware/proxy.go b/middleware/proxy.go index 34d361ac1..fd0c50780 100644 --- a/middleware/proxy.go +++ b/middleware/proxy.go @@ -333,6 +333,13 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { // This is needed for ProxyConfig.ModifyResponse and/or ProxyConfig.Transport to be able to process the Request // that Balancer may have replaced with c.SetRequest. req = c.Request() + if retries < config.RetryCount && req.GetBody != nil { + body, bodyErr := req.GetBody() + if bodyErr != nil { + return config.ErrorHandler(c, bodyErr) + } + req.Body = body + } // ReverseProxy validates upgrades and closes both sides when a tunnel ends. proxyHTTP(c, tgt, config, clientIP, scheme).ServeHTTP(res, req) diff --git a/middleware/proxy_test.go b/middleware/proxy_test.go index 4903d9841..10666610a 100644 --- a/middleware/proxy_test.go +++ b/middleware/proxy_test.go @@ -1428,3 +1428,62 @@ func TestProxy_DotSegmentsAfterRouting(t *testing.T) { assert.True(t, called) }) } + +func TestProxyRetryReplaysBody(t *testing.T) { + e := echo.New() + target, err := url.Parse("http://upstream.example.test") + assert.NoError(t, err) + attempts := 0 + transport := proxyRetryBodyTransport(func(req *http.Request) (*http.Response, error) { + attempts++ + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + _ = req.Body.Close() + assert.Equal(t, "request payload", string(body), "attempt %d", attempts) + if attempts == 1 { + return nil, errors.New("temporary transport failure") + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("ok"))}, nil + }) + handler := ProxyWithConfig(ProxyConfig{Balancer: NewRoundRobinBalancer([]*ProxyTarget{{URL: target}}), RetryCount: 1, Transport: transport})(func(*echo.Context) error { return nil }) + req, err := http.NewRequest(http.MethodPost, "http://proxy.example.test/", strings.NewReader("request payload")) + assert.NoError(t, err) + rec := httptest.NewRecorder() + err = handler(e.NewContext(req, rec)) + assert.NoError(t, err) + assert.Equal(t, 2, attempts) + assert.Equal(t, "ok", rec.Body.String()) +} + +func TestProxyRetryGetBodyError(t *testing.T) { + e := echo.New() + target, err := url.Parse("http://upstream.example.test") + assert.NoError(t, err) + sentinel := errors.New("cannot reopen request body") + attempts := 0 + transport := proxyRetryBodyTransport(func(req *http.Request) (*http.Response, error) { + attempts++ + _, _ = io.Copy(io.Discard, req.Body) + _ = req.Body.Close() + return nil, errors.New("temporary transport failure") + }) + var handled error + handler := ProxyWithConfig(ProxyConfig{ + Balancer: NewRoundRobinBalancer([]*ProxyTarget{{URL: target}}), + RetryCount: 1, Transport: transport, + ErrorHandler: func(_ *echo.Context, err error) error { handled = err; return err }, + })(func(*echo.Context) error { return nil }) + req, err := http.NewRequest(http.MethodPost, "http://proxy.example.test/", strings.NewReader("payload")) + assert.NoError(t, err) + req.GetBody = func() (io.ReadCloser, error) { return nil, sentinel } + err = handler(e.NewContext(req, httptest.NewRecorder())) + assert.ErrorIs(t, err, sentinel) + assert.ErrorIs(t, handled, sentinel) + assert.Equal(t, 1, attempts) +} + +type proxyRetryBodyTransport func(*http.Request) (*http.Response, error) + +func (f proxyRetryBodyTransport) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } From 169b3354e60d957223585d7a41a215e5fb9791ef Mon Sep 17 00:00:00 2001 From: Twiink Date: Wed, 2 Dec 2026 19:26:53 +0800 Subject: [PATCH 2/5] =?UTF-8?q?fix(proxy):=20=E4=BF=9D=E7=95=99=E8=B4=9F?= =?UTF-8?q?=E8=BD=BD=E5=9D=87=E8=A1=A1=E5=99=A8=E6=8F=90=E4=BE=9B=E7=9A=84?= =?UTF-8?q?=E9=87=8D=E8=AF=95=E6=AD=A3=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/proxy.go | 13 ++- middleware/proxy_retry_balancer_test.go | 148 ++++++++++++++++++++++++ 2 files changed, 160 insertions(+), 1 deletion(-) create mode 100644 middleware/proxy_retry_balancer_test.go diff --git a/middleware/proxy.go b/middleware/proxy.go index fd0c50780..9cad495b0 100644 --- a/middleware/proxy.go +++ b/middleware/proxy.go @@ -34,6 +34,7 @@ type ProxyConfig struct { // RetryCount defines the number of times a failed proxied request should be retried // using the next available ProxyTarget. Defaults to 0, meaning requests are never retried. + // Retrying can repeat upstream side effects; use RetryFilter to select operations that are safe to retry. RetryCount int // RetryFilter defines a function used to determine if a failed request to a @@ -312,6 +313,7 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { req.Header.Del("Forwarded") retries := config.RetryCount + var previousBody *proxyRetryBody for { tgt, err := config.Balancer.Next(c) if err != nil { @@ -333,13 +335,18 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { // This is needed for ProxyConfig.ModifyResponse and/or ProxyConfig.Transport to be able to process the Request // that Balancer may have replaced with c.SetRequest. req = c.Request() - if retries < config.RetryCount && req.GetBody != nil { + if previousBody != nil && req.Body == previousBody && req.GetBody != nil { body, bodyErr := req.GetBody() if bodyErr != nil { return config.ErrorHandler(c, bodyErr) } req.Body = body } + if retries > 0 && req.Body != nil && req.Body != http.NoBody { + // Mark the body forwarded by this attempt. A balancer may supply a fresh body on the next attempt. + previousBody = &proxyRetryBody{ReadCloser: req.Body} + req.Body = previousBody + } // ReverseProxy validates upgrades and closes both sides when a tunnel ends. proxyHTTP(c, tgt, config, clientIP, scheme).ServeHTTP(res, req) @@ -360,6 +367,10 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { }, nil } +type proxyRetryBody struct { + io.ReadCloser +} + // StatusCodeContextCanceled is a custom HTTP status code for situations // where a client unexpectedly closed the connection to the server. // As there is no standard error code for "client closed connection", but diff --git a/middleware/proxy_retry_balancer_test.go b/middleware/proxy_retry_balancer_test.go new file mode 100644 index 000000000..27c341130 --- /dev/null +++ b/middleware/proxy_retry_balancer_test.go @@ -0,0 +1,148 @@ +package middleware + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/labstack/echo/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestProxyRetryPreservesBalancerBody(t *testing.T) { + for _, replaceRequest := range []bool{false, true} { + for _, failGetBody := range []bool{false, true} { + name := "same request" + if replaceRequest { + name = "replacement request" + } + if failGetBody { + name += "/GetBody error" + } + t.Run(name, func(t *testing.T) { + e := echo.New() + target, err := url.Parse("http://upstream.example.test") + require.NoError(t, err) + original := &proxyBodyCloseCounter{Reader: strings.NewReader("original payload")} + fresh := &proxyBodyCloseCounter{Reader: strings.NewReader("balancer payload")} + req := httptest.NewRequest(http.MethodPost, "http://proxy.example.test/", nil) + req.Body = original + req.ContentLength = int64(len("original payload")) + attempts, selections, getBodyCalls := 0, 0, 0 + balancer := &proxyBodyReplacingBalancer{ + ProxyBalancer: NewRoundRobinBalancer([]*ProxyTarget{{URL: target}}), + beforeNext: func(c *echo.Context) { + selections++ + if selections != 2 { + return + } + r := c.Request() + if replaceRequest { + r = r.Clone(r.Context()) + } + r.Body = fresh + r.ContentLength = int64(len("balancer payload")) + r.GetBody = func() (io.ReadCloser, error) { + getBodyCalls++ + if failGetBody { + return nil, errors.New("fresh body does not need reopening") + } + return io.NopCloser(strings.NewReader("unused replay")), nil + } + c.SetRequest(r) + }, + } + transport := proxyRetryBodyTransport(func(r *http.Request) (*http.Response, error) { + attempts++ + b, readErr := io.ReadAll(r.Body) + require.NoError(t, readErr) + if attempts == 1 { + require.Equal(t, "original payload", string(b)) + return nil, errors.New("temporary transport failure") + } + assert.Equal(t, "balancer payload", string(b)) + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("ok"))}, nil + }) + handler := ProxyWithConfig(ProxyConfig{Balancer: balancer, RetryCount: 1, Transport: transport})(func(*echo.Context) error { return nil }) + err = handler(e.NewContext(req, httptest.NewRecorder())) + assert.NoError(t, err) + assert.Equal(t, 2, attempts) + assert.Zero(t, getBodyCalls, "a new body supplied by the balancer must be forwarded as supplied") + assert.Equal(t, 1, original.closes) + assert.Equal(t, 1, fresh.closes) + }) + } + } +} + +func TestProxyRetryReplaysClonedRequestBody(t *testing.T) { + e := echo.New() + target, err := url.Parse("http://upstream.example.test") + require.NoError(t, err) + original := &proxyBodyCloseCounter{Reader: strings.NewReader("payload")} + bodies := []*proxyBodyCloseCounter{original} + req := httptest.NewRequest(http.MethodPost, "http://proxy.example.test/", nil) + // Non-comparable implementations are valid io.ReadClosers too. + req.Body = proxyUncomparableBody{ReadCloser: original} + req.ContentLength = int64(len("payload")) + req.GetBody = func() (io.ReadCloser, error) { + body := &proxyBodyCloseCounter{Reader: strings.NewReader("payload")} + bodies = append(bodies, body) + return proxyUncomparableBody{ReadCloser: body}, nil + } + attempts := 0 + balancer := &proxyBodyReplacingBalancer{ + ProxyBalancer: NewRoundRobinBalancer([]*ProxyTarget{{URL: target}}), + beforeNext: func(c *echo.Context) { + c.SetRequest(c.Request().WithContext(context.WithValue(c.Request().Context(), testContextKey("attempt"), attempts))) + }, + } + transport := proxyRetryBodyTransport(func(r *http.Request) (*http.Response, error) { + attempts++ + b, readErr := io.ReadAll(r.Body) + require.NoError(t, readErr) + require.Equal(t, "payload", string(b)) + if attempts < 3 { + return nil, errors.New("temporary transport failure") + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("ok"))}, nil + }) + handler := ProxyWithConfig(ProxyConfig{Balancer: balancer, RetryCount: 2, Transport: transport})(func(*echo.Context) error { return nil }) + require.NoError(t, handler(e.NewContext(req, httptest.NewRecorder()))) + require.Equal(t, 3, attempts) + require.Len(t, bodies, 3) + for _, body := range bodies { + require.Equal(t, 1, body.closes) + } +} + +type proxyBodyCloseCounter struct { + *strings.Reader + closes int +} + +func (b *proxyBodyCloseCounter) Close() error { + b.closes++ + return nil +} + +type proxyUncomparableBody struct { + io.ReadCloser + _ []byte +} + +type proxyBodyReplacingBalancer struct { + ProxyBalancer + beforeNext func(*echo.Context) +} + +func (b *proxyBodyReplacingBalancer) Next(c *echo.Context) (*ProxyTarget, error) { + b.beforeNext(c) + return b.ProxyBalancer.Next(c) +} From 34e50cae4440abaa43151c9163c5809c7fd8109f Mon Sep 17 00:00:00 2001 From: Twiink Date: Wed, 2 Dec 2026 19:39:03 +0800 Subject: [PATCH 3/5] =?UTF-8?q?fix(proxy):=20=E7=BB=9F=E4=B8=80=E9=87=8D?= =?UTF-8?q?=E8=AF=95=E6=AD=A3=E6=96=87=E7=9A=84=E5=85=B3=E9=97=AD=E7=94=9F?= =?UTF-8?q?=E5=91=BD=E5=91=A8=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/proxy.go | 34 +++++++++++++++++++++---- middleware/proxy_retry_balancer_test.go | 8 ++++-- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/middleware/proxy.go b/middleware/proxy.go index 9cad495b0..16c2e2073 100644 --- a/middleware/proxy.go +++ b/middleware/proxy.go @@ -313,6 +313,11 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { req.Header.Del("Forwarded") retries := config.RetryCount + var incomingBody *proxyRetryBody + if retries > 0 && req.Body != nil && req.Body != http.NoBody { + incomingBody = &proxyRetryBody{ReadCloser: req.Body} + req.Body = incomingBody + } var previousBody *proxyRetryBody for { tgt, err := config.Balancer.Next(c) @@ -342,14 +347,24 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { } req.Body = body } - if retries > 0 && req.Body != nil && req.Body != http.NoBody { - // Mark the body forwarded by this attempt. A balancer may supply a fresh body on the next attempt. - previousBody = &proxyRetryBody{ReadCloser: req.Body} - req.Body = previousBody + var forwardedBody *proxyRetryBody + if config.RetryCount > 0 && req.Body != nil && req.Body != http.NoBody { + forwardedBody = incomingBody + if req.Body != incomingBody { + forwardedBody = &proxyRetryBody{ReadCloser: req.Body} + req.Body = forwardedBody + } + previousBody = forwardedBody } // ReverseProxy validates upgrades and closes both sides when a tunnel ends. - proxyHTTP(c, tgt, config, clientIP, scheme).ServeHTTP(res, req) + func() { + // The server owns the incoming body; the proxy owns reconstructed and balancer-supplied bodies. + if forwardedBody != nil && forwardedBody != incomingBody { + defer forwardedBody.Close() + } + proxyHTTP(c, tgt, config, clientIP, scheme).ServeHTTP(res, req) + }() err, hasError := c.Get("_error").(error) if !hasError { @@ -369,6 +384,15 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { type proxyRetryBody struct { io.ReadCloser + closeOnce sync.Once + closeErr error +} + +func (b *proxyRetryBody) Close() error { + b.closeOnce.Do(func() { + b.closeErr = b.ReadCloser.Close() + }) + return b.closeErr } // StatusCodeContextCanceled is a custom HTTP status code for situations diff --git a/middleware/proxy_retry_balancer_test.go b/middleware/proxy_retry_balancer_test.go index 27c341130..9521b621d 100644 --- a/middleware/proxy_retry_balancer_test.go +++ b/middleware/proxy_retry_balancer_test.go @@ -59,6 +59,7 @@ func TestProxyRetryPreservesBalancerBody(t *testing.T) { }, } transport := proxyRetryBodyTransport(func(r *http.Request) (*http.Response, error) { + defer func() { _ = r.Body.Close() }() attempts++ b, readErr := io.ReadAll(r.Body) require.NoError(t, readErr) @@ -74,7 +75,8 @@ func TestProxyRetryPreservesBalancerBody(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 2, attempts) assert.Zero(t, getBodyCalls, "a new body supplied by the balancer must be forwarded as supplied") - assert.Equal(t, 1, original.closes) + // The HTTP server owns the incoming body. Older ReverseProxy versions leave it for the server to close. + assert.LessOrEqual(t, original.closes, 1) assert.Equal(t, 1, fresh.closes) }) } @@ -104,6 +106,7 @@ func TestProxyRetryReplaysClonedRequestBody(t *testing.T) { }, } transport := proxyRetryBodyTransport(func(r *http.Request) (*http.Response, error) { + defer func() { _ = r.Body.Close() }() attempts++ b, readErr := io.ReadAll(r.Body) require.NoError(t, readErr) @@ -117,7 +120,8 @@ func TestProxyRetryReplaysClonedRequestBody(t *testing.T) { require.NoError(t, handler(e.NewContext(req, httptest.NewRecorder()))) require.Equal(t, 3, attempts) require.Len(t, bodies, 3) - for _, body := range bodies { + require.LessOrEqual(t, original.closes, 1) + for _, body := range bodies[1:] { require.Equal(t, 1, body.closes) } } From b70f6f8c957e72ea4eb88cba08c7bf3eb72c2fda Mon Sep 17 00:00:00 2001 From: Twiink Date: Thu, 3 Dec 2026 20:20:25 +0800 Subject: [PATCH 4/5] =?UTF-8?q?fix(proxy):=20=E4=BF=AE=E5=A4=8D=E5=85=8B?= =?UTF-8?q?=E9=9A=86=E6=97=A7=E8=AF=B7=E6=B1=82=E6=97=B6=E7=9A=84=E9=87=8D?= =?UTF-8?q?=E8=AF=95=E6=AD=A3=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/proxy.go | 8 ++- middleware/proxy_retry_balancer_test.go | 96 +++++++++++++++---------- 2 files changed, 62 insertions(+), 42 deletions(-) diff --git a/middleware/proxy.go b/middleware/proxy.go index 16c2e2073..92d08602e 100644 --- a/middleware/proxy.go +++ b/middleware/proxy.go @@ -318,7 +318,7 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { incomingBody = &proxyRetryBody{ReadCloser: req.Body} req.Body = incomingBody } - var previousBody *proxyRetryBody + forwardedBodies := make(map[*proxyRetryBody]struct{}) for { tgt, err := config.Balancer.Next(c) if err != nil { @@ -340,7 +340,9 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { // This is needed for ProxyConfig.ModifyResponse and/or ProxyConfig.Transport to be able to process the Request // that Balancer may have replaced with c.SetRequest. req = c.Request() - if previousBody != nil && req.Body == previousBody && req.GetBody != nil { + // A balancer can clone an earlier request and reuse its consumed body. + body, _ := req.Body.(*proxyRetryBody) + if _, sent := forwardedBodies[body]; sent && req.GetBody != nil { body, bodyErr := req.GetBody() if bodyErr != nil { return config.ErrorHandler(c, bodyErr) @@ -354,7 +356,7 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { forwardedBody = &proxyRetryBody{ReadCloser: req.Body} req.Body = forwardedBody } - previousBody = forwardedBody + forwardedBodies[forwardedBody] = struct{}{} } // ReverseProxy validates upgrades and closes both sides when a tunnel ends. diff --git a/middleware/proxy_retry_balancer_test.go b/middleware/proxy_retry_balancer_test.go index 9521b621d..fd47b2d47 100644 --- a/middleware/proxy_retry_balancer_test.go +++ b/middleware/proxy_retry_balancer_test.go @@ -84,45 +84,63 @@ func TestProxyRetryPreservesBalancerBody(t *testing.T) { } func TestProxyRetryReplaysClonedRequestBody(t *testing.T) { - e := echo.New() - target, err := url.Parse("http://upstream.example.test") - require.NoError(t, err) - original := &proxyBodyCloseCounter{Reader: strings.NewReader("payload")} - bodies := []*proxyBodyCloseCounter{original} - req := httptest.NewRequest(http.MethodPost, "http://proxy.example.test/", nil) - // Non-comparable implementations are valid io.ReadClosers too. - req.Body = proxyUncomparableBody{ReadCloser: original} - req.ContentLength = int64(len("payload")) - req.GetBody = func() (io.ReadCloser, error) { - body := &proxyBodyCloseCounter{Reader: strings.NewReader("payload")} - bodies = append(bodies, body) - return proxyUncomparableBody{ReadCloser: body}, nil - } - attempts := 0 - balancer := &proxyBodyReplacingBalancer{ - ProxyBalancer: NewRoundRobinBalancer([]*ProxyTarget{{URL: target}}), - beforeNext: func(c *echo.Context) { - c.SetRequest(c.Request().WithContext(context.WithValue(c.Request().Context(), testContextKey("attempt"), attempts))) - }, - } - transport := proxyRetryBodyTransport(func(r *http.Request) (*http.Response, error) { - defer func() { _ = r.Body.Close() }() - attempts++ - b, readErr := io.ReadAll(r.Body) - require.NoError(t, readErr) - require.Equal(t, "payload", string(b)) - if attempts < 3 { - return nil, errors.New("temporary transport failure") - } - return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("ok"))}, nil - }) - handler := ProxyWithConfig(ProxyConfig{Balancer: balancer, RetryCount: 2, Transport: transport})(func(*echo.Context) error { return nil }) - require.NoError(t, handler(e.NewContext(req, httptest.NewRecorder()))) - require.Equal(t, 3, attempts) - require.Len(t, bodies, 3) - require.LessOrEqual(t, original.closes, 1) - for _, body := range bodies[1:] { - require.Equal(t, 1, body.closes) + for _, tc := range []struct { + name string + retainFirst bool + }{ + {name: "clone current request"}, + {name: "clone retained request", retainFirst: true}, + } { + t.Run(tc.name, func(t *testing.T) { + e := echo.New() + target, err := url.Parse("http://upstream.example.test") + require.NoError(t, err) + original := &proxyBodyCloseCounter{Reader: strings.NewReader("payload")} + bodies := []*proxyBodyCloseCounter{original} + req := httptest.NewRequest(http.MethodPost, "http://proxy.example.test/", nil) + // Non-comparable implementations are valid io.ReadClosers too. + req.Body = proxyUncomparableBody{ReadCloser: original} + req.ContentLength = int64(len("payload")) + req.GetBody = func() (io.ReadCloser, error) { + body := &proxyBodyCloseCounter{Reader: strings.NewReader("payload")} + bodies = append(bodies, body) + return proxyUncomparableBody{ReadCloser: body}, nil + } + attempts := 0 + var first *http.Request + balancer := &proxyBodyReplacingBalancer{ + ProxyBalancer: NewRoundRobinBalancer([]*ProxyTarget{{URL: target}}), + beforeNext: func(c *echo.Context) { + r := c.Request() + if first == nil { + first = r + } + if tc.retainFirst { + r = first + } + c.SetRequest(r.Clone(context.WithValue(r.Context(), testContextKey("attempt"), attempts))) + }, + } + transport := proxyRetryBodyTransport(func(r *http.Request) (*http.Response, error) { + defer func() { _ = r.Body.Close() }() + attempts++ + b, readErr := io.ReadAll(r.Body) + require.NoError(t, readErr) + require.Equal(t, "payload", string(b), "attempt %d", attempts) + if attempts < 3 { + return nil, errors.New("temporary transport failure") + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("ok"))}, nil + }) + handler := ProxyWithConfig(ProxyConfig{Balancer: balancer, RetryCount: 2, Transport: transport})(func(*echo.Context) error { return nil }) + require.NoError(t, handler(e.NewContext(req, httptest.NewRecorder()))) + require.Equal(t, 3, attempts) + require.Len(t, bodies, 3) + require.LessOrEqual(t, original.closes, 1) + for _, body := range bodies[1:] { + require.Equal(t, 1, body.closes) + } + }) } } From 5f39543e05187d195f74fdf3049946ea5dc6d0e3 Mon Sep 17 00:00:00 2001 From: Twiink Date: Fri, 4 Dec 2026 14:56:13 +0800 Subject: [PATCH 5/5] =?UTF-8?q?fix(proxy):=20=E4=BF=AE=E6=AD=A3=E9=87=8D?= =?UTF-8?q?=E8=AF=95=E6=AD=A3=E6=96=87=E7=9A=84=E5=9B=9E=E6=94=BE=E6=9D=A1?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/proxy.go | 17 ++++-- middleware/proxy_retry_balancer_test.go | 70 +++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 5 deletions(-) diff --git a/middleware/proxy.go b/middleware/proxy.go index 92d08602e..e0e8dbdcc 100644 --- a/middleware/proxy.go +++ b/middleware/proxy.go @@ -314,11 +314,12 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { retries := config.RetryCount var incomingBody *proxyRetryBody + reopenIncoming := req.GetBody if retries > 0 && req.Body != nil && req.Body != http.NoBody { incomingBody = &proxyRetryBody{ReadCloser: req.Body} req.Body = incomingBody } - forwardedBodies := make(map[*proxyRetryBody]struct{}) + forwardedReplayableBodies := make(map[*proxyRetryBody]struct{}) for { tgt, err := config.Balancer.Next(c) if err != nil { @@ -340,10 +341,13 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { // This is needed for ProxyConfig.ModifyResponse and/or ProxyConfig.Transport to be able to process the Request // that Balancer may have replaced with c.SetRequest. req = c.Request() - // A balancer can clone an earlier request and reuse its consumed body. + // Clones may retain a previously forwarded body. Only the incoming + // body and copies made by its own callback can be replayed this way. body, _ := req.Body.(*proxyRetryBody) - if _, sent := forwardedBodies[body]; sent && req.GetBody != nil { - body, bodyErr := req.GetBody() + _, sent := forwardedReplayableBodies[body] + replaying := sent && req.ContentLength != 0 + if replaying { + body, bodyErr := reopenIncoming() if bodyErr != nil { return config.ErrorHandler(c, bodyErr) } @@ -356,7 +360,10 @@ func (config ProxyConfig) ToMiddleware() (echo.MiddlewareFunc, error) { forwardedBody = &proxyRetryBody{ReadCloser: req.Body} req.Body = forwardedBody } - forwardedBodies[forwardedBody] = struct{}{} + // ReverseProxy drops the body completely when ContentLength is zero. + if req.ContentLength != 0 && reopenIncoming != nil && (forwardedBody == incomingBody || replaying) { + forwardedReplayableBodies[forwardedBody] = struct{}{} + } } // ReverseProxy validates upgrades and closes both sides when a tunnel ends. diff --git a/middleware/proxy_retry_balancer_test.go b/middleware/proxy_retry_balancer_test.go index fd47b2d47..affbd46d9 100644 --- a/middleware/proxy_retry_balancer_test.go +++ b/middleware/proxy_retry_balancer_test.go @@ -144,6 +144,76 @@ func TestProxyRetryReplaysClonedRequestBody(t *testing.T) { } } +func TestProxyRetryDoesNotReopenBalancerBody(t *testing.T) { + e := echo.New() + target, err := url.Parse("http://upstream.example.test") + require.NoError(t, err) + req := httptest.NewRequest(http.MethodPost, "http://proxy.example.test/", strings.NewReader("request")) + replacements := &proxyBodyCloseCounter{Reader: strings.NewReader("replacement")} + getBodyCalls := 0 + req.GetBody = func() (io.ReadCloser, error) { + getBodyCalls++ + return nil, errors.New("callback belongs to the input body") + } + attempts := 0 + balancer := &proxyBodyReplacingBalancer{ + ProxyBalancer: NewRoundRobinBalancer([]*ProxyTarget{{URL: target}}), + beforeNext: func(c *echo.Context) { + if attempts == 0 { + replacement := c.Request().Clone(c.Request().Context()) + replacement.Body = replacements + replacement.ContentLength = int64(replacements.Len()) + c.SetRequest(replacement) + } + }, + } + transport := proxyRetryBodyTransport(func(r *http.Request) (*http.Response, error) { + defer func() { _ = r.Body.Close() }() + attempts++ + if attempts == 1 { + payload, err := io.ReadAll(r.Body) + require.NoError(t, err) + require.Equal(t, "replacement", string(payload)) + return nil, errors.New("temporary transport failure") + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: http.NoBody}, nil + }) + handler := ProxyWithConfig(ProxyConfig{Balancer: balancer, RetryCount: 1, Transport: transport})(func(*echo.Context) error { return nil }) + + assert.NoError(t, handler(e.NewContext(req, httptest.NewRecorder()))) + assert.Equal(t, 2, attempts) + assert.Zero(t, getBodyCalls) + assert.Equal(t, 1, replacements.closes) +} + +func TestProxyRetryDoesNotReopenZeroLengthBody(t *testing.T) { + e := echo.New() + target, err := url.Parse("http://upstream.example.test") + require.NoError(t, err) + req := httptest.NewRequest(http.MethodPost, "http://proxy.example.test/", nil) + req.Body = io.NopCloser(strings.NewReader("")) + getBodyCalls := 0 + req.GetBody = func() (io.ReadCloser, error) { + getBodyCalls++ + return nil, errors.New("empty body does not need reopening") + } + attempts := 0 + transport := proxyRetryBodyTransport(func(r *http.Request) (*http.Response, error) { + attempts++ + require.True(t, r.Body == nil || r.Body == http.NoBody) + if attempts == 1 { + return nil, errors.New("temporary transport failure") + } + return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: http.NoBody}, nil + }) + balancer := NewRoundRobinBalancer([]*ProxyTarget{{URL: target}}) + handler := ProxyWithConfig(ProxyConfig{Balancer: balancer, RetryCount: 1, Transport: transport})(func(*echo.Context) error { return nil }) + + assert.NoError(t, handler(e.NewContext(req, httptest.NewRecorder()))) + assert.Equal(t, 2, attempts) + assert.Zero(t, getBodyCalls) +} + type proxyBodyCloseCounter struct { *strings.Reader closes int