Repository navigation
Expand file tree
/
Copy pathexample_client_test.go
More file actions
513 lines (464 loc) · 13.5 KB
/
Copy pathexample_client_test.go
File metadata and controls
513 lines (464 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
package http_test
import (
"bytes"
"compress/flate"
"compress/zlib"
"crypto/x509"
"encoding/json"
"flag"
"fmt"
"io"
"net/url"
"os"
"strings"
"sync"
"testing"
"time"
tls "github.com/bogdanfinn/utls"
http "github.com/bogdanfinn/fhttp"
"github.com/bogdanfinn/fhttp/http2"
"github.com/bogdanfinn/fhttp/httptest"
)
// Basic http test with Header Order + enable push
func TestExample(t *testing.T) {
c := http.Client{}
// Otherwise the connection outlives the test and the goroutine-leak
// check in TestMain/afterTest flags every test that runs afterwards.
defer c.CloseIdleConnections()
req, err := http.NewRequest("GET", "https://httpbin.org/headers", strings.NewReader(""))
if err != nil {
t.Error(err)
return
}
req.Header = http.Header{
"sec-ch-ua": {"\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"90\", \"Google Chrome\";v=\"90\""},
"sec-ch-ua-mobile": {"?0"},
"upgrade-insecure-requests": {"1"},
"user-agent": {"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"},
"accept": {"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"},
"sec-fetch-site": {"none"},
"sec-fetch-mode": {"navigate"},
"sec-fetch-user": {"?1"},
"sec-fetch-dest": {"document"},
"accept-encoding": {"gzip, deflate, br"},
http.HeaderOrderKey: {
"sec-ch-ua",
"sec-ch-ua-mobile",
"upgrade-insecure-requests",
"user-agent",
"accept",
"sec-fetch-site",
"sec-fetch-mode",
"sec-fetch-user",
"sec-fetch-dest",
"accept-encoding",
},
}
resp, err := c.Do(req)
if err != nil {
t.Error(err)
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Errorf("Expected status code 200, got %v", resp.StatusCode)
}
var data interface{}
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
t.Error(err)
}
}
func getCharlesCert() (*x509.CertPool, error) {
home, err := os.UserHomeDir()
if err != nil {
return nil, err
}
caCert, err := os.ReadFile(fmt.Sprintf("%v/charles_cert.pem", home))
if err != nil {
return nil, err
}
certPool := x509.NewCertPool()
certPool.AppendCertsFromPEM(caCert)
return certPool, nil
}
func addCharlesToTransport(tr *http.Transport, proxy string) error {
caCertPool, err := getCharlesCert()
if err != nil {
return err
}
proxyURL, err := url.Parse(proxy)
if err != nil {
return err
}
tr.TLSClientConfig = &tls.Config{
RootCAs: caCertPool,
}
tr.Proxy = http.ProxyURL(proxyURL)
return nil
}
func addWiresharkToTransport(tr *http.Transport) error {
kl := flag.String("keylog", "ssl-keylog.txt", "file to dump ssl keys")
keylog, err := os.OpenFile(*kl, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
tr.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
KeyLogWriter: keylog,
}
return nil
}
// Test with Charles cert + proxy
func TestWithCert(t *testing.T) {
h1t := &http.Transport{
ForceAttemptHTTP2: true,
}
defer h1t.CloseIdleConnections()
if err := addCharlesToTransport(h1t, "http://localhost:8888"); err != nil {
// Requires a local Charles proxy and its CA cert in $HOME.
t.Skipf("Charles proxy not configured locally: %v", err)
}
t2, err := http2.ConfigureTransports(h1t)
if err != nil {
t.Fatal(err)
}
t2.Settings = map[http2.SettingID]uint32{
http2.SettingMaxConcurrentStreams: 1000,
http2.SettingMaxFrameSize: 16384,
http2.SettingMaxHeaderListSize: 262144,
}
t2.InitialWindowSize = 6291456
t2.HeaderTableSize = 65536
h1t.H2transport = t2
client := http.Client{
Transport: h1t,
}
req, err := http.NewRequest("GET", "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding", nil)
if err != nil {
t.Error(err)
return
}
req.Header = http.Header{
"sec-ch-ua": {"\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"90\", \"Google Chrome\";v=\"90\""},
"sec-ch-ua-mobile": {"?0"},
"upgrade-insecure-requests": {"1"},
"user-agent": {"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36", "I shouldn't be here"},
"accept": {"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"},
"sec-fetch-site": {"none"},
"sec-fetch-mode": {"navigate"},
"sec-fetch-user": {"?1"},
"cookie": {"cf_clearance=67f509a97bae8bb8349523a14c0ca3d7d8460c93-1620778862-0-250", "wp_customerGroup=NOT+LOGGED+IN"},
"sec-fetch-dest": {"document"},
"accept-encoding": {"gzip, deflate, br"},
"not-included-header": {"should be last"},
http.HeaderOrderKey: {
"sec-ch-ua",
"sec-ch-ua-mobile",
"upgrade-insecure-requests",
"user-agent",
"cookie",
"accept",
"sec-fetch-site",
"sec-fetch-mode",
"sec-fetch-user",
"sec-fetch-dest",
"accept-encoding",
},
http.PHeaderOrderKey: {":method", ":authority", ":scheme", ":path"},
}
resp, err := client.Do(req)
if err != nil {
t.Error(err)
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Errorf("Expected status code 200, got %v", resp.StatusCode)
}
}
// Test with push handler
func TestEnablePush(t *testing.T) {
t1 := &http.Transport{
ForceAttemptHTTP2: true,
}
defer t1.CloseIdleConnections()
t2, err := http2.ConfigureTransports(t1)
if err != nil {
t.Fatal(err)
}
t2.PushHandler = &http2.DefaultPushHandler{}
t1.H2transport = t2
c := &http.Client{
Transport: t1,
}
var req *http.Request
req, err = http.NewRequest("GET", "https://httpbin.org/headers", nil)
if err != nil {
t.Fatal(err)
}
resp, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
req, err = http.NewRequest("POST", "https://httpbin.org/post", nil)
if err != nil {
t.Fatal(err)
}
resp, err = c.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
}
// Test finishline
func TestFinishLine(t *testing.T) {
t1 := &http.Transport{
ForceAttemptHTTP2: true,
}
defer t1.CloseIdleConnections()
if err := addCharlesToTransport(t1, "http://localhost:8888"); err != nil {
// Requires a local Charles proxy and its CA cert in $HOME.
t.Skipf("Charles proxy not configured locally: %v", err)
}
// if err := addWiresharkToTransport(t1); err != nil {
// t.Fatal(err)
// }
t2, err := http2.ConfigureTransports(t1)
if err != nil {
t.Fatal(err)
}
t2.Settings = map[http2.SettingID]uint32{
http2.SettingMaxConcurrentStreams: 1000,
http2.SettingMaxFrameSize: 16384,
http2.SettingMaxHeaderListSize: 262144,
}
t2.InitialWindowSize = 6291456
t2.HeaderTableSize = 65536
t2.PushHandler = &http2.DefaultPushHandler{}
t1.H2transport = t2
c := &http.Client{
Transport: t1,
}
req, err := http.NewRequest("GET", "https://www.finishline.com/", nil)
if err != nil {
t.Fatal(err)
}
req.Header = http.Header{
"sec-ch-ua": {"\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"90\", \"Google Chrome\";v=\"90\""},
"sec-ch-ua-mobile": {"?0"},
"upgrade-insecure-requests": {"1"},
"user-agent": {"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"},
"accept": {"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"},
"sec-fetch-site": {"none"},
"sec-fetch-mode": {"navigate"},
"sec-fetch-user": {"?1"},
"sec-fetch-dest": {"document"},
"accept-encoding": {"gzip, deflate, br"},
http.HeaderOrderKey: {
"sec-ch-ua",
"sec-ch-ua-mobile",
"upgrade-insecure-requests",
"user-agent",
"accept",
"sec-fetch-site",
"sec-fetch-mode",
"sec-fetch-user",
"sec-fetch-dest",
"accept-encoding",
},
http.PHeaderOrderKey: {":method", ":authority", ":scheme", ":path"},
}
resp, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("Got status %v from finishline, expected 200", resp.StatusCode)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
fmt.Printf("resp: %v\n", string(b)[1])
}
// Test compression brotli
func TestCompressionBrotli(t *testing.T) {
t1 := &http.Transport{
ForceAttemptHTTP2: true,
}
defer t1.CloseIdleConnections()
c := http.Client{
Transport: t1,
}
req, _ := http.NewRequest("GET", "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding", nil)
req.Header = http.Header{
"accept-encoding": {"br"},
}
resp, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
// Both protocols decode the body even though the caller set Accept-Encoding.
if !resp.Uncompressed {
t.Fatal("brotli body was not decoded")
}
if h := resp.Header.Get("content-encoding"); h != "" {
t.Fatalf("Got content-encoding header %v, expected none", h)
}
}
const deflateBody = "Content-Encoding: deflate covers both zlib-wrapped and raw deflate streams."
// deflateServer serves deflateBody as Content-Encoding: deflate, either
// zlib-wrapped (RFC 1950) or as a raw deflate stream (RFC 1951).
func deflateServer(t *testing.T, zlibWrapped bool) *httptest.Server {
t.Helper()
var buf bytes.Buffer
var w io.WriteCloser
if zlibWrapped {
w = zlib.NewWriter(&buf)
} else {
fw, err := flate.NewWriter(&buf, flate.DefaultCompression)
if err != nil {
t.Fatal(err)
}
w = fw
}
if _, err := io.WriteString(w, deflateBody); err != nil {
t.Fatal(err)
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
payload := buf.Bytes()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Encoding", "deflate")
w.Write(payload)
}))
}
// The transport decodes by the response's Content-Encoding even when the caller
// set accept-encoding itself, and strips the header. Verify that for both deflate
// flavours.
func testCompressionDeflate(t *testing.T, zlibWrapped bool) {
t.Helper()
ts := deflateServer(t, zlibWrapped)
defer ts.Close()
req, err := http.NewRequest("GET", ts.URL, nil)
if err != nil {
t.Fatal(err)
}
req.Header = http.Header{
"accept-encoding": {"deflate"},
}
resp, err := ts.Client().Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if h := resp.Header.Get("content-encoding"); h != "" {
t.Fatalf("Expected no content encoding, got %q", h)
}
got, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if string(got) != deflateBody {
t.Errorf("body = %q; want %q", got, deflateBody)
}
}
// Test compression zlib deflate
func TestCompressionZlibDeflate(t *testing.T) {
testCompressionDeflate(t, true)
}
// Test compression deflate, a raw stream rather than a zlib-wrapped one
func TestCompressionDeflate(t *testing.T) {
testCompressionDeflate(t, false)
}
// A deflate body must not be read while the response is being built.
//
// Telling a zlib-wrapped stream from a raw one needs the first two bytes, and
// sniffing them during the round trip meant the request did not come back until
// the body did. On HTTP/2 it did not come back at all: the read waited for
// bytes the transport was not yet delivering, and the caller saw a timeout
// awaiting headers.
//
// The server here sends its headers and holds the body until the test lets it
// go, so a round trip that reads the body cannot return.
func TestDeflateResponseReturnsBeforeItsBody(t *testing.T) {
var buf bytes.Buffer
fw, err := flate.NewWriter(&buf, flate.DefaultCompression)
if err != nil {
t.Fatal(err)
}
if _, err := io.WriteString(fw, deflateBody); err != nil {
t.Fatal(err)
}
if err := fw.Close(); err != nil {
t.Fatal(err)
}
payload := buf.Bytes()
release := make(chan struct{})
var once sync.Once
releaseBody := func() { once.Do(func() { close(release) }) }
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Encoding", "deflate")
w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush()
<-release
w.Write(payload)
}))
ts.EnableHTTP2 = true
ts.StartTLS()
defer ts.Close()
defer releaseBody()
req, err := http.NewRequest("GET", ts.URL, nil)
if err != nil {
t.Fatal(err)
}
req.Header = http.Header{"accept-encoding": {"deflate"}}
done := make(chan *http.Response, 1)
errs := make(chan error, 1)
go func() {
resp, err := ts.Client().Do(req)
if err != nil {
errs <- err
return
}
done <- resp
}()
var resp *http.Response
select {
case resp = <-done:
case err := <-errs:
t.Fatalf("Do: %v", err)
case <-time.After(5 * time.Second):
t.Fatal("the response did not come back while the body was still being held")
}
defer resp.Body.Close()
// Only HTTP/2 decodes a body whose encoding the caller asked for itself.
if resp.ProtoMajor != 2 {
t.Skip("HTTP/2 is not in use")
}
// The control: the body really was still held, so returning proves the
// round trip did not wait for it.
select {
case <-release:
t.Fatal("the body was released before the response came back")
default:
}
releaseBody()
// Read it back as well, so a round trip that returns early but hands back
// an unusable body does not pass.
got, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
if string(got) != deflateBody {
t.Errorf("body = %q; want %q", got, deflateBody)
}
}
// Test with cookies
// Test with missing in header order, that should be added
// Test for UA that has empty string, excluding UA from being part of headers