forked from bradleyfalzon/ghinstallation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport_test.go
477 lines (424 loc) · 13.8 KB
/
transport_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
package ghinstallation
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-github/v66/github"
)
const (
installationID = 1
appID = 2
token = "abc123"
)
var key = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA0BUezcR7uycgZsfVLlAf4jXP7uFpVh4geSTY39RvYrAll0yh
q7uiQypP2hjQJ1eQXZvkAZx0v9lBYJmX7e0HiJckBr8+/O2kARL+GTCJDJZECpjy
97yylbzGBNl3s76fZ4CJ+4f11fCh7GJ3BJkMf9NFhe8g1TYS0BtSd/sauUQEuG/A
3fOJxKTNmICZr76xavOQ8agA4yW9V5hKcrbHzkfecg/sQsPMmrXixPNxMsqyOMmg
jdJ1aKr7ckEhd48ft4bPMO4DtVL/XFdK2wJZZ0gXJxWiT1Ny41LVql97Odm+OQyx
tcayMkGtMb1nwTcVVl+RG2U5E1lzOYpcQpyYFQIDAQABAoIBAAfUY55WgFlgdYWo
i0r81NZMNBDHBpGo/IvSaR6y/aX2/tMcnRC7NLXWR77rJBn234XGMeQloPb/E8iw
vtjDDH+FQGPImnQl9P/dWRZVjzKcDN9hNfNAdG/R9JmGHUz0JUddvNNsIEH2lgEx
C01u/Ntqdbk+cDvVlwuhm47MMgs6hJmZtS1KDPgYJu4IaB9oaZFN+pUyy8a1w0j9
RAhHpZrsulT5ThgCra4kKGDNnk2yfI91N9lkP5cnhgUmdZESDgrAJURLS8PgInM4
YPV9L68tJCO4g6k+hFiui4h/4cNXYkXnaZSBUoz28ICA6e7I3eJ6Y1ko4ou+Xf0V
csM8VFkCgYEA7y21JfECCfEsTHwwDg0fq2nld4o6FkIWAVQoIh6I6o6tYREmuZ/1
s81FPz/lvQpAvQUXGZlOPB9eW6bZZFytcuKYVNE/EVkuGQtpRXRT630CQiqvUYDZ
4FpqdBQUISt8KWpIofndrPSx6JzI80NSygShQsScWFw2wBIQAnV3TpsCgYEA3reL
L7AwlxCacsPvkazyYwyFfponblBX/OvrYUPPaEwGvSZmE5A/E4bdYTAixDdn4XvE
ChwpmRAWT/9C6jVJ/o1IK25dwnwg68gFDHlaOE+B5/9yNuDvVmg34PWngmpucFb/
6R/kIrF38lEfY0pRb05koW93uj1fj7Uiv+GWRw8CgYEAn1d3IIDQl+kJVydBKItL
tvoEur/m9N8wI9B6MEjhdEp7bXhssSvFF/VAFeQu3OMQwBy9B/vfaCSJy0t79uXb
U/dr/s2sU5VzJZI5nuDh67fLomMni4fpHxN9ajnaM0LyI/E/1FFPgqM+Rzb0lUQb
yqSM/ptXgXJls04VRl4VjtMCgYEAprO/bLx2QjxdPpXGFcXbz6OpsC92YC2nDlsP
3cfB0RFG4gGB2hbX/6eswHglLbVC/hWDkQWvZTATY2FvFps4fV4GrOt5Jn9+rL0U
elfC3e81Dw+2z7jhrE1ptepprUY4z8Fu33HNcuJfI3LxCYKxHZ0R2Xvzo+UYSBqO
ng0eTKUCgYEAxW9G4FjXQH0bjajntjoVQGLRVGWnteoOaQr/cy6oVii954yNMKSP
rezRkSNbJ8cqt9XQS+NNJ6Xwzl3EbuAt6r8f8VO1TIdRgFOgiUXRVNZ3ZyW8Hegd
kGTL0A6/0yAu9qQZlFbaD5bWhQo7eyx63u4hZGppBhkTSPikOYUPCH8=
-----END RSA PRIVATE KEY-----`)
func TestNew(t *testing.T) {
var authed bool
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Accept") != acceptHeader {
t.Fatalf("Request URI %q accept header got %q want: %q", r.RequestURI, r.Header.Get("Accept"), acceptHeader)
}
switch r.RequestURI {
case fmt.Sprintf("/app/installations/%d/access_tokens", installationID):
// respond with any token to installation transport
js, _ := json.Marshal(accessToken{
Token: token,
ExpiresAt: time.Now().Add(5 * time.Minute),
})
fmt.Fprintln(w, string(js))
authed = true
case "/auth/with/installation/token/endpoint":
if want := "token " + token; r.Header.Get("Authorization") != want {
t.Fatalf("Installation token got: %q want: %q", r.Header.Get("Authorization"), want)
}
default:
t.Fatalf("unexpected URI: %q", r.RequestURI)
}
}))
defer ts.Close()
tr, err := New(&http.Transport{}, appID, installationID, key)
if err != nil {
t.Fatal("unexpected error:", err)
}
tr.BaseURL = ts.URL
// test id getter methods
if tr.AppID() != appID {
t.Fatalf("appID got: %q want: %q", tr.AppID(), appID)
}
if tr.InstallationID() != installationID {
t.Fatalf("installationID got: %q want: %q", tr.InstallationID(), installationID)
}
client := http.Client{Transport: tr}
_, err = client.Get(ts.URL + "/auth/with/installation/token/endpoint")
if err != nil {
t.Fatal("unexpected error from client:", err)
}
if !authed {
t.Fatal("Expected fetch of access_token but none occurred")
}
// Check the token is reused by setting expires into far future
tr.token.ExpiresAt = time.Now().Add(time.Hour)
authed = false
_, err = client.Get(ts.URL + "/auth/with/installation/token/endpoint")
if err != nil {
t.Fatal("unexpected error from client:", err)
}
if authed {
t.Fatal("Unexpected fetch of access_token")
}
// Check the token is refreshed by setting expires into far past
tr.token.ExpiresAt = time.Unix(0, 0)
_, err = client.Get(ts.URL + "/auth/with/installation/token/endpoint")
if err != nil {
t.Fatal("unexpected error from client:", err)
}
if !authed {
t.Fatal("Expected fetch of access_token but none occurred")
}
}
func TestNewKeyFromFile(t *testing.T) {
tmpfile, err := os.CreateTemp("", "example")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name()) // clean up
if _, err := tmpfile.Write(key); err != nil {
t.Fatal(err)
}
if err := tmpfile.Close(); err != nil {
t.Fatal(err)
}
_, err = NewKeyFromFile(&http.Transport{}, appID, installationID, tmpfile.Name())
if err != nil {
t.Fatal("unexpected error:", err)
}
}
func TestNew_appendHeader(t *testing.T) {
var headers http.Header
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
headers = r.Header
fmt.Fprintln(w, `{}`) // dummy response that looks like json
}))
defer ts.Close()
// Create a new request adding our own Accept header
myheader := "my-header"
req, err := http.NewRequest("GET", ts.URL+"/auth/with/installation/token/endpoint", nil)
if err != nil {
t.Fatal("unexpected error from http.NewRequest:", err)
}
req.Header.Add("Accept", myheader)
tr, err := New(&http.Transport{}, appID, installationID, key)
if err != nil {
t.Fatal("unexpected error:", err)
}
tr.BaseURL = ts.URL
client := http.Client{Transport: tr}
_, err = client.Do(req)
if err != nil {
t.Fatal("unexpected error from client:", err)
}
found := false
for _, v := range headers["Accept"] {
if v == myheader {
found = true
break
}
}
if !found {
t.Errorf("could not find %v in request's accept headers: %v", myheader, headers["Accept"])
}
// Here we test that there isn't a second Accept header.
// Though the Accept header 'application/vnd.github.v3+json' is used for most
// interactions with the GitHub API, having this header will force the
// GitHub API response as JSON, which we don't want when downloading a
// release (octet-stream)
for _, v := range headers["Accept"] {
if v == acceptHeader {
t.Errorf("accept header '%s' should not be present when accept header '%s' is set: %v", acceptHeader, myheader, headers["Accept"])
break
}
}
}
func TestRefreshTokenWithParameters(t *testing.T) {
installationTokenOptions := &github.InstallationTokenOptions{
RepositoryIDs: []int64{1234},
Permissions: &github.InstallationPermissions{
Contents: github.String("write"),
Issues: github.String("read"),
},
}
// Convert InstallationTokenOptions into a ReadWriter to pass as an argument to http.NewRequest.
body, err := GetReadWriter(installationTokenOptions)
if err != nil {
t.Fatalf("error calling GetReadWriter: %v", err)
}
// Convert io.ReadWriter to String without deleting body data.
wantBody, _ := GetReadWriter(installationTokenOptions)
wantBodyBytes := new(bytes.Buffer)
wantBodyBytes.ReadFrom(wantBody)
wantBodyString := wantBodyBytes.String()
roundTripper := RoundTrip{
rt: func(req *http.Request) (*http.Response, error) {
// Convert io.ReadCloser to String without deleting body data.
var gotBodyBytes []byte
gotBodyBytes, _ = io.ReadAll(req.Body)
req.Body = io.NopCloser(bytes.NewBuffer(gotBodyBytes))
gotBodyString := string(gotBodyBytes)
// Compare request sent with request received.
if diff := cmp.Diff(wantBodyString, gotBodyString); diff != "" {
t.Errorf("HTTP body want->got: %s", diff)
}
// Return acceptable access token.
accessToken := accessToken{
Token: "token_string",
ExpiresAt: time.Now(),
Repositories: []github.Repository{{
ID: github.Int64(1234),
}},
Permissions: github.InstallationPermissions{
Contents: github.String("write"),
Issues: github.String("read"),
},
}
tokenReadWriter, err := GetReadWriter(accessToken)
if err != nil {
return nil, fmt.Errorf("error converting token into io.ReadWriter: %+v", err)
}
tokenBody := io.NopCloser(tokenReadWriter)
return &http.Response{
Body: tokenBody,
StatusCode: 200,
}, nil
},
}
tr, err := New(roundTripper, appID, installationID, key)
if err != nil {
t.Fatal("unexpected error:", err)
}
tr.InstallationTokenOptions = installationTokenOptions
req, err := http.NewRequest("POST", fmt.Sprintf("%s/app/installations/%v/access_tokens", tr.BaseURL, tr.installationID), body)
if err != nil {
t.Fatal("unexpected error:", err)
}
if _, err := tr.RoundTrip(req); err != nil {
t.Fatalf("error calling RoundTrip: %v", err)
}
}
func TestRefreshTokenWithTrailingSlashBaseURL(t *testing.T) {
installationTokenOptions := &github.InstallationTokenOptions{
RepositoryIDs: []int64{1234},
Permissions: &github.InstallationPermissions{
Contents: github.String("write"),
Issues: github.String("read"),
},
}
tokenToBe := "token_string"
// Convert io.ReadWriter to String without deleting body data.
wantBody, _ := GetReadWriter(installationTokenOptions)
wantBodyBytes := new(bytes.Buffer)
wantBodyBytes.ReadFrom(wantBody)
wantBodyString := wantBodyBytes.String()
roundTripper := RoundTrip{
rt: func(req *http.Request) (*http.Response, error) {
if strings.Contains(req.URL.Path, "//") {
return &http.Response{
Body: io.NopCloser(strings.NewReader("Forbidden\n")),
StatusCode: 401,
}, fmt.Errorf("Got simulated 401 Github Forbidden response")
}
if req.URL.Path == "test_endpoint/" && req.Header.Get("Authorization") == fmt.Sprintf("token %s", tokenToBe) {
return &http.Response{
Body: io.NopCloser(strings.NewReader("Beautiful\n")),
StatusCode: 200,
}, nil
}
// Convert io.ReadCloser to String without deleting body data.
var gotBodyBytes []byte
gotBodyBytes, _ = io.ReadAll(req.Body)
req.Body = io.NopCloser(bytes.NewBuffer(gotBodyBytes))
gotBodyString := string(gotBodyBytes)
// Compare request sent with request received.
if diff := cmp.Diff(wantBodyString, gotBodyString); diff != "" {
t.Errorf("HTTP body want->got: %s", diff)
}
// Return acceptable access token.
accessToken := accessToken{
Token: tokenToBe,
ExpiresAt: time.Now(),
Repositories: []github.Repository{{
ID: github.Int64(1234),
}},
Permissions: github.InstallationPermissions{
Contents: github.String("write"),
Issues: github.String("read"),
},
}
tokenReadWriter, err := GetReadWriter(accessToken)
if err != nil {
return nil, fmt.Errorf("error converting token into io.ReadWriter: %+v", err)
}
tokenBody := io.NopCloser(tokenReadWriter)
return &http.Response{
Body: tokenBody,
StatusCode: 200,
}, nil
},
}
tr, err := New(roundTripper, appID, installationID, key)
if err != nil {
t.Fatal("unexpected error:", err)
}
tr.InstallationTokenOptions = installationTokenOptions
tr.BaseURL = "http://localhost/github/api/v3/"
// Convert InstallationTokenOptions into a ReadWriter to pass as an argument to http.NewRequest.
body, err := GetReadWriter(installationTokenOptions)
if err != nil {
t.Fatalf("error calling GetReadWriter: %v", err)
}
req, err := http.NewRequest("POST", "http://localhost/test_endpoint/", body)
if err != nil {
t.Fatal("unexpected error:", err)
}
res, err := tr.RoundTrip(req)
if err != nil {
t.Fatalf("error calling RoundTrip: %v", err)
}
if res.StatusCode != 200 {
t.Fatalf("Unexpected RoundTrip response code: %d", res.StatusCode)
}
}
func TestRoundTripperContract(t *testing.T) {
tr := &Transport{
token: &accessToken{
ExpiresAt: time.Now().Add(1 * time.Hour),
Token: "42",
},
mu: &sync.Mutex{},
tr: roundTripperFunc(func(req *http.Request) (*http.Response, error) {
if auth := req.Header.Get("Authorization"); auth != "token 42" {
t.Errorf("got unexpected Authorization request header in parent RoundTripper: %q", auth)
}
return nil, nil
}),
}
req, err := http.NewRequest("GET", "http://localhost", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "xxx")
_, err = tr.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
if accept := req.Header.Get("Authorization"); accept != "xxx" {
t.Errorf("got unexpected Authorization request header in caller: %q", accept)
}
}
type roundTripperFunc func(*http.Request) (*http.Response, error)
func (fn roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return fn(req)
}
func TestExpiryAccessor(t *testing.T) {
now := time.Now()
future := now.Add(2 * time.Hour)
futureRefresh := future.Add(-time.Minute)
past := now.Add(-2 * time.Hour)
pastRefresh := past.Add(-time.Minute)
for _, tc := range []struct {
name string
token *accessToken
expectErr string
expectExpiry time.Time
expectRefresh time.Time
}{
{
name: "valid",
token: &accessToken{
Token: token,
ExpiresAt: future,
},
expectExpiry: future,
expectRefresh: futureRefresh,
},
{
name: "expired",
token: &accessToken{
Token: token,
ExpiresAt: past,
},
expectExpiry: past,
expectRefresh: pastRefresh,
},
{
name: "unset",
expectErr: "Expiry() = unknown, err: nil token",
},
} {
t.Run(tc.name, func(t *testing.T) {
tr := &Transport{token: tc.token}
expiresAt, refreshAt, err := tr.Expiry()
if err != nil {
if tc.expectErr != err.Error() {
t.Errorf("wrong error, expected=%q, actual=%q",
tc.expectErr, err.Error())
}
} else {
if tc.expectErr != "" {
t.Fatalf("unexpected error: %v", err)
}
}
if tc.expectExpiry != expiresAt {
t.Errorf("expiresAt mismatch, expected=%v, actual=%v",
tc.expectExpiry.String(), expiresAt.String())
}
if tc.expectRefresh != refreshAt {
t.Errorf("refreshAt mismatch, expected=%v, actual=%v",
tc.expectRefresh, refreshAt)
}
})
}
}
func TestHTTPErrorUnwrap(t *testing.T) {
wrappedError := errors.New("wrapped error")
err := &HTTPError{
RootCause: wrappedError,
}
if !errors.Is(err, wrappedError) {
t.Errorf("HTTPError should be unwrapped to the root cause")
}
}