| 1 | package reverseproxy |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "sync/atomic" |
| 13 | "testing" |
| 14 | |
| 15 | "go.uber.org/zap" |
| 16 | |
| 17 | "github.com/caddyserver/caddy/v2" |
| 18 | "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" |
| 19 | "github.com/caddyserver/caddy/v2/modules/caddyhttp" |
| 20 | ) |
| 21 | |
| 22 | // prepareTestRequest injects the context values that ServeHTTP and |
| 23 | // proxyLoopIteration require (caddy.ReplacerCtxKey, VarsCtxKey, etc.) using |
| 24 | // the same helper that the real HTTP server uses. |
| 25 | // |
| 26 | // A zero-value Server is passed so that caddyhttp.ServerCtxKey is set to a |
| 27 | // non-nil pointer; reverseProxy dereferences it to check ShouldLogCredentials. |
| 28 | func prepareTestRequest(req *http.Request) *http.Request { |
| 29 | repl := caddy.NewReplacer() |
| 30 | return caddyhttp.PrepareRequest(req, repl, nil, &caddyhttp.Server{}) |
| 31 | } |
| 32 | |
| 33 | // closeOnCloseReader is an io.ReadCloser whose Close method actually makes |
| 34 | // subsequent reads fail, mimicking the behaviour of a real HTTP request body |
| 35 | // (as opposed to io.NopCloser, whose Close is a no-op and would mask the bug |
| 36 | // we are testing). |
| 37 | type closeOnCloseReader struct { |
| 38 | mu sync.Mutex |
| 39 | r *strings.Reader |
| 40 | closed bool |
| 41 | } |
| 42 | |
| 43 | func newCloseOnCloseReader(s string) *closeOnCloseReader { |
| 44 | return &closeOnCloseReader{r: strings.NewReader(s)} |
| 45 | } |
| 46 | |
| 47 | func (c *closeOnCloseReader) Read(p []byte) (int, error) { |
| 48 | c.mu.Lock() |
| 49 | defer c.mu.Unlock() |
| 50 | if c.closed { |
| 51 | return 0, errors.New("http: invalid Read on closed Body") |
| 52 | } |
| 53 | return c.r.Read(p) |
| 54 | } |
| 55 | |
| 56 | func (c *closeOnCloseReader) Close() error { |
| 57 | c.mu.Lock() |
| 58 | defer c.mu.Unlock() |
| 59 | c.closed = true |
| 60 | return nil |
| 61 | } |
| 62 | |
| 63 | // deadUpstreamAddr returns a TCP address that is guaranteed to refuse |
| 64 | // connections: we bind a listener, note its address, close it immediately, |
| 65 | // and return the address. Any dial to that address will get ECONNREFUSED. |
| 66 | func deadUpstreamAddr(t *testing.T) string { |
| 67 | t.Helper() |
| 68 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 69 | if err != nil { |
| 70 | t.Fatalf("failed to create dead upstream listener: %v", err) |
| 71 | } |
| 72 | addr := ln.Addr().String() |
| 73 | ln.Close() |
| 74 | return addr |
| 75 | } |
| 76 | |
| 77 | // testTransport wraps http.Transport to: |
| 78 | // 1. Set the URL scheme to "http" when it is empty (matching what |
| 79 | // HTTPTransport.SetScheme does in production; cloneRequest strips the |
| 80 | // scheme intentionally so a plain *http.Transport would fail with |
| 81 | // "unsupported protocol scheme"). |
| 82 | // 2. Wrap dial errors as DialError so that tryAgain correctly identifies them |
| 83 | // as safe-to-retry regardless of request method (as HTTPTransport does in |
| 84 | // production via its custom dialer). |
| 85 | type testTransport struct{ *http.Transport } |
| 86 | |
| 87 | func (t testTransport) RoundTrip(req *http.Request) (*http.Response, error) { |
| 88 | if req.URL.Scheme == "" { |
| 89 | req.URL.Scheme = "http" |
| 90 | } |
| 91 | resp, err := t.Transport.RoundTrip(req) |
| 92 | if err != nil { |
| 93 | // Wrap dial errors as DialError to match production behaviour. |
| 94 | // Without this wrapping, tryAgain treats ECONNREFUSED on a POST |
| 95 | // request as non-retryable (only GET is retried by default when |
| 96 | // the error is not a DialError). |
| 97 | var opErr *net.OpError |
| 98 | if errors.As(err, &opErr) && opErr.Op == "dial" { |
| 99 | return nil, DialError{err} |
| 100 | } |
| 101 | } |
| 102 | return resp, err |
| 103 | } |
| 104 | |
| 105 | // minimalHandler returns a Handler with only the fields required by ServeHTTP |
| 106 | // set directly, bypassing Provision (which requires a full Caddy runtime). |
| 107 | // RoundRobinSelection is used so that successive iterations of the proxy loop |
| 108 | // advance through the upstream pool in a predictable order. |
| 109 | func minimalHandler(retries int, upstreams ...*Upstream) *Handler { |
| 110 | return &Handler{ |
| 111 | logger: zap.NewNop(), |
| 112 | Transport: testTransport{&http.Transport{}}, |
| 113 | Upstreams: upstreams, |
| 114 | LoadBalancing: &LoadBalancing{ |
| 115 | Retries: retries, |
| 116 | SelectionPolicy: &RoundRobinSelection{}, |
| 117 | // RetryMatch intentionally nil: dial errors are always retried |
| 118 | // regardless of RetryMatch or request method. |
| 119 | }, |
| 120 | // ctx, connections, connectionsMu, events: zero/nil values are safe |
| 121 | // for the code paths exercised by these tests (TryInterval=0 so |
| 122 | // ctx.Done() is never consulted; no WebSocket hijacking; no passive |
| 123 | // health-check event emission). |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | // TestDialErrorBodyRetry verifies that a POST request whose body has NOT been |
| 128 | // pre-buffered via request_buffers can still be retried after a dial error. |
| 129 | // |
| 130 | // Before the fix, a dial error caused Go's transport to close the shared body |
| 131 | // (via cloneRequest's shallow copy), so the retry attempt would read from an |
| 132 | // already-closed io.ReadCloser and produce: |
| 133 | // |
| 134 | // http: invalid Read on closed Body → HTTP 502 |
| 135 | // |
| 136 | // After the fix the handler wraps the body in noCloseBody when retries are |
| 137 | // configured, preventing the transport's Close() from propagating to the |
| 138 | // shared body. Since dial errors never read any bytes, the body remains at |
| 139 | // position 0 for the retry. |
| 140 | func TestDialErrorBodyRetry(t *testing.T) { |
| 141 | // Good upstream: echoes the request body with 200 OK. |
| 142 | goodServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 143 | body, err := io.ReadAll(r.Body) |
| 144 | if err != nil { |
| 145 | http.Error(w, "read body: "+err.Error(), http.StatusInternalServerError) |
| 146 | return |
| 147 | } |
| 148 | w.WriteHeader(http.StatusOK) |
| 149 | _, _ = w.Write(body) |
| 150 | })) |
| 151 | t.Cleanup(goodServer.Close) |
| 152 | |
| 153 | const requestBody = "hello, retry" |
| 154 | |
| 155 | tests := []struct { |
| 156 | name string |
| 157 | method string |
| 158 | body string |
| 159 | retries int |
| 160 | wantStatus int |
| 161 | wantBody string |
| 162 | }{ |
| 163 | { |
| 164 | // Core regression case: POST with a body, no request_buffers, |
| 165 | // dial error on first upstream → retry to second upstream succeeds. |
| 166 | name: "POST body retried after dial error", |
| 167 | method: http.MethodPost, |
| 168 | body: requestBody, |
| 169 | retries: 1, |
| 170 | wantStatus: http.StatusOK, |
| 171 | wantBody: requestBody, |
| 172 | }, |
| 173 | { |
| 174 | // Dial errors are always retried regardless of method, but there |
| 175 | // is no body to re-read, so GET has always worked. Keep it as a |
| 176 | // sanity check that we did not break the no-body path. |
| 177 | name: "GET without body retried after dial error", |
| 178 | method: http.MethodGet, |
| 179 | body: "", |
| 180 | retries: 1, |
| 181 | wantStatus: http.StatusOK, |
| 182 | wantBody: "", |
| 183 | }, |
| 184 | { |
| 185 | // Without any retry configuration the handler must give up on the |
| 186 | // first dial error and return a 502. Confirms no wrapping occurs |
| 187 | // in the no-retry path. |
| 188 | name: "no retries configured returns 502 on dial error", |
| 189 | method: http.MethodPost, |
| 190 | body: requestBody, |
| 191 | retries: 0, |
| 192 | wantStatus: http.StatusBadGateway, |
| 193 | wantBody: "", |
| 194 | }, |
| 195 | } |
| 196 | |
| 197 | for _, tc := range tests { |
| 198 | t.Run(tc.name, func(t *testing.T) { |
| 199 | dead := deadUpstreamAddr(t) |
| 200 | |
| 201 | // Build the upstream pool. RoundRobinSelection starts its |
| 202 | // counter at 0 and increments before returning, so with a |
| 203 | // two-element pool it picks index 1 first, then index 0. |
| 204 | // Put the good upstream at index 0 and the dead one at |
| 205 | // index 1 so that: |
| 206 | // attempt 1 → pool[1] = dead → DialError (ECONNREFUSED) |
| 207 | // attempt 2 → pool[0] = good → 200 |
| 208 | upstreams := []*Upstream{ |
| 209 | {Host: new(Host), Dial: goodServer.Listener.Addr().String()}, |
| 210 | {Host: new(Host), Dial: dead}, |
| 211 | } |
| 212 | if tc.retries == 0 { |
| 213 | // For the "no retries" case use only the dead upstream so |
| 214 | // there is nowhere to retry to. |
| 215 | upstreams = []*Upstream{ |
| 216 | {Host: new(Host), Dial: dead}, |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | h := minimalHandler(tc.retries, upstreams...) |
| 221 | |
| 222 | // Use closeOnCloseReader so that Close() truly prevents further |
| 223 | // reads, matching real http.body semantics. io.NopCloser would |
| 224 | // mask the bug because its Close is a no-op. |
| 225 | var bodyReader io.ReadCloser |
| 226 | if tc.body != "" { |
| 227 | bodyReader = newCloseOnCloseReader(tc.body) |
| 228 | } |
| 229 | req := httptest.NewRequest(tc.method, "http://example.com/", bodyReader) |
| 230 | if bodyReader != nil { |
| 231 | // httptest.NewRequest wraps the reader in NopCloser; replace |
| 232 | // it with our close-aware reader so Close() is propagated. |
| 233 | req.Body = bodyReader |
| 234 | req.ContentLength = int64(len(tc.body)) |
| 235 | } |
| 236 | req = prepareTestRequest(req) |
| 237 | |
| 238 | rec := httptest.NewRecorder() |
| 239 | err := h.ServeHTTP(rec, req, caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 240 | return nil |
| 241 | })) |
| 242 | |
| 243 | // For error cases (e.g. 502) ServeHTTP returns a HandlerError |
| 244 | // rather than writing the status itself. |
| 245 | gotStatus := rec.Code |
| 246 | if err != nil { |
| 247 | if herr, ok := err.(caddyhttp.HandlerError); ok { |
| 248 | gotStatus = herr.StatusCode |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | if gotStatus != tc.wantStatus { |
| 253 | t.Errorf("status: got %d, want %d (err=%v)", gotStatus, tc.wantStatus, err) |
| 254 | } |
| 255 | if tc.wantBody != "" && rec.Body.String() != tc.wantBody { |
| 256 | t.Errorf("body: got %q, want %q", rec.Body.String(), tc.wantBody) |
| 257 | } |
| 258 | }) |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | // newExpressionMatcher provisions a MatchExpression for use in tests |
| 263 | func newExpressionMatcher(t *testing.T, expr string) *caddyhttp.MatchExpression { |
| 264 | t.Helper() |
| 265 | ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) |
| 266 | t.Cleanup(cancel) |
| 267 | m := &caddyhttp.MatchExpression{Expr: expr} |
| 268 | if err := m.Provision(ctx); err != nil { |
| 269 | t.Fatalf("failed to provision expression %q: %v", expr, err) |
| 270 | } |
| 271 | return m |
| 272 | } |
| 273 | |
| 274 | // minimalHandlerWithRetryMatch is like minimalHandler but also configures |
| 275 | // RetryMatch so that response-based retry can be tested |
| 276 | func minimalHandlerWithRetryMatch(retries int, retryMatch caddyhttp.MatcherSets, upstreams ...*Upstream) *Handler { |
| 277 | h := minimalHandler(retries, upstreams...) |
| 278 | h.LoadBalancing.RetryMatch = retryMatch |
| 279 | return h |
| 280 | } |
| 281 | |
| 282 | // TestResponseRetryStatusCode verifies that when an upstream returns a status |
| 283 | // code matching a retry_match expression, the request is retried on the next |
| 284 | // upstream |
| 285 | func TestResponseRetryStatusCode(t *testing.T) { |
| 286 | // Bad upstream: returns 502 |
| 287 | badServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 288 | w.WriteHeader(http.StatusBadGateway) |
| 289 | })) |
| 290 | t.Cleanup(badServer.Close) |
| 291 | |
| 292 | // Good upstream: returns 200 |
| 293 | goodServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 294 | w.WriteHeader(http.StatusOK) |
| 295 | w.Write([]byte("ok")) |
| 296 | })) |
| 297 | t.Cleanup(goodServer.Close) |
| 298 | |
| 299 | retryMatch := caddyhttp.MatcherSets{ |
| 300 | caddyhttp.MatcherSet{ |
| 301 | newExpressionMatcher(t, "{http.reverse_proxy.status_code} in [502, 503]"), |
| 302 | }, |
| 303 | } |
| 304 | |
| 305 | // RoundRobin picks index 1 first, then 0 |
| 306 | upstreams := []*Upstream{ |
| 307 | {Host: new(Host), Dial: goodServer.Listener.Addr().String()}, |
| 308 | {Host: new(Host), Dial: badServer.Listener.Addr().String()}, |
| 309 | } |
| 310 | |
| 311 | h := minimalHandlerWithRetryMatch(1, retryMatch, upstreams...) |
| 312 | |
| 313 | req := httptest.NewRequest(http.MethodGet, "http://example.com/", nil) |
| 314 | req = prepareTestRequest(req) |
| 315 | rec := httptest.NewRecorder() |
| 316 | |
| 317 | err := h.ServeHTTP(rec, req, caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 318 | return nil |
| 319 | })) |
| 320 | |
| 321 | gotStatus := rec.Code |
| 322 | if err != nil { |
| 323 | if herr, ok := err.(caddyhttp.HandlerError); ok { |
| 324 | gotStatus = herr.StatusCode |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | if gotStatus != http.StatusOK { |
| 329 | t.Errorf("status: got %d, want %d (err=%v)", gotStatus, http.StatusOK, err) |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | // TestResponseRetryHeader verifies that response header matching triggers |
| 334 | // retries via a CEL expression checking {rp.header.*} |
| 335 | func TestResponseRetryHeader(t *testing.T) { |
| 336 | // Bad upstream: returns 200 but with X-Upstream-Retry header |
| 337 | badServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 338 | w.Header().Set("X-Upstream-Retry", "true") |
| 339 | w.WriteHeader(http.StatusOK) |
| 340 | w.Write([]byte("bad")) |
| 341 | })) |
| 342 | t.Cleanup(badServer.Close) |
| 343 | |
| 344 | // Good upstream: returns 200 without retry header |
| 345 | goodServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 346 | w.WriteHeader(http.StatusOK) |
| 347 | w.Write([]byte("good")) |
| 348 | })) |
| 349 | t.Cleanup(goodServer.Close) |
| 350 | |
| 351 | retryMatch := caddyhttp.MatcherSets{ |
| 352 | caddyhttp.MatcherSet{ |
| 353 | newExpressionMatcher(t, `{http.reverse_proxy.header.X-Upstream-Retry} == "true"`), |
| 354 | }, |
| 355 | } |
| 356 | |
| 357 | // RoundRobin picks index 1 first, then 0 |
| 358 | upstreams := []*Upstream{ |
| 359 | {Host: new(Host), Dial: goodServer.Listener.Addr().String()}, |
| 360 | {Host: new(Host), Dial: badServer.Listener.Addr().String()}, |
| 361 | } |
| 362 | |
| 363 | h := minimalHandlerWithRetryMatch(1, retryMatch, upstreams...) |
| 364 | |
| 365 | req := httptest.NewRequest(http.MethodGet, "http://example.com/", nil) |
| 366 | req = prepareTestRequest(req) |
| 367 | rec := httptest.NewRecorder() |
| 368 | |
| 369 | err := h.ServeHTTP(rec, req, caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 370 | return nil |
| 371 | })) |
| 372 | if err != nil { |
| 373 | t.Fatalf("unexpected error: %v", err) |
| 374 | } |
| 375 | |
| 376 | if rec.Code != http.StatusOK { |
| 377 | t.Errorf("status: got %d, want %d", rec.Code, http.StatusOK) |
| 378 | } |
| 379 | if rec.Body.String() != "good" { |
| 380 | t.Errorf("body: got %q, want %q (retried to wrong upstream)", rec.Body.String(), "good") |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | // TestResponseRetryNoMatchNoRetry verifies that when no retry_match entries |
| 385 | // match the response, the original response is returned without retrying |
| 386 | func TestResponseRetryNoMatchNoRetry(t *testing.T) { |
| 387 | var hits atomic.Int32 |
| 388 | |
| 389 | // Server that returns 500 - but retry_match only matches 502/503 |
| 390 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 391 | hits.Add(1) |
| 392 | w.WriteHeader(http.StatusInternalServerError) |
| 393 | })) |
| 394 | t.Cleanup(server.Close) |
| 395 | |
| 396 | retryMatch := caddyhttp.MatcherSets{ |
| 397 | caddyhttp.MatcherSet{ |
| 398 | newExpressionMatcher(t, "{http.reverse_proxy.status_code} in [502, 503]"), |
| 399 | }, |
| 400 | } |
| 401 | |
| 402 | upstreams := []*Upstream{ |
| 403 | {Host: new(Host), Dial: server.Listener.Addr().String()}, |
| 404 | {Host: new(Host), Dial: server.Listener.Addr().String()}, |
| 405 | } |
| 406 | |
| 407 | h := minimalHandlerWithRetryMatch(2, retryMatch, upstreams...) |
| 408 | |
| 409 | req := httptest.NewRequest(http.MethodGet, "http://example.com/", nil) |
| 410 | req = prepareTestRequest(req) |
| 411 | rec := httptest.NewRecorder() |
| 412 | |
| 413 | _ = h.ServeHTTP(rec, req, caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 414 | return nil |
| 415 | })) |
| 416 | |
| 417 | // Only one hit - no retry since 500 doesn't match [502, 503] |
| 418 | if hits.Load() != 1 { |
| 419 | t.Errorf("upstream hits: got %d, want 1 (should not have retried)", hits.Load()) |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | // TestResponseRetryExhaustedPreservesStatusCode verifies that when retries |
| 424 | // are exhausted, the actual upstream status code (e.g. 503) is reported |
| 425 | // to the client, not a generic 502 |
| 426 | func TestResponseRetryExhaustedPreservesStatusCode(t *testing.T) { |
| 427 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 428 | w.WriteHeader(http.StatusServiceUnavailable) // 503 |
| 429 | })) |
| 430 | t.Cleanup(server.Close) |
| 431 | |
| 432 | retryMatch := caddyhttp.MatcherSets{ |
| 433 | caddyhttp.MatcherSet{ |
| 434 | newExpressionMatcher(t, "{http.reverse_proxy.status_code} == 503"), |
| 435 | }, |
| 436 | } |
| 437 | |
| 438 | upstreams := []*Upstream{ |
| 439 | {Host: new(Host), Dial: server.Listener.Addr().String()}, |
| 440 | {Host: new(Host), Dial: server.Listener.Addr().String()}, |
| 441 | } |
| 442 | |
| 443 | h := minimalHandlerWithRetryMatch(1, retryMatch, upstreams...) |
| 444 | |
| 445 | req := httptest.NewRequest(http.MethodGet, "http://example.com/", nil) |
| 446 | req = prepareTestRequest(req) |
| 447 | rec := httptest.NewRecorder() |
| 448 | |
| 449 | err := h.ServeHTTP(rec, req, caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 450 | return nil |
| 451 | })) |
| 452 | |
| 453 | gotStatus := rec.Code |
| 454 | if err != nil { |
| 455 | if herr, ok := err.(caddyhttp.HandlerError); ok { |
| 456 | gotStatus = herr.StatusCode |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | // Must return 503 (actual upstream status), not 502 (generic proxy error) |
| 461 | if gotStatus != http.StatusServiceUnavailable { |
| 462 | t.Errorf("status: got %d, want %d (status code not preserved)", gotStatus, http.StatusServiceUnavailable) |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | // TestResponseRetryHeaderCleanup verifies that stale response header |
| 467 | // placeholders from a previous upstream attempt are cleaned up before the |
| 468 | // next retry evaluation. Without cleanup, a header like X-Retry: true from |
| 469 | // upstream A would leak into the retry match for upstream B even if B does |
| 470 | // not set that header |
| 471 | func TestResponseRetryHeaderCleanup(t *testing.T) { |
| 472 | // First upstream: returns 200 with X-Retry header (triggers retry) |
| 473 | firstServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 474 | w.Header().Set("X-Retry", "true") |
| 475 | w.WriteHeader(http.StatusOK) |
| 476 | w.Write([]byte("first")) |
| 477 | })) |
| 478 | t.Cleanup(firstServer.Close) |
| 479 | |
| 480 | // Second upstream: returns 200 WITHOUT X-Retry header (should NOT retry) |
| 481 | secondServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 482 | w.WriteHeader(http.StatusOK) |
| 483 | w.Write([]byte("second")) |
| 484 | })) |
| 485 | t.Cleanup(secondServer.Close) |
| 486 | |
| 487 | retryMatch := caddyhttp.MatcherSets{ |
| 488 | caddyhttp.MatcherSet{ |
| 489 | newExpressionMatcher(t, `{http.reverse_proxy.header.X-Retry} == "true"`), |
| 490 | }, |
| 491 | } |
| 492 | |
| 493 | // RoundRobin picks index 1 first, then 0 |
| 494 | upstreams := []*Upstream{ |
| 495 | {Host: new(Host), Dial: secondServer.Listener.Addr().String()}, |
| 496 | {Host: new(Host), Dial: firstServer.Listener.Addr().String()}, |
| 497 | } |
| 498 | |
| 499 | h := minimalHandlerWithRetryMatch(2, retryMatch, upstreams...) |
| 500 | |
| 501 | req := httptest.NewRequest(http.MethodGet, "http://example.com/", nil) |
| 502 | req = prepareTestRequest(req) |
| 503 | rec := httptest.NewRecorder() |
| 504 | |
| 505 | err := h.ServeHTTP(rec, req, caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 506 | return nil |
| 507 | })) |
| 508 | if err != nil { |
| 509 | t.Fatalf("unexpected error: %v", err) |
| 510 | } |
| 511 | |
| 512 | // Should get "second" - the first upstream's X-Retry header must not |
| 513 | // leak into the second upstream's retry evaluation |
| 514 | if rec.Body.String() != "second" { |
| 515 | t.Errorf("body: got %q, want %q (stale header leaked between retries)", rec.Body.String(), "second") |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | // TestRequestOnlyMatcherDoesNotRetryResponses verifies that a pure request |
| 520 | // matcher like method PUT in lb_retry_match does NOT trigger response-based |
| 521 | // retries. Only expression matchers (which can reference response data) |
| 522 | // should trigger response retries |
| 523 | func TestRequestOnlyMatcherDoesNotRetryResponses(t *testing.T) { |
| 524 | var hits atomic.Int32 |
| 525 | |
| 526 | // Server returns 200 OK for all requests |
| 527 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 528 | hits.Add(1) |
| 529 | w.WriteHeader(http.StatusOK) |
| 530 | w.Write([]byte("ok")) |
| 531 | })) |
| 532 | t.Cleanup(server.Close) |
| 533 | |
| 534 | // method PUT matcher - should NOT trigger response retries |
| 535 | retryMatch := caddyhttp.MatcherSets{ |
| 536 | caddyhttp.MatcherSet{ |
| 537 | caddyhttp.MatchMethod{"PUT"}, |
| 538 | }, |
| 539 | } |
| 540 | |
| 541 | upstreams := []*Upstream{ |
| 542 | {Host: new(Host), Dial: server.Listener.Addr().String()}, |
| 543 | {Host: new(Host), Dial: server.Listener.Addr().String()}, |
| 544 | } |
| 545 | |
| 546 | h := minimalHandlerWithRetryMatch(2, retryMatch, upstreams...) |
| 547 | |
| 548 | req := httptest.NewRequest(http.MethodPut, "http://example.com/", nil) |
| 549 | req = prepareTestRequest(req) |
| 550 | rec := httptest.NewRecorder() |
| 551 | |
| 552 | err := h.ServeHTTP(rec, req, caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 553 | return nil |
| 554 | })) |
| 555 | if err != nil { |
| 556 | t.Fatalf("unexpected error: %v", err) |
| 557 | } |
| 558 | |
| 559 | // Should hit only once - no retry for 200 OK even though method matches |
| 560 | if hits.Load() != 1 { |
| 561 | t.Errorf("upstream hits: got %d, want 1 (should not retry successful responses)", hits.Load()) |
| 562 | } |
| 563 | if rec.Code != http.StatusOK { |
| 564 | t.Errorf("status: got %d, want %d", rec.Code, http.StatusOK) |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | // brokenUpstreamAddr returns the address of a TCP listener that accepts |
| 569 | // connections but immediately closes them, causing a transport error (not |
| 570 | // a dial error). This simulates an upstream that is reachable but broken |
| 571 | func brokenUpstreamAddr(t *testing.T) string { |
| 572 | t.Helper() |
| 573 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 574 | if err != nil { |
| 575 | t.Fatalf("failed to listen: %v", err) |
| 576 | } |
| 577 | t.Cleanup(func() { ln.Close() }) |
| 578 | go func() { |
| 579 | for { |
| 580 | conn, err := ln.Accept() |
| 581 | if err != nil { |
| 582 | return |
| 583 | } |
| 584 | conn.Close() |
| 585 | } |
| 586 | }() |
| 587 | return ln.Addr().String() |
| 588 | } |
| 589 | |
| 590 | // TestTransportErrorPlaceholder verifies that the is_transport_error |
| 591 | // placeholder is set to true during transport error evaluation in tryAgain() |
| 592 | // and that expression matchers using {rp.is_transport_error} can match it |
| 593 | func TestTransportErrorPlaceholder(t *testing.T) { |
| 594 | broken := brokenUpstreamAddr(t) |
| 595 | |
| 596 | goodServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 597 | w.WriteHeader(http.StatusOK) |
| 598 | w.Write([]byte("ok")) |
| 599 | })) |
| 600 | t.Cleanup(goodServer.Close) |
| 601 | |
| 602 | retryMatch := caddyhttp.MatcherSets{ |
| 603 | caddyhttp.MatcherSet{ |
| 604 | newExpressionMatcher(t, "{http.reverse_proxy.is_transport_error} == true"), |
| 605 | }, |
| 606 | } |
| 607 | |
| 608 | // RoundRobin picks index 1 first (broken), then 0 (good) |
| 609 | upstreams := []*Upstream{ |
| 610 | {Host: new(Host), Dial: goodServer.Listener.Addr().String()}, |
| 611 | {Host: new(Host), Dial: broken}, |
| 612 | } |
| 613 | |
| 614 | h := minimalHandlerWithRetryMatch(1, retryMatch, upstreams...) |
| 615 | |
| 616 | req := httptest.NewRequest(http.MethodPost, "http://example.com/", nil) |
| 617 | req = prepareTestRequest(req) |
| 618 | rec := httptest.NewRecorder() |
| 619 | |
| 620 | err := h.ServeHTTP(rec, req, caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 621 | return nil |
| 622 | })) |
| 623 | |
| 624 | gotStatus := rec.Code |
| 625 | if err != nil { |
| 626 | if herr, ok := err.(caddyhttp.HandlerError); ok { |
| 627 | gotStatus = herr.StatusCode |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | // POST transport error should be retried because is_transport_error matched |
| 632 | if gotStatus != http.StatusOK { |
| 633 | t.Errorf("status: got %d, want %d (transport error should have been retried)", gotStatus, http.StatusOK) |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | // TestTransportErrorPlaceholderNotSetForResponses verifies that the |
| 638 | // is_transport_error placeholder is NOT set when evaluating response |
| 639 | // matchers, so {rp.is_transport_error} is false for response retries |
| 640 | func TestTransportErrorPlaceholderNotSetForResponses(t *testing.T) { |
| 641 | var hits atomic.Int32 |
| 642 | |
| 643 | // Server returns 502 - but the matcher only checks is_transport_error |
| 644 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 645 | hits.Add(1) |
| 646 | w.WriteHeader(http.StatusBadGateway) |
| 647 | })) |
| 648 | t.Cleanup(server.Close) |
| 649 | |
| 650 | // Only matches transport errors, not response errors |
| 651 | retryMatch := caddyhttp.MatcherSets{ |
| 652 | caddyhttp.MatcherSet{ |
| 653 | newExpressionMatcher(t, "{http.reverse_proxy.is_transport_error} == true"), |
| 654 | }, |
| 655 | } |
| 656 | |
| 657 | upstreams := []*Upstream{ |
| 658 | {Host: new(Host), Dial: server.Listener.Addr().String()}, |
| 659 | {Host: new(Host), Dial: server.Listener.Addr().String()}, |
| 660 | } |
| 661 | |
| 662 | h := minimalHandlerWithRetryMatch(2, retryMatch, upstreams...) |
| 663 | |
| 664 | req := httptest.NewRequest(http.MethodGet, "http://example.com/", nil) |
| 665 | req = prepareTestRequest(req) |
| 666 | rec := httptest.NewRecorder() |
| 667 | |
| 668 | _ = h.ServeHTTP(rec, req, caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 669 | return nil |
| 670 | })) |
| 671 | |
| 672 | // Should hit only once - is_transport_error is false during response |
| 673 | // evaluation so the 502 is NOT retried |
| 674 | if hits.Load() != 1 { |
| 675 | t.Errorf("upstream hits: got %d, want 1 (is_transport_error should be false for responses)", hits.Load()) |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | // TestRetryMatchAllowsExpressionMixedWithOtherMatchers verifies that |
| 680 | // lb_retry_match accepts a block mixing expression with other matchers |
| 681 | func TestRetryMatchAllowsExpressionMixedWithOtherMatchers(t *testing.T) { |
| 682 | tests := []struct { |
| 683 | name string |
| 684 | input string |
| 685 | }{ |
| 686 | { |
| 687 | name: "expression alone", |
| 688 | input: `reverse_proxy localhost:9080 { |
| 689 | lb_retry_match { |
| 690 | expression ` + "`{rp.status_code} in [502, 503]`" + ` |
| 691 | } |
| 692 | }`, |
| 693 | }, |
| 694 | { |
| 695 | name: "method alone", |
| 696 | input: `reverse_proxy localhost:9080 { |
| 697 | lb_retry_match { |
| 698 | method PUT |
| 699 | } |
| 700 | }`, |
| 701 | }, |
| 702 | { |
| 703 | name: "expression mixed with method", |
| 704 | input: `reverse_proxy localhost:9080 { |
| 705 | lb_retry_match { |
| 706 | method POST |
| 707 | expression ` + "`{rp.status_code} in [502, 503]`" + ` |
| 708 | } |
| 709 | }`, |
| 710 | }, |
| 711 | { |
| 712 | name: "expression mixed with path", |
| 713 | input: `reverse_proxy localhost:9080 { |
| 714 | lb_retry_match { |
| 715 | path /api* |
| 716 | expression ` + "`{rp.status_code} == 502`" + ` |
| 717 | } |
| 718 | }`, |
| 719 | }, |
| 720 | } |
| 721 | |
| 722 | for _, tc := range tests { |
| 723 | t.Run(tc.name, func(t *testing.T) { |
| 724 | h := &Handler{} |
| 725 | d := caddyfile.NewTestDispenser(tc.input) |
| 726 | err := h.UnmarshalCaddyfile(d) |
| 727 | if err != nil { |
| 728 | t.Errorf("unexpected error: %v", err) |
| 729 | } |
| 730 | }) |
| 731 | } |
| 732 | } |
| 733 | |
| 734 | // TestSubrouteErrorFallbackWithBody is similar to TestDialErrorBodyRetry but |
| 735 | // mimics Subroute's Error handler rather than testing retries specifically |
| 736 | func TestSubrouteErrorFallbackWithBody(t *testing.T) { |
| 737 | // Good upstream: echoes the request body with 200 OK. |
| 738 | goodServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 739 | body, err := io.ReadAll(r.Body) |
| 740 | if err != nil { |
| 741 | http.Error(w, "read body: "+err.Error(), http.StatusInternalServerError) |
| 742 | return |
| 743 | } |
| 744 | w.WriteHeader(http.StatusOK) |
| 745 | _, err = w.Write(body) |
| 746 | if err != nil { |
| 747 | t.Errorf("error writing in good server: %v", err) |
| 748 | } |
| 749 | })) |
| 750 | t.Cleanup(goodServer.Close) |
| 751 | |
| 752 | // Handler which will dial error |
| 753 | badProxy := minimalHandler(0, &Upstream{Host: new(Host), Dial: deadUpstreamAddr(t)}) |
| 754 | |
| 755 | bodyReader := newCloseOnCloseReader("hello world") |
| 756 | req := httptest.NewRequest("POST", "http://localhost/", bodyReader) |
| 757 | // httptest.NewRequest wraps the reader in NopCloser; replace |
| 758 | // it with our close-aware reader so Close() is propagated. |
| 759 | req.Body = bodyReader |
| 760 | |
| 761 | req = prepareTestRequest(req) |
| 762 | rec := httptest.NewRecorder() |
| 763 | err := badProxy.ServeHTTP(rec, req, caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 764 | return nil |
| 765 | })) |
| 766 | if err == nil { |
| 767 | t.Fatalf("Expected error from badProxy.ServeHTTP") |
| 768 | } |
| 769 | |
| 770 | // Simulate the Subroute's Error handler by calling another handler with the |
| 771 | // same request and recorder |
| 772 | goodProxy := minimalHandler(0, &Upstream{Host: new(Host), Dial: goodServer.Listener.Addr().String()}) |
| 773 | err = goodProxy.ServeHTTP(rec, req, caddyhttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 774 | return nil |
| 775 | })) |
| 776 | |
| 777 | if err != nil { |
| 778 | t.Fatalf("Expected no error from goodProxy.ServeHTTP, got: %v", err) |
| 779 | } |
| 780 | if rec.Code != http.StatusOK { |
| 781 | t.Errorf("status: got %d, want %d", rec.Code, http.StatusOK) |
| 782 | } |
| 783 | expectedBody := "hello world" |
| 784 | if rec.Body.String() != expectedBody { |
| 785 | t.Errorf("body: got %q, want %q", rec.Body.String(), expectedBody) |
| 786 | } |
| 787 | } |