forked from taskcluster/taskcluster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_test.go
523 lines (480 loc) · 14.4 KB
/
http_test.go
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
514
515
516
517
518
519
520
521
522
523
package tcclient
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/cenkalti/backoff/v3"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/taskcluster/httpbackoff/v3"
"github.com/taskcluster/taskcluster/v40/internal/jsontest"
)
func quickBackoff() func() {
oldBackoff := defaultBackoff
settings := backoff.NewExponentialBackOff()
settings.MaxElapsedTime = 100 * time.Millisecond
defaultBackoff = httpbackoff.Client{
BackOffSettings: settings,
}
return func() {
defaultBackoff = oldBackoff
}
}
// TestExtHeaderPermAuthScopes checks that the generated hawk ext http header
// for permanent credentials with authorized scopes listed matches what is
// expected.
func TestExtHeaderPermAuthScopes(t *testing.T) {
checkExtHeader(
t,
&Credentials{
ClientID: "abc",
AccessToken: "def",
AuthorizedScopes: []string{"a", "b", "c"},
},
// base64 of `{"authorizedScopes":["a","b","c"]}`
"eyJhdXRob3JpemVkU2NvcGVzIjpbImEiLCJiIiwiYyJdfQ==",
)
}
// TestExtHeaderPermNilAuthScopes checks that when permanent credentials are
// provided and the Authorized Scopes are not set (i.e. are nil) that the hawk
// ext header is an empty string.
func TestExtHeaderPermNilAuthScopes(t *testing.T) {
checkExtHeader(
t,
&Credentials{
ClientID: "abc",
AccessToken: "def",
},
"",
)
}
// TestExtHeaderPermNoAuthScopes checks that when permanent credentials are
// provided and an empty list of authorized scopes is used, that the hawk ext
// http header is explicitly showing an empty list of authorized scopes.
func TestExtHeaderPermNoAuthScopes(t *testing.T) {
checkExtHeader(
t,
&Credentials{
ClientID: "abc",
AccessToken: "def",
AuthorizedScopes: []string{},
},
// base64 of `{"authorizedScopes":[]}`
"eyJhdXRob3JpemVkU2NvcGVzIjpbXX0=",
)
}
// TestExtHeaderTempAuthScopes checks that the hawk ext header is set to the
// expected value when using temp credentials and an explicit list of
// authorized scopes.
func TestExtHeaderTempAuthScopes(t *testing.T) {
checkExtHeaderTempCreds(
t,
&Credentials{
ClientID: "abc",
AccessToken: "def",
AuthorizedScopes: []string{"a", "b", "c"},
},
)
}
// TestExtHeaderTempNilAuthScopes checks that the hawk ext header includes the
// temporary credentials certificate, but no authorized scopes property when
// using temp credentials but not restricting the authorized scopes.
func TestExtHeaderTempNilAuthScopes(t *testing.T) {
checkExtHeaderTempCreds(
t,
&Credentials{
ClientID: "abc",
AccessToken: "def",
},
)
}
// TestExtHeaderTempNoAuthScopes checks that the hawk ext header includes an
// empty list of authorized scopes when an empty list is provided, and that the
// temp credentials certificate is also included.
func TestExtHeaderTempNoAuthScopes(t *testing.T) {
checkExtHeaderTempCreds(
t,
&Credentials{
ClientID: "abc",
AccessToken: "def",
AuthorizedScopes: []string{},
},
)
}
type ExtHeaderRawCert struct {
Certificate json.RawMessage `json:"certificate"`
AuthorizedScopes []string `json:"authorizedScopes"`
}
// checkExtHeaderTempCreds generates temporary credentials from the given
// permanent credentials and then checks what the ext header looks like
// according to getExtHeader function. It base64 decodes the results, and then
// checks that the temporary credentials match the ones given, and then
// evaluates whether authorizedScopes is correct. It checks that if no
// authorized scopes were set, that the authorizedScopes are not set in the
// header; if they are set to anything, including an empty array, that this
// matches what is found in the header.
func checkExtHeaderTempCreds(t *testing.T, permCreds *Credentials) {
tempCredentials, err := permCreds.CreateTemporaryCredentials(time.Second*1, "d", "e", "f")
if err != nil {
t.Fatalf("Received error when generating temporary credentials: %s", err)
}
actualHeader, err := getExtHeader(tempCredentials)
if err != nil {
t.Fatalf("Received error when generating ext header: %s", err)
}
decoded, err := base64.StdEncoding.DecodeString(actualHeader)
if err != nil {
t.Fatalf("Received error when base64 decoding ext header: %s", err)
}
extHeader := new(ExtHeaderRawCert)
err = json.Unmarshal(decoded, extHeader)
if err != nil {
t.Fatalf("Cannot marshal results back into ExtHeader: %s", err)
}
if permCreds.AuthorizedScopes == nil {
if strings.Contains(string(decoded), "authorizedScopes") {
t.Fatalf("Did not expected authorizedScopes to be in ext header")
}
} else {
if !reflect.DeepEqual(permCreds.AuthorizedScopes, extHeader.AuthorizedScopes) {
t.Log("Expected AuthorizedScopes in Hawk Ext header to match AuthorizedScopes in credentials, but they didn't.")
t.Logf("Expected: %q", permCreds.AuthorizedScopes)
t.Logf("Actual: %q", extHeader.AuthorizedScopes)
t.Logf("Full ext header: %s", string(decoded))
t.FailNow()
}
}
jsonCorrect, formattedExpected, formattedActual, err := jsontest.JsonEqual([]byte(tempCredentials.Certificate), extHeader.Certificate)
if err != nil {
t.Fatalf("Exception thrown formatting json data!\n%s\n\nStruggled to format either:\n%s\n\nor:\n\n%s", err, tempCredentials.Certificate, string(extHeader.Certificate))
}
if !jsonCorrect {
t.Log("Anticipated json not generated. Expected:")
t.Logf("%s", formattedExpected)
t.Log("Actual:")
t.Logf("%s", formattedActual)
t.FailNow()
}
}
// checkExtHeader simply checks if getExtHeader returns the same results as the
// specified expected header.
func checkExtHeader(t *testing.T, creds *Credentials, expectedHeader string) {
actualHeader, err := getExtHeader(creds)
if err != nil {
t.Fatalf("Received error when generating ext header: %s", err)
}
if actualHeader != expectedHeader {
t.Fatalf("Expected header %q but got %q", expectedHeader, actualHeader)
}
}
func TestRequestWithContext(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Second)
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"value": "hello world"}`))
}))
defer s.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c := Client{
RootURL: s.URL,
Authenticate: false,
Context: ctx,
}
// Make a call
var result struct {
Value string `json:"value"`
}
_, _, err := c.APICall(nil, "GET", "/whatever", &result, nil)
if err != nil {
t.Fatal("Unexpected error: ", err)
}
// Make a call and cancel
time.AfterFunc(100*time.Millisecond, cancel)
_, _, err = c.APICall(nil, "GET", "/whatever", &result, nil)
if err == nil {
t.Fatal("Should have had a cancel error")
}
if err != context.Canceled {
t.Fatalf("Expected canceled error but got %T %v", err, err)
}
}
// Make sure Content-Type is only set if there is a payload
func TestContentTypeHeader(t *testing.T) {
// This mock service just returns the value of the Content-Type request
// header in the response body so we can check what value it had.
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
_, _ = w.Write([]byte(r.Header.Get("Content-Type")))
}))
defer s.Close()
client := Client{
RootURL: s.URL,
Authenticate: false,
}
// Three following calls should have no Content-Header set since request body is empty
// 1) calling APICall with a nil payload
_, cs, err := client.APICall(nil, "GET", "/whatever", nil, nil)
if err != nil {
t.Errorf("Unexpected error: %s", err)
}
if ct := cs.HTTPResponseBody; ct != "" {
t.Errorf("Expected no Content-Type header, but got '%v'", ct)
}
// 2) calling Request with nil body
cs, err = client.Request(nil, "GET", "/whatever", nil)
if err != nil {
t.Errorf("Unexpected error: %s", err)
}
if ct := cs.HTTPResponseBody; ct != "" {
t.Errorf("Expected no Content-Type header, but got '%v'", ct)
}
// 3) calling Request with array of 0 bytes for body
cs, err = client.Request([]byte{}, "GET", "/whatever", nil)
if err != nil {
t.Errorf("Unexpected error: %s", err)
}
if ct := cs.HTTPResponseBody; ct != "" {
t.Errorf("Expected no Content-Type header, but got '%v'", ct)
}
// This tests that given a payload > 0 bytes, Content-Type is set
cs, err = client.Request([]byte("{}"), "PUT", "/whatever", nil)
if err != nil {
t.Errorf("Unexpected error: %s", err)
}
if ct := cs.HTTPResponseBody; ct != "application/json" {
t.Errorf("Expected Content-Type application/json header, but got '%v'", ct)
}
}
// Verify that the client does not follow redirects
func TestNoFollowRedirects(t *testing.T) {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header()["Location"] = []string{"http://nosuch.example.com"}
w.WriteHeader(303)
fmt.Fprintln(w, "{}")
}))
defer s.Close()
client := Client{
RootURL: s.URL,
Authenticate: false,
}
_, cs, err := client.APICall(nil, "GET", "/whatever", nil, nil)
assert.Error(t, err) // expect an error in this case
assert.Equal(t, 303, cs.HTTPResponse.StatusCode)
}
type MockHTTPClient struct {
mu sync.Mutex
requests []MockHTTPRequest
T *testing.T
}
type MockHTTPRequest struct {
URL string
Method string
Body []byte
}
func (m *MockHTTPClient) Do(req *http.Request) (*http.Response, error) {
m.mu.Lock()
defer m.mu.Unlock()
mockRequestBody, err := ioutil.ReadAll(req.Body)
if err != nil {
m.T.Fatalf("Hit error reading mock http request request body: %s", err)
}
mockRequest := MockHTTPRequest{
URL: req.URL.String(),
Method: req.Method,
Body: mockRequestBody,
}
if m.requests == nil {
m.requests = []MockHTTPRequest{mockRequest}
} else {
m.requests = append(m.requests, mockRequest)
}
return &http.Response{
Status: "200 OK",
Body: ioutil.NopCloser(&bytes.Buffer{}),
}, nil
}
// Requests returns an array of all http requests made since this method was
// last called.
func (m *MockHTTPClient) Requests() []MockHTTPRequest {
m.mu.Lock()
defer m.mu.Unlock()
defer func() {
m.requests = nil
}()
return m.requests
}
type RequestTestCase struct {
RootURL string
ServiceName string
APIVersion string
RequestBody []byte
Method string
Route string
QueryParameters url.Values
}
func TestHTTPRequestGeneration(t *testing.T) {
testCases := []RequestTestCase{
// routes should always start with '/', however base URLs can be
// configured by user, so we should test with both trailing and
// non-trailing slash; see https://bugzil.la/1484702
{
RootURL: "https://tc.example.com",
ServiceName: "testy",
APIVersion: "v2",
RequestBody: nil,
Method: "GET",
Route: "/a/b",
QueryParameters: nil,
},
{
RootURL: "https://tc.example.com/", // trailing /
ServiceName: "testy",
APIVersion: "v2",
RequestBody: nil,
Method: "GET",
Route: "/a/b",
QueryParameters: nil,
},
// test a request with a payload body and query string parameters
{
RootURL: "https://tc.example.com",
ServiceName: "testy",
APIVersion: "v2",
RequestBody: []byte{1, 2, 3, 4, 5},
Method: "POST",
Route: "/a/b",
QueryParameters: url.Values{"a": []string{"A", "B"}},
},
}
expectedRequests := []MockHTTPRequest{
{
URL: "https://tc.example.com/api/testy/v2/a/b",
Method: "GET",
Body: []byte{},
},
{
URL: "https://tc.example.com/api/testy/v2/a/b",
Method: "GET",
Body: []byte{},
},
{
URL: "https://tc.example.com/api/testy/v2/a/b?a=A&a=B",
Method: "POST",
Body: []byte{1, 2, 3, 4, 5},
},
}
mockHTTPClient := &MockHTTPClient{T: t}
c := Client{
Authenticate: false,
HTTPClient: mockHTTPClient,
}
for _, testCase := range testCases {
c.RootURL = testCase.RootURL
c.ServiceName = testCase.ServiceName
c.APIVersion = testCase.APIVersion
_, _ = c.Request(testCase.RequestBody, testCase.Method, testCase.Route, testCase.QueryParameters)
}
actualRequests := mockHTTPClient.Requests()
if !reflect.DeepEqual(expectedRequests, actualRequests) {
t.Log("Expected requests:")
t.Logf("%#v", expectedRequests)
t.Log("Actual requests:")
t.Logf("%#v", actualRequests)
t.Fail()
}
}
func TestSignedURL_FullURL(t *testing.T) {
client := Client{
Credentials: &Credentials{
ClientID: "test-signin",
AccessToken: "fake-key",
},
RootURL: "https://tc.example.com",
ServiceName: "grapes",
APIVersion: "v2",
}
res, err := client.SignedURL("https://tc.example.com/api/barley/v1/foo/bar", url.Values{"param": []string{"p1"}}, time.Minute)
if err != nil {
t.Error(err)
return
}
if res.Host != "tc.example.com" {
t.Fatalf("Got unexpected host %s", res.Host)
return
}
if res.Path != "/api/barley/v1/foo/bar" {
t.Fatalf("Got unexpected path %s", res.Path)
return
}
if res.Query()["param"][0] != "p1" {
t.Fatalf("Got unexpected query %s", res.Query())
return
}
_, ok := res.Query()["bewit"]
if !ok {
t.Fatalf("Query does not have a 'bewit'")
return
}
}
func TestSignedURL_PartialURL(t *testing.T) {
client := Client{
Credentials: &Credentials{
ClientID: "test-signin",
AccessToken: "fake-key",
},
RootURL: "https://tc.example.com",
ServiceName: "grapes",
APIVersion: "v2",
}
res, err := client.SignedURL("foo/bar", url.Values{"param": []string{"p1"}}, time.Minute)
if err != nil {
t.Error(err)
return
}
if res.Host != "tc.example.com" {
t.Fatalf("Got unexpected host %s", res.Host)
return
}
if res.Path != "/api/grapes/v2/foo/bar" {
t.Fatalf("Got unexpected path %s", res.Path)
return
}
if res.Query()["param"][0] != "p1" {
t.Fatalf("Got unexpected query %s", res.Query())
return
}
_, ok := res.Query()["bewit"]
if !ok {
t.Fatalf("Query does not have a 'bewit'")
return
}
}
func TestRetryFailure(t *testing.T) {
defer quickBackoff()()
// This mock service just returns 500's
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
_, _ = w.Write([]byte("{}"))
}))
defer s.Close()
client := Client{
RootURL: s.URL,
Authenticate: false,
}
// Three following calls should have no Content-Header set since request body is empty
// 1) calling APICall with a nil payload
_, _, err := client.APICall(nil, "GET", "/whatever", nil, nil)
require.Error(t, err)
}