http2_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. package connection
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net"
  9. "net/http"
  10. "net/http/httptest"
  11. "sync"
  12. "testing"
  13. "time"
  14. "github.com/gobwas/ws/wsutil"
  15. "github.com/google/uuid"
  16. "github.com/rs/zerolog"
  17. "github.com/stretchr/testify/assert"
  18. "github.com/stretchr/testify/require"
  19. "golang.org/x/net/http2"
  20. "github.com/cloudflare/cloudflared/tunnelrpc"
  21. "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
  22. )
  23. var (
  24. testTransport = http2.Transport{}
  25. )
  26. func newTestHTTP2Connection() (*HTTP2Connection, net.Conn) {
  27. edgeConn, cfdConn := net.Pipe()
  28. var connIndex = uint8(0)
  29. log := zerolog.Nop()
  30. obs := NewObserver(&log, &log)
  31. controlStream := NewControlStream(
  32. obs,
  33. mockConnectedFuse{},
  34. &TunnelProperties{},
  35. connIndex,
  36. nil,
  37. nil,
  38. 1*time.Second,
  39. nil,
  40. 1*time.Second,
  41. HTTP2,
  42. )
  43. return NewHTTP2Connection(
  44. cfdConn,
  45. // OriginProxy is set in testConfigManager
  46. testOrchestrator,
  47. &pogs.ConnectionOptions{},
  48. obs,
  49. connIndex,
  50. controlStream,
  51. &log,
  52. ), edgeConn
  53. }
  54. func TestHTTP2ConfigurationSet(t *testing.T) {
  55. http2Conn, edgeConn := newTestHTTP2Connection()
  56. ctx, cancel := context.WithCancel(context.Background())
  57. var wg sync.WaitGroup
  58. wg.Add(1)
  59. go func() {
  60. defer wg.Done()
  61. http2Conn.Serve(ctx)
  62. }()
  63. edgeHTTP2Conn, err := testTransport.NewClientConn(edgeConn)
  64. require.NoError(t, err)
  65. endpoint := fmt.Sprintf("http://localhost:8080/ok")
  66. reqBody := []byte(`{
  67. "version": 2,
  68. "config": {"warp-routing": {"enabled": true}, "originRequest" : {"connectTimeout": 10}, "ingress" : [ {"hostname": "test", "service": "https://localhost:8000" } , {"service": "http_status:404"} ]}}
  69. `)
  70. reader := bytes.NewReader(reqBody)
  71. req, err := http.NewRequestWithContext(ctx, http.MethodPut, endpoint, reader)
  72. require.NoError(t, err)
  73. req.Header.Set(InternalUpgradeHeader, ConfigurationUpdate)
  74. resp, err := edgeHTTP2Conn.RoundTrip(req)
  75. require.NoError(t, err)
  76. require.Equal(t, http.StatusOK, resp.StatusCode)
  77. bdy, err := io.ReadAll(resp.Body)
  78. require.NoError(t, err)
  79. assert.Equal(t, `{"lastAppliedVersion":2,"err":null}`, string(bdy))
  80. cancel()
  81. wg.Wait()
  82. }
  83. func TestServeHTTP(t *testing.T) {
  84. tests := []testRequest{
  85. {
  86. name: "ok",
  87. endpoint: "ok",
  88. expectedStatus: http.StatusOK,
  89. expectedBody: []byte(http.StatusText(http.StatusOK)),
  90. },
  91. {
  92. name: "large_file",
  93. endpoint: "large_file",
  94. expectedStatus: http.StatusOK,
  95. expectedBody: testLargeResp,
  96. },
  97. {
  98. name: "Bad request",
  99. endpoint: "400",
  100. expectedStatus: http.StatusBadRequest,
  101. expectedBody: []byte(http.StatusText(http.StatusBadRequest)),
  102. },
  103. {
  104. name: "Internal server error",
  105. endpoint: "500",
  106. expectedStatus: http.StatusInternalServerError,
  107. expectedBody: []byte(http.StatusText(http.StatusInternalServerError)),
  108. },
  109. {
  110. name: "Proxy error",
  111. endpoint: "error",
  112. expectedStatus: http.StatusBadGateway,
  113. expectedBody: nil,
  114. isProxyError: true,
  115. },
  116. }
  117. http2Conn, edgeConn := newTestHTTP2Connection()
  118. ctx, cancel := context.WithCancel(context.Background())
  119. var wg sync.WaitGroup
  120. wg.Add(1)
  121. go func() {
  122. defer wg.Done()
  123. http2Conn.Serve(ctx)
  124. }()
  125. edgeHTTP2Conn, err := testTransport.NewClientConn(edgeConn)
  126. require.NoError(t, err)
  127. for _, test := range tests {
  128. endpoint := fmt.Sprintf("http://localhost:8080/%s", test.endpoint)
  129. req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
  130. require.NoError(t, err)
  131. resp, err := edgeHTTP2Conn.RoundTrip(req)
  132. require.NoError(t, err)
  133. require.Equal(t, test.expectedStatus, resp.StatusCode)
  134. if test.expectedBody != nil {
  135. respBody, err := io.ReadAll(resp.Body)
  136. require.NoError(t, err)
  137. require.Equal(t, test.expectedBody, respBody)
  138. }
  139. if test.isProxyError {
  140. require.Equal(t, responseMetaHeaderCfd, resp.Header.Get(ResponseMetaHeader))
  141. } else {
  142. require.Equal(t, responseMetaHeaderOrigin, resp.Header.Get(ResponseMetaHeader))
  143. }
  144. }
  145. cancel()
  146. wg.Wait()
  147. }
  148. type mockNamedTunnelRPCClient struct {
  149. shouldFail error
  150. registered chan struct{}
  151. unregistered chan struct{}
  152. }
  153. func (mc mockNamedTunnelRPCClient) SendLocalConfiguration(c context.Context, config []byte) error {
  154. return nil
  155. }
  156. func (mc mockNamedTunnelRPCClient) RegisterConnection(
  157. ctx context.Context,
  158. auth pogs.TunnelAuth,
  159. tunnelID uuid.UUID,
  160. options *pogs.ConnectionOptions,
  161. connIndex uint8,
  162. edgeAddress net.IP,
  163. ) (*pogs.ConnectionDetails, error) {
  164. if mc.shouldFail != nil {
  165. return nil, mc.shouldFail
  166. }
  167. close(mc.registered)
  168. return &pogs.ConnectionDetails{
  169. Location: "LIS",
  170. UUID: uuid.New(),
  171. TunnelIsRemotelyManaged: false,
  172. }, nil
  173. }
  174. func (mc mockNamedTunnelRPCClient) GracefulShutdown(ctx context.Context, gracePeriod time.Duration) error {
  175. close(mc.unregistered)
  176. return nil
  177. }
  178. func (mockNamedTunnelRPCClient) Close() {}
  179. type mockRPCClientFactory struct {
  180. shouldFail error
  181. registered chan struct{}
  182. unregistered chan struct{}
  183. }
  184. func (mf *mockRPCClientFactory) newMockRPCClient(context.Context, io.ReadWriteCloser, time.Duration) tunnelrpc.RegistrationClient {
  185. return &mockNamedTunnelRPCClient{
  186. shouldFail: mf.shouldFail,
  187. registered: mf.registered,
  188. unregistered: mf.unregistered,
  189. }
  190. }
  191. type wsRespWriter struct {
  192. *httptest.ResponseRecorder
  193. readPipe *io.PipeReader
  194. writePipe *io.PipeWriter
  195. closed bool
  196. panicked bool
  197. }
  198. func newWSRespWriter() *wsRespWriter {
  199. readPipe, writePipe := io.Pipe()
  200. return &wsRespWriter{
  201. httptest.NewRecorder(),
  202. readPipe,
  203. writePipe,
  204. false,
  205. false,
  206. }
  207. }
  208. type nowriter struct {
  209. io.Reader
  210. }
  211. func (nowriter) Write(_ []byte) (int, error) {
  212. return 0, fmt.Errorf("writer not implemented")
  213. }
  214. func (w *wsRespWriter) RespBody() io.ReadWriter {
  215. return nowriter{w.readPipe}
  216. }
  217. func (w *wsRespWriter) Write(data []byte) (n int, err error) {
  218. if w.closed {
  219. w.panicked = true
  220. return 0, errors.New("wsRespWriter panicked")
  221. }
  222. return w.writePipe.Write(data)
  223. }
  224. func (w *wsRespWriter) close() {
  225. w.closed = true
  226. }
  227. func TestServeWS(t *testing.T) {
  228. http2Conn, _ := newTestHTTP2Connection()
  229. ctx, cancel := context.WithCancel(context.Background())
  230. respWriter := newWSRespWriter()
  231. readPipe, writePipe := io.Pipe()
  232. req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8080/ws/echo", readPipe)
  233. require.NoError(t, err)
  234. req.Header.Set(InternalUpgradeHeader, WebsocketUpgrade)
  235. serveDone := make(chan struct{})
  236. go func() {
  237. defer close(serveDone)
  238. http2Conn.ServeHTTP(respWriter, req)
  239. respWriter.close()
  240. }()
  241. data := []byte("test websocket")
  242. err = wsutil.WriteClientBinary(writePipe, data)
  243. require.NoError(t, err)
  244. respBody, err := wsutil.ReadServerBinary(respWriter.RespBody())
  245. require.NoError(t, err)
  246. require.Equal(t, data, respBody, fmt.Sprintf("Expect %s, got %s", string(data), string(respBody)))
  247. cancel()
  248. resp := respWriter.Result()
  249. // http2RespWriter should rewrite status 101 to 200
  250. require.Equal(t, http.StatusOK, resp.StatusCode)
  251. require.Equal(t, responseMetaHeaderOrigin, resp.Header.Get(ResponseMetaHeader))
  252. <-serveDone
  253. require.False(t, respWriter.panicked)
  254. }
  255. // TestNoWriteAfterServeHTTPReturns is a regression test of https://jira.cfops.it/browse/TUN-5184
  256. // to make sure we don't write to the ResponseWriter after the ServeHTTP method returns
  257. func TestNoWriteAfterServeHTTPReturns(t *testing.T) {
  258. cfdHTTP2Conn, edgeTCPConn := newTestHTTP2Connection()
  259. ctx, cancel := context.WithCancel(context.Background())
  260. var wg sync.WaitGroup
  261. serverDone := make(chan struct{})
  262. go func() {
  263. defer close(serverDone)
  264. cfdHTTP2Conn.Serve(ctx)
  265. }()
  266. edgeTransport := http2.Transport{}
  267. edgeHTTP2Conn, err := edgeTransport.NewClientConn(edgeTCPConn)
  268. require.NoError(t, err)
  269. message := []byte(t.Name())
  270. for i := 0; i < 100; i++ {
  271. wg.Add(1)
  272. go func() {
  273. defer wg.Done()
  274. readPipe, writePipe := io.Pipe()
  275. reqCtx, reqCancel := context.WithCancel(ctx)
  276. req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, "http://localhost:8080/ws/flaky", readPipe)
  277. require.NoError(t, err)
  278. req.Header.Set(InternalUpgradeHeader, WebsocketUpgrade)
  279. resp, err := edgeHTTP2Conn.RoundTrip(req)
  280. require.NoError(t, err)
  281. // http2RespWriter should rewrite status 101 to 200
  282. require.Equal(t, http.StatusOK, resp.StatusCode)
  283. wg.Add(1)
  284. go func() {
  285. defer wg.Done()
  286. for {
  287. select {
  288. case <-reqCtx.Done():
  289. return
  290. default:
  291. }
  292. _ = wsutil.WriteClientBinary(writePipe, message)
  293. }
  294. }()
  295. time.Sleep(time.Millisecond * 100)
  296. reqCancel()
  297. }()
  298. }
  299. wg.Wait()
  300. cancel()
  301. <-serverDone
  302. }
  303. func TestServeControlStream(t *testing.T) {
  304. http2Conn, edgeConn := newTestHTTP2Connection()
  305. rpcClientFactory := mockRPCClientFactory{
  306. registered: make(chan struct{}),
  307. unregistered: make(chan struct{}),
  308. }
  309. obs := NewObserver(&log, &log)
  310. controlStream := NewControlStream(
  311. obs,
  312. mockConnectedFuse{},
  313. &TunnelProperties{},
  314. 1,
  315. nil,
  316. rpcClientFactory.newMockRPCClient,
  317. 1*time.Second,
  318. nil,
  319. 1*time.Second,
  320. HTTP2,
  321. )
  322. http2Conn.controlStreamHandler = controlStream
  323. ctx, cancel := context.WithCancel(context.Background())
  324. var wg sync.WaitGroup
  325. wg.Add(1)
  326. go func() {
  327. defer wg.Done()
  328. http2Conn.Serve(ctx)
  329. }()
  330. req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8080/", nil)
  331. require.NoError(t, err)
  332. req.Header.Set(InternalUpgradeHeader, ControlStreamUpgrade)
  333. edgeHTTP2Conn, err := testTransport.NewClientConn(edgeConn)
  334. require.NoError(t, err)
  335. wg.Add(1)
  336. go func() {
  337. defer wg.Done()
  338. edgeHTTP2Conn.RoundTrip(req)
  339. }()
  340. <-rpcClientFactory.registered
  341. cancel()
  342. <-rpcClientFactory.unregistered
  343. assert.False(t, http2Conn.stoppedGracefully)
  344. wg.Wait()
  345. }
  346. func TestFailRegistration(t *testing.T) {
  347. http2Conn, edgeConn := newTestHTTP2Connection()
  348. rpcClientFactory := mockRPCClientFactory{
  349. shouldFail: errDuplicationConnection,
  350. registered: make(chan struct{}),
  351. unregistered: make(chan struct{}),
  352. }
  353. obs := NewObserver(&log, &log)
  354. controlStream := NewControlStream(
  355. obs,
  356. mockConnectedFuse{},
  357. &TunnelProperties{},
  358. http2Conn.connIndex,
  359. nil,
  360. rpcClientFactory.newMockRPCClient,
  361. 1*time.Second,
  362. nil,
  363. 1*time.Second,
  364. HTTP2,
  365. )
  366. http2Conn.controlStreamHandler = controlStream
  367. ctx, cancel := context.WithCancel(context.Background())
  368. var wg sync.WaitGroup
  369. wg.Add(1)
  370. go func() {
  371. defer wg.Done()
  372. http2Conn.Serve(ctx)
  373. }()
  374. req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8080/", nil)
  375. require.NoError(t, err)
  376. req.Header.Set(InternalUpgradeHeader, ControlStreamUpgrade)
  377. edgeHTTP2Conn, err := testTransport.NewClientConn(edgeConn)
  378. require.NoError(t, err)
  379. resp, err := edgeHTTP2Conn.RoundTrip(req)
  380. require.NoError(t, err)
  381. require.Equal(t, http.StatusBadGateway, resp.StatusCode)
  382. assert.NotNil(t, http2Conn.controlStreamErr)
  383. cancel()
  384. wg.Wait()
  385. }
  386. func TestGracefulShutdownHTTP2(t *testing.T) {
  387. http2Conn, edgeConn := newTestHTTP2Connection()
  388. rpcClientFactory := mockRPCClientFactory{
  389. registered: make(chan struct{}),
  390. unregistered: make(chan struct{}),
  391. }
  392. events := &eventCollectorSink{}
  393. shutdownC := make(chan struct{})
  394. obs := NewObserver(&log, &log)
  395. obs.RegisterSink(events)
  396. controlStream := NewControlStream(
  397. obs,
  398. mockConnectedFuse{},
  399. &TunnelProperties{},
  400. http2Conn.connIndex,
  401. nil,
  402. rpcClientFactory.newMockRPCClient,
  403. 1*time.Second,
  404. shutdownC,
  405. 1*time.Second,
  406. HTTP2,
  407. )
  408. http2Conn.controlStreamHandler = controlStream
  409. ctx, cancel := context.WithCancel(context.Background())
  410. var wg sync.WaitGroup
  411. wg.Add(1)
  412. go func() {
  413. defer wg.Done()
  414. http2Conn.Serve(ctx)
  415. }()
  416. req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8080/", nil)
  417. require.NoError(t, err)
  418. req.Header.Set(InternalUpgradeHeader, ControlStreamUpgrade)
  419. edgeHTTP2Conn, err := testTransport.NewClientConn(edgeConn)
  420. require.NoError(t, err)
  421. wg.Add(1)
  422. go func() {
  423. defer wg.Done()
  424. _, _ = edgeHTTP2Conn.RoundTrip(req)
  425. }()
  426. select {
  427. case <-rpcClientFactory.registered:
  428. break // ok
  429. case <-time.Tick(time.Second):
  430. t.Fatal("timeout out waiting for registration")
  431. }
  432. // signal graceful shutdown
  433. close(shutdownC)
  434. select {
  435. case <-rpcClientFactory.unregistered:
  436. break // ok
  437. case <-time.Tick(time.Second):
  438. t.Fatal("timeout out waiting for unregistered signal")
  439. }
  440. assert.True(t, controlStream.IsStopped())
  441. cancel()
  442. wg.Wait()
  443. events.assertSawEvent(t, Event{
  444. Index: http2Conn.connIndex,
  445. EventType: Unregistering,
  446. })
  447. }
  448. func benchmarkServeHTTP(b *testing.B, test testRequest) {
  449. http2Conn, edgeConn := newTestHTTP2Connection()
  450. ctx, cancel := context.WithCancel(context.Background())
  451. var wg sync.WaitGroup
  452. wg.Add(1)
  453. go func() {
  454. defer wg.Done()
  455. http2Conn.Serve(ctx)
  456. }()
  457. endpoint := fmt.Sprintf("http://localhost:8080/%s", test.endpoint)
  458. req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
  459. require.NoError(b, err)
  460. edgeHTTP2Conn, err := testTransport.NewClientConn(edgeConn)
  461. require.NoError(b, err)
  462. b.ResetTimer()
  463. for i := 0; i < b.N; i++ {
  464. b.StartTimer()
  465. resp, err := edgeHTTP2Conn.RoundTrip(req)
  466. b.StopTimer()
  467. require.NoError(b, err)
  468. require.Equal(b, test.expectedStatus, resp.StatusCode)
  469. if test.expectedBody != nil {
  470. respBody, err := io.ReadAll(resp.Body)
  471. require.NoError(b, err)
  472. require.Equal(b, test.expectedBody, respBody)
  473. }
  474. resp.Body.Close()
  475. }
  476. cancel()
  477. wg.Wait()
  478. }
  479. func BenchmarkServeHTTPSimple(b *testing.B) {
  480. test := testRequest{
  481. name: "ok",
  482. endpoint: "ok",
  483. expectedStatus: http.StatusOK,
  484. expectedBody: []byte(http.StatusText(http.StatusOK)),
  485. }
  486. benchmarkServeHTTP(b, test)
  487. }
  488. func BenchmarkServeHTTPLargeFile(b *testing.B) {
  489. test := testRequest{
  490. name: "large_file",
  491. endpoint: "large_file",
  492. expectedStatus: http.StatusOK,
  493. expectedBody: testLargeResp,
  494. }
  495. benchmarkServeHTTP(b, test)
  496. }