|
4 | 4 | package proxy |
5 | 5 |
|
6 | 6 | import ( |
| 7 | + "bufio" |
| 8 | + "io" |
| 9 | + "net" |
7 | 10 | "net/http" |
8 | 11 | "net/http/httputil" |
9 | 12 | "net/url" |
10 | 13 | "testing" |
| 14 | + "time" |
11 | 15 |
|
12 | 16 | "github.com/stretchr/testify/assert" |
13 | 17 | "github.com/stretchr/testify/require" |
14 | 18 |
|
| 19 | + "github.com/ory/graceful" |
15 | 20 | "github.com/ory/x/proxy" |
16 | 21 | ) |
17 | 22 |
|
| 23 | +func TestNewServer(t *testing.T) { |
| 24 | + build := func(t *testing.T, conf *config) *http.Server { |
| 25 | + t.Helper() |
| 26 | + srv, err := newServer("", http.NewServeMux(), conf) |
| 27 | + require.NoError(t, err) |
| 28 | + return srv |
| 29 | + } |
| 30 | + |
| 31 | + t.Run("case=defaults to no read or write timeout", func(t *testing.T) { |
| 32 | + srv := build(t, &config{}) |
| 33 | + |
| 34 | + // graceful.WithDefaults would otherwise impose 10s write / 5s read, |
| 35 | + // truncating any slower exchange with an empty reply. |
| 36 | + assert.Zero(t, srv.WriteTimeout) |
| 37 | + assert.Zero(t, srv.ReadTimeout) |
| 38 | + |
| 39 | + // Headers must still arrive promptly and idle connections must still be |
| 40 | + // recycled. |
| 41 | + assert.Equal(t, graceful.DefaultReadHeaderTimeout, srv.ReadHeaderTimeout) |
| 42 | + assert.Equal(t, graceful.DefaultIdleTimeout, srv.IdleTimeout) |
| 43 | + }) |
| 44 | + |
| 45 | + t.Run("case=honors explicitly configured timeouts", func(t *testing.T) { |
| 46 | + srv := build(t, &config{readTimeout: 7 * time.Second, writeTimeout: 3 * time.Second}) |
| 47 | + |
| 48 | + assert.Equal(t, 7*time.Second, srv.ReadTimeout) |
| 49 | + assert.Equal(t, 3*time.Second, srv.WriteTimeout) |
| 50 | + assert.Equal(t, graceful.DefaultReadHeaderTimeout, srv.ReadHeaderTimeout) |
| 51 | + }) |
| 52 | + |
| 53 | + t.Run("case=a read timeout below the header deadline lowers it", func(t *testing.T) { |
| 54 | + // net/http prefers a non-zero ReadHeaderTimeout over ReadTimeout, so the |
| 55 | + // header deadline has to come down too or the configured limit is |
| 56 | + // silently exceeded while the headers arrive. |
| 57 | + srv := build(t, &config{readTimeout: time.Second}) |
| 58 | + |
| 59 | + assert.Equal(t, time.Second, srv.ReadTimeout) |
| 60 | + assert.Equal(t, time.Second, srv.ReadHeaderTimeout) |
| 61 | + }) |
| 62 | + |
| 63 | + t.Run("case=rejects negative timeouts", func(t *testing.T) { |
| 64 | + // net/http reads a negative timeout as "no timeout", the opposite of |
| 65 | + // what the caller asked for. |
| 66 | + _, err := newServer("", http.NewServeMux(), &config{readTimeout: -time.Second}) |
| 67 | + assert.ErrorContains(t, err, ReadTimeoutFlag) |
| 68 | + |
| 69 | + _, err = newServer("", http.NewServeMux(), &config{writeTimeout: -time.Second}) |
| 70 | + assert.ErrorContains(t, err, WriteTimeoutFlag) |
| 71 | + }) |
| 72 | +} |
| 73 | + |
| 74 | +// TestServerWriteTimeout is the regression test for |
| 75 | +// https://github.com/ory/cli/issues/302: a response slower than the write |
| 76 | +// deadline used to be cut off mid-flight, leaving the client with an empty |
| 77 | +// reply and no error to go on. |
| 78 | +func TestServerWriteTimeout(t *testing.T) { |
| 79 | + const body = "this took a while" |
| 80 | + |
| 81 | + // Slower than the configured deadline in the bounded case below, but still |
| 82 | + // fast enough to keep the test quick. |
| 83 | + const handlerDelay = 300 * time.Millisecond |
| 84 | + |
| 85 | + for _, tc := range []struct { |
| 86 | + name string |
| 87 | + writeTimeout time.Duration |
| 88 | + expectBody bool |
| 89 | + }{ |
| 90 | + {name: "case=slow response survives the default config", writeTimeout: 0, expectBody: true}, |
| 91 | + {name: "case=slow response is cut off when a write timeout is set", writeTimeout: 50 * time.Millisecond, expectBody: false}, |
| 92 | + } { |
| 93 | + t.Run(tc.name, func(t *testing.T) { |
| 94 | + mux := http.NewServeMux() |
| 95 | + mux.HandleFunc("/fast", func(w http.ResponseWriter, _ *http.Request) { |
| 96 | + _, _ = io.WriteString(w, body) |
| 97 | + }) |
| 98 | + mux.HandleFunc("/slow", func(w http.ResponseWriter, _ *http.Request) { |
| 99 | + time.Sleep(handlerDelay) |
| 100 | + _, _ = io.WriteString(w, body) |
| 101 | + }) |
| 102 | + |
| 103 | + // Built exactly as runReverseProxy builds its server. |
| 104 | + srv, err := newServer("127.0.0.1:0", mux, &config{writeTimeout: tc.writeTimeout}) |
| 105 | + require.NoError(t, err) |
| 106 | + |
| 107 | + ln, err := net.Listen("tcp", srv.Addr) |
| 108 | + require.NoError(t, err) |
| 109 | + |
| 110 | + served := make(chan struct{}) |
| 111 | + go func() { defer close(served); _ = srv.Serve(ln) }() |
| 112 | + t.Cleanup(func() { |
| 113 | + _ = srv.Close() |
| 114 | + _ = ln.Close() |
| 115 | + <-served |
| 116 | + }) |
| 117 | + |
| 118 | + // Give every request its own connection: a cut-off response on a |
| 119 | + // pooled one would be silently retried by the transport. |
| 120 | + cl := &http.Client{Timeout: 10 * time.Second, Transport: &http.Transport{DisableKeepAlives: true}} |
| 121 | + t.Cleanup(cl.CloseIdleConnections) |
| 122 | + baseURL := "http://" + ln.Addr().String() |
| 123 | + |
| 124 | + // Positive control: the server is up and answering, so a failure |
| 125 | + // below can only come from the write deadline. |
| 126 | + requireBody(t, cl, baseURL+"/fast", body) |
| 127 | + |
| 128 | + if !tc.expectBody { |
| 129 | + _, err := cl.Get(baseURL + "/slow") |
| 130 | + require.Error(t, err, "server should have cut the response off") |
| 131 | + return |
| 132 | + } |
| 133 | + requireBody(t, cl, baseURL+"/slow", body) |
| 134 | + }) |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +type recordingResponseWriter struct { |
| 139 | + header http.Header |
| 140 | + flushed, hijacked bool |
| 141 | +} |
| 142 | + |
| 143 | +func (f *recordingResponseWriter) Header() http.Header { return f.header } |
| 144 | +func (f *recordingResponseWriter) Write(b []byte) (int, error) { return len(b), nil } |
| 145 | +func (f *recordingResponseWriter) WriteHeader(int) {} |
| 146 | +func (f *recordingResponseWriter) Flush() { f.flushed = true } |
| 147 | +func (f *recordingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { |
| 148 | + f.hijacked = true |
| 149 | + return nil, nil, nil |
| 150 | +} |
| 151 | + |
| 152 | +// TestResponseStatusCatcher guards the ResponseWriter wrapper the proxy puts in |
| 153 | +// front of every response. httputil.ReverseProxy reaches the underlying writer |
| 154 | +// through http.ResponseController: Flush for streaming responses, Hijack for |
| 155 | +// protocol upgrades such as WebSockets. A wrapper that does not expose Unwrap |
| 156 | +// hides both, and the upgrade fails with "can't switch protocols using |
| 157 | +// non-Hijacker ResponseWriter type". |
| 158 | +func TestResponseStatusCatcher(t *testing.T) { |
| 159 | + inner := &recordingResponseWriter{header: http.Header{}} |
| 160 | + catcher := &responseStatusCatcher{ResponseWriter: inner} |
| 161 | + rc := http.NewResponseController(catcher) |
| 162 | + |
| 163 | + require.NoError(t, rc.Flush()) |
| 164 | + assert.True(t, inner.flushed, "flush must reach the wrapped ResponseWriter") |
| 165 | + |
| 166 | + _, _, err := rc.Hijack() |
| 167 | + require.NoError(t, err) |
| 168 | + assert.True(t, inner.hijacked, "hijack must reach the wrapped ResponseWriter") |
| 169 | + |
| 170 | + catcher.WriteHeader(http.StatusTeapot) |
| 171 | + assert.Equal(t, http.StatusTeapot, catcher.status) |
| 172 | +} |
| 173 | + |
| 174 | +func requireBody(t *testing.T, cl *http.Client, url, expected string) { |
| 175 | + t.Helper() |
| 176 | + |
| 177 | + res, err := cl.Get(url) |
| 178 | + require.NoError(t, err) |
| 179 | + defer res.Body.Close() |
| 180 | + |
| 181 | + got, err := io.ReadAll(res.Body) |
| 182 | + require.NoError(t, err) |
| 183 | + assert.Equal(t, expected, string(got)) |
| 184 | +} |
| 185 | + |
18 | 186 | func TestReqMiddleware(t *testing.T) { |
19 | 187 | oryURL := &url.URL{Scheme: "https", Host: "example.projects.oryapis.com"} |
20 | 188 | publicURL := &url.URL{Scheme: "http", Host: "localhost:4000"} |
|
0 commit comments