-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathoauth2_test.go
504 lines (457 loc) · 16.2 KB
/
oauth2_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
// Copyright 2019 James Cote
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package esign_test
import (
"context"
"net/http"
"net/url"
"strings"
"testing"
"github.com/jfcote87/esign"
"github.com/jfcote87/oauth2"
"github.com/jfcote87/testutils"
)
const tokenSuccessResponse = `{
"access_token": "ISSUED_ACCESS_TOKEN",
"token_type": "Bearer",
"refresh_token": "ISSUED_REFRESH_TOKEN",
"expires_in": 28800
}`
const userInfoSuccessResponse = `{
"sub": "50d89ab1-dad5-d00d-b410-92ee3110b970",
"accounts": [
{
"account_id": "fe0b61a3-3b9b-cafe-b7be-4592af32aa9b",
"is_default": true,
"account_name": "World Wide Co",
"base_uri": "https://gotest.docusign.net"
},
{
"account_id": "abcd61a3-3b9b-cafe-b7be-4592af32aa9b",
"is_default": false,
"account_name": "Account2",
"base_uri": "https://gotest.docusign.net"
}
],
"name": "Susan Smart",
"given_name": "Susan",
"family_name": "Smart",
"email": "susan.smart@example.com"
}`
func getOAuth2ConfigTransport() (*esign.OAuth2Config, *testutils.Transport) {
testTransport := &testutils.Transport{}
clx := &http.Client{Transport: testTransport}
cfg := &esign.OAuth2Config{
IntegratorKey: "KEY",
Secret: "SECRET",
RedirURL: "https://www.example.com/token",
IsDemo: true,
HTTPClientFunc: func(ctx context.Context) (*http.Client, error) {
return clx, nil
},
}
return cfg, testTransport
}
func TestOuauth2Config_AuthURL(t *testing.T) {
cfg, _ := getOAuth2ConfigTransport()
authURL := cfg.AuthURL("STATE")
expectedURL := "https://account-d.docusign.com/oauth/auth?client_id=KEY&redirect_uri=https%3A%2F%2Fwww.example.com%2Ftoken&response_type=code&scope=signature&state=STATE"
if authURL != expectedURL {
t.Errorf("expected %s; got %s", expectedURL, authURL)
return
}
// check for %20 replacement
cfg.ExtendedLifetime = true
cfg.Prompt = true
cfg.UIlocales = []string{"en-us"}
authURL = cfg.AuthURL("STATE")
expectedURL = "https://account-d.docusign.com/oauth/auth?client_id=KEY&prompt=login&redirect_uri=https%3A%2F%2Fwww.example.com%2Ftoken&response_type=code&scope=signature%20extended&state=STATE&ui_locales=en-us"
if authURL != expectedURL {
t.Errorf("expected %s; got %s", expectedURL, authURL)
return
}
cfg.UIlocales = nil
cfg.Prompt = false
authURL = cfg.AuthURL("STATE", "ASCOPE", "extended")
expectedURL = "https://account-d.docusign.com/oauth/auth?client_id=KEY&redirect_uri=https%3A%2F%2Fwww.example.com%2Ftoken&response_type=code&scope=ASCOPE%20extended&state=STATE"
if authURL != expectedURL {
t.Errorf("expected %s; got %s", expectedURL, authURL)
return
}
authURL = cfg.AuthURL("STATE", "ASCOPE")
if authURL != expectedURL {
t.Errorf("expected %s; got %s", expectedURL, authURL)
return
}
}
var exchangeResponseTest = &testutils.RequestTester{
Host: "account-d.docusign.com",
Path: "/oauth/token",
Method: "POST",
Auth: "Basic S0VZOlNFQ1JFVA==",
Payload: []byte("code=CODE&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fwww.example.com%2Ftoken"),
ResponseFunc: func(r *http.Request) (*http.Response, error) {
return testutils.MakeResponse(200, []byte(tokenSuccessResponse), nil), nil
},
}
var userinfoResponseDemoTest = &testutils.RequestTester{
Host: "account-d.docusign.com",
Path: "/oauth/userinfo",
Method: "GET",
Auth: "Bearer ISSUED_ACCESS_TOKEN",
ResponseFunc: func(r *http.Request) (*http.Response, error) {
return testutils.MakeResponse(200, []byte(userInfoSuccessResponse), nil), nil
},
}
var userinfoResponseTest = &testutils.RequestTester{
Host: "account.docusign.com",
Path: "/oauth/userinfo",
Method: "GET",
Auth: "Bearer ISSUED_ACCESS_TOKEN",
ResponseFunc: func(r *http.Request) (*http.Response, error) {
return testutils.MakeResponse(200, []byte(userInfoSuccessResponse), nil), nil
},
}
var refreshResponseTest = &testutils.RequestTester{
Path: "/oauth/token",
Payload: []byte("grant_type=refresh_token&refresh_token=refresh"),
ResponseFunc: func(r *http.Request) (*http.Response, error) {
return testutils.MakeResponse(200, []byte(tokenSuccessResponse), nil), nil
},
}
func TestOAuth2Config_Exchange(t *testing.T) {
// Test OAuth2Credential flow
cfg, testTransport := getOAuth2ConfigTransport()
testTransport.Add(exchangeResponseTest, userinfoResponseDemoTest)
ctx := context.Background()
var savedToken *oauth2.Token
var savedUserInfo *esign.UserInfo
cfg.CacheFunc = func(cx context.Context, tk oauth2.Token, ui esign.UserInfo) {
savedToken = &tk
savedUserInfo = &ui
}
ocr, err := cfg.Exchange(ctx, "CODE")
if err != nil {
t.Fatalf("expected successful code exchage; got %v", err)
}
u, err := ocr.UserInfo(ctx)
if err != nil {
t.Fatalf("expected userInfo for Susan Smart; got error %v", err)
}
if u.Name != "Susan Smart" {
t.Fatalf("expected user name Susan Smart; got %s", u.Name)
}
if savedToken == nil || savedUserInfo == nil {
t.Fatalf("token and userinfo should be cached; got savedToken is nil %v and savedUserInfo is nil %v", (savedToken == nil), (savedUserInfo == nil))
}
tk, err := ocr.Token(ctx)
if err != nil {
t.Fatalf("expected token; got %v", err)
}
cfg.AccountID = "INVALID ACCOUNT"
if _, err = cfg.Credential(tk, u); err == nil || err.Error() != "no account INVALID ACCOUNT for susan.smart@example.com" {
t.Fatalf("expected no account INVALID ACCOUNT for susan.smart@example.com; got %v", err)
}
cfg.AccountID = "fe0b61a3-3b9b-cafe-b7be-4592af32aa9b"
if _, err = cfg.Credential(tk, u); err != nil {
t.Fatalf("expected successful credential; got %v", err)
}
if _, err = cfg.Credential(nil, nil); err == nil || err.Error() != "token may not be nil" {
t.Fatalf("expected \"token may not be nil\"; got %v", err)
}
}
var tverV2 = &testVersion{
Host: "gotest.docusign.net",
Demo: "gotest-d.docusign.net",
Prefix: "/restapi",
Ver: "/v2",
}
var tverV21 = &testVersion{
Host: "gotest.docusign.net",
Demo: "gotest-d.docusign.net",
Prefix: "/restapi",
Ver: "/v2.1",
}
func TestOAuth2Config_Refresh(t *testing.T) {
cfg, testTransport := getOAuth2ConfigTransport()
var savedToken *oauth2.Token
var savedUserInfo *esign.UserInfo
cfg.CacheFunc = func(cx context.Context, tk oauth2.Token, ui esign.UserInfo) {
savedToken = &tk
savedUserInfo = &ui
}
testTransport.Add(refreshResponseTest, userinfoResponseDemoTest)
var tk *oauth2.Token
ctx := context.Background()
cfg.IsDemo = true
ocra, err := cfg.Credential(&oauth2.Token{RefreshToken: "refresh"}, nil)
if err != nil {
t.Fatalf("expected successful credential create; got %v", err)
}
if tk, err = ocra.Token(ctx); err != nil {
t.Fatalf("expected token; got %v", err)
}
if tk.AccessToken != "ISSUED_ACCESS_TOKEN" {
t.Fatalf("expected token ISSUED_ACCESS_TOKEN; got %s", tk.AccessToken)
}
testTransport.Add(refreshResponseTest, userinfoResponseTest)
cfg.IsDemo = false
ocr, err := cfg.Credential(&oauth2.Token{RefreshToken: "refresh"}, nil)
if err != nil {
t.Fatalf("expected successful credential create; got %v", err)
}
u, err := ocr.UserInfo(ctx)
if err != nil {
t.Fatalf("expecte userinfo success; got %v", err)
}
if u.Email != "susan.smart@example.com" {
t.Fatalf("expected email susan.smart@example.com; got %s", u.Email)
}
if savedToken == nil || savedUserInfo == nil {
t.Fatalf("token and userinfo should be cached; got savedToken is nil %v and savedUserInfo is nil %v", (savedToken == nil), (savedUserInfo == nil))
}
testTransport.Add(&testutils.RequestTester{
Path: "/restapi/v2/accounts/" + u.Accounts[0].AccountID + "/abc/def",
Header: http.Header{"Authorization": {"Bearer ISSUED_ACCESS_TOKEN"}},
Host: "gotest.docusign.net",
}, &testutils.RequestTester{
Path: "/restapi/v2.1/accounts/" + u.Accounts[0].AccountID + "/abc/def",
Header: http.Header{"Authorization": {"Bearer ISSUED_ACCESS_TOKEN"}},
Host: "gotest-d.docusign.net",
})
op := &esign.Op{
Method: "GET",
Path: "abc/def",
Version: tverV2,
}
if res, err := ocr.AuthDo(ctx, op); err != nil {
_ = res
t.Errorf("authdo(GET, abc/def, nil) expected success; got %v", err)
} else {
res.Body.Close()
}
op.Version = tverV21
if res, err := ocra.AuthDo(ctx, op); err != nil {
t.Errorf("authdo(GET, abc/def, VersionV21) expected success; got %v", err)
} else {
res.Body.Close()
}
}
func TestJWTConfig(t *testing.T) {
var testPK = `-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAyki3KNQlqFYHQOg+uywV1GNbi/Zvgs2MLYVMiJ/NYeBIZgMm
STDW8mtiR1kLSMq/glzvQdFWPZTzbxkIqiYESoUsErIbZVsMzDNgneDy3XZqXYAS
qT5X2QH1vsCP6Cni4T7Ooj6aFqAsq/7ERGoudP4CO8he82QlcWNMupoWrNZw12AB
J4HSqGT6ebi2YaPXCPCVMr3NqBc8AJGkaFG+RokhRCqSUZUboVQ52vLt7f4Xn4FI
0HAWYegA3kEsCTVQmsNSX/3pUGoCtg4kAOKDUfyPHPCWjA94M8OAU5qnXg/HnZTP
1uP5XnaNhd+po/LklqxMY2tCUf6VUhilUNyw0QIDAQABAoIBAQCh0oIT+4MUo52x
4xksCxx7h/CYi1Cxx1W4pMaRFaXsAsxoL2TVcGjEDfvVL/rDBM8nrskIUjs3kI0d
91zjIP6VzutvGWSpNKmMQh2sr2QanryAiBBlrCYCyHqbWtjE1Z1WrDQJvyLtrr2N
6oWAZaE8nmeTA7xR4W/CwbmEHfi90nB9xxtb6iJNMJAguMsvQ+oBxN4tQYCeNUGo
r88wd8vQyQjFCuU7Jzt8oSzcrP7D/pCgR4XhpU4ODsif8KMaAXS6H7Pt0QfLTkST
AaIq9NBjBvQ5VqkpwWvGHzE2oZ2cfVBu3+sfhi3bmNCkHnmoPlOhfortVDDObwpw
FA4+f71BAoGBAP80L/WseRIOqDkQ+wKbdMOwmyk8p6AlqnDiiGNXe2OsOarImTNn
U2L4xr8MpmOjkDr1aF7e6lIXvtDWyqrIaqmlMf/8xNGMNu24kFTRNxqlII9Yq3fP
sB0LGygnm1aEznK3uKzEIPFdHG0liOdsI3O6TF0PZXPFDFkJV+ERaRFFAoGBAMrq
Q9MjCYrVX2hlyYnv8l2EhQA3AtUXcQhM2JoH1pY/0QwLjloPrUnHSsWuRxf3vuA0
jkSzaoqOu2g/RyVEIPfhaLSptSs82vnLytsE+oPOKfQB28EyfJZcddbONmnCuJY1
4QKYVOzZBqDArD1U5JMZu3UotL2QmXDZDzamtIwdAoGBAMtU0UF0gaIZe368QMH7
CjVAaN+aLBQ07m+yjehYsz7e4bNo0GdcU9vvSqq9cXTBxRC0psuv4BI4SRgrip43
wIQZ0pSa2FX82WbePmDVsInSNvb/Nt7m4vLA/oonxGRSvAo6xzEfsv+bqCJuXX3F
cxmpvV4H/lUXEpd+Ej6ImKXhAoGBALBQ0tJ5lWcPdLGQEIlM97oO1kqTgmCK1+qw
a12cBffUR99Bg1X6XUbIZs5SWvAWk8LZp+1GQQNYdrtkkHtvMX5yXLru479IR7Xa
QNADCXLSB15A5yR+rAczHCmkUV+glSfgdT3+A30yLzIreP5p75tqNprc3gABz3Jh
CXkhbax5AoGAMrZdtA8h9gTdQfqo7QTpUHVP7sFm1Cv/JVDR+iIguF9inLPA/jqN
LHOH+9K3mKx8s6FIuSKsB9it1xCBx5PcP5lBE/9E0z72HC4S7eVVZJEQU2YxfLyS
ZhC2gm1mAAZF9SBYwxTJ7vIcXRWi8uOB6yM7QQhuUpduK236a1lJZao=
-----END RSA PRIVATE KEY-----`
testTransport := &testutils.Transport{}
clx := &http.Client{Transport: testTransport}
cfg := esign.JWTConfig{
IntegratorKey: "KEY",
PrivateKey: testPK,
KeyPairID: "1234567890123",
IsDemo: true,
HTTPClientFunc: func(ctx context.Context) (*http.Client, error) {
return clx, nil
},
}
var expectedConsentURL = "https://account-d.docusign.com/oauth/auth?client_id=KEY&redirect_uri=https%3A%2F%2Fwww.docusign.com&response_type=code&scope=signature%20impersonation"
if userConsentURL := cfg.UserConsentURL("https://www.docusign.com"); userConsentURL != expectedConsentURL {
t.Fatalf("expected %s; got %s", expectedConsentURL, userConsentURL)
}
ocr, _ := cfg.Credential("50d89ab1-dad5-d00d-b410-92ee3110b970", nil, nil)
var exchangeResponseTest = &testutils.RequestTester{
Host: "account-d.docusign.com",
Path: "/oauth/token",
Method: "POST",
ResponseFunc: func(r *http.Request) (*http.Response, error) {
return testutils.MakeResponse(200, []byte(tokenSuccessResponse), nil), nil
},
}
var userinfoResponseTest = &testutils.RequestTester{
Host: "account-d.docusign.com",
Path: "/oauth/userinfo",
Method: "GET",
Auth: "Bearer ISSUED_ACCESS_TOKEN",
ResponseFunc: func(r *http.Request) (*http.Response, error) {
return testutils.MakeResponse(200, []byte(userInfoSuccessResponse), nil), nil
},
}
testTransport.Add(exchangeResponseTest, userinfoResponseTest)
ctx := context.Background()
tk, err := ocr.Token(ctx)
if err != nil {
t.Errorf("expected token; got error %v", err)
}
ocr, _ = cfg.Credential("50d89ab1-dad5-d00d-b410-92ee3110b970", tk, nil)
testTransport.Add(userinfoResponseTest)
u, err := ocr.UserInfo(ctx)
if err != nil {
t.Errorf("userinf error: %v", err)
}
testTransport.Add(&testutils.RequestTester{
Path: "/restapi/v2/accounts/" + u.Accounts[0].AccountID + "/abc/def",
Header: http.Header{"Authorization": {"Bearer ISSUED_ACCESS_TOKEN"}},
Host: "gotest-d.docusign.net",
}, &testutils.RequestTester{
Path: "/restapi/v2.1/accounts/" + u.Accounts[0].AccountID + "/abc/def",
Header: http.Header{"Authorization": {"Bearer ISSUED_ACCESS_TOKEN"}},
Host: "gotest-d.docusign.net",
})
op := &esign.Op{
Method: "GET",
Path: "abc/def",
Version: tverV2,
}
if res, err := ocr.AuthDo(ctx, op); err != nil {
_ = res
t.Errorf("%v", err)
} else {
res.Body.Close()
}
op.Version = tverV21
if res, err := ocr.AuthDo(ctx, op); err != nil {
t.Errorf("%v", err)
} else {
res.Body.Close()
}
}
func TestTokenCredential(t *testing.T) {
ctx := context.Background()
testTransport := &testutils.Transport{}
cred := esign.TokenCredential("ABCDEF", true).
SetClientFunc(func(ctx context.Context) (*http.Client, error) {
return &http.Client{Transport: testTransport}, nil
})
testOp := &esign.Op{
Credential: cred,
Method: "GET",
Path: "testcmd",
Version: esign.APIv2,
}
_ = testOp
expectedAuthHeader := http.Header{
"Authorization": []string{"Bearer ABCDEF"},
}
testTransport.Add(
&testutils.RequestTester{
Path: "/oauth/userinfo",
Header: expectedAuthHeader,
Response: testutils.MakeResponse(400, []byte("invalid token"), nil),
},
&testutils.RequestTester{
Path: "/oauth/userinfo",
Header: expectedAuthHeader,
Response: testutils.MakeResponse(200, []byte(userInfoSuccessResponse), nil),
},
&testutils.RequestTester{
Path: "/restapi/v2/accounts/fe0b61a3-3b9b-cafe-b7be-4592af32aa9b/testcmd",
Header: expectedAuthHeader,
Response: testutils.MakeResponse(200, []byte("{}"), nil),
},
&testutils.RequestTester{
Path: "/restapi/v2/accounts/abcd61a3-3b9b-cafe-b7be-4592af32aa9b/testcmd",
Header: expectedAuthHeader,
Response: testutils.MakeResponse(200, []byte("{}"), nil),
},
)
// check for userinfo fail
switch err := testOp.Do(ctx, nil).(type) {
case nil:
t.Errorf("invalid token expected 400 status; got success")
return
case *esign.ResponseError:
default:
t.Errorf("%v", err)
return
}
if err := testOp.Do(ctx, nil); err != nil {
t.Errorf("%v", err)
}
testOp.Credential = cred.WithAccountID("BAD_ACCT")
if err := testOp.Do(ctx, nil); err == nil || err.Error() != "no account BAD_ACCT for susan.smart@example.com" {
t.Errorf("expected no account BAD_ACCT; got %v", err)
return
}
testOp.Credential = cred.WithAccountID("abcd61a3-3b9b-cafe-b7be-4592af32aa9b")
if err := testOp.Do(ctx, nil); err != nil {
t.Errorf("expected success; got %v", err)
}
}
func TestJWTExternalAdminConsentURL(t *testing.T) {
jwtCfg := esign.JWTConfig{
IntegratorKey: "INT_KEY",
IsDemo: false,
}
// invalid authType
_, err := jwtCfg.ExternalAdminConsentURL("https://www.example.com", "a", "", false)
if err == nil {
t.Errorf("expected error; got success")
}
// scopes empty
_, err = jwtCfg.ExternalAdminConsentURL("https://www.example.com", "code", "STATE", false)
if err == nil {
t.Errorf("expected error; got success")
}
authURL, _ := jwtCfg.ExternalAdminConsentURL("https://www.example.com", "code", "STATE", false, "signature", "impersonation")
expectedURL := "https://account.docusign.com/oauth/auth?admin_consent_scope=signature%20impersonation&client_id=INT_KEY&redirect_uri=https%3A%2F%2Fwww.example.com&response_type=code&scope=openid&state=STATE"
if authURL != expectedURL {
t.Errorf("expected %s; got %s", expectedURL, authURL)
return
}
authURL, _ = jwtCfg.ExternalAdminConsentURL("https://www.example.com", "token", "STATE", true, "signature", "impersonation")
expectedURL = "https://account.docusign.com/oauth/auth?admin_consent_scope=signature%20impersonation&client_id=INT_KEY&prompt=login&redirect_uri=https%3A%2F%2Fwww.example.com&response_type=token&scope=openid&state=STATE"
if authURL != expectedURL {
t.Errorf("expected %s; got %s", expectedURL, authURL)
return
}
}
type testVersion struct {
Host string
Demo string
Prefix string
Ver string
}
func (tv *testVersion) Name() string {
return tv.Ver
}
func (tv *testVersion) ResolveDSURL(u *url.URL, host string, accountID string, isDemo bool) *url.URL {
if tv == nil {
return u
}
newURL := *u
newURL.Scheme = "https"
newURL.Host = tv.Host
if isDemo {
newURL.Host = tv.Demo
}
if !strings.HasPrefix(u.Path, "/") {
newURL.Path = tv.Prefix + tv.Ver + "/accounts/" + accountID + "/" + u.Path
return &newURL
}
newURL.Path = tv.Prefix + u.Path
return &newURL
}