-
Notifications
You must be signed in to change notification settings - Fork 657
Expand file tree
/
Copy pathcustom_oauth_test.go
More file actions
636 lines (579 loc) · 19.6 KB
/
custom_oauth_test.go
File metadata and controls
636 lines (579 loc) · 19.6 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
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
package provider
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
)
func TestNewCustomOAuthProvider(t *testing.T) {
provider := NewCustomOAuthProvider(
"test-client-id",
"test-client-secret",
"https://example.com/authorize",
"https://example.com/token",
"https://example.com/userinfo",
"https://myapp.com/callback",
[]string{"openid", "profile"},
true, // PKCE enabled
[]string{"ios-client-id", "android-client-id"},
map[string]interface{}{
"email": "user_email",
},
map[string]interface{}{
"prompt": "consent",
},
)
assert.NotNil(t, provider)
assert.Equal(t, "test-client-id", provider.config.ClientID)
assert.Equal(t, "test-client-secret", provider.config.ClientSecret)
assert.Equal(t, "https://myapp.com/callback", provider.config.RedirectURL)
assert.Equal(t, []string{"openid", "profile"}, provider.config.Scopes)
assert.Equal(t, "https://example.com/authorize", provider.config.Endpoint.AuthURL)
assert.Equal(t, "https://example.com/token", provider.config.Endpoint.TokenURL)
assert.Equal(t, "https://example.com/userinfo", provider.userinfoURL)
assert.True(t, provider.RequiresPKCE())
assert.Equal(t, []string{"ios-client-id", "android-client-id"}, provider.acceptableClientIDs)
assert.Equal(t, "user_email", provider.attributeMapping["email"])
assert.Equal(t, "consent", provider.authorizationParams["prompt"])
}
func TestCustomOAuthProvider_AuthCodeURL(t *testing.T) {
t.Run("Auth URL with authorization params", func(t *testing.T) {
provider := NewCustomOAuthProvider(
"client-id",
"client-secret",
"https://example.com/authorize",
"https://example.com/token",
"https://example.com/userinfo",
"https://myapp.com/callback",
[]string{"openid", "profile"},
false,
nil,
nil,
map[string]interface{}{
"prompt": "consent",
"access_type": "offline",
"custom_param": "custom_value",
},
)
authURL := provider.AuthCodeURL("test-state")
assert.Contains(t, authURL, "client_id=client-id")
assert.Contains(t, authURL, "redirect_uri=https")
assert.Contains(t, authURL, "response_type=code")
assert.Contains(t, authURL, "state=test-state")
assert.Contains(t, authURL, "prompt=consent")
assert.Contains(t, authURL, "access_type=offline")
assert.Contains(t, authURL, "custom_param=custom_value")
})
}
func TestCustomOAuthProvider_GetUserData(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Verify bearer token
authHeader := r.Header.Get("Authorization")
if authHeader != "Bearer test-access-token" {
w.WriteHeader(http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"sub": "user-123",
"email": "test@example.com",
"email_verified": true,
"name": "Test User",
"picture": "https://example.com/avatar.jpg",
})
}))
defer server.Close()
provider := NewCustomOAuthProvider(
"client-id",
"client-secret",
"https://example.com/authorize",
"https://example.com/token",
server.URL, // userinfo URL
"https://myapp.com/callback",
[]string{"openid", "profile", "email"},
false,
nil,
nil,
nil,
)
token := &oauth2.Token{
AccessToken: "test-access-token",
TokenType: "Bearer",
}
userData, err := provider.GetUserData(context.Background(), token)
require.NoError(t, err)
require.NotNil(t, userData)
require.Len(t, userData.Emails, 1)
assert.Equal(t, "test@example.com", userData.Emails[0].Email)
assert.True(t, userData.Emails[0].Verified)
assert.True(t, userData.Emails[0].Primary)
}
func TestCustomOAuthProvider_GetUserDataWithAttributeMapping(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"sub": "user-123",
"email": "test@example.com",
"email_verified": false, // Will be overridden by literal mapping
"full_name": "John Doe",
})
}))
defer server.Close()
provider := NewCustomOAuthProvider(
"client-id",
"client-secret",
"https://example.com/authorize",
"https://example.com/token",
server.URL,
"https://myapp.com/callback",
[]string{"openid"},
false,
nil,
map[string]interface{}{
"email_verified": true, // Override with literal boolean value
"name": "full_name", // Map full_name field to name
},
nil,
)
token := &oauth2.Token{
AccessToken: "test-access-token",
TokenType: "Bearer",
}
userData, err := provider.GetUserData(context.Background(), token)
require.NoError(t, err)
require.NotNil(t, userData)
require.Len(t, userData.Emails, 1)
assert.Equal(t, "test@example.com", userData.Emails[0].Email)
assert.True(t, userData.Emails[0].Verified) // Should be true from literal mapping
}
func TestCustomOAuthProvider_GetUserDataPreservesCustomClaims(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"sub": "user-123",
"email": "test@example.com",
"email_verified": true,
"name": "Test User",
// Non-standard claims that previously got silently dropped.
"groups": []string{"admins", "billing"},
"org_id": "org_42",
"tenant_id": "tenant-abc",
})
}))
defer server.Close()
provider := NewCustomOAuthProvider(
"client-id",
"client-secret",
"https://example.com/authorize",
"https://example.com/token",
server.URL,
"https://myapp.com/callback",
[]string{"openid", "profile", "email"},
false,
nil,
nil,
nil,
)
token := &oauth2.Token{AccessToken: "test-access-token", TokenType: "Bearer"}
userData, err := provider.GetUserData(context.Background(), token)
require.NoError(t, err)
require.NotNil(t, userData)
require.NotNil(t, userData.Metadata)
// Standard fields still populated.
assert.Equal(t, "user-123", userData.Metadata.Subject)
assert.Equal(t, "test@example.com", userData.Metadata.Email)
assert.Equal(t, "Test User", userData.Metadata.Name)
// Non-standard claims preserved under CustomClaims.
require.NotNil(t, userData.Metadata.CustomClaims)
assert.Equal(t, "org_42", userData.Metadata.CustomClaims["org_id"])
assert.Equal(t, "tenant-abc", userData.Metadata.CustomClaims["tenant_id"])
groups, ok := userData.Metadata.CustomClaims["groups"].([]interface{})
require.True(t, ok, "groups should round-trip as []interface{}")
require.Len(t, groups, 2)
assert.Equal(t, "admins", groups[0])
assert.Equal(t, "billing", groups[1])
// Known fields must NOT also leak into CustomClaims.
_, hasEmail := userData.Metadata.CustomClaims["email"]
assert.False(t, hasEmail)
_, hasSub := userData.Metadata.CustomClaims["sub"]
assert.False(t, hasSub)
}
func TestCustomClaimsUnmarshalCapturesCustomClaims(t *testing.T) {
t.Run("standard claims fill typed fields and non-standard claims land in CustomClaims", func(t *testing.T) {
body := []byte(`{
"sub": "u-1",
"email": "a@b.com",
"email_verified": true,
"groups": ["x"],
"org_id": "o1"
}`)
var c customClaims
require.NoError(t, json.Unmarshal(body, &c))
assert.Equal(t, "u-1", c.Subject)
assert.Equal(t, "a@b.com", c.Email)
assert.True(t, c.EmailVerified)
require.NotNil(t, c.CustomClaims)
assert.Equal(t, "o1", c.CustomClaims["org_id"])
assert.Equal(t, []interface{}{"x"}, c.CustomClaims["groups"])
_, hasEmail := c.CustomClaims["email"]
assert.False(t, hasEmail, "standard claims must not also leak into CustomClaims")
})
t.Run("only standard claims means CustomClaims stays nil", func(t *testing.T) {
body := []byte(`{"sub":"u","email":"a@b.com"}`)
var c customClaims
require.NoError(t, json.Unmarshal(body, &c))
assert.Nil(t, c.CustomClaims)
})
t.Run("provider that literally returns custom_claims is preserved flat (not re-nested)", func(t *testing.T) {
body := []byte(`{"sub":"u-2","custom_claims":{"foo":"bar"}}`)
var c customClaims
require.NoError(t, json.Unmarshal(body, &c))
assert.Equal(t, "u-2", c.Subject)
require.NotNil(t, c.CustomClaims)
assert.Equal(t, "bar", c.CustomClaims["foo"])
_, nested := c.CustomClaims["custom_claims"]
assert.False(t, nested, "custom_claims must not be re-nested under itself")
})
t.Run("custom_claims object and other non-standard keys are merged at top level", func(t *testing.T) {
body := []byte(`{
"sub": "u-3",
"custom_claims": {"foo": "bar"},
"groups": ["admins"],
"org_id": "o1"
}`)
var c customClaims
require.NoError(t, json.Unmarshal(body, &c))
assert.Equal(t, "u-3", c.Subject)
require.NotNil(t, c.CustomClaims)
assert.Equal(t, "bar", c.CustomClaims["foo"])
assert.Equal(t, "o1", c.CustomClaims["org_id"])
assert.Equal(t, []interface{}{"admins"}, c.CustomClaims["groups"])
_, nested := c.CustomClaims["custom_claims"]
assert.False(t, nested, "custom_claims must not be re-nested under itself")
})
t.Run("entries inside custom_claims win over same-named top-level keys", func(t *testing.T) {
// IdP returns "groups" both inside custom_claims and at the top
// level. The typed decode places the inner value into CustomClaims
// first; the outer one must not silently overwrite it.
body := []byte(`{
"sub": "u-4",
"custom_claims": {"groups": ["from-inner"]},
"groups": ["from-outer"]
}`)
var c customClaims
require.NoError(t, json.Unmarshal(body, &c))
require.NotNil(t, c.CustomClaims)
assert.Equal(t, []interface{}{"from-inner"}, c.CustomClaims["groups"])
})
t.Run("plain Claims still drops non-standard claims (proves scoping)", func(t *testing.T) {
body := []byte(`{"sub":"u","groups":["x"]}`)
var c Claims
require.NoError(t, json.Unmarshal(body, &c))
assert.Equal(t, "u", c.Subject)
assert.Nil(t, c.CustomClaims, "non-custom providers must keep existing drop behaviour")
})
}
func TestApplyAttributeMapping(t *testing.T) {
tests := []struct {
name string
claims Claims
mapping map[string]interface{}
expected Claims
}{
{
name: "Map with literal non-string values",
claims: Claims{
Subject: "user-456",
Email: "test@example.com",
},
mapping: map[string]interface{}{
"email_verified": true, // Literal boolean value
"iat": float64(1234567890), // Literal number value
},
expected: Claims{
Subject: "user-456",
Email: "test@example.com",
EmailVerified: true,
Iat: float64(1234567890),
},
},
{
name: "Map between existing fields",
claims: Claims{
Subject: "user-123",
Email: "test@example.com",
FullName: "John Doe",
AvatarURL: "https://example.com/avatar.jpg",
},
mapping: map[string]interface{}{
"name": "full_name", // Map full_name -> name
"picture": "avatar_url", // Map avatar_url -> picture
},
expected: Claims{
Subject: "user-123",
Email: "test@example.com",
Name: "John Doe",
Picture: "https://example.com/avatar.jpg",
FullName: "John Doe", // Original field still exists
AvatarURL: "https://example.com/avatar.jpg",
},
},
{
name: "Empty mapping returns original claims",
claims: Claims{
Subject: "user-789",
Email: "unchanged@example.com",
},
mapping: map[string]interface{}{},
expected: Claims{
Subject: "user-789",
Email: "unchanged@example.com",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := applyAttributeMapping(tt.claims, tt.mapping)
assert.Equal(t, tt.expected.Subject, result.Subject)
assert.Equal(t, tt.expected.Email, result.Email)
assert.Equal(t, tt.expected.EmailVerified, result.EmailVerified)
assert.Equal(t, tt.expected.Name, result.Name)
if tt.expected.Picture != "" {
assert.Equal(t, tt.expected.Picture, result.Picture)
}
})
}
}
func TestNewCustomOIDCProvider(t *testing.T) {
// Mock OIDC provider server
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/.well-known/openid-configuration" {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"issuer": server.URL,
"authorization_endpoint": server.URL + "/authorize",
"token_endpoint": server.URL + "/token",
"userinfo_endpoint": server.URL + "/userinfo",
"jwks_uri": server.URL + "/jwks",
})
} else if r.URL.Path == "/jwks" {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"keys": []interface{}{},
})
}
}))
defer server.Close()
// Pass issuer URL directly - oidc.NewProvider will fetch discovery automatically
provider, err := NewCustomOIDCProvider(
context.Background(),
"test-client-id",
"test-client-secret",
"https://myapp.com/callback",
[]string{"profile", "email"}, // Without openid
server.URL, // issuer
true, // PKCE enabled
[]string{"ios-client", "android-client"},
map[string]interface{}{"email": "user_email"},
map[string]interface{}{"prompt": "consent"},
NewOIDCProviderCache(0),
)
require.NoError(t, err)
require.NotNil(t, provider)
// Verify openid scope was automatically added
assert.Contains(t, provider.config.Scopes, "openid")
assert.Contains(t, provider.config.Scopes, "profile")
assert.Contains(t, provider.config.Scopes, "email")
assert.True(t, provider.RequiresPKCE())
assert.Equal(t, []string{"ios-client", "android-client"}, provider.acceptableClientIDs)
}
func TestCustomOIDCProvider_ValidateAudience(t *testing.T) {
tests := []struct {
name string
clientID string
acceptableClientIDs []string
tokenAudiences []string
wantErr bool
}{
{
name: "Valid single audience matches client ID",
clientID: "web-client-id",
acceptableClientIDs: nil,
tokenAudiences: []string{"web-client-id"},
wantErr: false,
},
{
name: "Valid audience matches one of acceptable client IDs",
clientID: "web-client-id",
acceptableClientIDs: []string{"ios-client-id", "android-client-id"},
tokenAudiences: []string{"ios-client-id"},
wantErr: false,
},
{
name: "Valid audience matches different acceptable client ID",
clientID: "web-client-id",
acceptableClientIDs: []string{"ios-client-id", "android-client-id"},
tokenAudiences: []string{"android-client-id"},
wantErr: false,
},
{
name: "Valid multiple audiences, one matches",
clientID: "web-client-id",
acceptableClientIDs: []string{"ios-client-id"},
tokenAudiences: []string{"web-client-id", "other-client-id"},
wantErr: false,
},
{
name: "Invalid - no matching audience",
clientID: "web-client-id",
acceptableClientIDs: []string{"ios-client-id", "android-client-id"},
tokenAudiences: []string{"unknown-client-id"},
wantErr: true,
},
{
name: "Invalid - empty token audiences",
clientID: "web-client-id",
acceptableClientIDs: []string{"ios-client-id"},
tokenAudiences: []string{},
wantErr: true,
},
{
name: "Valid - multiple acceptable client IDs, multi-platform scenario",
clientID: "web-client-id",
acceptableClientIDs: []string{"com.myapp.ios", "com.myapp.android", "com.myapp.macos"},
tokenAudiences: []string{"com.myapp.ios"},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a minimal OIDC provider for testing validateAudience
provider := &CustomOIDCProvider{
config: &oauth2.Config{
ClientID: tt.clientID,
},
acceptableClientIDs: tt.acceptableClientIDs,
}
err := provider.validateAudience(tt.tokenAudiences)
if tt.wantErr {
assert.Error(t, err)
assert.Contains(t, err.Error(), "does not match any acceptable client ID")
} else {
assert.NoError(t, err)
}
})
}
}
func TestCustomOIDCProvider_AuthCodeURL(t *testing.T) {
// Mock OIDC provider server
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/.well-known/openid-configuration" {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"issuer": server.URL,
"authorization_endpoint": server.URL + "/authorize",
"token_endpoint": server.URL + "/token",
"jwks_uri": server.URL + "/jwks",
})
} else if r.URL.Path == "/jwks" {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"keys": []interface{}{},
})
}
}))
defer server.Close()
// Pass issuer URL directly - oidc.NewProvider will fetch discovery automatically
provider, err := NewCustomOIDCProvider(
context.Background(),
"client-id",
"client-secret",
"https://myapp.com/callback",
[]string{"openid", "profile"},
server.URL, // issuer
false,
nil,
nil,
map[string]interface{}{
"prompt": "consent",
"max_age": "3600",
"ui_locales": "en",
"login_hint": "user@example.com",
},
NewOIDCProviderCache(0),
)
require.NoError(t, err)
authURL := provider.AuthCodeURL("test-state")
// Verify standard OAuth2 params
assert.Contains(t, authURL, "client_id=client-id")
assert.Contains(t, authURL, "state=test-state")
assert.Contains(t, authURL, "response_type=code")
// Verify custom authorization params
assert.Contains(t, authURL, "prompt=consent")
assert.Contains(t, authURL, "max_age=3600")
assert.Contains(t, authURL, "ui_locales=en")
assert.Contains(t, authURL, "login_hint=user")
}
func TestCustomOIDCProvider_RequiresPKCE(t *testing.T) {
// Mock OIDC provider server
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/.well-known/openid-configuration" {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"issuer": server.URL,
"authorization_endpoint": server.URL + "/authorize",
"token_endpoint": server.URL + "/token",
"jwks_uri": server.URL + "/jwks",
})
} else if r.URL.Path == "/jwks" {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"keys": []interface{}{},
})
}
}))
defer server.Close()
t.Run("PKCE enabled", func(t *testing.T) {
// Pass issuer URL directly - oidc.NewProvider will fetch discovery automatically
provider, err := NewCustomOIDCProvider(
context.Background(),
"client-id",
"client-secret",
"https://myapp.com/callback",
[]string{"openid"},
server.URL, // issuer
true, // PKCE enabled
nil,
nil,
nil,
NewOIDCProviderCache(0),
)
require.NoError(t, err)
assert.True(t, provider.RequiresPKCE())
})
t.Run("PKCE disabled", func(t *testing.T) {
// Pass issuer URL directly - oidc.NewProvider will fetch discovery automatically
provider, err := NewCustomOIDCProvider(
context.Background(),
"client-id",
"client-secret",
"https://myapp.com/callback",
[]string{"openid"},
server.URL, // issuer
false, // PKCE disabled
nil,
nil,
nil,
NewOIDCProviderCache(0),
)
require.NoError(t, err)
assert.False(t, provider.RequiresPKCE())
})
}