Debian Codegraph @

caddytest/integration/reverseproxy_test.go

raw symbols SCIP
1 package integration
2
3 import (
4 "fmt"
5 "net"
6 "net/http"
7 "os"
8 "runtime"
9 "strings"
10 "sync/atomic"
11 "testing"
12
13 "github.com/caddyserver/caddy/v2/caddytest"
14 )
15
16 func TestSRVReverseProxy(t *testing.T) {
17 tester := caddytest.NewTester(t)
18 tester.InitServer(`
19 {
20 "admin": {
21 "listen": "localhost:2999"
22 },
23 "apps": {
24 "pki": {
25 "certificate_authorities": {
26 "local": {
27 "install_trust": false
28 }
29 }
30 },
31 "http": {
32 "grace_period": 1,
33 "servers": {
34 "srv0": {
35 "listen": [
36 ":18080"
37 ],
38 "routes": [
39 {
40 "handle": [
41 {
42 "handler": "reverse_proxy",
43 "dynamic_upstreams": {
44 "source": "srv",
45 "name": "srv.host.service.consul"
46 }
47 }
48 ]
49 }
50 ]
51 }
52 }
53 }
54 }
55 }
56 `, "json")
57 }
58
59 func TestDialWithPlaceholderUnix(t *testing.T) {
60 if runtime.GOOS == "windows" {
61 t.SkipNow()
62 }
63
64 f, err := os.CreateTemp("", "*.sock")
65 if err != nil {
66 t.Errorf("failed to create TempFile: %s", err)
67 return
68 }
69 // a hack to get a file name within a valid path to use as socket
70 socketName := f.Name()
71 os.Remove(f.Name())
72
73 server := http.Server{
74 Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
75 w.Write([]byte("Hello, World!"))
76 }),
77 }
78
79 unixListener, err := net.Listen("unix", socketName)
80 if err != nil {
81 t.Errorf("failed to listen on the socket: %s", err)
82 return
83 }
84 go server.Serve(unixListener)
85 t.Cleanup(func() {
86 server.Close()
87 })
88 runtime.Gosched() // Allow other goroutines to run
89
90 tester := caddytest.NewTester(t)
91 tester.InitServer(`
92 {
93 "admin": {
94 "listen": "localhost:2999"
95 },
96 "apps": {
97 "pki": {
98 "certificate_authorities": {
99 "local": {
100 "install_trust": false
101 }
102 }
103 },
104 "http": {
105 "grace_period": 1,
106 "servers": {
107 "srv0": {
108 "listen": [
109 ":18080"
110 ],
111 "routes": [
112 {
113 "handle": [
114 {
115 "handler": "reverse_proxy",
116 "upstreams": [
117 {
118 "dial": "unix/{http.request.header.X-Caddy-Upstream-Dial}"
119 }
120 ]
121 }
122 ]
123 }
124 ]
125 }
126 }
127 }
128 }
129 }
130 `, "json")
131
132 req, err := http.NewRequest(http.MethodGet, "http://localhost:18080", nil)
133 if err != nil {
134 t.Fail()
135 return
136 }
137 req.Header.Set("X-Caddy-Upstream-Dial", socketName)
138 tester.AssertResponse(req, 200, "Hello, World!")
139 }
140
141 func TestReverseProxyWithPlaceholderDialAddress(t *testing.T) {
142 tester := caddytest.NewTester(t)
143 tester.InitServer(`
144 {
145 "admin": {
146 "listen": "localhost:2999"
147 },
148 "apps": {
149 "pki": {
150 "certificate_authorities": {
151 "local": {
152 "install_trust": false
153 }
154 }
155 },
156 "http": {
157 "grace_period": 1,
158 "servers": {
159 "srv0": {
160 "listen": [
161 ":18080"
162 ],
163 "routes": [
164 {
165 "match": [
166 {
167 "host": [
168 "localhost"
169 ]
170 }
171 ],
172 "handle": [
173 {
174 "handler": "static_response",
175 "body": "Hello, World!"
176 }
177 ],
178 "terminal": true
179 }
180 ],
181 "automatic_https": {
182 "skip": [
183 "localhost"
184 ]
185 }
186 },
187 "srv1": {
188 "listen": [
189 ":9080"
190 ],
191 "routes": [
192 {
193 "match": [
194 {
195 "host": [
196 "localhost"
197 ]
198 }
199 ],
200 "handle": [
201 {
202
203 "handler": "reverse_proxy",
204 "upstreams": [
205 {
206 "dial": "{http.request.header.X-Caddy-Upstream-Dial}"
207 }
208 ]
209 }
210 ],
211 "terminal": true
212 }
213 ],
214 "automatic_https": {
215 "skip": [
216 "localhost"
217 ]
218 }
219 }
220 }
221 }
222 }
223 }
224 `, "json")
225
226 req, err := http.NewRequest(http.MethodGet, "http://localhost:9080", nil)
227 if err != nil {
228 t.Fail()
229 return
230 }
231 req.Header.Set("X-Caddy-Upstream-Dial", "localhost:18080")
232 tester.AssertResponse(req, 200, "Hello, World!")
233 }
234
235 func TestReverseProxyWithPlaceholderTCPDialAddress(t *testing.T) {
236 tester := caddytest.NewTester(t)
237 tester.InitServer(`
238 {
239 "admin": {
240 "listen": "localhost:2999"
241 },
242 "apps": {
243 "pki": {
244 "certificate_authorities": {
245 "local": {
246 "install_trust": false
247 }
248 }
249 },
250 "http": {
251 "grace_period": 1,
252 "servers": {
253 "srv0": {
254 "listen": [
255 ":18080"
256 ],
257 "routes": [
258 {
259 "match": [
260 {
261 "host": [
262 "localhost"
263 ]
264 }
265 ],
266 "handle": [
267 {
268 "handler": "static_response",
269 "body": "Hello, World!"
270 }
271 ],
272 "terminal": true
273 }
274 ],
275 "automatic_https": {
276 "skip": [
277 "localhost"
278 ]
279 }
280 },
281 "srv1": {
282 "listen": [
283 ":9080"
284 ],
285 "routes": [
286 {
287 "match": [
288 {
289 "host": [
290 "localhost"
291 ]
292 }
293 ],
294 "handle": [
295 {
296
297 "handler": "reverse_proxy",
298 "upstreams": [
299 {
300 "dial": "tcp/{http.request.header.X-Caddy-Upstream-Dial}:18080"
301 }
302 ]
303 }
304 ],
305 "terminal": true
306 }
307 ],
308 "automatic_https": {
309 "skip": [
310 "localhost"
311 ]
312 }
313 }
314 }
315 }
316 }
317 }
318 `, "json")
319
320 req, err := http.NewRequest(http.MethodGet, "http://localhost:9080", nil)
321 if err != nil {
322 t.Fail()
323 return
324 }
325 req.Header.Set("X-Caddy-Upstream-Dial", "localhost")
326 tester.AssertResponse(req, 200, "Hello, World!")
327 }
328
329 func TestReverseProxyHealthCheck(t *testing.T) {
330 // Start lightweight backend servers so they're ready before Caddy's
331 // active health checker runs; this avoids a startup race where the
332 // health checker probes backends that haven't yet begun accepting
333 // connections and marks them unhealthy.
334 //
335 // This mirrors how health checks are typically used in practice (to a separate
336 // backend service) and avoids probing the same Caddy instance while it's still
337 // provisioning and not ready to accept connections.
338
339 // backend server that responds to proxied requests
340 helloSrv := &http.Server{
341 Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
342 _, _ = w.Write([]byte("Hello, World!"))
343 }),
344 }
345 ln0, err := net.Listen("tcp", "127.0.0.1:2020")
346 if err != nil {
347 t.Fatalf("failed to listen on 127.0.0.1:2020: %v", err)
348 }
349 go helloSrv.Serve(ln0)
350 t.Cleanup(func() { helloSrv.Close(); ln0.Close() })
351
352 // backend server that serves health checks
353 healthSrv := &http.Server{
354 Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
355 _, _ = w.Write([]byte("ok"))
356 }),
357 }
358 ln1, err := net.Listen("tcp", "127.0.0.1:2021")
359 if err != nil {
360 t.Fatalf("failed to listen on 127.0.0.1:2021: %v", err)
361 }
362 go healthSrv.Serve(ln1)
363 t.Cleanup(func() { healthSrv.Close(); ln1.Close() })
364
365 tester := caddytest.NewTester(t)
366 tester.InitServer(`
367 {
368 skip_install_trust
369 admin localhost:2999
370 http_port 9080
371 https_port 9443
372 grace_period 1ns
373 }
374 http://localhost:9080 {
375 reverse_proxy {
376 to localhost:2020
377
378 health_uri /health
379 health_port 2021
380 health_interval 10ms
381 health_timeout 100ms
382 health_passes 1
383 health_fails 1
384 }
385 }
386 `, "caddyfile")
387 tester.AssertGetResponse("http://localhost:9080/", 200, "Hello, World!")
388 }
389
390 // TestReverseProxyHealthCheckPortUsed verifies that health_port is actually
391 // used for active health checks and not the upstream's main port. This is a
392 // regression test for https://github.com/caddyserver/caddy/issues/7524.
393 func TestReverseProxyHealthCheckPortUsed(t *testing.T) {
394 // upstream server: serves proxied requests normally, but returns 503 for
395 // /health so that if health checks mistakenly hit this port the upstream
396 // gets marked unhealthy and the proxy returns 503.
397 upstreamSrv := &http.Server{
398 Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
399 if req.URL.Path == "/health" {
400 w.WriteHeader(http.StatusServiceUnavailable)
401 return
402 }
403 _, _ = w.Write([]byte("Hello, World!"))
404 }),
405 }
406 ln0, err := net.Listen("tcp", "127.0.0.1:2022")
407 if err != nil {
408 t.Fatalf("failed to listen on 127.0.0.1:2022: %v", err)
409 }
410 go upstreamSrv.Serve(ln0)
411 t.Cleanup(func() { upstreamSrv.Close(); ln0.Close() })
412
413 // separate health check server on the configured health_port: returns 200
414 // so the upstream is marked healthy only if health checks go to this port.
415 healthSrv := &http.Server{
416 Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
417 _, _ = w.Write([]byte("ok"))
418 }),
419 }
420 ln1, err := net.Listen("tcp", "127.0.0.1:2023")
421 if err != nil {
422 t.Fatalf("failed to listen on 127.0.0.1:2023: %v", err)
423 }
424 go healthSrv.Serve(ln1)
425 t.Cleanup(func() { healthSrv.Close(); ln1.Close() })
426
427 tester := caddytest.NewTester(t)
428 tester.InitServer(`
429 {
430 skip_install_trust
431 admin localhost:2999
432 http_port 9080
433 https_port 9443
434 grace_period 1ns
435 }
436 http://localhost:9080 {
437 reverse_proxy {
438 to localhost:2022
439
440 health_uri /health
441 health_port 2023
442 health_interval 10ms
443 health_timeout 100ms
444 health_passes 1
445 health_fails 1
446 }
447 }
448 `, "caddyfile")
449 tester.AssertGetResponse("http://localhost:9080/", 200, "Hello, World!")
450 }
451
452 func TestReverseProxyHealthCheckUnixSocket(t *testing.T) {
453 if runtime.GOOS == "windows" {
454 t.SkipNow()
455 }
456 tester := caddytest.NewTester(t)
457 f, err := os.CreateTemp("", "*.sock")
458 if err != nil {
459 t.Errorf("failed to create TempFile: %s", err)
460 return
461 }
462 // a hack to get a file name within a valid path to use as socket
463 socketName := f.Name()
464 os.Remove(f.Name())
465
466 server := http.Server{
467 Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
468 if strings.HasPrefix(req.URL.Path, "/health") {
469 w.Write([]byte("ok"))
470 return
471 }
472 w.Write([]byte("Hello, World!"))
473 }),
474 }
475
476 unixListener, err := net.Listen("unix", socketName)
477 if err != nil {
478 t.Errorf("failed to listen on the socket: %s", err)
479 return
480 }
481 go server.Serve(unixListener)
482 t.Cleanup(func() {
483 server.Close()
484 })
485 runtime.Gosched() // Allow other goroutines to run
486
487 tester.InitServer(fmt.Sprintf(`
488 {
489 skip_install_trust
490 admin localhost:2999
491 http_port 9080
492 https_port 9443
493 grace_period 1ns
494 }
495 http://localhost:9080 {
496 reverse_proxy {
497 to unix/%s
498
499 health_uri /health
500 health_port 2021
501 health_interval 2s
502 health_timeout 5s
503 }
504 }
505 `, socketName), "caddyfile")
506
507 tester.AssertGetResponse("http://localhost:9080/", 200, "Hello, World!")
508 }
509
510 func TestReverseProxyHealthCheckUnixSocketWithoutPort(t *testing.T) {
511 if runtime.GOOS == "windows" {
512 t.SkipNow()
513 }
514 tester := caddytest.NewTester(t)
515 f, err := os.CreateTemp("", "*.sock")
516 if err != nil {
517 t.Errorf("failed to create TempFile: %s", err)
518 return
519 }
520 // a hack to get a file name within a valid path to use as socket
521 socketName := f.Name()
522 os.Remove(f.Name())
523
524 server := http.Server{
525 Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
526 if strings.HasPrefix(req.URL.Path, "/health") {
527 w.Write([]byte("ok"))
528 return
529 }
530 w.Write([]byte("Hello, World!"))
531 }),
532 }
533
534 unixListener, err := net.Listen("unix", socketName)
535 if err != nil {
536 t.Errorf("failed to listen on the socket: %s", err)
537 return
538 }
539 go server.Serve(unixListener)
540 t.Cleanup(func() {
541 server.Close()
542 })
543 runtime.Gosched() // Allow other goroutines to run
544
545 tester.InitServer(fmt.Sprintf(`
546 {
547 skip_install_trust
548 admin localhost:2999
549 http_port 9080
550 https_port 9443
551 grace_period 1ns
552 }
553 http://localhost:9080 {
554 reverse_proxy {
555 to unix/%s
556
557 health_uri /health
558 health_interval 2s
559 health_timeout 5s
560 }
561 }
562 `, socketName), "caddyfile")
563
564 tester.AssertGetResponse("http://localhost:9080/", 200, "Hello, World!")
565 }
566
567 // TestReverseProxyRetryMatchStatusCode verifies that lb_retry_match with a
568 // CEL expression matching on {rp.status_code} causes the request to be
569 // retried on the next upstream when the first upstream returns a matching
570 // status code
571 func TestReverseProxyRetryMatchStatusCode(t *testing.T) {
572 // Bad upstream: returns 502
573 badSrv := &http.Server{
574 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
575 w.WriteHeader(http.StatusBadGateway)
576 }),
577 }
578 badLn, err := net.Listen("tcp", "127.0.0.1:0")
579 if err != nil {
580 t.Fatalf("failed to listen: %v", err)
581 }
582 go badSrv.Serve(badLn)
583 t.Cleanup(func() { badSrv.Close(); badLn.Close() })
584
585 // Good upstream: returns 200
586 goodSrv := &http.Server{
587 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
588 w.Write([]byte("ok"))
589 }),
590 }
591 goodLn, err := net.Listen("tcp", "127.0.0.1:0")
592 if err != nil {
593 t.Fatalf("failed to listen: %v", err)
594 }
595 go goodSrv.Serve(goodLn)
596 t.Cleanup(func() { goodSrv.Close(); goodLn.Close() })
597
598 tester := caddytest.NewTester(t)
599 tester.InitServer(fmt.Sprintf(`
600 {
601 skip_install_trust
602 admin localhost:2999
603 http_port 9080
604 https_port 9443
605 grace_period 1ns
606 }
607 http://localhost:9080 {
608 reverse_proxy %s %s {
609 lb_policy round_robin
610 lb_retries 1
611 lb_retry_match {
612 expression `+"`{rp.status_code} in [502, 503]`"+`
613 }
614 }
615 }
616 `, goodLn.Addr().String(), badLn.Addr().String()), "caddyfile")
617
618 tester.AssertGetResponse("http://localhost:9080/", 200, "ok")
619 }
620
621 // TestReverseProxyRetryMatchHeader verifies that lb_retry_match with a CEL
622 // expression matching on {rp.header.*} causes the request to be retried when
623 // the upstream sets a matching response header
624 func TestReverseProxyRetryMatchHeader(t *testing.T) {
625 var badHits atomic.Int32
626
627 // Bad upstream: returns 200 but signals retry via header
628 badSrv := &http.Server{
629 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
630 badHits.Add(1)
631 w.Header().Set("X-Upstream-Retry", "true")
632 w.Write([]byte("bad"))
633 }),
634 }
635 badLn, err := net.Listen("tcp", "127.0.0.1:0")
636 if err != nil {
637 t.Fatalf("failed to listen: %v", err)
638 }
639 go badSrv.Serve(badLn)
640 t.Cleanup(func() { badSrv.Close(); badLn.Close() })
641
642 // Good upstream: returns 200 without retry header
643 goodSrv := &http.Server{
644 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
645 w.Write([]byte("good"))
646 }),
647 }
648 goodLn, err := net.Listen("tcp", "127.0.0.1:0")
649 if err != nil {
650 t.Fatalf("failed to listen: %v", err)
651 }
652 go goodSrv.Serve(goodLn)
653 t.Cleanup(func() { goodSrv.Close(); goodLn.Close() })
654
655 tester := caddytest.NewTester(t)
656 tester.InitServer(fmt.Sprintf(`
657 {
658 skip_install_trust
659 admin localhost:2999
660 http_port 9080
661 https_port 9443
662 grace_period 1ns
663 }
664 http://localhost:9080 {
665 reverse_proxy %s %s {
666 lb_policy round_robin
667 lb_retries 1
668 lb_retry_match {
669 expression `+"`{rp.header.X-Upstream-Retry} == \"true\"`"+`
670 }
671 }
672 }
673 `, goodLn.Addr().String(), badLn.Addr().String()), "caddyfile")
674
675 tester.AssertGetResponse("http://localhost:9080/", 200, "good")
676
677 if badHits.Load() != 1 {
678 t.Errorf("bad upstream hits: got %d, want 1", badHits.Load())
679 }
680 }
681
682 // TestReverseProxyRetryMatchCombined verifies that a CEL expression combining
683 // request path matching with response status code matching works correctly -
684 // only retrying when both conditions are met
685 func TestReverseProxyRetryMatchCombined(t *testing.T) {
686 // Upstream: returns 502 for all requests
687 srv := &http.Server{
688 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
689 w.WriteHeader(http.StatusBadGateway)
690 }),
691 }
692 ln, err := net.Listen("tcp", "127.0.0.1:0")
693 if err != nil {
694 t.Fatalf("failed to listen: %v", err)
695 }
696 go srv.Serve(ln)
697 t.Cleanup(func() { srv.Close(); ln.Close() })
698
699 // Good upstream
700 goodSrv := &http.Server{
701 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
702 w.Write([]byte("ok"))
703 }),
704 }
705 goodLn, err := net.Listen("tcp", "127.0.0.1:0")
706 if err != nil {
707 t.Fatalf("failed to listen: %v", err)
708 }
709 go goodSrv.Serve(goodLn)
710 t.Cleanup(func() { goodSrv.Close(); goodLn.Close() })
711
712 tester := caddytest.NewTester(t)
713 tester.InitServer(fmt.Sprintf(`
714 {
715 skip_install_trust
716 admin localhost:2999
717 http_port 9080
718 https_port 9443
719 grace_period 1ns
720 }
721 http://localhost:9080 {
722 reverse_proxy %s %s {
723 lb_policy round_robin
724 lb_retries 1
725 lb_retry_match {
726 expression `+"`path('/retry*') && {rp.status_code} in [502, 503]`"+`
727 }
728 }
729 }
730 `, goodLn.Addr().String(), ln.Addr().String()), "caddyfile")
731
732 // /retry path matches the expression - should retry to good upstream
733 tester.AssertGetResponse("http://localhost:9080/retry", 200, "ok")
734
735 // /other path does NOT match - should return the 502
736 req, _ := http.NewRequest(http.MethodGet, "http://localhost:9080/other", nil)
737 tester.AssertResponse(req, 502, "")
738 }
739
740 // TestReverseProxyRetryMatchIsTransportError verifies that the
741 // {rp.is_transport_error} == true CEL function correctly identifies transport errors
742 // and allows retrying them alongside response-based matching
743 func TestReverseProxyRetryMatchIsTransportError(t *testing.T) {
744 // Good upstream: returns 200
745 goodSrv := &http.Server{
746 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
747 w.Write([]byte("ok"))
748 }),
749 }
750 goodLn, err := net.Listen("tcp", "127.0.0.1:0")
751 if err != nil {
752 t.Fatalf("failed to listen: %v", err)
753 }
754 go goodSrv.Serve(goodLn)
755 t.Cleanup(func() { goodSrv.Close(); goodLn.Close() })
756
757 // Broken upstream: accepts connections but closes immediately
758 brokenLn, err := net.Listen("tcp", "127.0.0.1:0")
759 if err != nil {
760 t.Fatalf("failed to listen: %v", err)
761 }
762 t.Cleanup(func() { brokenLn.Close() })
763 go func() {
764 for {
765 conn, err := brokenLn.Accept()
766 if err != nil {
767 return
768 }
769 conn.Close()
770 }
771 }()
772
773 tester := caddytest.NewTester(t)
774 tester.InitServer(fmt.Sprintf(`
775 {
776 skip_install_trust
777 admin localhost:2999
778 http_port 9080
779 https_port 9443
780 grace_period 1ns
781 }
782 http://localhost:9080 {
783 reverse_proxy %s %s {
784 lb_policy round_robin
785 lb_retries 1
786 lb_retry_match {
787 expression `+"`{rp.is_transport_error} || {rp.status_code} in [502, 503]`"+`
788 }
789 }
790 }
791 `, goodLn.Addr().String(), brokenLn.Addr().String()), "caddyfile")
792
793 // Transport error on broken upstream should be retried to good upstream
794 tester.AssertGetResponse("http://localhost:9080/", 200, "ok")
795 }