File: jwt_test.go

package info (click to toggle)
golang-github-lestrrat-go-jwx 2.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,872 kB
  • sloc: sh: 222; makefile: 86; perl: 62
file content (1872 lines) | stat: -rw-r--r-- 53,417 bytes parent folder | download
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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
package jwt_test

import (
	"bytes"
	"context"
	"crypto/ecdsa"
	"crypto/ed25519"
	"crypto/rand"
	"crypto/rsa"
	"encoding/base64"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/lestrrat-go/jwx/v2/internal/ecutil"
	"github.com/lestrrat-go/jwx/v2/internal/json"
	"github.com/lestrrat-go/jwx/v2/internal/jwxtest"
	"github.com/lestrrat-go/jwx/v2/jwe"
	"github.com/lestrrat-go/jwx/v2/jwt/internal/types"

	"github.com/lestrrat-go/jwx/v2/jwa"
	"github.com/lestrrat-go/jwx/v2/jwk"
	"github.com/lestrrat-go/jwx/v2/jws"
	"github.com/lestrrat-go/jwx/v2/jwt"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

/* This is commented out, because it is intended to cause compilation errors */
/*
func TestOption(t *testing.T) {
	var p jwt.ParseOption
	var v jwt.ValidateOption
	var o jwt.Option
	p = o // should be error
	v = o // should be error
	_ = p
	_ = v
}
*/

func TestJWTParse(t *testing.T) {
	t.Parallel()

	alg := jwa.RS256

	key, err := jwxtest.GenerateRsaKey()
	if !assert.NoError(t, err, `jwxtest.GenerateRsaKey should succeed`) {
		return
	}
	t1 := jwt.New()
	signed, err := jwt.Sign(t1, jwt.WithKey(alg, key))
	if !assert.NoError(t, err, `jwt.Sign should succeed`) {
		return
	}

	t.Logf("%s", signed)

	t.Run("Parse (no signature verification)", func(t *testing.T) {
		t.Parallel()
		t2, err := jwt.ParseInsecure(signed)
		if !assert.NoError(t, err, `jwt.Parse should succeed`) {
			return
		}
		if !assert.True(t, jwt.Equal(t1, t2), `t1 == t2`) {
			return
		}
	})
	t.Run("ParseString (no signature verification)", func(t *testing.T) {
		t.Parallel()
		t2, err := jwt.ParseString(string(signed), jwt.WithVerify(false), jwt.WithValidate(false))
		if !assert.NoError(t, err, `jwt.ParseString should succeed`) {
			return
		}
		if !assert.True(t, jwt.Equal(t1, t2), `t1 == t2`) {
			return
		}
	})
	t.Run("ParseReader (no signature verification)", func(t *testing.T) {
		t.Parallel()
		t2, err := jwt.ParseReader(bytes.NewReader(signed), jwt.WithVerify(false), jwt.WithValidate(false))
		if !assert.NoError(t, err, `jwt.ParseReader should succeed`) {
			return
		}
		if !assert.True(t, jwt.Equal(t1, t2), `t1 == t2`) {
			return
		}
	})
	t.Run("Parse (correct signature key)", func(t *testing.T) {
		t.Parallel()
		t2, err := jwt.Parse(signed, jwt.WithKey(alg, &key.PublicKey))
		if !assert.NoError(t, err, `jwt.Parse should succeed`) {
			return
		}
		if !assert.True(t, jwt.Equal(t1, t2), `t1 == t2`) {
			return
		}
	})
	t.Run("parse (wrong signature algorithm)", func(t *testing.T) {
		t.Parallel()
		_, err := jwt.Parse(signed, jwt.WithKey(jwa.RS512, &key.PublicKey))
		if !assert.Error(t, err, `jwt.Parse should fail`) {
			return
		}
	})
	t.Run("parse (wrong signature key)", func(t *testing.T) {
		t.Parallel()
		pubkey := key.PublicKey
		pubkey.E = 0 // bogus value
		_, err := jwt.Parse(signed, jwt.WithKey(alg, &pubkey))
		if !assert.Error(t, err, `jwt.Parse should fail`) {
			return
		}
	})
}

func TestJWTParseVerify(t *testing.T) {
	t.Parallel()

	keys := make([]interface{}, 0, 6)

	keys = append(keys, []byte("abracadabra"))

	rsaPrivKey, err := jwxtest.GenerateRsaKey()
	if !assert.NoError(t, err, "RSA key generated") {
		return
	}
	keys = append(keys, rsaPrivKey)

	for _, alg := range []jwa.EllipticCurveAlgorithm{jwa.P256, jwa.P384, jwa.P521} {
		ecdsaPrivKey, err := jwxtest.GenerateEcdsaKey(alg)
		if !assert.NoError(t, err, "jwxtest.GenerateEcdsaKey should succeed for %s", alg) {
			return
		}
		keys = append(keys, ecdsaPrivKey)
	}

	ed25519PrivKey, err := jwxtest.GenerateEd25519Key()
	if !assert.NoError(t, err, `jwxtest.GenerateEd25519Key should succeed`) {
		return
	}
	keys = append(keys, ed25519PrivKey)

	for _, key := range keys {
		key := key
		t.Run(fmt.Sprintf("Key=%T", key), func(t *testing.T) {
			t.Parallel()
			algs, err := jws.AlgorithmsForKey(key)
			if !assert.NoError(t, err, `jwas.AlgorithmsForKey should succeed`) {
				return
			}

			var dummyRawKey interface{}
			switch pk := key.(type) {
			case *rsa.PrivateKey:
				dummyRawKey, err = jwxtest.GenerateRsaKey()
				if !assert.NoError(t, err, `jwxtest.GenerateRsaKey should succeed`) {
					return
				}
			case *ecdsa.PrivateKey:
				curveAlg, ok := ecutil.AlgorithmForCurve(pk.Curve)
				if !assert.True(t, ok, `ecutil.AlgorithmForCurve should succeed`) {
					return
				}
				dummyRawKey, err = jwxtest.GenerateEcdsaKey(curveAlg)
				if !assert.NoError(t, err, `jwxtest.GenerateEcdsaKey should succeed`) {
					return
				}
			case ed25519.PrivateKey:
				dummyRawKey, err = jwxtest.GenerateEd25519Key()
				if !assert.NoError(t, err, `jwxtest.GenerateEd25519Key should succeed`) {
					return
				}
			case []byte:
				dummyRawKey = jwxtest.GenerateSymmetricKey()
			default:
				assert.Fail(t, fmt.Sprintf("Unhandled key type %T", key))
				return
			}

			testcases := []struct {
				SetAlgorithm   bool
				SetKid         bool
				InferAlgorithm bool
				Error          bool
			}{
				{
					SetAlgorithm:   true,
					SetKid:         true,
					InferAlgorithm: true,
				},
				{
					SetAlgorithm:   true,
					SetKid:         true,
					InferAlgorithm: false,
				},
				{
					SetAlgorithm:   true,
					SetKid:         false,
					InferAlgorithm: true,
					Error:          true,
				},
				{
					SetAlgorithm:   false,
					SetKid:         true,
					InferAlgorithm: true,
				},
				{
					SetAlgorithm:   false,
					SetKid:         true,
					InferAlgorithm: false,
					Error:          true,
				},
				{
					SetAlgorithm:   false,
					SetKid:         false,
					InferAlgorithm: true,
					Error:          true,
				},
				{
					SetAlgorithm:   true,
					SetKid:         false,
					InferAlgorithm: false,
					Error:          true,
				},
				{
					SetAlgorithm:   false,
					SetKid:         false,
					InferAlgorithm: false,
					Error:          true,
				},
			}
			for _, alg := range algs {
				alg := alg
				for _, tc := range testcases {
					tc := tc
					t.Run(fmt.Sprintf("Algorithm=%s, SetAlgorithm=%t, SetKid=%t, InferAlgorithm=%t, Expect Error=%t", alg, tc.SetAlgorithm, tc.SetKid, tc.InferAlgorithm, tc.Error), func(t *testing.T) {
						t.Parallel()

						const kid = "test-jwt-parse-verify-kid"
						const dummyKid = "test-jwt-parse-verify-dummy-kid"
						hdrs := jws.NewHeaders()
						hdrs.Set(jws.KeyIDKey, kid)

						t1 := jwt.New()
						signed, err := jwt.Sign(t1, jwt.WithKey(alg, key, jws.WithProtectedHeaders(hdrs)))
						if !assert.NoError(t, err, "token.Sign should succeed") {
							return
						}

						pubkey, err := jwk.PublicKeyOf(key)
						if !assert.NoError(t, err, `jwk.PublicKeyOf should succeed`) {
							return
						}

						if tc.SetAlgorithm {
							pubkey.Set(jwk.AlgorithmKey, alg)
						}

						dummyKey, err := jwk.PublicKeyOf(dummyRawKey)
						if !assert.NoError(t, err, `jwk.PublicKeyOf should succeed`) {
							return
						}

						if tc.SetKid {
							pubkey.Set(jwk.KeyIDKey, kid)
							dummyKey.Set(jwk.KeyIDKey, dummyKid)
						}

						// Permute on the location of the correct key, to check for possible
						// cases where we loop too little or too much.
						for i := 0; i < 6; i++ {
							var name string
							set := jwk.NewSet()
							switch i {
							case 0:
								name = "Lone key"
								set.AddKey(pubkey)
							case 1:
								name = "Two keys, correct one at the end"
								set.AddKey(dummyKey)
								set.AddKey(pubkey)
							case 2:
								name = "Two keys, correct one at the beginning"
								set.AddKey(pubkey)
								set.AddKey(dummyKey)
							case 3:
								name = "Three keys, correct one at the end"
								set.AddKey(dummyKey)
								set.AddKey(dummyKey)
								set.AddKey(pubkey)
							case 4:
								name = "Three keys, correct one at the middle"
								set.AddKey(dummyKey)
								set.AddKey(pubkey)
								set.AddKey(dummyKey)
							case 5:
								name = "Three keys, correct one at the beginning"
								set.AddKey(pubkey)
								set.AddKey(dummyKey)
								set.AddKey(dummyKey)
							}

							t.Run(name, func(t *testing.T) {
								options := []jwt.ParseOption{
									jwt.WithKeySet(set, jws.WithInferAlgorithmFromKey(tc.InferAlgorithm)),
								}
								t2, err := jwt.Parse(signed, options...)

								if tc.Error {
									assert.Error(t, err, `jwt.Parse should fail`)
									return
								}

								if !assert.NoError(t, err, `jwt.Parse should succeed`) {
									return
								}

								if !assert.True(t, jwt.Equal(t1, t2), `t1 == t2`) {
									return
								}
							})
						}
					})
				}
			}
		})
	}
	t.Run("Miscellaneous", func(t *testing.T) {
		key, err := jwxtest.GenerateRsaKey()
		if !assert.NoError(t, err, "RSA key generated") {
			return
		}
		const alg = jwa.RS256
		const kid = "my-very-special-key"
		hdrs := jws.NewHeaders()
		hdrs.Set(jws.KeyIDKey, kid)
		t1 := jwt.New()
		signed, err := jwt.Sign(t1, jwt.WithKey(alg, key, jws.WithProtectedHeaders(hdrs)))
		if !assert.NoError(t, err, "token.Sign should succeed") {
			return
		}

		t.Run("Alg does not match", func(t *testing.T) {
			t.Parallel()
			pubkey, err := jwk.PublicKeyOf(key)
			if !assert.NoError(t, err) {
				return
			}

			pubkey.Set(jwk.AlgorithmKey, jwa.HS256)
			pubkey.Set(jwk.KeyIDKey, kid)
			set := jwk.NewSet()
			set.AddKey(pubkey)

			_, err = jwt.Parse(signed, jwt.WithKeySet(set, jws.WithInferAlgorithmFromKey(true), jws.WithUseDefault(true)))
			if !assert.Error(t, err, `jwt.Parse should fail`) {
				return
			}
		})
		t.Run("UseDefault with a key set with 1 key", func(t *testing.T) {
			t.Parallel()
			pubkey, err := jwk.PublicKeyOf(key)
			if !assert.NoError(t, err) {
				return
			}

			pubkey.Set(jwk.AlgorithmKey, alg)
			pubkey.Set(jwk.KeyIDKey, kid)
			signedNoKid, err := jwt.Sign(t1, jwt.WithKey(alg, key))
			if err != nil {
				t.Fatal("Failed to sign JWT")
			}
			set := jwk.NewSet()
			set.AddKey(pubkey)
			t2, err := jwt.Parse(signedNoKid, jwt.WithKeySet(set, jws.WithUseDefault(true)))
			if !assert.NoError(t, err, `jwt.Parse with key set should succeed`) {
				return
			}
			if !assert.True(t, jwt.Equal(t1, t2), `t1 == t2`) {
				return
			}
		})
		t.Run("UseDefault with multiple keys should fail", func(t *testing.T) {
			t.Parallel()
			pubkey1, err := jwk.FromRaw(&key.PublicKey)
			if !assert.NoError(t, err) {
				return
			}
			pubkey2, err := jwk.FromRaw(&key.PublicKey)
			if !assert.NoError(t, err) {
				return
			}

			pubkey1.Set(jwk.KeyIDKey, kid)
			pubkey2.Set(jwk.KeyIDKey, "test-jwt-parse-verify-kid-2")
			signedNoKid, err := jwt.Sign(t1, jwt.WithKey(alg, key))
			if err != nil {
				t.Fatal("Failed to sign JWT")
			}
			set := jwk.NewSet()
			set.AddKey(pubkey1)
			set.AddKey(pubkey2)
			_, err = jwt.Parse(signedNoKid, jwt.WithKeySet(set, jws.WithUseDefault(true)))
			if !assert.Error(t, err, `jwt.Parse should fail`) {
				return
			}
		})
		// This is a test to check if we allow alg: none in the protected header section.
		// But in truth, since we delegate everything to jws.Verify anyways, it's really
		// a test to see if jws.Verify returns an error if alg: none is specified in the
		// header section. Move this test to jws if need be.
		t.Run("Check alg=none", func(t *testing.T) {
			t.Parallel()
			// Create a signed payload, but use alg=none
			_, payload, signature, err := jws.SplitCompact(signed)
			if !assert.NoError(t, err, `jws.SplitCompact should succeed`) {
				return
			}

			dummyHeader := jws.NewHeaders()
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()
			for iter := hdrs.Iterate(ctx); iter.Next(ctx); {
				pair := iter.Pair()
				dummyHeader.Set(pair.Key.(string), pair.Value)
			}
			dummyHeader.Set(jws.AlgorithmKey, jwa.NoSignature)

			dummyMarshaled, err := json.Marshal(dummyHeader)
			if !assert.NoError(t, err, `json.Marshal should succeed`) {
				return
			}
			dummyEncoded := make([]byte, base64.RawURLEncoding.EncodedLen(len(dummyMarshaled)))
			base64.RawURLEncoding.Encode(dummyEncoded, dummyMarshaled)

			signedButNot := bytes.Join([][]byte{dummyEncoded, payload, signature}, []byte{'.'})

			pubkey, err := jwk.FromRaw(&key.PublicKey)
			if !assert.NoError(t, err) {
				return
			}

			pubkey.Set(jwk.KeyIDKey, kid)

			set := jwk.NewSet()
			set.AddKey(pubkey)
			_, err = jwt.Parse(signedButNot, jwt.WithKeySet(set))
			// This should fail
			if !assert.Error(t, err, `jwt.Parse with key set + alg=none should fail`) {
				return
			}
		})
	})
}

func TestValidateClaims(t *testing.T) {
	t.Parallel()
	// GitHub issue #37: tokens are invalid in the second they are created (because Now() is not after IssuedAt())
	t.Run("Empty fields", func(t *testing.T) {
		t.Parallel()
		token := jwt.New()
		require.Error(t, jwt.Validate(token, jwt.WithIssuer("foo")), `token.Validate should fail`)
		require.Error(t, jwt.Validate(token, jwt.WithJwtID("foo")), `token.Validate should fail`)
		require.Error(t, jwt.Validate(token, jwt.WithSubject("foo")), `token.Validate should fail`)
	})
	t.Run("Reset Validator, No validator", func(t *testing.T) {
		t.Parallel()
		token := jwt.New()
		now := time.Now().UTC()
		token.Set(jwt.IssuedAtKey, now)

		err := jwt.Validate(token, jwt.WithResetValidators(true))
		require.Error(t, err, `token.Validate should fail`)
		require.Contains(t, err.Error(), "no validators specified", `error message should contain "no validators specified"`)
	})
	t.Run("Reset Validator, Check iss only", func(t *testing.T) {
		t.Parallel()
		token := jwt.New()
		iat := time.Now().UTC().Add(time.Hour * 24)
		token.Set(jwt.IssuedAtKey, iat)
		token.Set(jwt.IssuerKey, "github.com/lestrrat-go")

		err := jwt.Validate(token, jwt.WithResetValidators(true), jwt.WithIssuer("github.com/lestrrat-go"))
		require.NoError(t, err, `token.Validate should succeed`)
	})
	t.Run(jwt.IssuedAtKey+"+skew", func(t *testing.T) {
		t.Parallel()
		token := jwt.New()
		now := time.Now().UTC()
		token.Set(jwt.IssuedAtKey, now)

		const DefaultSkew = 0

		args := []jwt.ValidateOption{
			jwt.WithClock(jwt.ClockFunc(func() time.Time { return now })),
			jwt.WithAcceptableSkew(DefaultSkew),
		}

		if !assert.NoError(t, jwt.Validate(token, args...), "token.Validate should validate tokens in the same second they are created") {
			if now.Equal(token.IssuedAt()) {
				t.Errorf("iat claim failed: iat == now")
			}
			return
		}
	})
}

const aLongLongTimeAgo = 233431200
const aLongLongTimeAgoString = "233431200"

func TestUnmarshal(t *testing.T) {
	t.Parallel()
	testcases := []struct {
		Title        string
		Source       string
		Expected     func() jwt.Token
		ExpectedJSON string
	}{
		{
			Title:  "single aud",
			Source: `{"aud":"foo"}`,
			Expected: func() jwt.Token {
				t := jwt.New()
				t.Set("aud", "foo")
				return t
			},
			ExpectedJSON: `{"aud":["foo"]}`,
		},
		{
			Title:  "multiple aud's",
			Source: `{"aud":["foo","bar"]}`,
			Expected: func() jwt.Token {
				t := jwt.New()
				t.Set("aud", []string{"foo", "bar"})
				return t
			},
			ExpectedJSON: `{"aud":["foo","bar"]}`,
		},
		{
			Title:  "issuedAt",
			Source: `{"` + jwt.IssuedAtKey + `":` + aLongLongTimeAgoString + `}`,
			Expected: func() jwt.Token {
				t := jwt.New()
				t.Set(jwt.IssuedAtKey, aLongLongTimeAgo)
				return t
			},
			ExpectedJSON: `{"` + jwt.IssuedAtKey + `":` + aLongLongTimeAgoString + `}`,
		},
	}

	for _, tc := range testcases {
		tc := tc
		t.Run(tc.Title, func(t *testing.T) {
			t.Parallel()
			token := jwt.New()
			if !assert.NoError(t, json.Unmarshal([]byte(tc.Source), &token), `json.Unmarshal should succeed`) {
				return
			}
			if !assert.Equal(t, tc.Expected(), token, `token should match expected value`) {
				return
			}

			var buf bytes.Buffer
			if !assert.NoError(t, json.NewEncoder(&buf).Encode(token), `json.Marshal should succeed`) {
				return
			}
			if !assert.Equal(t, tc.ExpectedJSON, strings.TrimSpace(buf.String()), `json should match`) {
				return
			}
		})
	}
}

func TestGH52(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	t.Parallel()
	priv, err := jwxtest.GenerateEcdsaKey(jwa.P521)
	if !assert.NoError(t, err) {
		return
	}

	pub := &priv.PublicKey
	if !assert.NoError(t, err) {
		return
	}
	const iterations = 100
	var wg sync.WaitGroup
	wg.Add(iterations)
	for i := 0; i < iterations; i++ {
		// Do not use t.Run here as it will clutter up the outpuA
		go func(t *testing.T, priv *ecdsa.PrivateKey, i int) {
			defer wg.Done()
			tok := jwt.New()

			s, err := jwt.Sign(tok, jwt.WithKey(jwa.ES256, priv))
			if !assert.NoError(t, err) {
				return
			}

			if _, err = jws.Verify(s, jws.WithKey(jwa.ES256, pub)); !assert.NoError(t, err, `test should pass (run %d)`, i) {
				return
			}
		}(t, priv, i)
	}
	wg.Wait()
}

func TestUnmarshalJSON(t *testing.T) {
	t.Parallel()
	t.Run("Unmarshal audience with multiple values", func(t *testing.T) {
		t.Parallel()
		t1 := jwt.New()
		if !assert.NoError(t, json.Unmarshal([]byte(`{"aud":["foo", "bar", "baz"]}`), &t1), `jwt.Parse should succeed`) {
			return
		}
		aud, ok := t1.Get(jwt.AudienceKey)
		if !assert.True(t, ok, `jwt.Get(jwt.AudienceKey) should succeed`) {
			t.Logf("%#v", t1)
			return
		}

		if !assert.Equal(t, aud.([]string), []string{"foo", "bar", "baz"}, "audience should match. got %v", aud) {
			return
		}
	})
}

func TestSignErrors(t *testing.T) {
	t.Parallel()
	priv, err := jwxtest.GenerateEcdsaKey(jwa.P521)
	if !assert.NoError(t, err, `jwxtest.GenerateEcdsaKey should succeed`) {
		return
	}

	tok := jwt.New()
	_, err = jwt.Sign(tok, jwt.WithKey(jwa.SignatureAlgorithm("BOGUS"), priv))
	if !assert.Error(t, err) {
		return
	}

	if !assert.Contains(t, err.Error(), `unsupported signature algorithm "BOGUS"`) {
		return
	}

	_, err = jwt.Sign(tok, jwt.WithKey(jwa.ES256, nil))
	if !assert.Error(t, err) {
		return
	}

	if !assert.Contains(t, err.Error(), "missing private key") {
		return
	}
}

func TestSignJWK(t *testing.T) {
	t.Parallel()
	priv, err := jwxtest.GenerateRsaKey()
	assert.Nil(t, err)

	key, err := jwk.FromRaw(priv)
	assert.Nil(t, err)

	key.Set(jwk.KeyIDKey, "test")
	key.Set(jwk.AlgorithmKey, jwa.RS256)

	tok := jwt.New()
	signed, err := jwt.Sign(tok, jwt.WithKey(key.Algorithm(), key))
	assert.Nil(t, err)

	header, err := jws.ParseString(string(signed))
	assert.Nil(t, err)

	signatures := header.LookupSignature("test")
	assert.Len(t, signatures, 1)
}

func getJWTHeaders(jwt []byte) (jws.Headers, error) {
	msg, err := jws.Parse(jwt)
	if err != nil {
		return nil, err
	}
	return msg.Signatures()[0].ProtectedHeaders(), nil
}

func TestSignTyp(t *testing.T) {
	t.Parallel()
	key, err := jwxtest.GenerateRsaKey()
	if !assert.NoError(t, err) {
		return
	}

	t.Run(`"typ" header parameter should be set to JWT by default`, func(t *testing.T) {
		t.Parallel()
		t1 := jwt.New()
		signed, err := jwt.Sign(t1, jwt.WithKey(jwa.RS256, key))
		if !assert.NoError(t, err) {
			return
		}
		got, err := getJWTHeaders(signed)
		if !assert.NoError(t, err) {
			return
		}
		if !assert.Equal(t, `JWT`, got.Type(), `"typ" header parameter should be set to JWT`) {
			return
		}
	})

	t.Run(`"typ" header parameter should be customizable by WithHeaders`, func(t *testing.T) {
		t.Parallel()
		t1 := jwt.New()
		hdrs := jws.NewHeaders()
		hdrs.Set(`typ`, `custom-typ`)
		signed, err := jwt.Sign(t1, jwt.WithKey(jwa.RS256, key, jws.WithProtectedHeaders(hdrs)))
		if !assert.NoError(t, err) {
			return
		}
		got, err := getJWTHeaders(signed)
		if !assert.NoError(t, err) {
			return
		}
		if !assert.Equal(t, `custom-typ`, got.Type(), `"typ" header parameter should be set to the custom value`) {
			return
		}
	})
}

func TestReadFile(t *testing.T) {
	t.Parallel()

	f, err := os.CreateTemp(t.TempDir(), "test-read-file-*.jwt")
	if !assert.NoError(t, err, `os.CreateTemp should succeed`) {
		return
	}
	defer f.Close()

	token := jwt.New()
	token.Set(jwt.IssuerKey, `lestrrat`)
	if !assert.NoError(t, json.NewEncoder(f).Encode(token), `json.NewEncoder.Encode should succeed`) {
		return
	}

	if _, err := jwt.ReadFile(f.Name(), jwt.WithVerify(false), jwt.WithValidate(true), jwt.WithIssuer("lestrrat")); !assert.NoError(t, err, `jwt.ReadFile should succeed`) {
		return
	}
	if _, err := jwt.ReadFile(f.Name(), jwt.WithVerify(false), jwt.WithValidate(true), jwt.WithIssuer("lestrrrrrat")); !assert.Error(t, err, `jwt.ReadFile should fail`) {
		return
	}
}

func TestCustomField(t *testing.T) {
	// XXX has global effect!!!
	jwt.RegisterCustomField(`x-birthday`, time.Time{})
	defer jwt.RegisterCustomField(`x-birthday`, nil)

	expected := time.Date(2015, 11, 4, 5, 12, 52, 0, time.UTC)
	bdaybytes, _ := expected.MarshalText() // RFC3339

	var b strings.Builder
	b.WriteString(`{"iss": "github.com/lesstrrat-go/jwx", "x-birthday": "`)
	b.Write(bdaybytes)
	b.WriteString(`"}`)
	src := b.String()

	t.Run("jwt.Parse", func(t *testing.T) {
		token, err := jwt.ParseInsecure([]byte(src))
		if !assert.NoError(t, err, `jwt.Parse should succeed`) {
			t.Logf("%q", src)
			return
		}

		v, ok := token.Get(`x-birthday`)
		if !assert.True(t, ok, `token.Get("x-birthday") should succeed`) {
			return
		}

		if !assert.Equal(t, expected, v, `values should match`) {
			return
		}
	})
	t.Run("json.Unmarshal", func(t *testing.T) {
		token := jwt.New()
		if !assert.NoError(t, json.Unmarshal([]byte(src), token), `json.Unmarshal should succeed`) {
			return
		}

		v, ok := token.Get(`x-birthday`)
		if !assert.True(t, ok, `token.Get("x-birthday") should succeed`) {
			return
		}

		if !assert.Equal(t, expected, v, `values should match`) {
			return
		}
	})
}

func TestParseRequest(t *testing.T) {
	const u = "https://github.com/lestrrat-gow/jwx/jwt"
	const xauth = "X-Authorization"

	privkey, _ := jwxtest.GenerateEcdsaJwk()
	privkey.Set(jwk.AlgorithmKey, jwa.ES256)
	privkey.Set(jwk.KeyIDKey, `my-awesome-key`)
	pubkey, _ := jwk.PublicKeyOf(privkey)
	pubkey.Set(jwk.AlgorithmKey, jwa.ES256)

	tok := jwt.New()
	tok.Set(jwt.IssuerKey, u)
	tok.Set(jwt.IssuedAtKey, time.Now().Round(0))

	signed, _ := jwt.Sign(tok, jwt.WithKey(jwa.ES256, privkey))

	testcases := []struct {
		Request func() *http.Request
		Parse   func(*http.Request) (jwt.Token, error)
		Name    string
		Error   bool
	}{
		{
			Name: "Token not present (w/ multiple options)",
			Request: func() *http.Request {
				return httptest.NewRequest(http.MethodGet, u, nil)
			},
			Parse: func(req *http.Request) (jwt.Token, error) {
				return jwt.ParseRequest(req,
					jwt.WithHeaderKey("Authorization"),
					jwt.WithHeaderKey(xauth),
					jwt.WithFormKey("access_token"),
					jwt.WithFormKey("token"),
					jwt.WithCookieKey("cookie"),
					jwt.WithKey(jwa.ES256, pubkey))
			},
			Error: true,
		},
		{
			Name: "Token not present (w/o options)",
			Request: func() *http.Request {
				return httptest.NewRequest(http.MethodGet, u, nil)
			},
			Parse: func(req *http.Request) (jwt.Token, error) {
				return jwt.ParseRequest(req, jwt.WithKey(jwa.ES256, pubkey))
			},
			Error: true,
		},
		{
			Name: "Token in Authorization header (w/o extra options)",
			Request: func() *http.Request {
				req := httptest.NewRequest(http.MethodGet, u, nil)
				req.Header.Add("Authorization", "Bearer "+string(signed))
				return req
			},
			Parse: func(req *http.Request) (jwt.Token, error) {
				return jwt.ParseRequest(req, jwt.WithKey(jwa.ES256, pubkey))
			},
		},
		{
			Name: "Token in Authorization header (w/o extra options, using jwk.Set)",
			Request: func() *http.Request {
				req := httptest.NewRequest(http.MethodGet, u, nil)
				req.Header.Add("Authorization", "Bearer "+string(signed))
				return req
			},
			Parse: func(req *http.Request) (jwt.Token, error) {
				set := jwk.NewSet()
				set.AddKey(pubkey)
				return jwt.ParseRequest(req, jwt.WithKeySet(set))
			},
		},
		{
			Name: "Token in Authorization header but we specified another header key",
			Request: func() *http.Request {
				req := httptest.NewRequest(http.MethodGet, u, nil)
				req.Header.Add("Authorization", "Bearer "+string(signed))
				return req
			},
			Parse: func(req *http.Request) (jwt.Token, error) {
				return jwt.ParseRequest(req, jwt.WithHeaderKey(xauth), jwt.WithKey(jwa.ES256, pubkey))
			},
			Error: true,
		},
		{
			Name: fmt.Sprintf("Token in %s header (w/ option)", xauth),
			Request: func() *http.Request {
				req := httptest.NewRequest(http.MethodGet, u, nil)
				req.Header.Add(xauth, string(signed))
				return req
			},
			Parse: func(req *http.Request) (jwt.Token, error) {
				return jwt.ParseRequest(req, jwt.WithHeaderKey(xauth), jwt.WithKey(jwa.ES256, pubkey))
			},
		},
		{
			Name: fmt.Sprintf("Invalid token in %s header", xauth),
			Request: func() *http.Request {
				req := httptest.NewRequest(http.MethodGet, u, nil)
				req.Header.Add(xauth, string(signed)+"foobarbaz")
				return req
			},
			Parse: func(req *http.Request) (jwt.Token, error) {
				return jwt.ParseRequest(req, jwt.WithHeaderKey(xauth), jwt.WithKey(jwa.ES256, pubkey))
			},
			Error: true,
		},
		{
			Name: "Token in access_token form field (w/ option)",
			Request: func() *http.Request {
				req := httptest.NewRequest(http.MethodPost, u, nil)
				// for whatever reason, I can't populate req.Body and get this to work
				// so populating req.Form directly instead
				req.Form = url.Values{}
				req.Form.Add("access_token", string(signed))
				return req
			},
			Parse: func(req *http.Request) (jwt.Token, error) {
				return jwt.ParseRequest(req, jwt.WithFormKey("access_token"), jwt.WithKey(jwa.ES256, pubkey))
			},
		},
		{
			Name: "Token in cookie (w/ option)",
			Request: func() *http.Request {
				req := httptest.NewRequest(http.MethodGet, u, nil)
				req.AddCookie(&http.Cookie{Name: "cookie", Value: string(signed)})
				return req
			},
			Parse: func(req *http.Request) (jwt.Token, error) {
				return jwt.ParseRequest(req, jwt.WithCookieKey("cookie"), jwt.WithKey(jwa.ES256, pubkey))
			},
		},
		{
			Name: "Invalid token in cookie",
			Request: func() *http.Request {
				req := httptest.NewRequest(http.MethodGet, u, nil)
				req.AddCookie(&http.Cookie{Name: "cookie", Value: string(signed) + "foobarbaz"})
				return req
			},
			Parse: func(req *http.Request) (jwt.Token, error) {
				return jwt.ParseRequest(req, jwt.WithCookieKey("cookie"), jwt.WithKey(jwa.ES256, pubkey))
			},
			Error: true,
		},
		{
			Name: "Token in access_token form field (w/o option)",
			Request: func() *http.Request {
				req := httptest.NewRequest(http.MethodPost, u, nil)
				// for whatever reason, I can't populate req.Body and get this to work
				// so populating req.Form directly instead
				req.Form = url.Values{}
				req.Form.Add("access_token", string(signed))
				return req
			},
			Parse: func(req *http.Request) (jwt.Token, error) {
				return jwt.ParseRequest(req, jwt.WithKey(jwa.ES256, pubkey))
			},
			Error: true,
		},
		{
			Name: "Invalid token in access_token form field",
			Request: func() *http.Request {
				req := httptest.NewRequest(http.MethodPost, u, nil)
				// for whatever reason, I can't populate req.Body and get this to work
				// so populating req.Form directly instead
				req.Form = url.Values{}
				req.Form.Add("access_token", string(signed)+"foobarbarz")
				return req
			},
			Parse: func(req *http.Request) (jwt.Token, error) {
				return jwt.ParseRequest(req, jwt.WithKey(jwa.ES256, pubkey), jwt.WithFormKey("access_token"))
			},
			Error: true,
		},
	}

	for _, tc := range testcases {
		tc := tc
		t.Run(tc.Name, func(t *testing.T) {
			got, err := tc.Parse(tc.Request())
			if tc.Error {
				t.Logf("%s", err)
				assert.Error(t, err, `tc.Parse should fail`)
				return
			}

			if !assert.NoError(t, err, `tc.Parse should succeed`) {
				return
			}

			if !assert.True(t, jwt.Equal(tok, got), `tokens should match`) {
				{
					buf, _ := json.MarshalIndent(tok, "", "  ")
					t.Logf("expected: %s", buf)
				}
				{
					buf, _ := json.MarshalIndent(got, "", "  ")
					t.Logf("got: %s", buf)
				}
				return
			}
		})
	}

	// One extra test. Make sure we can extract the cookie object that we used
	// when parsing from cookies
	t.Run("jwt.WithCookie", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, u, nil)
		req.AddCookie(&http.Cookie{Name: "cookie", Value: string(signed)})
		var dst *http.Cookie
		_, err := jwt.ParseRequest(req, jwt.WithCookieKey("cookie"), jwt.WithCookie(&dst), jwt.WithKey(jwa.ES256, pubkey))
		require.NoError(t, err, `jwt.ParseRequest should succeed`)
		require.NotNil(t, dst, `cookie should be extracted`)
	})
}

func TestGHIssue368(t *testing.T) {
	// DO NOT RUN THIS IN PARALLEL
	t.Run("Per-object control of flatten audience", func(t *testing.T) {
		for _, globalFlatten := range []bool{true, false} {
			globalFlatten := globalFlatten
			for _, perObjectFlatten := range []bool{true, false} {
				perObjectFlatten := perObjectFlatten
				// per-object settings always wins
				t.Run(fmt.Sprintf("Global=%t, Per-Object=%t", globalFlatten, perObjectFlatten), func(t *testing.T) {
					defer jwt.Settings(jwt.WithFlattenAudience(false))
					jwt.Settings(jwt.WithFlattenAudience(globalFlatten))

					tok, _ := jwt.NewBuilder().
						Audience([]string{"hello"}).
						Build()

					if perObjectFlatten {
						tok.Options().Enable(jwt.FlattenAudience)
					} else {
						tok.Options().Disable(jwt.FlattenAudience)
					}
					buf, err := json.MarshalIndent(tok, "", "  ")
					if !assert.NoError(t, err, `json.MarshalIndent should succeed`) {
						return
					}

					var expected string
					if perObjectFlatten {
						expected = `{
  "aud": "hello"
}`
					} else {
						expected = `{
  "aud": [
    "hello"
  ]
}`
					}

					if !assert.Equal(t, expected, string(buf), `output should match`) {
						return
					}
				})
			}
		}
	})

	for _, flatten := range []bool{true, false} {
		flatten := flatten
		t.Run(fmt.Sprintf("Test serialization (WithFlattenAudience(%t))", flatten), func(t *testing.T) {
			jwt.Settings(jwt.WithFlattenAudience(flatten))

			t.Run("Single Key", func(t *testing.T) {
				tok := jwt.New()
				_ = tok.Set(jwt.AudienceKey, "hello")

				buf, err := json.MarshalIndent(tok, "", "  ")
				if !assert.NoError(t, err, `json.MarshalIndent should succeed`) {
					return
				}

				var expected string
				if flatten {
					expected = `{
  "aud": "hello"
}`
				} else {
					expected = `{
  "aud": [
    "hello"
  ]
}`
				}

				if !assert.Equal(t, expected, string(buf), `output should match`) {
					return
				}
			})
			t.Run("Multiple Keys", func(t *testing.T) {
				tok, err := jwt.NewBuilder().
					Audience([]string{"hello", "world"}).
					Build()
				if !assert.NoError(t, err, `jwt.Builder should succeed`) {
					return
				}

				buf, err := json.MarshalIndent(tok, "", "  ")
				if !assert.NoError(t, err, `json.MarshalIndent should succeed`) {
					return
				}

				const expected = `{
  "aud": [
    "hello",
    "world"
  ]
}`

				if !assert.Equal(t, expected, string(buf), `output should match`) {
					return
				}
			})
		})
	}
}

func TestGH375(t *testing.T) {
	key, err := jwxtest.GenerateRsaJwk()
	if !assert.NoError(t, err, `jwxtest.GenerateRsaJwk should succeed`) {
		return
	}
	key.Set(jwk.KeyIDKey, `test`)

	token, err := jwt.NewBuilder().
		Issuer(`foobar`).
		Build()
	if !assert.NoError(t, err, `jwt.Builder should succeed`) {
		return
	}

	signAlg := jwa.RS512
	signed, err := jwt.Sign(token, jwt.WithKey(signAlg, key))
	if !assert.NoError(t, err, `jwt.Sign should succeed`) {
		return
	}

	verifyKey, err := jwk.PublicKeyOf(key)
	if !assert.NoError(t, err, `jwk.PublicKeyOf should succeed`) {
		return
	}

	verifyKey.Set(jwk.KeyIDKey, `test`)
	verifyKey.Set(jwk.AlgorithmKey, jwa.RS256) // != jwa.RS512

	ks := jwk.NewSet()
	ks.AddKey(verifyKey)

	_, err = jwt.Parse(signed, jwt.WithKeySet(ks))
	if !assert.Error(t, err, `jwt.Parse should fail`) {
		return
	}
}

type Claim struct {
	Foo string
	Bar int64
}

func TestJWTParseWithTypedClaim(t *testing.T) {
	testcases := []struct {
		Name        string
		Options     []jwt.ParseOption
		PostProcess func(*testing.T, interface{}) (*Claim, error)
	}{
		{
			Name:    "Basic",
			Options: []jwt.ParseOption{jwt.WithTypedClaim("typed-claim", Claim{})},
			PostProcess: func(t *testing.T, claim interface{}) (*Claim, error) {
				t.Helper()
				v, ok := claim.(Claim)
				if !ok {
					return nil, fmt.Errorf(`claim value should be of type "Claim", but got %T`, claim)
				}
				return &v, nil
			},
		},
		{
			Name:    "json.RawMessage",
			Options: []jwt.ParseOption{jwt.WithTypedClaim("typed-claim", json.RawMessage{})},
			PostProcess: func(t *testing.T, claim interface{}) (*Claim, error) {
				t.Helper()
				v, ok := claim.(json.RawMessage)
				if !ok {
					return nil, fmt.Errorf(`claim value should be of type "json.RawMessage", but got %T`, claim)
				}

				var c Claim
				if err := json.Unmarshal(v, &c); err != nil {
					return nil, fmt.Errorf(`json.Unmarshal failed: %w`, err)
				}

				return &c, nil
			},
		},
	}

	expected := &Claim{Foo: "Foo", Bar: 0xdeadbeef}
	key, err := jwxtest.GenerateRsaKey()
	if !assert.NoError(t, err, `jwxtest.GenerateRsaKey should succeed`) {
		return
	}

	var signed []byte
	{
		token := jwt.New()
		if !assert.NoError(t, token.Set("typed-claim", expected), `expected.Set should succeed`) {
			return
		}
		v, err := jwt.Sign(token, jwt.WithKey(jwa.RS256, key))
		if !assert.NoError(t, err, `jwt.Sign should succeed`) {
			return
		}
		signed = v
	}

	for _, tc := range testcases {
		tc := tc
		t.Run(tc.Name, func(t *testing.T) {
			options := append(tc.Options, jwt.WithVerify(false))
			got, err := jwt.Parse(signed, options...)
			if !assert.NoError(t, err, `jwt.Parse should succeed`) {
				return
			}

			v, ok := got.Get("typed-claim")
			if !assert.True(t, ok, `got.Get() should succeed`) {
				return
			}
			claim, err := tc.PostProcess(t, v)
			if !assert.NoError(t, err, `tc.PostProcess should succeed`) {
				return
			}

			if !assert.Equal(t, claim, expected, `claim should match expected value`) {
				return
			}
		})
	}
}

func TestGH393(t *testing.T) {
	t.Run("Non-existent required claims", func(t *testing.T) {
		tok := jwt.New()
		if !assert.Error(t, jwt.Validate(tok, jwt.WithRequiredClaim(jwt.IssuedAtKey)), `jwt.Validate should fail`) {
			return
		}
	})
	t.Run("exp - iat < WithMaxDelta(10 secs)", func(t *testing.T) {
		now := time.Now()
		tok, err := jwt.NewBuilder().
			IssuedAt(now).
			Expiration(now.Add(5 * time.Second)).
			Build()
		if !assert.NoError(t, err, `jwt.Builder should succeed`) {
			return
		}

		if !assert.Error(t, jwt.Validate(tok, jwt.WithMaxDelta(2*time.Second, jwt.ExpirationKey, jwt.IssuedAtKey)), `jwt.Validate should fail`) {
			return
		}

		if !assert.NoError(t, jwt.Validate(tok, jwt.WithMaxDelta(10*time.Second, jwt.ExpirationKey, jwt.IssuedAtKey)), `jwt.Validate should succeed`) {
			return
		}
	})
	t.Run("iat - exp (5 secs) < WithMinDelta(10 secs)", func(t *testing.T) {
		now := time.Now()
		tok, err := jwt.NewBuilder().
			IssuedAt(now).
			Expiration(now.Add(5 * time.Second)).
			Build()
		if !assert.NoError(t, err, `jwt.Builder should succeed`) {
			return
		}

		if !assert.Error(t, jwt.Validate(tok, jwt.WithMinDelta(10*time.Second, jwt.ExpirationKey, jwt.IssuedAtKey)), `jwt.Validate should fail`) {
			return
		}
	})
	t.Run("iat - exp (5 secs) > WithMinDelta(10 secs)", func(t *testing.T) {
		now := time.Now()
		tok, err := jwt.NewBuilder().
			IssuedAt(now).
			Expiration(now.Add(5 * time.Second)).
			Build()
		if !assert.NoError(t, err, `jwt.Builder should succeed`) {
			return
		}

		if !assert.NoError(t, jwt.Validate(tok, jwt.WithMinDelta(10*time.Second, jwt.ExpirationKey, jwt.IssuedAtKey), jwt.WithAcceptableSkew(5*time.Second)), `jwt.Validate should succeed`) {
			return
		}
	})
	t.Run("now - iat < WithMaxDelta(10 secs)", func(t *testing.T) {
		now := time.Now()
		tok, err := jwt.NewBuilder().
			IssuedAt(now).
			Build()
		if !assert.NoError(t, err, `jwt.Builder should succeed`) {
			return
		}

		if !assert.NoError(t, jwt.Validate(tok, jwt.WithMaxDelta(10*time.Second, "", jwt.IssuedAtKey), jwt.WithClock(jwt.ClockFunc(func() time.Time { return now.Add(5 * time.Second) }))), `jwt.Validate should succeed`) {
			return
		}
	})
	t.Run("invalid claim name (c1)", func(t *testing.T) {
		now := time.Now()
		tok, err := jwt.NewBuilder().
			Claim("foo", now).
			Expiration(now.Add(5 * time.Second)).
			Build()
		if !assert.NoError(t, err, `jwt.Builder should succeed`) {
			return
		}

		if !assert.Error(t, jwt.Validate(tok, jwt.WithMinDelta(10*time.Second, jwt.ExpirationKey, "foo"), jwt.WithAcceptableSkew(5*time.Second)), `jwt.Validate should fail`) {
			return
		}
	})
	t.Run("invalid claim name (c2)", func(t *testing.T) {
		now := time.Now()
		tok, err := jwt.NewBuilder().
			Claim("foo", now.Add(5*time.Second)).
			IssuedAt(now).
			Build()
		if !assert.NoError(t, err, `jwt.Builder should succeed`) {
			return
		}

		if !assert.Error(t, jwt.Validate(tok, jwt.WithMinDelta(10*time.Second, "foo", jwt.IssuedAtKey), jwt.WithAcceptableSkew(5*time.Second)), `jwt.Validate should fail`) {
			return
		}
	})

	// Following tests deviate a little from the original issue, but
	// since they were added for the same issue, we just bundle the
	// tests together
	t.Run(`WithRequiredClaim fails for non-existent claim`, func(t *testing.T) {
		tok := jwt.New()
		if !assert.Error(t, jwt.Validate(tok, jwt.WithRequiredClaim("foo")), `jwt.Validate should fail`) {
			return
		}
	})
	t.Run(`WithRequiredClaim succeeds for existing claim`, func(t *testing.T) {
		tok, err := jwt.NewBuilder().
			Claim(`foo`, 1).
			Build()
		if !assert.NoError(t, err, `jwt.Builder should succeed`) {
			return
		}
		if !assert.NoError(t, jwt.Validate(tok, jwt.WithRequiredClaim("foo")), `jwt.Validate should fail`) {
			return
		}
	})
}

func TestGH430(t *testing.T) {
	t1 := jwt.New()
	err := t1.Set("payload", map[string]interface{}{
		"name": "someone",
	})
	if !assert.NoError(t, err, `t1.Set should succeed`) {
		return
	}

	key := []byte("secret")
	signed, err := jwt.Sign(t1, jwt.WithKey(jwa.HS256, key))
	if !assert.NoError(t, err, `jwt.Sign should succeed`) {
		return
	}

	if _, err = jwt.Parse(signed, jwt.WithKey(jwa.HS256, key)); !assert.NoError(t, err, `jwt.Parse should succeed`) {
		return
	}
}

func TestGH706(t *testing.T) {
	err := jwt.Validate(jwt.New(), jwt.WithRequiredClaim("foo"))
	if !assert.True(t, jwt.IsValidationError(err), `error should be a validation error`) {
		return
	}

	if !assert.ErrorIs(t, err, jwt.ErrRequiredClaim(), `jwt.Validate should fail`) {
		return
	}
}

func TestBenHigginsByPassRegression(t *testing.T) {
	key, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		panic(err)
	}
	// Test if an access token JSON payload parses when provided directly
	//
	// The JSON below is slightly modified example payload from:
	// https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-access-token.html

	// Case 1: add "aud", and adjust exp to be valid
	// Case 2: do not add "aud", adjust exp

	exp := strconv.Itoa(int(time.Now().Unix()) + 1000)
	const tmpl = `{%s
    "sub": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "device_key": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "cognito:groups": ["admin"],
    "token_use": "access",
    "scope": "aws.cognito.signin.user.admin",
    "auth_time": 1562190524,
    "iss": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_example",
    "exp": %s,
    "iat": 1562190524,
    "origin_jti": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "jti": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "client_id": "57cbishk4j24pabc1234567890",
    "username": "janedoe@example.com"
  }`

	testcases := [][]byte{
		[]byte(fmt.Sprintf(tmpl, `"aud": ["test"],`, exp)),
		[]byte(fmt.Sprintf(tmpl, ``, exp)),
	}

	for _, tc := range testcases {
		for _, pedantic := range []bool{true, false} {
			_, err = jwt.Parse(
				tc,
				jwt.WithValidate(true),
				jwt.WithPedantic(pedantic),
				jwt.WithKey(jwa.RS256, &key.PublicKey),
			)
			t.Logf("%s", err)
			if !assert.Error(t, err, `jwt.Parse should fail`) {
				return
			}
		}
	}
}

func TestVerifyAuto(t *testing.T) {
	key, err := jwxtest.GenerateRsaJwk()
	if !assert.NoError(t, err, `jwxtest.GenerateRsaJwk should succeed`) {
		return
	}

	key.Set(jwk.KeyIDKey, `my-awesome-key`)

	pubkey, err := jwk.PublicKeyOf(key)
	if !assert.NoError(t, err, `jwk.PublicKeyOf should succeed`) {
		return
	}
	set := jwk.NewSet()
	set.AddKey(pubkey)
	backoffCount := 0
	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Query().Get(`type`) {
		case "backoff":
			backoffCount++
			if backoffCount == 1 {
				w.WriteHeader(http.StatusInternalServerError)
				return
			}
		}
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(set)
	}))
	defer srv.Close()

	tok, err := jwt.NewBuilder().
		Claim(jwt.IssuerKey, `https://github.com/lestrrat-go/jwx/v2`).
		Claim(jwt.SubjectKey, `jku-test`).
		Build()

	if !assert.NoError(t, err, `jwt.NewBuilder.Build() should succeed`) {
		return
	}

	hdrs := jws.NewHeaders()
	hdrs.Set(jws.JWKSetURLKey, srv.URL)

	signed, err := jwt.Sign(tok, jwt.WithKey(jwa.RS256, key, jws.WithProtectedHeaders(hdrs)))
	if !assert.NoError(t, err, `jwt.Sign() should succeed`) {
		return
	}

	wl := jwk.NewMapWhitelist().
		Add(srv.URL)

	parsed, err := jwt.Parse(signed, jwt.WithVerifyAuto(nil, jwk.WithFetchWhitelist(wl), jwk.WithHTTPClient(srv.Client())))
	if !assert.NoError(t, err, `jwt.Parse should succeed`) {
		return
	}

	if !assert.True(t, jwt.Equal(tok, parsed), `tokens should be equal`) {
		return
	}

	_, err = jwt.Parse(signed, jwt.WithVerifyAuto(nil))
	if !assert.Error(t, err, `jwt.Parse should fail`) {
		return
	}
	wl = jwk.NewMapWhitelist().
		Add(`https://github.com/lestrrat-go/jwx/v2`)
	_, err = jwt.Parse(signed, jwt.WithVerifyAuto(nil, jwk.WithFetchWhitelist(wl)))
	if !assert.Error(t, err, `jwt.Parse should fail`) {
		return
	}

	// now with Cache
	c := jwk.NewCache(context.TODO())
	parsed, err = jwt.Parse(signed,
		jwt.WithVerifyAuto(
			jwk.FetchFunc(func(ctx context.Context, u string, options ...jwk.FetchOption) (jwk.Set, error) {
				var registeropts []jwk.RegisterOption
				// jwk.FetchOption is also an CacheOption, but the container
				// doesn't match the signature... so... we need to convert them...
				for _, option := range options {
					registeropts = append(registeropts, option)
				}
				c.Register(u, registeropts...)
				return c.Get(ctx, u)
			}),
			jwk.WithHTTPClient(srv.Client()),
			jwk.WithFetchWhitelist(jwk.InsecureWhitelist{}),
		),
	)
	if !assert.NoError(t, err, `jwt.Parse should succeed`) {
		return
	}

	if !assert.True(t, jwt.Equal(tok, parsed), `tokens should be equal`) {
		return
	}
}

func TestSerializer(t *testing.T) {
	t.Run(`Invalid sign suboption`, func(t *testing.T) {
		_, err := jwt.NewSerializer().
			Sign(jwt.WithKey(jwa.HS256, []byte("abracadabra"), jwe.WithCompress(jwa.Deflate))).
			Serialize(jwt.New())
		if !assert.Error(t, err, `Serialize() should fail`) {
			return
		}
	})
	t.Run(`Invalid SignatureAglrotihm`, func(t *testing.T) {
		_, err := jwt.NewSerializer().
			Encrypt(jwt.WithKey(jwa.A256KW, []byte("abracadabra"))).
			Serialize(jwt.New())
		if !assert.Error(t, err, `Serialize() should succeedl`) {
			return
		}
	})
	t.Run(`Invalid encrypt suboption`, func(t *testing.T) {
		_, err := jwt.NewSerializer().
			Encrypt(jwt.WithKey(jwa.A256KW, []byte("abracadabra"), jws.WithPretty(true))).
			Serialize(jwt.New())
		if !assert.Error(t, err, `Serialize() should fail`) {
			return
		}
	})
	t.Run(`Invalid KeyEncryptionAglrotihm`, func(t *testing.T) {
		_, err := jwt.NewSerializer().
			Encrypt(jwt.WithKey(jwa.HS256, []byte("abracadabra"))).
			Serialize(jwt.New())
		if !assert.Error(t, err, `Serialize() should succeedl`) {
			return
		}
	})
}

func TestFractional(t *testing.T) {
	t.Run("FormatPrecision", func(t *testing.T) {
		var nd types.NumericDate
		jwt.Settings(jwt.WithNumericDateParsePrecision(int(types.MaxPrecision)))
		s := fmt.Sprintf("%d.100000001", aLongLongTimeAgo)
		_ = nd.Accept(s)
		jwt.Settings(jwt.WithNumericDateParsePrecision(0))
		testcases := []struct {
			Input     types.NumericDate
			Expected  string
			Precision int
		}{
			{
				Input:    nd,
				Expected: fmt.Sprintf(`%d`, aLongLongTimeAgo),
			},
			{
				Input:    types.NumericDate{Time: time.Unix(0, 1).UTC()},
				Expected: "0",
			},
			{
				Input:     types.NumericDate{Time: time.Unix(0, 1).UTC()},
				Precision: 9,
				Expected:  "0.000000001",
			},
			{
				Input:     types.NumericDate{Time: time.Unix(0, 100000000).UTC()},
				Precision: 9,
				Expected:  "0.100000000",
			},
		}

		for i := 1; i <= int(types.MaxPrecision); i++ {
			fractional := (fmt.Sprintf(`%d`, 100000001))[:i]
			testcases = append(testcases, struct {
				Input     types.NumericDate
				Expected  string
				Precision int
			}{
				Input:     nd,
				Precision: i,
				Expected:  fmt.Sprintf(`%d.%s`, aLongLongTimeAgo, fractional),
			})
		}

		for _, tc := range testcases {
			tc := tc
			t.Run(fmt.Sprintf("%s (precision=%d)", tc.Input, tc.Precision), func(t *testing.T) {
				jwt.Settings(jwt.WithNumericDateFormatPrecision(tc.Precision))
				require.Equal(t, tc.Expected, tc.Input.String())
			})
		}
		jwt.Settings(jwt.WithNumericDateFormatPrecision(0))
	})
	t.Run("ParsePrecision", func(t *testing.T) {
		const template = `{"iat":"%s"}`

		testcases := []struct {
			Input     string
			Expected  time.Time
			Precision int
		}{
			{
				Input:    "0",
				Expected: time.Unix(0, 0).UTC(),
			},
			{
				Input:    "0.000000001",
				Expected: time.Unix(0, 0).UTC(),
			},
			{
				Input:    fmt.Sprintf("%d.111111111", aLongLongTimeAgo),
				Expected: time.Unix(aLongLongTimeAgo, 0).UTC(),
			},
			{
				// Max precision
				Input:     fmt.Sprintf("%d.100000001", aLongLongTimeAgo),
				Precision: int(types.MaxPrecision),
				Expected:  time.Unix(aLongLongTimeAgo, 100000001).UTC(),
			},
		}

		for i := 1; i < int(types.MaxPrecision); i++ {
			testcases = append(testcases, struct {
				Input     string
				Expected  time.Time
				Precision int
			}{
				Input:     fmt.Sprintf("%d.100000001", aLongLongTimeAgo),
				Precision: i,
				Expected:  time.Unix(aLongLongTimeAgo, 100000000).UTC(),
			})
		}

		for _, tc := range testcases {
			tc := tc
			t.Run(fmt.Sprintf("%s (precision=%d)", tc.Input, tc.Precision), func(t *testing.T) {
				jwt.Settings(jwt.WithNumericDateParsePrecision(tc.Precision))
				tok, err := jwt.Parse(
					[]byte(fmt.Sprintf(template, tc.Input)),
					jwt.WithVerify(false),
					jwt.WithValidate(false),
				)
				require.NoError(t, err, `jwt.Parse should succeed`)

				require.Equal(t, tc.Expected, tok.IssuedAt(), `iat should match`)
			})
		}
		jwt.Settings(jwt.WithNumericDateParsePrecision(0))
	})
}

func TestGH836(t *testing.T) {
	// tests on TokenOptionSet are found elsewhere.

	t1 := jwt.New()
	t1.Options().Enable(jwt.FlattenAudience)

	require.True(t, t1.Options().IsEnabled(jwt.FlattenAudience), `flag should be enabled`)

	t2, err := t1.Clone()
	require.NoError(t, err, `t1.Clone should succeed`)

	require.True(t, t2.Options().IsEnabled(jwt.FlattenAudience), `cloned token should have same settings`)

	t2.Options().Disable(jwt.FlattenAudience)
	require.True(t, t1.Options().IsEnabled(jwt.FlattenAudience), `flag should be enabled (t2.Options should have no effect on t1.Options)`)
}

func TestGH850(t *testing.T) {
	var testToken = `eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiJ0ZXN0IiwiaWF0IjoxNjY2MDkxMzczLCJmb28iOiJiYXIifQ.3GWevx1z2_uCBB9Vj-D0rsT_CMsMeP9GP2rEqGDWpesoG8nHEjAXJOEQV1jOVkkCtTnS18JhcQdb7dW4i-zmqg.trailing-rubbish`

	_, err := jwt.Parse([]byte(testToken), jwt.WithVerify(false))
	require.True(t, errors.Is(err, jwt.ErrInvalidJWT()))
}

func TestGH888(t *testing.T) {
	// Use of "none" is insecure, and we just don't allow it by default.
	// In order to allow none, we must tell jwx that we actually want it.
	token, err := jwt.NewBuilder().
		Subject("foo").
		Issuer("bar").
		Build()

	require.NoError(t, err, `jwt.Builder should succeed`)

	// 1) "none" must be triggered by its own option. Can't use jwt.WithKey(jwa.NoSignature, ...)
	t.Run("jwt.Sign(token, jwt.WithKey(jwa.NoSignature)) should fail", func(t *testing.T) {
		_, err := jwt.Sign(token, jwt.WithKey(jwa.NoSignature, nil))
		require.Error(t, err, `jwt.Sign with jwt.WithKey should fail`)
	})
	t.Run("jwt.Sign(token, jwt.WithInsecureNoSignature())", func(t *testing.T) {
		signed, err := jwt.Sign(token, jwt.WithInsecureNoSignature())
		require.NoError(t, err, `jwt.Sign should succeed`)

		require.Equal(t, `eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJpc3MiOiJiYXIiLCJzdWIiOiJmb28ifQ.`, string(signed))

		_, err = jwt.Parse(signed)
		require.Error(t, err, `jwt.Parse with alg=none should fail`)
	})
}

func TestGH951(t *testing.T) {
	signKey, err := jwxtest.GenerateRsaKey()
	require.NoError(t, err, `jwxtest.GenerateRsaKey should succeed`)

	sharedKey := []byte{
		25, 172, 32, 130, 225, 114, 26, 181, 138, 106, 254, 192, 95, 133, 74, 82,
	}

	token, err := jwt.NewBuilder().
		Subject(`test-951`).
		Issuer(`jwt.Test951`).
		Build()
	require.NoError(t, err, `jwt.NewBuilder should succeed`)

	// this whole workflow actually works even if the bug in #951 is present.
	// so we shall compare the results with and without the encryption
	// options to see if there is a difference in the length of the
	// cipher text, which is the second from last component in the message
	serialized, err := jwt.NewSerializer().
		Sign(jwt.WithKey(jwa.RS256, signKey)).
		Encrypt(
			jwt.WithKey(jwa.A128KW, sharedKey),
			jwt.WithEncryptOption(jwe.WithContentEncryption(jwa.A128GCM)),
			jwt.WithEncryptOption(jwe.WithCompress(jwa.Deflate)),
		).
		Serialize(token)
	require.NoError(t, err, `jwt.NewSerializer()....Serizlie() should succeed`)

	serialized2, err := jwt.NewSerializer().
		Sign(jwt.WithKey(jwa.RS256, signKey)).
		Encrypt(
			jwt.WithKey(jwa.A128KW, sharedKey),
		).
		Serialize(token)
	require.NoError(t, err, `jwt.NewSerializer()....Serizlie() should succeed`)

	require.NotEqual(t,
		len(bytes.Split(serialized, []byte{'.'})[3]),
		len(bytes.Split(serialized2, []byte{'.'})[3]),
	)

	decrypted, err := jwe.Decrypt(serialized, jwe.WithKey(jwa.A128KW, sharedKey))
	require.NoError(t, err, `jwe.Decrypt should succeed`)

	verified, err := jwt.Parse(decrypted, jwt.WithKey(jwa.RS256, signKey.PublicKey))
	require.NoError(t, err, `jwt.Parse should succeed`)

	require.True(t, jwt.Equal(verified, token), `tokens should be equal`)
}

func TestGH1007(t *testing.T) {
	key, err := jwxtest.GenerateRsaJwk()
	require.NoError(t, err, `jwxtest.GenerateRsaJwk should succeed`)

	tok, err := jwt.NewBuilder().
		Claim(`claim1`, `value1`).
		Claim(`claim2`, `value2`).
		Issuer(`github.com/lestrrat-go/jwx`).
		Audience([]string{`users`}).
		Build()
	require.NoError(t, err, `jwt.NewBuilder should succeed`)

	signed, err := jwt.Sign(tok, jwt.WithKey(jwa.RS256, key))
	require.NoError(t, err, `jwt.Sign should succeed`)

	// This was the intended usage (no WithKey). This worked from the beginning
	_, err = jwt.ParseInsecure(signed)
	require.NoError(t, err, `jwt.ParseInsecure should succeed`)

	// This is the problematic behavior reporded in #1007.
	// The fact that we're specifying a wrong key caused Parse() to check for
	// verification and yet fail :/
	wrongPubKey, err := jwxtest.GenerateRsaPublicJwk()
	require.NoError(t, err, `jwxtest.GenerateRsaPublicJwk should succeed`)
	require.NoError(t, err, `jwk.PublicKeyOf should succeed`)

	_, err = jwt.ParseInsecure(signed, jwt.WithKey(jwa.RS256, wrongPubKey))
	require.NoError(t, err, `jwt.ParseInsecure with jwt.WithKey() should succeed`)
}

func TestParseJSON(t *testing.T) {
	// NOTE: jwt.Settings has global effect!
	defer jwt.Settings(jwt.WithCompactOnly(false))
	for _, compactOnly := range []bool{true, false} {
		t.Run("compactOnly="+strconv.FormatBool(compactOnly), func(t *testing.T) {
			jwt.Settings(jwt.WithCompactOnly(compactOnly))

			privKey, err := jwxtest.GenerateRsaJwk()
			require.NoError(t, err, `jwxtest.GenerateRsaJwk should succeed`)

			signedJSON, err := jws.Sign([]byte(`{}`), jws.WithKey(jwa.RS256, privKey), jws.WithValidateKey(true), jws.WithJSON())
			require.NoError(t, err, `jws.Sign should succeed`)

			// jws.Verify should succeed
			_, err = jws.Verify(signedJSON, jws.WithKey(jwa.RS256, privKey))
			require.NoError(t, err, `jws.Parse should succeed`)

			if compactOnly {
				// jwt.Parse should fail
				_, err = jwt.Parse(signedJSON, jwt.WithKey(jwa.RS256, privKey))
				require.Error(t, err, `jws.Parse should fail`)
			} else {
				// for backward compatibility, this should succeed
				_, err = jwt.Parse(signedJSON, jwt.WithKey(jwa.RS256, privKey))
				require.NoError(t, err, `jws.Parse should succeed`)
			}
		})
	}
}

func TestGH1175(t *testing.T) {
	token, err := jwt.NewBuilder().
		Expiration(time.Now().Add(-1 * time.Hour)).
		Build()
	require.NoError(t, err, `jwt.NewBuilder should succeed`)
	secret := []byte("secret")
	signed, err := jwt.Sign(token, jwt.WithKey(jwa.HS256, secret))
	require.NoError(t, err, `jwt.Sign should succeed`)

	req := httptest.NewRequest(http.MethodGet, `http://example.com`, nil)
	req.Header.Set("Authorization", "Bearer "+string(signed))

	_, err = jwt.ParseRequest(req, jwt.WithKey(jwa.HS256, secret))
	require.Error(t, err, `jwt.ParseRequest should fail`)
	require.ErrorIs(t, err, jwt.ErrTokenExpired(), `jwt.ParseRequest should fail with jwt.ErrTokenExpired`)
}