-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparser_test.go
More file actions
775 lines (676 loc) · 21.9 KB
/
Copy pathparser_test.go
File metadata and controls
775 lines (676 loc) · 21.9 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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
// Copyright The Linux Foundation and each contributor to LFX.
// SPDX-License-Identifier: MIT
package jwt
import (
"context"
"crypto/rand"
"crypto/rsa"
"encoding/base64"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestParseUnverified(t *testing.T) {
ctx := context.Background()
t.Run("valid token with all claims", func(t *testing.T) {
// Create a test token
now := time.Now()
exp := now.Add(time.Hour)
iat := now.Add(-time.Minute)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "user123",
"exp": exp.Unix(),
"iat": iat.Unix(),
"iss": "test-issuer",
"aud": "test-audience",
"scope": "read write update:current_user_metadata",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
claims, err := ParseUnverified(ctx, tokenString, DefaultParseOptions())
require.NoError(t, err)
assert.Equal(t, "user123", claims.Subject)
assert.NotNil(t, claims.ExpiresAt)
assert.WithinDuration(t, exp, *claims.ExpiresAt, time.Second)
assert.NotNil(t, claims.IssuedAt)
assert.WithinDuration(t, iat, *claims.IssuedAt, time.Second)
assert.Equal(t, "test-issuer", claims.Issuer)
assert.Equal(t, "test-audience", claims.Audience)
assert.Equal(t, "read write update:current_user_metadata", claims.Scope)
})
t.Run("token with Bearer prefix", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "user123",
"exp": time.Now().Add(time.Hour).Unix(),
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
bearerToken := "Bearer " + tokenString
claims, err := ParseUnverified(ctx, bearerToken, DefaultParseOptions())
require.NoError(t, err)
assert.Equal(t, "user123", claims.Subject)
})
t.Run("expired token", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "user123",
"exp": time.Now().Add(-time.Hour).Unix(), // Expired
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
_, err = ParseUnverified(ctx, tokenString, DefaultParseOptions())
assert.Error(t, err)
assert.Contains(t, err.Error(), "exp")
})
t.Run("missing required scope", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "user123",
"exp": time.Now().Add(time.Hour).Unix(),
"scope": "read write",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
opts := &ParseOptions{
RequireExpiration: true,
RequiredScopes: []string{"update:current_user_metadata"},
AllowBearerPrefix: true,
}
_, err = ParseUnverified(ctx, tokenString, opts)
assert.Error(t, err)
assert.Contains(t, err.Error(), "missing required scope")
})
t.Run("valid token with required scope", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "user123",
"exp": time.Now().Add(time.Hour).Unix(),
"scope": "read write update:current_user_metadata",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
opts := &ParseOptions{
RequireExpiration: true,
RequiredScopes: []string{"update:current_user_metadata"},
AllowBearerPrefix: true,
}
claims, err := ParseUnverified(ctx, tokenString, opts)
require.NoError(t, err)
assert.Equal(t, "user123", claims.Subject)
assert.True(t, claims.HasScope("update:current_user_metadata"))
assert.True(t, claims.HasScope("read"))
assert.False(t, claims.HasScope("admin"))
})
t.Run("empty token", func(t *testing.T) {
_, err := ParseUnverified(ctx, "", DefaultParseOptions())
assert.Error(t, err)
assert.Contains(t, err.Error(), "token is required")
})
t.Run("invalid token format", func(t *testing.T) {
_, err := ParseUnverified(ctx, "invalid.token", DefaultParseOptions())
assert.Error(t, err)
assert.Contains(t, err.Error(), "failed to parse JWT token")
})
}
func TestExtractSubject(t *testing.T) {
ctx := context.Background()
t.Run("valid token", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "user123",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
subject, err := ExtractSubject(ctx, tokenString)
require.NoError(t, err)
assert.Equal(t, "user123", subject)
})
t.Run("token with Bearer prefix", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "user456",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
bearerToken := "Bearer " + tokenString
subject, err := ExtractSubject(ctx, bearerToken)
require.NoError(t, err)
assert.Equal(t, "user456", subject)
})
t.Run("missing sub claim", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"iss": "test-issuer",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
_, err = ExtractSubject(ctx, tokenString)
assert.Error(t, err)
assert.Contains(t, err.Error(), "missing or invalid 'sub' claim")
})
t.Run("empty sub claim", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
_, err = ExtractSubject(ctx, tokenString)
assert.Error(t, err)
assert.Contains(t, err.Error(), "missing or invalid 'sub' claim")
})
}
func TestExtractEmail(t *testing.T) {
ctx := context.Background()
t.Run("valid token with email", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"email": "user@example.com",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
email, err := ExtractEmail(ctx, tokenString)
require.NoError(t, err)
assert.Equal(t, "user@example.com", email)
})
t.Run("valid token with email and other claims", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"email": "john.doe@company.com",
"sub": "auth0|123456789",
"iss": "https://test.auth0.com/",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
email, err := ExtractEmail(ctx, tokenString)
require.NoError(t, err)
assert.Equal(t, "john.doe@company.com", email)
})
t.Run("token with Bearer prefix", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"email": "bearer-test@example.com",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
bearerToken := "Bearer " + tokenString
email, err := ExtractEmail(ctx, bearerToken)
require.NoError(t, err)
assert.Equal(t, "bearer-test@example.com", email)
})
t.Run("missing email claim", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": "user123",
"iss": "test-issuer",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
_, err = ExtractEmail(ctx, tokenString)
assert.Error(t, err)
assert.Contains(t, err.Error(), "missing or invalid 'email' claim")
})
t.Run("empty email claim", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"email": "",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
_, err = ExtractEmail(ctx, tokenString)
assert.Error(t, err)
assert.Contains(t, err.Error(), "missing or invalid 'email' claim")
})
t.Run("whitespace-only email claim", func(t *testing.T) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"email": " ",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
_, err = ExtractEmail(ctx, tokenString)
assert.Error(t, err)
assert.Contains(t, err.Error(), "missing or invalid 'email' claim")
})
t.Run("invalid token format", func(t *testing.T) {
_, err := ExtractEmail(ctx, "invalid.token")
assert.Error(t, err)
})
t.Run("empty token", func(t *testing.T) {
_, err := ExtractEmail(ctx, "")
assert.Error(t, err)
})
t.Run("identity token with verified email", func(t *testing.T) {
// Simulates an identity token from email verification flow
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"email": "verified@example.com",
"email_verified": true,
"sub": "passwordless|654321",
})
tokenString, err := token.SignedString([]byte("secret"))
require.NoError(t, err)
email, err := ExtractEmail(ctx, tokenString)
require.NoError(t, err)
assert.Equal(t, "verified@example.com", email)
})
}
func TestClaimsHelpers(t *testing.T) {
claims := &Claims{
Subject: "user123",
Scope: "read write admin",
Raw: jwt.MapClaims{
"custom_field": "custom_value",
"number_field": 42,
},
}
t.Run("GetClaim", func(t *testing.T) {
value, exists := claims.GetClaim("custom_field")
assert.True(t, exists)
assert.Equal(t, "custom_value", value)
_, exists = claims.GetClaim("nonexistent")
assert.False(t, exists)
})
t.Run("GetStringClaim", func(t *testing.T) {
value, ok := claims.GetStringClaim("custom_field")
assert.True(t, ok)
assert.Equal(t, "custom_value", value)
_, ok = claims.GetStringClaim("number_field")
assert.False(t, ok) // Not a string
_, ok = claims.GetStringClaim("nonexistent")
assert.False(t, ok)
})
t.Run("HasScope", func(t *testing.T) {
assert.True(t, claims.HasScope("read"))
assert.True(t, claims.HasScope("write"))
assert.True(t, claims.HasScope("admin"))
assert.False(t, claims.HasScope("delete"))
})
}
func TestParseVerified(t *testing.T) {
// Generate a test RSA key pair
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("Failed to generate RSA key: %v", err)
}
publicKey := &privateKey.PublicKey
// Create a test JWT token
now := time.Now()
claims := jwt.MapClaims{
"sub": "test-user-123",
"iss": "https://test.auth0.com/",
"aud": "https://test.auth0.com/api/v2/",
"exp": now.Add(time.Hour).Unix(),
"iat": now.Unix(),
"scope": "read:current_user update:current_user_metadata",
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
tokenString, err := token.SignedString(privateKey)
if err != nil {
t.Fatalf("Failed to sign token: %v", err)
}
tests := []struct {
name string
token string
opts *ParseOptions
expectError bool
errorType error
}{
{
name: "valid token with signature verification",
token: tokenString,
opts: &ParseOptions{
VerifySignature: true,
SigningKey: publicKey,
ExpectedIssuer: "https://test.auth0.com/",
ExpectedAudience: "https://test.auth0.com/api/v2/",
RequireExpiration: true,
RequireSubject: true,
RequiredScopes: []string{"read:current_user"},
},
expectError: false,
},
{
name: "valid token with Bearer prefix",
token: "Bearer " + tokenString,
opts: &ParseOptions{
VerifySignature: true,
SigningKey: publicKey,
ExpectedIssuer: "https://test.auth0.com/",
ExpectedAudience: "https://test.auth0.com/api/v2/",
RequireExpiration: true,
RequireSubject: true,
AllowBearerPrefix: true,
},
expectError: false,
},
{
name: "invalid signature",
token: tokenString,
opts: &ParseOptions{
VerifySignature: true,
SigningKey: &rsa.PublicKey{}, // Wrong key
ExpectedIssuer: "https://test.auth0.com/",
ExpectedAudience: "https://test.auth0.com/api/v2/",
RequireExpiration: true,
RequireSubject: true,
},
expectError: true,
},
{
name: "wrong issuer",
token: tokenString,
opts: &ParseOptions{
VerifySignature: true,
SigningKey: publicKey,
ExpectedIssuer: "https://wrong.auth0.com/",
ExpectedAudience: "https://test.auth0.com/api/v2/",
RequireExpiration: true,
RequireSubject: true,
},
expectError: true,
},
{
name: "wrong audience",
token: tokenString,
opts: &ParseOptions{
VerifySignature: true,
SigningKey: publicKey,
ExpectedIssuer: "https://test.auth0.com/",
ExpectedAudience: "https://wrong.auth0.com/api/v2/",
RequireExpiration: true,
RequireSubject: true,
},
expectError: true,
},
{
name: "audience in ExpectedAudiences allow-list",
token: tokenString,
opts: &ParseOptions{
VerifySignature: true,
SigningKey: publicKey,
ExpectedIssuer: "https://test.auth0.com/",
ExpectedAudiences: []string{"https://other-api.example.org/", "https://test.auth0.com/api/v2/"},
RequireExpiration: true,
RequireSubject: true,
},
expectError: false,
},
{
name: "audience not in ExpectedAudiences allow-list",
token: tokenString,
opts: &ParseOptions{
VerifySignature: true,
SigningKey: publicKey,
ExpectedIssuer: "https://test.auth0.com/",
ExpectedAudiences: []string{"https://other-api.example.org/", "https://another.example.org/"},
RequireExpiration: true,
RequireSubject: true,
},
expectError: true,
},
{
name: "ExpectedAudiences takes precedence over mismatched ExpectedAudience",
token: tokenString,
opts: &ParseOptions{
VerifySignature: true,
SigningKey: publicKey,
ExpectedIssuer: "https://test.auth0.com/",
ExpectedAudience: "https://wrong.auth0.com/api/v2/",
ExpectedAudiences: []string{"https://test.auth0.com/api/v2/"},
RequireExpiration: true,
RequireSubject: true,
},
expectError: false,
},
{
name: "expired token",
token: createExpiredToken(t, privateKey),
opts: &ParseOptions{
VerifySignature: true,
SigningKey: publicKey,
ExpectedIssuer: "https://test.auth0.com/",
ExpectedAudience: "https://test.auth0.com/api/v2/",
RequireExpiration: true,
RequireSubject: true,
},
expectError: true,
},
{
name: "missing required scope",
token: tokenString,
opts: &ParseOptions{
VerifySignature: true,
SigningKey: publicKey,
ExpectedIssuer: "https://test.auth0.com/",
ExpectedAudience: "https://test.auth0.com/api/v2/",
RequireExpiration: true,
RequireSubject: true,
RequiredScopes: []string{"admin:all"}, // Not in token
},
expectError: true,
},
{
name: "missing signing key",
token: tokenString,
opts: &ParseOptions{
VerifySignature: true,
SigningKey: nil,
ExpectedIssuer: "https://test.auth0.com/",
ExpectedAudience: "https://test.auth0.com/api/v2/",
RequireExpiration: true,
RequireSubject: true,
},
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
claims, err := ParseVerified(ctx, tt.token, tt.opts)
if tt.expectError {
if err == nil {
t.Errorf("Expected error but got none")
return
}
if tt.errorType != nil {
// Check if error is of expected type (simplified check)
if err.Error() == "" {
t.Errorf("Expected error type %v, got %v", tt.errorType, err)
}
}
return
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
return
}
if claims == nil {
t.Error("Expected claims but got nil")
return
}
if claims.Subject != "test-user-123" {
t.Errorf("Expected subject 'test-user-123', got '%s'", claims.Subject)
}
})
}
}
func TestLoadRSAPublicKeyFromJWK(t *testing.T) {
// Generate a test RSA key pair
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("Failed to generate RSA key: %v", err)
}
// Create JWK data
jwkData := []byte(`{
"kty": "RSA",
"use": "sig",
"kid": "test-key-1",
"alg": "RS256",
"n": "` + encodeBase64URL(privateKey.N.Bytes()) + `",
"e": "` + encodeBase64URL([]byte{1, 0, 1}) + `"
}`)
// Test loading the key
loadedKey, err := LoadRSAPublicKeyFromJWK(jwkData)
if err != nil {
t.Fatalf("Failed to load RSA public key from JWK: %v", err)
}
if loadedKey.N.Cmp(privateKey.N) != 0 {
t.Error("Loaded key modulus doesn't match original")
}
if loadedKey.E != privateKey.E {
t.Error("Loaded key exponent doesn't match original")
}
}
func createExpiredToken(t *testing.T, privateKey *rsa.PrivateKey) string {
// Create an expired JWT token
claims := jwt.MapClaims{
"sub": "test-user-123",
"iss": "https://test.auth0.com/",
"aud": "https://test.auth0.com/api/v2/",
"exp": time.Now().Add(-time.Hour).Unix(), // Expired 1 hour ago
"iat": time.Now().Add(-2 * time.Hour).Unix(),
"scope": "read:current_user",
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
tokenString, err := token.SignedString(privateKey)
if err != nil {
t.Fatalf("Failed to sign expired token: %v", err)
}
return tokenString
}
func encodeBase64URL(data []byte) string {
// Convert to base64url encoding
encoded := base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(data)
return encoded
}
func TestLooksLikeJWT(t *testing.T) {
tests := []struct {
name string
tokenStr string
expectedToken string
expectedResult bool
description string
}{
{
name: "empty string",
tokenStr: "",
expectedToken: "",
expectedResult: false,
description: "Empty string should not be recognized as JWT",
},
{
name: "whitespace only",
tokenStr: " ",
expectedToken: "",
expectedResult: false,
description: "Whitespace-only string should not be recognized as JWT",
},
{
name: "valid JWT without Bearer prefix",
tokenStr: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJleHAiOjE2MzQ1Njc4OTAsImlhdCI6MTYzNDU2NDI5MCwic2NvcGUiOiJyZWFkOmN1cnJlbnRfdXNlciJ9.signature",
expectedToken: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJleHAiOjE2MzQ1Njc4OTAsImlhdCI6MTYzNDU2NDI5MCwic2NvcGUiOiJyZWFkOmN1cnJlbnRfdXNlciJ9.signature", expectedResult: true,
description: "Valid JWT structure should be recognized",
},
{
name: "valid JWT with Bearer prefix",
tokenStr: "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJleHAiOjE2MzQ1Njc4OTAsImlhdCI6MTYzNDU2NDI5MCwic2NvcGUiOiJyZWFkOmN1cnJlbnRfdXNlciJ9.signature", expectedToken: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhdXRoMHwxMjM0NTY3ODkiLCJleHAiOjE2MzQ1Njc4OTAsImlhdCI6MTYzNDU2NDI5MCwic2NvcGUiOiJyZWFkOmN1cnJlbnRfdXNlciJ9.signature", expectedResult: true,
description: "Valid JWT with Bearer prefix should be recognized and cleaned",
},
{
name: "invalid JWT - only two parts",
tokenStr: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhdXRoMHwxMjM0NTY3ODki", expectedToken: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhdXRoMHwxMjM0NTY3ODki",
expectedResult: false,
description: "JWT with only two parts should not be recognized",
},
{
name: "invalid JWT - malformed structure",
tokenStr: "not.a.valid.jwt",
expectedToken: "not.a.valid.jwt",
expectedResult: false,
description: "Malformed JWT structure should not be recognized",
},
{
name: "username - should not be JWT",
tokenStr: "john.doe",
expectedToken: "john.doe",
expectedResult: false,
description: "Username should not be recognized as JWT",
},
{
name: "sub with pipe - should not be JWT",
tokenStr: "auth0|123456789",
expectedToken: "auth0|123456789",
expectedResult: false,
description: "Sub with pipe should not be recognized as JWT",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cleanToken, isJWT := LooksLikeJWT(tt.tokenStr)
// Check the boolean result
if isJWT != tt.expectedResult {
t.Errorf("LooksLikeJWT() %s: result = %v, expected %v", tt.name, isJWT, tt.expectedResult)
}
// Check the cleaned token
if cleanToken != tt.expectedToken {
t.Errorf("LooksLikeJWT() %s: cleanToken = %q, expected %q", tt.name, cleanToken, tt.expectedToken)
}
})
}
}
func TestParseVerifiedMultipleTokenAudiences(t *testing.T) {
ctx := context.Background()
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
require.NoError(t, err)
publicKey := &privateKey.PublicKey
// Auth0 access tokens commonly carry multiple audiences (API + /userinfo)
claims := jwt.MapClaims{
"sub": "test-user-123",
"iss": "https://test.auth0.com/",
"aud": []string{"https://lfx-api.example.org/", "https://test.auth0.com/userinfo"},
"exp": time.Now().Add(time.Hour).Unix(),
"iat": time.Now().Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
tokenString, err := token.SignedString(privateKey)
require.NoError(t, err)
opts := &ParseOptions{
VerifySignature: true,
SigningKey: publicKey,
ExpectedIssuer: "https://test.auth0.com/",
ExpectedAudience: "https://test.auth0.com/userinfo", // matches the second audience
RequireExpiration: true,
RequireSubject: true,
}
parsed, err := ParseVerified(ctx, tokenString, opts)
require.NoError(t, err)
assert.Equal(t, "https://lfx-api.example.org/", parsed.Audience)
assert.Equal(t, []string{"https://lfx-api.example.org/", "https://test.auth0.com/userinfo"}, parsed.Audiences)
}
func TestClaimsHasAudience(t *testing.T) {
tests := []struct {
name string
claims *Claims
audience string
expected bool
}{
{
name: "match in Audiences list",
claims: &Claims{Audience: "a", Audiences: []string{"a", "b"}},
audience: "b",
expected: true,
},
{
name: "no match",
claims: &Claims{Audience: "a", Audiences: []string{"a", "b"}},
audience: "c",
expected: false,
},
{
name: "fallback to single Audience field",
claims: &Claims{Audience: "a"},
audience: "a",
expected: true,
},
{
name: "empty claims",
claims: &Claims{},
audience: "a",
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.expected, tt.claims.HasAudience(tt.audience))
})
}
}