This repository was archived by the owner on Apr 13, 2025. It is now read-only.
forked from oauth2-proxy/oauth2-proxy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprovider_data_test.go
614 lines (575 loc) · 17.3 KB
/
provider_data_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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
package providers
import (
"context"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/url"
"strings"
"testing"
"time"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
"github.com/stretchr/testify/assert"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/golang-jwt/jwt"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/encryption"
internaloidc "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/providers/oidc"
. "github.com/onsi/gomega"
"golang.org/x/oauth2"
)
const (
idToken = "eyJfoobar123.eyJbaz987.IDToken"
accessToken = "eyJfoobar123.eyJbaz987.AccessToken"
refreshToken = "eyJfoobar123.eyJbaz987.RefreshToken"
oidcIssuer = "https://issuer.example.com"
oidcClientID = "https://test.myapp.com"
oidcSecret = "SuperSecret123456789"
oidcNonce = "abcde12345edcba09876abcde12345ff"
failureTokenID = "this-id-fails-verification"
)
var (
verified = true
unverified = false
standardClaims = jwt.StandardClaims{
Audience: oidcClientID,
ExpiresAt: time.Now().Add(time.Duration(5) * time.Minute).Unix(),
Id: "id-some-id",
IssuedAt: time.Now().Unix(),
Issuer: oidcIssuer,
NotBefore: 0,
Subject: "123456789",
}
defaultIDToken = idTokenClaims{
Name: "Jane Dobbs",
Email: "[email protected]",
Phone: "+4798765432",
Picture: "http://mugbook.com/janed/me.jpg",
Groups: []string{"test:a", "test:b"},
Roles: []string{"test:c", "test:d"},
Verified: &verified,
Nonce: encryption.HashNonce([]byte(oidcNonce)),
StandardClaims: standardClaims,
}
numericGroupsIDToken = idTokenClaims{
Name: "Jane Dobbs",
Email: "[email protected]",
Phone: "+4798765432",
Picture: "http://mugbook.com/janed/me.jpg",
Groups: []interface{}{1, 2, 3},
Roles: []string{"test:c", "test:d"},
Verified: &verified,
Nonce: encryption.HashNonce([]byte(oidcNonce)),
StandardClaims: standardClaims,
}
complexGroupsIDToken = idTokenClaims{
Name: "Complex Claim",
Email: "[email protected]",
Phone: "+5439871234",
Picture: "http://mugbook.com/complex/claims.jpg",
Groups: []interface{}{
map[string]interface{}{
"groupId": "Admin Group Id",
"roles": []string{"Admin"},
},
12345,
"Just::A::String",
},
Roles: []string{"test:simple", "test:roles"},
Verified: &verified,
StandardClaims: standardClaims,
}
unverifiedIDToken = idTokenClaims{
Name: "Mystery Man",
Email: "[email protected]",
Phone: "+4025205729",
Picture: "http://mugbook.com/unverified/email.jpg",
Groups: []string{"test:a", "test:b"},
Roles: []string{"test:c", "test:d"},
Verified: &unverified,
StandardClaims: standardClaims,
}
minimalIDToken = idTokenClaims{
StandardClaims: standardClaims,
}
)
type idTokenClaims struct {
Name string `json:"preferred_username,omitempty"`
Email string `json:"email,omitempty"`
Phone string `json:"phone_number,omitempty"`
Picture string `json:"picture,omitempty"`
Groups interface{} `json:"groups,omitempty"`
Roles interface{} `json:"roles,omitempty"`
Verified *bool `json:"email_verified,omitempty"`
Nonce string `json:"nonce,omitempty"`
jwt.StandardClaims
}
type mockJWKS struct{}
func (mockJWKS) VerifySignature(_ context.Context, jwt string) ([]byte, error) {
decoded, err := base64.RawURLEncoding.DecodeString(strings.Split(jwt, ".")[1])
if err != nil {
return nil, err
}
tokenClaims := &idTokenClaims{}
err = json.Unmarshal(decoded, tokenClaims)
if err != nil || tokenClaims.Id == failureTokenID {
return nil, fmt.Errorf("the validation failed for subject [%v]", tokenClaims.Subject)
}
return decoded, nil
}
func newSignedTestIDToken(tokenClaims idTokenClaims) (string, error) {
key, _ := rsa.GenerateKey(rand.Reader, 2048)
standardClaims := jwt.NewWithClaims(jwt.SigningMethodRS256, tokenClaims)
return standardClaims.SignedString(key)
}
func newTestOauth2Token() *oauth2.Token {
return &oauth2.Token{
AccessToken: accessToken,
TokenType: "Bearer",
RefreshToken: refreshToken,
Expiry: time.Time{}.Add(time.Duration(5) * time.Second),
}
}
func TestProviderData_verifyIDToken(t *testing.T) {
failureIDToken := defaultIDToken
failureIDToken.Id = failureTokenID
testCases := map[string]struct {
IDToken *idTokenClaims
Verifier bool
ExpectIDToken bool
ExpectedError error
}{
"Valid ID Token": {
IDToken: &defaultIDToken,
Verifier: true,
ExpectIDToken: true,
ExpectedError: nil,
},
"Invalid ID Token": {
IDToken: &failureIDToken,
Verifier: true,
ExpectIDToken: false,
ExpectedError: errors.New("failed to verify token: failed to verify signature: " +
"the validation failed for subject [123456789]"),
},
"Missing ID Token": {
IDToken: nil,
Verifier: true,
ExpectIDToken: false,
ExpectedError: ErrMissingIDToken,
},
"OIDC Verifier not Configured": {
IDToken: &defaultIDToken,
Verifier: false,
ExpectIDToken: false,
ExpectedError: ErrMissingOIDCVerifier,
},
}
for testName, tc := range testCases {
t.Run(testName, func(t *testing.T) {
g := NewWithT(t)
token := newTestOauth2Token()
if tc.IDToken != nil {
idToken, err := newSignedTestIDToken(*tc.IDToken)
g.Expect(err).ToNot(HaveOccurred())
token = token.WithExtra(map[string]interface{}{
"id_token": idToken,
})
}
provider := &ProviderData{}
if tc.Verifier {
verificationOptions := internaloidc.IDTokenVerificationOptions{
AudienceClaims: []string{"aud"},
ClientID: oidcClientID,
}
provider.Verifier = internaloidc.NewVerifier(oidc.NewVerifier(
oidcIssuer,
mockJWKS{},
&oidc.Config{ClientID: oidcClientID},
), verificationOptions)
}
verified, err := provider.verifyIDToken(context.Background(), token)
if err != nil {
g.Expect(err).To(Equal(tc.ExpectedError))
}
if tc.ExpectIDToken {
g.Expect(verified).ToNot(BeNil())
g.Expect(*verified).To(BeAssignableToTypeOf(oidc.IDToken{}))
} else {
g.Expect(verified).To(BeNil())
}
})
}
}
func TestProviderData_buildSessionFromClaims(t *testing.T) {
testCases := map[string]struct {
IDToken idTokenClaims
AllowUnverified bool
UserClaim string
EmailClaim string
GroupsClaim string
ExpectedError error
ExpectedSession *sessions.SessionState
}{
"Standard": {
IDToken: defaultIDToken,
AllowUnverified: false,
EmailClaim: "email",
GroupsClaim: "groups",
UserClaim: "sub",
ExpectedSession: &sessions.SessionState{
User: "123456789",
Email: "[email protected]",
Groups: []string{"test:a", "test:b"},
PreferredUsername: "Jane Dobbs",
},
},
"Unverified Denied": {
IDToken: unverifiedIDToken,
AllowUnverified: false,
EmailClaim: "email",
GroupsClaim: "groups",
ExpectedError: errors.New("email in id_token ([email protected]) isn't verified"),
},
"Unverified Allowed": {
IDToken: unverifiedIDToken,
AllowUnverified: true,
EmailClaim: "email",
GroupsClaim: "groups",
UserClaim: "sub",
ExpectedSession: &sessions.SessionState{
User: "123456789",
Email: "[email protected]",
Groups: []string{"test:a", "test:b"},
PreferredUsername: "Mystery Man",
},
},
"Complex Groups": {
IDToken: complexGroupsIDToken,
AllowUnverified: true,
EmailClaim: "email",
GroupsClaim: "groups",
UserClaim: "sub",
ExpectedSession: &sessions.SessionState{
User: "123456789",
Email: "[email protected]",
Groups: []string{
"{\"groupId\":\"Admin Group Id\",\"roles\":[\"Admin\"]}",
"12345",
"Just::A::String",
},
PreferredUsername: "Complex Claim",
},
},
"User Claim Switched": {
IDToken: defaultIDToken,
AllowUnverified: true,
UserClaim: "phone_number",
EmailClaim: "email",
GroupsClaim: "groups",
ExpectedSession: &sessions.SessionState{
User: "+4798765432",
Email: "[email protected]",
Groups: []string{"test:a", "test:b"},
PreferredUsername: "Jane Dobbs",
},
},
"User Claim switched to non string": {
IDToken: defaultIDToken,
AllowUnverified: true,
UserClaim: "roles",
EmailClaim: "email",
GroupsClaim: "groups",
ExpectedSession: &sessions.SessionState{
User: "[\"test:c\",\"test:d\"]",
Email: "[email protected]",
Groups: []string{"test:a", "test:b"},
PreferredUsername: "Jane Dobbs",
},
},
"Email Claim Switched": {
IDToken: unverifiedIDToken,
AllowUnverified: true,
EmailClaim: "phone_number",
GroupsClaim: "groups",
UserClaim: "sub",
ExpectedSession: &sessions.SessionState{
User: "123456789",
Email: "+4025205729",
Groups: []string{"test:a", "test:b"},
PreferredUsername: "Mystery Man",
},
},
"Email Claim Switched to Non String": {
IDToken: unverifiedIDToken,
AllowUnverified: true,
EmailClaim: "roles",
GroupsClaim: "groups",
UserClaim: "sub",
ExpectedSession: &sessions.SessionState{
User: "123456789",
Email: "[\"test:c\",\"test:d\"]",
Groups: []string{"test:a", "test:b"},
PreferredUsername: "Mystery Man",
},
},
"Email Claim Non Existent": {
IDToken: unverifiedIDToken,
AllowUnverified: true,
EmailClaim: "aksjdfhjksadh",
GroupsClaim: "groups",
UserClaim: "sub",
ExpectedSession: &sessions.SessionState{
User: "123456789",
Email: "",
Groups: []string{"test:a", "test:b"},
PreferredUsername: "Mystery Man",
},
},
"Groups Claim Switched": {
IDToken: defaultIDToken,
AllowUnverified: false,
EmailClaim: "email",
GroupsClaim: "roles",
UserClaim: "sub",
ExpectedSession: &sessions.SessionState{
User: "123456789",
Email: "[email protected]",
Groups: []string{"test:c", "test:d"},
PreferredUsername: "Jane Dobbs",
},
},
"Groups Claim Non Existent": {
IDToken: defaultIDToken,
AllowUnverified: false,
EmailClaim: "email",
GroupsClaim: "alskdjfsalkdjf",
UserClaim: "sub",
ExpectedSession: &sessions.SessionState{
User: "123456789",
Email: "[email protected]",
Groups: nil,
PreferredUsername: "Jane Dobbs",
},
},
"Groups Claim Numeric values": {
IDToken: numericGroupsIDToken,
AllowUnverified: false,
EmailClaim: "email",
GroupsClaim: "groups",
UserClaim: "sub",
ExpectedSession: &sessions.SessionState{
User: "123456789",
Email: "[email protected]",
Groups: []string{"1", "2", "3"},
PreferredUsername: "Jane Dobbs",
},
},
"Groups Claim string values": {
IDToken: defaultIDToken,
AllowUnverified: false,
EmailClaim: "email",
GroupsClaim: "email",
UserClaim: "sub",
ExpectedSession: &sessions.SessionState{
User: "123456789",
Email: "[email protected]",
Groups: []string{"[email protected]"},
PreferredUsername: "Jane Dobbs",
},
},
}
for testName, tc := range testCases {
t.Run(testName, func(t *testing.T) {
g := NewWithT(t)
verificationOptions := internaloidc.IDTokenVerificationOptions{
AudienceClaims: []string{"aud"},
ClientID: oidcClientID,
}
provider := &ProviderData{
Verifier: internaloidc.NewVerifier(oidc.NewVerifier(
oidcIssuer,
mockJWKS{},
&oidc.Config{ClientID: oidcClientID},
), verificationOptions),
}
provider.AllowUnverifiedEmail = tc.AllowUnverified
provider.UserClaim = tc.UserClaim
provider.EmailClaim = tc.EmailClaim
provider.GroupsClaim = tc.GroupsClaim
rawIDToken, err := newSignedTestIDToken(tc.IDToken)
g.Expect(err).ToNot(HaveOccurred())
ss, err := provider.buildSessionFromClaims(rawIDToken, "")
if err != nil {
g.Expect(err).To(Equal(tc.ExpectedError))
}
if ss != nil {
g.Expect(ss).To(Equal(tc.ExpectedSession))
}
})
}
}
func TestProviderData_checkNonce(t *testing.T) {
testCases := map[string]struct {
Session *sessions.SessionState
IDToken idTokenClaims
ExpectedError error
}{
"Nonces match": {
Session: &sessions.SessionState{
Nonce: []byte(oidcNonce),
},
IDToken: defaultIDToken,
ExpectedError: nil,
},
"Nonces do not match": {
Session: &sessions.SessionState{
Nonce: []byte("WrongWrongWrong"),
},
IDToken: defaultIDToken,
ExpectedError: errors.New("id_token nonce claim does not match the session nonce"),
},
"Missing nonce claim": {
Session: &sessions.SessionState{
Nonce: []byte(oidcNonce),
},
IDToken: minimalIDToken,
ExpectedError: errors.New("id_token nonce claim does not match the session nonce"),
},
}
for testName, tc := range testCases {
t.Run(testName, func(t *testing.T) {
g := NewWithT(t)
// Ensure that the ID token in the session is valid (signed and contains a nonce)
// as the nonce claim is extracted to compare with the session nonce
rawIDToken, err := newSignedTestIDToken(tc.IDToken)
g.Expect(err).ToNot(HaveOccurred())
tc.Session.IDToken = rawIDToken
verificationOptions := internaloidc.IDTokenVerificationOptions{
AudienceClaims: []string{"aud"},
ClientID: oidcClientID,
}
provider := &ProviderData{
Verifier: internaloidc.NewVerifier(oidc.NewVerifier(
oidcIssuer,
mockJWKS{},
&oidc.Config{ClientID: oidcClientID},
), verificationOptions),
}
if err := provider.checkNonce(tc.Session); err != nil {
g.Expect(err).To(Equal(tc.ExpectedError))
} else {
g.Expect(err).ToNot(HaveOccurred())
}
})
}
}
func TestProviderData_loginURLParameters(t *testing.T) {
testCases := []struct {
name string
overrides url.Values
has url.Values
notHas []string
}{
{
name: "no overrides",
overrides: url.Values{},
has: url.Values{
"fixed": {"fixed-value"},
"enum_with_default": {"default-value"},
"free_with_default": {"default-value"},
},
notHas: []string{"enum_no_default", "free_no_default"},
},
{
name: "attempt to override fixed value",
overrides: url.Values{"fixed": {"another-value"}},
has: url.Values{
"fixed": {"fixed-value"},
"enum_with_default": {"default-value"},
"free_with_default": {"default-value"},
},
notHas: []string{"enum_no_default", "free_no_default"},
},
{
name: "set one allowed and one forbidden enum",
overrides: url.Values{
"enum_no_default": {"allowed1", "not-allowed"},
},
has: url.Values{
"fixed": {"fixed-value"},
"enum_with_default": {"default-value"},
"free_with_default": {"default-value"},
"enum_no_default": {"allowed1"},
},
notHas: []string{"free_no_default"},
},
{
name: "replace default value",
overrides: url.Values{"free_with_default": {"something-else"}},
has: url.Values{
"fixed": {"fixed-value"},
"enum_with_default": {"default-value"},
"free_with_default": {"something-else"},
},
notHas: []string{"enum_no_default", "free_no_default"},
},
{
name: "set free text value",
overrides: url.Values{"free_no_default": {"some-value"}},
has: url.Values{
"fixed": {"fixed-value"},
"enum_with_default": {"default-value"},
"free_with_default": {"default-value"},
"free_no_default": {"some-value"},
},
notHas: []string{"enum_no_default"},
},
{
name: "attempt to set unapproved parameter",
overrides: url.Values{"malicious_value": {"evil"}},
has: url.Values{
"fixed": {"fixed-value"},
"enum_with_default": {"default-value"},
"free_with_default": {"default-value"},
},
notHas: []string{"enum_no_default", "free_no_default"},
},
}
// fixed list of two allowed values
allowed1 := "allowed1"
allowed2 := "allowed2"
allowEnum := []options.URLParameterRule{
{Value: &allowed1},
{Value: &allowed2},
}
// regex that will allow anything
anything := "^.*$"
allowAnything := []options.URLParameterRule{
{Pattern: &anything},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// set up LoginURLParameters for testing
data := ProviderData{}
data.compileLoginParams([]options.LoginURLParameter{
{Name: "fixed", Default: []string{"fixed-value"}},
{Name: "enum_with_default", Default: []string{"default-value"}, Allow: allowEnum},
{Name: "enum_no_default", Allow: allowEnum},
{Name: "free_with_default", Default: []string{"default-value"}, Allow: allowAnything},
{Name: "free_no_default", Allow: allowAnything},
})
redirectParams := data.LoginURLParams(tc.overrides)
for _, k := range tc.notHas {
assert.NotContains(t, redirectParams, k)
}
for k, vs := range tc.has {
actualVals := redirectParams[k]
assert.ElementsMatch(t, vs, actualVals)
}
})
}
}