| 1 | package integration |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "math/rand/v2" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | |
| 12 | "github.com/caddyserver/caddy/v2/caddytest" |
| 13 | ) |
| 14 | |
| 15 | func setupListenerWrapperTest(t *testing.T, handlerFunc http.HandlerFunc) *caddytest.Tester { |
| 16 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 17 | if err != nil { |
| 18 | t.Fatalf("failed to listen: %s", err) |
| 19 | } |
| 20 | |
| 21 | mux := http.NewServeMux() |
| 22 | mux.Handle("/", handlerFunc) |
| 23 | srv := &http.Server{ |
| 24 | Handler: mux, |
| 25 | } |
| 26 | go srv.Serve(l) |
| 27 | t.Cleanup(func() { |
| 28 | _ = srv.Close() |
| 29 | _ = l.Close() |
| 30 | }) |
| 31 | tester := caddytest.NewTester(t) |
| 32 | tester.InitServer(fmt.Sprintf(` |
| 33 | { |
| 34 | skip_install_trust |
| 35 | admin localhost:2999 |
| 36 | http_port 9080 |
| 37 | https_port 9443 |
| 38 | local_certs |
| 39 | servers :9443 { |
| 40 | listener_wrappers { |
| 41 | http_redirect |
| 42 | tls |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | localhost { |
| 47 | reverse_proxy %s |
| 48 | } |
| 49 | `, l.Addr().String()), "caddyfile") |
| 50 | return tester |
| 51 | } |
| 52 | |
| 53 | func TestHTTPRedirectWrapperWithLargeUpload(t *testing.T) { |
| 54 | const uploadSize = (1024 * 1024) + 1 // 1 MB + 1 byte |
| 55 | // 1 more than an MB |
| 56 | body := make([]byte, uploadSize) |
| 57 | rand.NewChaCha8([32]byte{}).Read(body) |
| 58 | |
| 59 | tester := setupListenerWrapperTest(t, func(writer http.ResponseWriter, request *http.Request) { |
| 60 | buf := new(bytes.Buffer) |
| 61 | _, err := buf.ReadFrom(request.Body) |
| 62 | if err != nil { |
| 63 | t.Fatalf("failed to read body: %s", err) |
| 64 | } |
| 65 | |
| 66 | if !bytes.Equal(buf.Bytes(), body) { |
| 67 | t.Fatalf("body not the same") |
| 68 | } |
| 69 | |
| 70 | writer.WriteHeader(http.StatusNoContent) |
| 71 | }) |
| 72 | resp, err := tester.Client.Post("https://localhost:9443", "application/octet-stream", bytes.NewReader(body)) |
| 73 | if err != nil { |
| 74 | t.Fatalf("failed to post: %s", err) |
| 75 | } |
| 76 | |
| 77 | if resp.StatusCode != http.StatusNoContent { |
| 78 | t.Fatalf("unexpected status: %d != %d", resp.StatusCode, http.StatusNoContent) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | func TestLargeHttpRequest(t *testing.T) { |
| 83 | tester := setupListenerWrapperTest(t, func(writer http.ResponseWriter, request *http.Request) { |
| 84 | t.Fatal("not supposed to handle a request") |
| 85 | }) |
| 86 | |
| 87 | // We never read the body in any way, set an extra long header instead. |
| 88 | req, _ := http.NewRequest("POST", "http://localhost:9443", nil) |
| 89 | req.Header.Set("Long-Header", strings.Repeat("X", 1024*1024)) |
| 90 | _, err := tester.Client.Do(req) |
| 91 | if err == nil { |
| 92 | t.Fatal("not supposed to succeed") |
| 93 | } |
| 94 | } |