File
Blob: tun/client/proxy_eof_test.go
| 1 | package client |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "io" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "net/url" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/stretchr/testify/require" |
| 14 | "go.uber.org/zap" |
| 15 | ) |
| 16 | |
| 17 | func TestHTTPProxyUpstreamEOF(t *testing.T) { |
| 18 | upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 19 | if _, err := io.Copy(io.Discard, r.Body); err != nil { |
| 20 | t.Error(err) |
| 21 | return |
| 22 | } |
| 23 | conn, _, err := http.NewResponseController(w).Hijack() |
| 24 | if err != nil { |
| 25 | t.Error(err) |
| 26 | return |
| 27 | } |
| 28 | conn.Close() |
| 29 | })) |
| 30 | defer upstream.Close() |
| 31 | |
| 32 | u, err := url.Parse(upstream.URL) |
| 33 | require.NoError(t, err) |
| 34 | f := newForwarder(zap.NewNop()) |
| 35 | hp := f.newHTTPProxy("eof", Tunnel{parsed: u}) |
| 36 | defer hp.close() |
| 37 | proxy := httptest.NewServer(hp.forwarder.Handler) |
| 38 | defer proxy.Close() |
| 39 | |
| 40 | visitor := proxy.Client() |
| 41 | visitor.Timeout = 5 * time.Second |
| 42 | resp, err := visitor.Post(proxy.URL, "text/plain", strings.NewReader("complete request")) |
| 43 | require.NoError(t, err) |
| 44 | defer resp.Body.Close() |
| 45 | body, err := io.ReadAll(resp.Body) |
| 46 | require.NoError(t, err) |
| 47 | require.Equal(t, http.StatusBadGateway, resp.StatusCode) |
| 48 | require.Equal(t, "Forwarding target returned error: EOF", string(body)) |
| 49 | } |
| 50 | |
| 51 | func TestHTTPProxyCanceledRequest(t *testing.T) { |
| 52 | f := newForwarder(zap.NewNop()) |
| 53 | hp := f.newHTTPProxy("canceled", Tunnel{parsed: &url.URL{Scheme: "http", Host: "upstream.invalid"}}) |
| 54 | defer hp.close() |
| 55 | |
| 56 | ctx, cancel := context.WithCancel(t.Context()) |
| 57 | cancel() |
| 58 | req := httptest.NewRequestWithContext(ctx, http.MethodGet, "http://app.example.com/", nil) |
| 59 | rw := httptest.NewRecorder() |
| 60 | rw.Code = 0 // Distinguish an unwritten response from an implicit 200. |
| 61 | hp.forwarder.Handler.ServeHTTP(rw, req) |
| 62 | require.Zero(t, rw.Code) |
| 63 | require.Empty(t, rw.Body.String()) |
| 64 | } |