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
1873
1874
1875
// Copyright 2024 New Vector Ltd.
// Copyright 2021-2024 The Matrix.org Foundation C.I.C.
//
// SPDX-License-Identifier: AGPL-3.0-only
// Please see LICENSE in the repository root for full details.

//! Types to interact with the [OpenID Connect] specification.
//!
//! [OpenID Connect]: https://openid.net/connect/

use std::{fmt, ops::Deref};

use language_tags::LanguageTag;
use mas_iana::{
    jose::{JsonWebEncryptionAlg, JsonWebEncryptionEnc, JsonWebSignatureAlg},
    oauth::{OAuthAccessTokenType, OAuthClientAuthenticationMethod, PkceCodeChallengeMethod},
};
use serde::{Deserialize, Serialize};
use serde_with::{
    formats::SpaceSeparator, serde_as, skip_serializing_none, DeserializeFromStr, SerializeDisplay,
    StringWithSeparator,
};
use thiserror::Error;
use url::Url;

use crate::{
    requests::{Display, GrantType, Prompt, ResponseMode},
    response_type::ResponseType,
};

/// An enum for types that accept either an [`OAuthClientAuthenticationMethod`]
/// or an [`OAuthAccessTokenType`].
#[derive(SerializeDisplay, DeserializeFromStr, Clone, PartialEq, Eq, Hash, Debug)]
pub enum AuthenticationMethodOrAccessTokenType {
    /// An authentication method.
    AuthenticationMethod(OAuthClientAuthenticationMethod),

    /// An access token type.
    AccessTokenType(OAuthAccessTokenType),

    /// An unknown value.
    ///
    /// Note that this variant should only be used as the result parsing a
    /// string of unknown type. To build a custom variant, first parse a
    /// string with the wanted type then use `.into()`.
    Unknown(String),
}

impl core::fmt::Display for AuthenticationMethodOrAccessTokenType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::AuthenticationMethod(m) => m.fmt(f),
            Self::AccessTokenType(t) => t.fmt(f),
            Self::Unknown(s) => s.fmt(f),
        }
    }
}

impl core::str::FromStr for AuthenticationMethodOrAccessTokenType {
    type Err = core::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match OAuthClientAuthenticationMethod::from_str(s) {
            Ok(OAuthClientAuthenticationMethod::Unknown(_)) | Err(_) => {}
            Ok(m) => return Ok(m.into()),
        }

        match OAuthAccessTokenType::from_str(s) {
            Ok(OAuthAccessTokenType::Unknown(_)) | Err(_) => {}
            Ok(m) => return Ok(m.into()),
        }

        Ok(Self::Unknown(s.to_owned()))
    }
}

impl AuthenticationMethodOrAccessTokenType {
    /// Get the authentication method of this
    /// `AuthenticationMethodOrAccessTokenType`.
    #[must_use]
    pub fn authentication_method(&self) -> Option<&OAuthClientAuthenticationMethod> {
        match self {
            Self::AuthenticationMethod(m) => Some(m),
            _ => None,
        }
    }

    /// Get the access token type of this
    /// `AuthenticationMethodOrAccessTokenType`.
    #[must_use]
    pub fn access_token_type(&self) -> Option<&OAuthAccessTokenType> {
        match self {
            Self::AccessTokenType(t) => Some(t),
            _ => None,
        }
    }
}

impl From<OAuthClientAuthenticationMethod> for AuthenticationMethodOrAccessTokenType {
    fn from(t: OAuthClientAuthenticationMethod) -> Self {
        Self::AuthenticationMethod(t)
    }
}

impl From<OAuthAccessTokenType> for AuthenticationMethodOrAccessTokenType {
    fn from(t: OAuthAccessTokenType) -> Self {
        Self::AccessTokenType(t)
    }
}

/// The kind of an application.
#[derive(SerializeDisplay, DeserializeFromStr, Clone, PartialEq, Eq, Hash, Debug)]
pub enum ApplicationType {
    /// A web application.
    Web,

    /// A native application.
    Native,

    /// An unknown value.
    Unknown(String),
}

impl core::fmt::Display for ApplicationType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Web => f.write_str("web"),
            Self::Native => f.write_str("native"),
            Self::Unknown(s) => f.write_str(s),
        }
    }
}

impl core::str::FromStr for ApplicationType {
    type Err = core::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "web" => Ok(Self::Web),
            "native" => Ok(Self::Native),
            s => Ok(Self::Unknown(s.to_owned())),
        }
    }
}

/// Subject Identifier types.
///
/// A Subject Identifier is a locally unique and never reassigned identifier
/// within the Issuer for the End-User, which is intended to be consumed by the
/// Client.
#[derive(SerializeDisplay, DeserializeFromStr, Clone, PartialEq, Eq, Hash, Debug)]
pub enum SubjectType {
    /// This provides the same `sub` (subject) value to all Clients.
    Public,

    /// This provides a different `sub` value to each Client, so as not to
    /// enable Clients to correlate the End-User's activities without
    /// permission.
    Pairwise,

    /// An unknown value.
    Unknown(String),
}

impl core::fmt::Display for SubjectType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Public => f.write_str("public"),
            Self::Pairwise => f.write_str("pairwise"),
            Self::Unknown(s) => f.write_str(s),
        }
    }
}

impl core::str::FromStr for SubjectType {
    type Err = core::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "public" => Ok(Self::Public),
            "pairwise" => Ok(Self::Pairwise),
            s => Ok(Self::Unknown(s.to_owned())),
        }
    }
}

/// Claim types.
#[derive(SerializeDisplay, DeserializeFromStr, Clone, PartialEq, Eq, Hash, Debug)]
pub enum ClaimType {
    /// Claims that are directly asserted by the OpenID Provider.
    Normal,

    /// Claims that are asserted by a Claims Provider other than the OpenID
    /// Provider but are returned by OpenID Provider.
    Aggregated,

    /// Claims that are asserted by a Claims Provider other than the OpenID
    /// Provider but are returned as references by the OpenID Provider.
    Distributed,

    /// An unknown value.
    Unknown(String),
}

impl core::fmt::Display for ClaimType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Normal => f.write_str("normal"),
            Self::Aggregated => f.write_str("aggregated"),
            Self::Distributed => f.write_str("distributed"),
            Self::Unknown(s) => f.write_str(s),
        }
    }
}

impl core::str::FromStr for ClaimType {
    type Err = core::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "normal" => Ok(Self::Normal),
            "aggregated" => Ok(Self::Aggregated),
            "distributed" => Ok(Self::Distributed),
            s => Ok(Self::Unknown(s.to_owned())),
        }
    }
}

/// An account management action that a user can take.
///
/// Source: <https://github.com/matrix-org/matrix-spec-proposals/pull/2965>
#[derive(
    SerializeDisplay, DeserializeFromStr, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
#[non_exhaustive]
pub enum AccountManagementAction {
    /// `org.matrix.profile`
    ///
    /// The user wishes to view their profile (name, avatar, contact details).
    Profile,

    /// `org.matrix.sessions_list`
    ///
    /// The user wishes to view a list of their sessions.
    SessionsList,

    /// `org.matrix.session_view`
    ///
    /// The user wishes to view the details of a specific session.
    SessionView,

    /// `org.matrix.session_end`
    ///
    /// The user wishes to end/log out of a specific session.
    SessionEnd,

    /// `org.matrix.account_deactivate`
    ///
    /// The user wishes to deactivate their account.
    AccountDeactivate,

    /// `org.matrix.cross_signing_reset`
    ///
    /// The user wishes to reset their cross-signing keys.
    CrossSigningReset,

    /// An unknown value.
    Unknown(String),
}

impl core::fmt::Display for AccountManagementAction {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Profile => write!(f, "org.matrix.profile"),
            Self::SessionsList => write!(f, "org.matrix.sessions_list"),
            Self::SessionView => write!(f, "org.matrix.session_view"),
            Self::SessionEnd => write!(f, "org.matrix.session_end"),
            Self::AccountDeactivate => write!(f, "org.matrix.account_deactivate"),
            Self::CrossSigningReset => write!(f, "org.matrix.cross_signing_reset"),
            Self::Unknown(value) => write!(f, "{value}"),
        }
    }
}

impl core::str::FromStr for AccountManagementAction {
    type Err = core::convert::Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "org.matrix.profile" => Ok(Self::Profile),
            "org.matrix.sessions_list" => Ok(Self::SessionsList),
            "org.matrix.session_view" => Ok(Self::SessionView),
            "org.matrix.session_end" => Ok(Self::SessionEnd),
            "org.matrix.account_deactivate" => Ok(Self::AccountDeactivate),
            "org.matrix.cross_signing_reset" => Ok(Self::CrossSigningReset),
            value => Ok(Self::Unknown(value.to_owned())),
        }
    }
}

/// The default value of `response_modes_supported` if it is not set.
pub static DEFAULT_RESPONSE_MODES_SUPPORTED: &[ResponseMode] =
    &[ResponseMode::Query, ResponseMode::Fragment];

/// The default value of `grant_types_supported` if it is not set.
pub static DEFAULT_GRANT_TYPES_SUPPORTED: &[GrantType] =
    &[GrantType::AuthorizationCode, GrantType::Implicit];

/// The default value of `token_endpoint_auth_methods_supported` if it is not
/// set.
pub static DEFAULT_AUTH_METHODS_SUPPORTED: &[OAuthClientAuthenticationMethod] =
    &[OAuthClientAuthenticationMethod::ClientSecretBasic];

/// The default value of `claim_types_supported` if it is not set.
pub static DEFAULT_CLAIM_TYPES_SUPPORTED: &[ClaimType] = &[ClaimType::Normal];

/// Authorization server metadata, as described by the [IANA registry].
///
/// All the fields with a default value are accessible via methods.
///
/// [IANA registry]: https://www.iana.org/assignments/oauth-parameters/oauth-parameters.xhtml#authorization-server-metadata
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct ProviderMetadata {
    /// Authorization server's issuer identifier URL.
    ///
    /// This field is required. The URL must use a `https` scheme, and must not
    /// contain a query or fragment. It must match the one used to build the
    /// well-known URI to query this metadata.
    pub issuer: Option<String>,

    /// URL of the authorization server's [authorization endpoint].
    ///
    /// This field is required. The URL must use a `https` scheme, and must not
    /// contain a fragment.
    ///
    /// [authorization endpoint]: https://www.rfc-editor.org/rfc/rfc6749.html#section-3.1
    pub authorization_endpoint: Option<Url>,

    /// URL of the authorization server's [token endpoint].
    ///
    /// This field is required. The URL must use a `https` scheme, and must not
    /// contain a fragment.
    ///
    /// [token endpoint]: https://www.rfc-editor.org/rfc/rfc6749.html#section-3.2
    pub token_endpoint: Option<Url>,

    /// URL of the authorization server's [JWK] Set document.
    ///
    /// This field is required. The URL must use a `https` scheme.
    ///
    /// [JWK]: https://www.rfc-editor.org/rfc/rfc7517.html
    pub jwks_uri: Option<Url>,

    /// URL of the authorization server's [OAuth 2.0 Dynamic Client
    /// Registration] endpoint.
    ///
    /// If this field is present, the URL must use a `https` scheme.
    ///
    /// [OAuth 2.0 Dynamic Client Registration]: https://www.rfc-editor.org/rfc/rfc7591
    pub registration_endpoint: Option<Url>,

    /// JSON array containing a list of the OAuth 2.0 `scope` values that this
    /// authorization server supports.
    ///
    /// If this field is present, it must contain at least the `openid` scope
    /// value.
    pub scopes_supported: Option<Vec<String>>,

    /// JSON array containing a list of the [OAuth 2.0 `response_type` values]
    /// that this authorization server supports.
    ///
    /// This field is required.
    ///
    /// [OAuth 2.0 `response_type` values]: https://www.rfc-editor.org/rfc/rfc7591#page-9
    pub response_types_supported: Option<Vec<ResponseType>>,

    /// JSON array containing a list of the [OAuth 2.0 `response_mode` values]
    /// that this authorization server supports.
    ///
    /// Defaults to [`DEFAULT_RESPONSE_MODES_SUPPORTED`].
    ///
    /// [OAuth 2.0 `response_mode` values]: https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html
    pub response_modes_supported: Option<Vec<ResponseMode>>,

    /// JSON array containing a list of the [OAuth 2.0 `grant_type` values] that
    /// this authorization server supports.
    ///
    /// Defaults to [`DEFAULT_GRANT_TYPES_SUPPORTED`].
    ///
    /// [OAuth 2.0 `grant_type` values]: https://www.rfc-editor.org/rfc/rfc7591#page-9
    pub grant_types_supported: Option<Vec<GrantType>>,

    /// JSON array containing a list of client authentication methods supported
    /// by this token endpoint.
    ///
    /// Defaults to [`DEFAULT_AUTH_METHODS_SUPPORTED`].
    pub token_endpoint_auth_methods_supported: Option<Vec<OAuthClientAuthenticationMethod>>,

    /// JSON array containing a list of the JWS signing algorithms supported
    /// by the token endpoint for the signature on the JWT used to
    /// authenticate the client at the token endpoint.
    ///
    /// If this field is present, it must not contain
    /// [`JsonWebSignatureAlg::None`]. This field is required if
    /// `token_endpoint_auth_methods_supported` contains
    /// [`OAuthClientAuthenticationMethod::PrivateKeyJwt`] or
    /// [`OAuthClientAuthenticationMethod::ClientSecretJwt`].
    pub token_endpoint_auth_signing_alg_values_supported: Option<Vec<JsonWebSignatureAlg>>,

    /// URL of a page containing human-readable information that developers
    /// might want or need to know when using the authorization server.
    pub service_documentation: Option<Url>,

    /// Languages and scripts supported for the user interface, represented as a
    /// JSON array of language tag values from BCP 47.
    ///
    /// If omitted, the set of supported languages and scripts is unspecified.
    pub ui_locales_supported: Option<Vec<LanguageTag>>,

    /// URL that the authorization server provides to the person registering the
    /// client to read about the authorization server's requirements on how the
    /// client can use the data provided by the authorization server.
    pub op_policy_uri: Option<Url>,

    /// URL that the authorization server provides to the person registering the
    /// client to read about the authorization server's terms of service.
    pub op_tos_uri: Option<Url>,

    /// URL of the authorization server's [OAuth 2.0 revocation endpoint].
    ///
    /// If this field is present, the URL must use a `https` scheme, and must
    /// not contain a fragment.
    ///
    /// [OAuth 2.0 revocation endpoint]: https://www.rfc-editor.org/rfc/rfc7009
    pub revocation_endpoint: Option<Url>,

    /// JSON array containing a list of client authentication methods supported
    /// by this revocation endpoint.
    ///
    /// Defaults to [`DEFAULT_AUTH_METHODS_SUPPORTED`].
    pub revocation_endpoint_auth_methods_supported: Option<Vec<OAuthClientAuthenticationMethod>>,

    /// JSON array containing a list of the JWS signing algorithms supported by
    /// the revocation endpoint for the signature on the JWT used to
    /// authenticate the client at the revocation endpoint.
    ///
    /// If this field is present, it must not contain
    /// [`JsonWebSignatureAlg::None`]. This field is required if
    /// `revocation_endpoint_auth_methods_supported` contains
    /// [`OAuthClientAuthenticationMethod::PrivateKeyJwt`] or
    /// [`OAuthClientAuthenticationMethod::ClientSecretJwt`].
    pub revocation_endpoint_auth_signing_alg_values_supported: Option<Vec<JsonWebSignatureAlg>>,

    /// URL of the authorization server's [OAuth 2.0 introspection endpoint].
    ///
    /// If this field is present, the URL must use a `https` scheme.
    ///
    /// [OAuth 2.0 introspection endpoint]: https://www.rfc-editor.org/rfc/rfc7662
    pub introspection_endpoint: Option<Url>,

    /// JSON array containing a list of client authentication methods or token
    /// types supported by this introspection endpoint.
    pub introspection_endpoint_auth_methods_supported:
        Option<Vec<AuthenticationMethodOrAccessTokenType>>,

    /// JSON array containing a list of the JWS signing algorithms supported by
    /// the introspection endpoint for the signature on the JWT used to
    /// authenticate the client at the introspection endpoint.
    ///
    /// If this field is present, it must not contain
    /// [`JsonWebSignatureAlg::None`]. This field is required if
    /// `intospection_endpoint_auth_methods_supported` contains
    /// [`OAuthClientAuthenticationMethod::PrivateKeyJwt`] or
    /// [`OAuthClientAuthenticationMethod::ClientSecretJwt`].
    pub introspection_endpoint_auth_signing_alg_values_supported: Option<Vec<JsonWebSignatureAlg>>,

    /// [PKCE code challenge methods] supported by this authorization server.
    /// If omitted, the authorization server does not support PKCE.
    ///
    /// [PKCE code challenge]: https://www.rfc-editor.org/rfc/rfc7636
    pub code_challenge_methods_supported: Option<Vec<PkceCodeChallengeMethod>>,

    /// URL of the OP's [UserInfo Endpoint].
    ///
    /// [UserInfo Endpoint]: https://openid.net/specs/openid-connect-core-1_0.html#UserInfo
    pub userinfo_endpoint: Option<Url>,

    /// JSON array containing a list of the Authentication Context Class
    /// References that this OP supports.
    pub acr_values_supported: Option<Vec<String>>,

    /// JSON array containing a list of the Subject Identifier types that this
    /// OP supports.
    ///
    /// This field is required.
    pub subject_types_supported: Option<Vec<SubjectType>>,

    /// JSON array containing a list of the JWS signing algorithms (`alg`
    /// values) supported by the OP for the ID Token.
    ///
    /// This field is required.
    pub id_token_signing_alg_values_supported: Option<Vec<JsonWebSignatureAlg>>,

    /// JSON array containing a list of the JWE encryption algorithms (`alg`
    /// values) supported by the OP for the ID Token.
    pub id_token_encryption_alg_values_supported: Option<Vec<JsonWebEncryptionAlg>>,

    /// JSON array containing a list of the JWE encryption algorithms (`enc`
    /// values) supported by the OP for the ID Token.
    pub id_token_encryption_enc_values_supported: Option<Vec<JsonWebEncryptionEnc>>,

    /// JSON array containing a list of the JWS signing algorithms (`alg`
    /// values) supported by the UserInfo Endpoint.
    pub userinfo_signing_alg_values_supported: Option<Vec<JsonWebSignatureAlg>>,

    /// JSON array containing a list of the JWE encryption algorithms (`alg`
    /// values) supported by the UserInfo Endpoint.
    pub userinfo_encryption_alg_values_supported: Option<Vec<JsonWebEncryptionAlg>>,

    /// JSON array containing a list of the JWE encryption algorithms (`enc`
    /// values) supported by the UserInfo Endpoint.
    pub userinfo_encryption_enc_values_supported: Option<Vec<JsonWebEncryptionEnc>>,

    /// JSON array containing a list of the JWS signing algorithms (`alg`
    /// values) supported by the OP for Request Objects.
    pub request_object_signing_alg_values_supported: Option<Vec<JsonWebSignatureAlg>>,

    /// JSON array containing a list of the JWE encryption algorithms (`alg`
    /// values) supported by the OP for Request Objects.
    pub request_object_encryption_alg_values_supported: Option<Vec<JsonWebEncryptionAlg>>,

    /// JSON array containing a list of the JWE encryption algorithms (`enc`
    /// values) supported by the OP for Request Objects.
    pub request_object_encryption_enc_values_supported: Option<Vec<JsonWebEncryptionEnc>>,

    /// JSON array containing a list of the "display" parameter values that the
    /// OpenID Provider supports.
    pub display_values_supported: Option<Vec<Display>>,

    /// JSON array containing a list of the Claim Types that the OpenID Provider
    /// supports.
    ///
    /// Defaults to [`DEFAULT_CLAIM_TYPES_SUPPORTED`].
    pub claim_types_supported: Option<Vec<ClaimType>>,

    /// JSON array containing a list of the Claim Names of the Claims that the
    /// OpenID Provider MAY be able to supply values for.
    pub claims_supported: Option<Vec<String>>,

    /// Languages and scripts supported for values in Claims being returned,
    /// represented as a JSON array of BCP 47 language tag values.
    pub claims_locales_supported: Option<Vec<LanguageTag>>,

    /// Boolean value specifying whether the OP supports use of the `claims`
    /// parameter.
    ///
    /// Defaults to `false`.
    pub claims_parameter_supported: Option<bool>,

    /// Boolean value specifying whether the OP supports use of the `request`
    /// parameter.
    ///
    /// Defaults to `false`.
    pub request_parameter_supported: Option<bool>,

    /// Boolean value specifying whether the OP supports use of the
    /// `request_uri` parameter.
    ///
    /// Defaults to `true`.
    pub request_uri_parameter_supported: Option<bool>,

    /// Boolean value specifying whether the OP requires any `request_uri`
    /// values used to be pre-registered.
    ///
    /// Defaults to `false`.
    pub require_request_uri_registration: Option<bool>,

    /// Indicates where authorization request needs to be protected as [Request
    /// Object] and provided through either request or request_uri parameter.
    ///
    /// Defaults to `false`.
    ///
    /// [Request Object]: https://www.rfc-editor.org/rfc/rfc9101.html
    pub require_signed_request_object: Option<bool>,

    /// URL of the authorization server's [pushed authorization request
    /// endpoint].
    ///
    /// [pushed authorization request endpoint]: https://www.rfc-editor.org/rfc/rfc9126.html
    pub pushed_authorization_request_endpoint: Option<Url>,

    /// Indicates whether the authorization server accepts authorization
    /// requests only via PAR.
    ///
    /// Defaults to `false`.
    pub require_pushed_authorization_requests: Option<bool>,

    /// Array containing the list of prompt values that this OP supports.
    ///
    /// This field can be used to detect if the OP supports the [prompt
    /// `create`] value.
    ///
    /// [prompt `create`]: https://openid.net/specs/openid-connect-prompt-create-1_0.html
    pub prompt_values_supported: Option<Vec<Prompt>>,

    /// URL of the authorization server's [device authorization endpoint].
    ///
    /// [device authorization endpoint]: https://www.rfc-editor.org/rfc/rfc8628
    pub device_authorization_endpoint: Option<Url>,

    /// URL of the authorization server's [RP-Initiated Logout endpoint].
    ///
    /// [RP-Initiated Logout endpoint]: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
    pub end_session_endpoint: Option<Url>,

    /// URL where the user is able to access the account management capabilities
    /// of this OP.
    ///
    /// This is a Matrix extension introduced in [MSC2965](https://github.com/matrix-org/matrix-spec-proposals/pull/2965).
    pub account_management_uri: Option<Url>,

    /// Array of actions that the account management URL supports.
    ///
    /// This is a Matrix extension introduced in [MSC2965](https://github.com/matrix-org/matrix-spec-proposals/pull/2965).
    pub account_management_actions_supported: Option<Vec<AccountManagementAction>>,
}

impl ProviderMetadata {
    /// Validate this `ProviderMetadata` according to the [OpenID Connect
    /// Discovery Spec 1.0].
    ///
    /// # Parameters
    ///
    /// - `issuer`: The issuer that was discovered to get this
    ///   `ProviderMetadata`.
    ///
    /// # Errors
    ///
    /// Will return `Err` if validation fails.
    ///
    /// [OpenID Connect Discovery Spec 1.0]: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
    pub fn validate(
        self,
        issuer: &str,
    ) -> Result<VerifiedProviderMetadata, ProviderMetadataVerificationError> {
        let metadata = self.insecure_verify_metadata()?;

        if metadata.issuer() != issuer {
            return Err(ProviderMetadataVerificationError::IssuerUrlsDontMatch);
        }

        validate_url(
            "issuer",
            &metadata
                .issuer()
                .parse()
                .map_err(|_| ProviderMetadataVerificationError::IssuerNotUrl)?,
            ExtraUrlRestrictions::NoQueryOrFragment,
        )?;

        validate_url(
            "authorization_endpoint",
            metadata.authorization_endpoint(),
            ExtraUrlRestrictions::NoFragment,
        )?;

        validate_url(
            "token_endpoint",
            metadata.token_endpoint(),
            ExtraUrlRestrictions::NoFragment,
        )?;

        validate_url("jwks_uri", metadata.jwks_uri(), ExtraUrlRestrictions::None)?;

        if let Some(url) = &metadata.registration_endpoint {
            validate_url("registration_endpoint", url, ExtraUrlRestrictions::None)?;
        }

        if let Some(scopes) = &metadata.scopes_supported {
            if !scopes.iter().any(|s| s == "openid") {
                return Err(ProviderMetadataVerificationError::ScopesMissingOpenid);
            }
        }

        validate_signing_alg_values_supported(
            "token_endpoint",
            metadata
                .token_endpoint_auth_signing_alg_values_supported
                .iter()
                .flatten(),
            metadata
                .token_endpoint_auth_methods_supported
                .iter()
                .flatten(),
        )?;

        if let Some(url) = &metadata.revocation_endpoint {
            validate_url("revocation_endpoint", url, ExtraUrlRestrictions::NoFragment)?;
        }

        validate_signing_alg_values_supported(
            "revocation_endpoint",
            metadata
                .revocation_endpoint_auth_signing_alg_values_supported
                .iter()
                .flatten(),
            metadata
                .revocation_endpoint_auth_methods_supported
                .iter()
                .flatten(),
        )?;

        if let Some(url) = &metadata.introspection_endpoint {
            validate_url("introspection_endpoint", url, ExtraUrlRestrictions::None)?;
        }

        // The list can also contain token types so remove them as we don't need to
        // check them.
        let introspection_methods = metadata
            .introspection_endpoint_auth_methods_supported
            .as_ref()
            .map(|v| {
                v.iter()
                    .filter_map(AuthenticationMethodOrAccessTokenType::authentication_method)
                    .collect::<Vec<_>>()
            });
        validate_signing_alg_values_supported(
            "introspection_endpoint",
            metadata
                .introspection_endpoint_auth_signing_alg_values_supported
                .iter()
                .flatten(),
            introspection_methods.into_iter().flatten(),
        )?;

        if let Some(url) = &metadata.userinfo_endpoint {
            validate_url("userinfo_endpoint", url, ExtraUrlRestrictions::None)?;
        }

        if let Some(url) = &metadata.pushed_authorization_request_endpoint {
            validate_url(
                "pushed_authorization_request_endpoint",
                url,
                ExtraUrlRestrictions::None,
            )?;
        }

        if let Some(url) = &metadata.end_session_endpoint {
            validate_url("end_session_endpoint", url, ExtraUrlRestrictions::None)?;
        }

        Ok(metadata)
    }

    /// Verify this `ProviderMetadata`.
    ///
    /// Contrary to [`ProviderMetadata::validate()`], it only checks that the
    /// required fields are present.
    ///
    /// This can be used during development to test against a local OpenID
    /// Provider, for example.
    ///
    /// # Parameters
    ///
    /// - `issuer`: The issuer that was discovered to get this
    ///   `ProviderMetadata`.
    ///
    /// # Errors
    ///
    /// Will return `Err` if a required field is missing.
    ///
    /// # Warning
    ///
    /// It is not recommended to use this method in production as it doesn't
    /// ensure that the issuer implements the proper security practices.
    pub fn insecure_verify_metadata(
        self,
    ) -> Result<VerifiedProviderMetadata, ProviderMetadataVerificationError> {
        self.issuer
            .as_ref()
            .ok_or(ProviderMetadataVerificationError::MissingIssuer)?;

        self.authorization_endpoint
            .as_ref()
            .ok_or(ProviderMetadataVerificationError::MissingAuthorizationEndpoint)?;

        self.token_endpoint
            .as_ref()
            .ok_or(ProviderMetadataVerificationError::MissingTokenEndpoint)?;

        self.jwks_uri
            .as_ref()
            .ok_or(ProviderMetadataVerificationError::MissingJwksUri)?;

        self.response_types_supported
            .as_ref()
            .ok_or(ProviderMetadataVerificationError::MissingResponseTypesSupported)?;

        self.subject_types_supported
            .as_ref()
            .ok_or(ProviderMetadataVerificationError::MissingSubjectTypesSupported)?;

        self.id_token_signing_alg_values_supported
            .as_ref()
            .ok_or(ProviderMetadataVerificationError::MissingIdTokenSigningAlgValuesSupported)?;

        Ok(VerifiedProviderMetadata { inner: self })
    }

    /// JSON array containing a list of the OAuth 2.0 `response_mode` values
    /// that this authorization server supports.
    ///
    /// Defaults to [`DEFAULT_RESPONSE_MODES_SUPPORTED`].
    #[must_use]
    pub fn response_modes_supported(&self) -> &[ResponseMode] {
        self.response_modes_supported
            .as_deref()
            .unwrap_or(DEFAULT_RESPONSE_MODES_SUPPORTED)
    }

    /// JSON array containing a list of the OAuth 2.0 grant type values that
    /// this authorization server supports.
    ///
    /// Defaults to [`DEFAULT_GRANT_TYPES_SUPPORTED`].
    #[must_use]
    pub fn grant_types_supported(&self) -> &[GrantType] {
        self.grant_types_supported
            .as_deref()
            .unwrap_or(DEFAULT_GRANT_TYPES_SUPPORTED)
    }

    /// JSON array containing a list of client authentication methods supported
    /// by the token endpoint.
    ///
    /// Defaults to [`DEFAULT_AUTH_METHODS_SUPPORTED`].
    #[must_use]
    pub fn token_endpoint_auth_methods_supported(&self) -> &[OAuthClientAuthenticationMethod] {
        self.token_endpoint_auth_methods_supported
            .as_deref()
            .unwrap_or(DEFAULT_AUTH_METHODS_SUPPORTED)
    }

    /// JSON array containing a list of client authentication methods supported
    /// by the revocation endpoint.
    ///
    /// Defaults to [`DEFAULT_AUTH_METHODS_SUPPORTED`].
    #[must_use]
    pub fn revocation_endpoint_auth_methods_supported(&self) -> &[OAuthClientAuthenticationMethod] {
        self.revocation_endpoint_auth_methods_supported
            .as_deref()
            .unwrap_or(DEFAULT_AUTH_METHODS_SUPPORTED)
    }

    /// JSON array containing a list of the Claim Types that the OpenID Provider
    /// supports.
    ///
    /// Defaults to [`DEFAULT_CLAIM_TYPES_SUPPORTED`].
    #[must_use]
    pub fn claim_types_supported(&self) -> &[ClaimType] {
        self.claim_types_supported
            .as_deref()
            .unwrap_or(DEFAULT_CLAIM_TYPES_SUPPORTED)
    }

    /// Boolean value specifying whether the OP supports use of the `claims`
    /// parameter.
    ///
    /// Defaults to `false`.
    #[must_use]
    pub fn claims_parameter_supported(&self) -> bool {
        self.claims_parameter_supported.unwrap_or(false)
    }

    /// Boolean value specifying whether the OP supports use of the `request`
    /// parameter.
    ///
    /// Defaults to `false`.
    #[must_use]
    pub fn request_parameter_supported(&self) -> bool {
        self.request_parameter_supported.unwrap_or(false)
    }

    /// Boolean value specifying whether the OP supports use of the
    /// `request_uri` parameter.
    ///
    /// Defaults to `true`.
    #[must_use]
    pub fn request_uri_parameter_supported(&self) -> bool {
        self.request_uri_parameter_supported.unwrap_or(true)
    }

    /// Boolean value specifying whether the OP requires any `request_uri`
    /// values used to be pre-registered.
    ///
    /// Defaults to `false`.
    #[must_use]
    pub fn require_request_uri_registration(&self) -> bool {
        self.require_request_uri_registration.unwrap_or(false)
    }

    /// Indicates where authorization request needs to be protected as Request
    /// Object and provided through either `request` or `request_uri` parameter.
    ///
    /// Defaults to `false`.
    #[must_use]
    pub fn require_signed_request_object(&self) -> bool {
        self.require_signed_request_object.unwrap_or(false)
    }

    /// Indicates whether the authorization server accepts authorization
    /// requests only via PAR.
    ///
    /// Defaults to `false`.
    #[must_use]
    pub fn require_pushed_authorization_requests(&self) -> bool {
        self.require_pushed_authorization_requests.unwrap_or(false)
    }
}

/// The verified authorization server metadata.
///
/// All the fields required by the [OpenID Connect Discovery Spec 1.0] or with
/// a default value are accessible via methods.
///
/// To access other fields, use this type's `Deref` implementation.
///
/// # Example
///
/// ```no_run
/// use oauth2_types::{
///     oidc::VerifiedProviderMetadata,
///     requests::GrantType,
/// };
/// use url::Url;
/// # use oauth2_types::oidc::{ProviderMetadata, ProviderMetadataVerificationError};
/// # let metadata = ProviderMetadata::default();
/// # let issuer = "http://localhost/";
/// let verified_metadata = metadata.validate(&issuer)?;
///
/// // The endpoint is required during validation so this is not an `Option`.
/// let _: &Url = verified_metadata.authorization_endpoint();
///
/// // The field has a default value so this is not an `Option`.
/// let _: &[GrantType] = verified_metadata.grant_types_supported();
///
/// // Other fields can be accessed via `Deref`.
/// if let Some(registration_endpoint) = &verified_metadata.registration_endpoint {
///     println!("Registration is supported at {registration_endpoint}");
/// }
/// # Ok::<(), ProviderMetadataVerificationError>(())
/// ```
///
/// [OpenID Connect Discovery Spec 1.0]: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
#[derive(Debug, Clone)]
pub struct VerifiedProviderMetadata {
    inner: ProviderMetadata,
}

impl VerifiedProviderMetadata {
    /// Authorization server's issuer identifier URL.
    #[must_use]
    pub fn issuer(&self) -> &str {
        match &self.issuer {
            Some(u) => u,
            None => unreachable!(),
        }
    }

    /// URL of the authorization server's authorization endpoint.
    #[must_use]
    pub fn authorization_endpoint(&self) -> &Url {
        match &self.authorization_endpoint {
            Some(u) => u,
            None => unreachable!(),
        }
    }

    /// URL of the authorization server's token endpoint.
    #[must_use]
    pub fn token_endpoint(&self) -> &Url {
        match &self.token_endpoint {
            Some(u) => u,
            None => unreachable!(),
        }
    }

    /// URL of the authorization server's JWK Set document.
    #[must_use]
    pub fn jwks_uri(&self) -> &Url {
        match &self.jwks_uri {
            Some(u) => u,
            None => unreachable!(),
        }
    }

    /// JSON array containing a list of the OAuth 2.0 `response_type` values
    /// that this authorization server supports.
    #[must_use]
    pub fn response_types_supported(&self) -> &[ResponseType] {
        match &self.response_types_supported {
            Some(u) => u,
            None => unreachable!(),
        }
    }

    /// JSON array containing a list of the Subject Identifier types that this
    /// OP supports.
    #[must_use]
    pub fn subject_types_supported(&self) -> &[SubjectType] {
        match &self.subject_types_supported {
            Some(u) => u,
            None => unreachable!(),
        }
    }

    /// JSON array containing a list of the JWS `alg` values supported by the OP
    /// for the ID Token.
    #[must_use]
    pub fn id_token_signing_alg_values_supported(&self) -> &[JsonWebSignatureAlg] {
        match &self.id_token_signing_alg_values_supported {
            Some(u) => u,
            None => unreachable!(),
        }
    }
}

impl Deref for VerifiedProviderMetadata {
    type Target = ProviderMetadata;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

/// All errors that can happen when verifying [`ProviderMetadata`]
#[derive(Debug, Error)]
pub enum ProviderMetadataVerificationError {
    /// The issuer is missing.
    #[error("issuer is missing")]
    MissingIssuer,

    /// The issuer is not a valid URL.
    #[error("issuer is not a valid URL")]
    IssuerNotUrl,

    /// The authorization endpoint is missing.
    #[error("authorization endpoint is missing")]
    MissingAuthorizationEndpoint,

    /// The token endpoint is missing.
    #[error("token endpoint is missing")]
    MissingTokenEndpoint,

    /// The JWK Set URI is missing.
    #[error("JWK Set URI is missing")]
    MissingJwksUri,

    /// The supported response types are missing.
    #[error("supported response types are missing")]
    MissingResponseTypesSupported,

    /// The supported subject types are missing.
    #[error("supported subject types are missing")]
    MissingSubjectTypesSupported,

    /// The supported ID token signing algorithm values are missing.
    #[error("supported ID token signing algorithm values are missing")]
    MissingIdTokenSigningAlgValuesSupported,

    /// The URL of the given field doesn't use a `https` scheme.
    #[error("{0}'s URL doesn't use a https scheme: {1}")]
    UrlNonHttpsScheme(&'static str, Url),

    /// The URL of the given field contains a query, but it's not allowed.
    #[error("{0}'s URL contains a query: {1}")]
    UrlWithQuery(&'static str, Url),

    /// The URL of the given field contains a fragment, but it's not allowed.
    #[error("{0}'s URL contains a fragment: {1}")]
    UrlWithFragment(&'static str, Url),

    /// The issuer URL doesn't match the one that was discovered.
    #[error("issuer URLs don't match")]
    IssuerUrlsDontMatch,

    /// `openid` is missing from the supported scopes.
    #[error("missing openid scope")]
    ScopesMissingOpenid,

    /// `code` is missing from the supported response types.
    #[error("missing `code` response type")]
    ResponseTypesMissingCode,

    /// `id_token` is missing from the supported response types.
    #[error("missing `id_token` response type")]
    ResponseTypesMissingIdToken,

    /// `id_token token` is missing from the supported response types.
    #[error("missing `id_token token` response type")]
    ResponseTypesMissingIdTokenToken,

    /// `authorization_code` is missing from the supported grant types.
    #[error("missing `authorization_code` grant type")]
    GrantTypesMissingAuthorizationCode,

    /// `implicit` is missing from the supported grant types.
    #[error("missing `implicit` grant type")]
    GrantTypesMissingImplicit,

    /// The given endpoint is missing auth signing algorithm values, but they
    /// are required because it supports at least one of the `client_secret_jwt`
    /// or `private_key_jwt` authentication methods.
    #[error("{0} missing auth signing algorithm values")]
    MissingAuthSigningAlgValues(&'static str),

    /// `none` is in the given endpoint's signing algorithm values, but is not
    /// allowed.
    #[error("{0} signing algorithm values contain `none`")]
    SigningAlgValuesWithNone(&'static str),
}

/// Possible extra restrictions on a URL.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ExtraUrlRestrictions {
    /// No extra restrictions.
    None,

    /// The URL must not contain a fragment.
    NoFragment,

    /// The URL must not contain a query or a fragment.
    NoQueryOrFragment,
}

impl ExtraUrlRestrictions {
    fn can_have_fragment(self) -> bool {
        self == Self::None
    }

    fn can_have_query(self) -> bool {
        self != Self::NoQueryOrFragment
    }
}

/// Validate the URL of the field with the given extra restrictions.
///
/// The basic restriction is that the URL must use the `https` scheme.
fn validate_url(
    field: &'static str,
    url: &Url,
    restrictions: ExtraUrlRestrictions,
) -> Result<(), ProviderMetadataVerificationError> {
    if url.scheme() != "https" {
        return Err(ProviderMetadataVerificationError::UrlNonHttpsScheme(
            field,
            url.clone(),
        ));
    }

    if !restrictions.can_have_query() && url.query().is_some() {
        return Err(ProviderMetadataVerificationError::UrlWithQuery(
            field,
            url.clone(),
        ));
    }

    if !restrictions.can_have_fragment() && url.fragment().is_some() {
        return Err(ProviderMetadataVerificationError::UrlWithFragment(
            field,
            url.clone(),
        ));
    }

    Ok(())
}

/// Validate the algorithm values of the endpoint according to the
/// authentication methods.
///
/// The restrictions are:
/// - The algorithm values must not contain `none`,
/// - If the `client_secret_jwt` or `private_key_jwt` authentication methods are
///   supported, the values must be present.
fn validate_signing_alg_values_supported<'a>(
    endpoint: &'static str,
    values: impl Iterator<Item = &'a JsonWebSignatureAlg>,
    mut methods: impl Iterator<Item = &'a OAuthClientAuthenticationMethod>,
) -> Result<(), ProviderMetadataVerificationError> {
    let mut no_values = true;

    for value in values {
        if *value == JsonWebSignatureAlg::None {
            return Err(ProviderMetadataVerificationError::SigningAlgValuesWithNone(
                endpoint,
            ));
        }

        no_values = false;
    }

    if no_values
        && methods.any(|method| {
            matches!(
                method,
                OAuthClientAuthenticationMethod::ClientSecretJwt
                    | OAuthClientAuthenticationMethod::PrivateKeyJwt
            )
        })
    {
        return Err(ProviderMetadataVerificationError::MissingAuthSigningAlgValues(endpoint));
    }

    Ok(())
}

/// The body of a request to the [RP-Initiated Logout Endpoint].
///
/// [RP-Initiated Logout Endpoint]: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
#[skip_serializing_none]
#[serde_as]
#[derive(Default, Serialize, Deserialize, Clone)]
pub struct RpInitiatedLogoutRequest {
    /// ID Token previously issued by the OP to the RP.
    ///
    /// Recommended, used as a hint about the End-User's current authenticated
    /// session with the Client.
    pub id_token_hint: Option<String>,

    /// Hint to the Authorization Server about the End-User that is logging out.
    ///
    /// The value and meaning of this parameter is left up to the OP's
    /// discretion. For instance, the value might contain an email address,
    /// phone number, username, or session identifier pertaining to the RP's
    /// session with the OP for the End-User.
    pub logout_hint: Option<String>,

    /// OAuth 2.0 Client Identifier valid at the Authorization Server.
    ///
    /// The most common use case for this parameter is to specify the Client
    /// Identifier when `post_logout_redirect_uri` is used but `id_token_hint`
    /// is not. Another use is for symmetrically encrypted ID Tokens used as
    /// `id_token_hint` values that require the Client Identifier to be
    /// specified by other means, so that the ID Tokens can be decrypted by
    /// the OP.
    pub client_id: Option<String>,

    /// URI to which the RP is requesting that the End-User's User Agent be
    /// redirected after a logout has been performed.
    ///
    /// The value MUST have been previously registered with the OP, using the
    /// `post_logout_redirect_uris` registration parameter.
    pub post_logout_redirect_uri: Option<Url>,

    /// Opaque value used by the RP to maintain state between the logout request
    /// and the callback to the endpoint specified by the
    /// `post_logout_redirect_uri` parameter.
    pub state: Option<String>,

    /// End-User's preferred languages and scripts for the user interface,
    /// ordered by preference.
    #[serde_as(as = "Option<StringWithSeparator::<SpaceSeparator, LanguageTag>>")]
    #[serde(default)]
    pub ui_locales: Option<Vec<LanguageTag>>,
}

impl fmt::Debug for RpInitiatedLogoutRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RpInitiatedLogoutRequest")
            .field("logout_hint", &self.logout_hint)
            .field("post_logout_redirect_uri", &self.post_logout_redirect_uri)
            .field("ui_locales", &self.ui_locales)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use assert_matches::assert_matches;
    use mas_iana::{
        jose::JsonWebSignatureAlg,
        oauth::{OAuthAuthorizationEndpointResponseType, OAuthClientAuthenticationMethod},
    };
    use url::Url;

    use super::*;

    fn valid_provider_metadata() -> (ProviderMetadata, String) {
        let issuer = "https://localhost".to_owned();
        let metadata = ProviderMetadata {
            issuer: Some(issuer.clone()),
            authorization_endpoint: Some(Url::parse("https://localhost/auth").unwrap()),
            token_endpoint: Some(Url::parse("https://localhost/token").unwrap()),
            jwks_uri: Some(Url::parse("https://localhost/jwks").unwrap()),
            response_types_supported: Some(vec![
                OAuthAuthorizationEndpointResponseType::Code.into()
            ]),
            subject_types_supported: Some(vec![SubjectType::Public]),
            id_token_signing_alg_values_supported: Some(vec![JsonWebSignatureAlg::Rs256]),
            ..Default::default()
        };

        (metadata, issuer)
    }

    #[test]
    fn validate_required_metadata() {
        let (metadata, issuer) = valid_provider_metadata();
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_issuer() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Err - Missing
        metadata.issuer = None;
        assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::MissingIssuer)
        );

        // Err - Not an url
        metadata.issuer = Some("not-an-url".to_owned());
        assert_matches!(
            metadata.clone().validate("not-an-url"),
            Err(ProviderMetadataVerificationError::IssuerNotUrl)
        );

        // Err - Wrong issuer
        metadata.issuer = Some("https://example.com/".to_owned());
        assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::IssuerUrlsDontMatch)
        );

        // Err - Not https
        let issuer = "http://localhost/".to_owned();
        metadata.issuer = Some(issuer.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlNonHttpsScheme(field, url)) => (field, url)
        );
        assert_eq!(field, "issuer");
        assert_eq!(url.as_str(), issuer);

        // Err - Query
        let issuer = "https://localhost/?query".to_owned();
        metadata.issuer = Some(issuer.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlWithQuery(field, url)) => (field, url)
        );
        assert_eq!(field, "issuer");
        assert_eq!(url.as_str(), issuer);

        // Err - Fragment
        let issuer = "https://localhost/#fragment".to_owned();
        metadata.issuer = Some(issuer.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlWithFragment(field, url)) => (field, url)
        );
        assert_eq!(field, "issuer");
        assert_eq!(url.as_str(), issuer);

        // Ok - Path
        let issuer = "https://localhost/issuer1".to_owned();
        metadata.issuer = Some(issuer.clone());
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_authorization_endpoint() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Err - Missing
        metadata.authorization_endpoint = None;
        assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::MissingAuthorizationEndpoint)
        );

        // Err - Not https
        let endpoint = Url::parse("http://localhost/auth").unwrap();
        metadata.authorization_endpoint = Some(endpoint.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlNonHttpsScheme(field, url)) => (field, url)
        );
        assert_eq!(field, "authorization_endpoint");
        assert_eq!(url, endpoint);

        // Err - Fragment
        let endpoint = Url::parse("https://localhost/auth#fragment").unwrap();
        metadata.authorization_endpoint = Some(endpoint.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlWithFragment(field, url)) => (field, url)
        );
        assert_eq!(field, "authorization_endpoint");
        assert_eq!(url, endpoint);

        // Ok - Query
        metadata.authorization_endpoint = Some(Url::parse("https://localhost/auth?query").unwrap());
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_token_endpoint() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Err - Missing
        metadata.token_endpoint = None;
        assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::MissingTokenEndpoint)
        );

        // Err - Not https
        let endpoint = Url::parse("http://localhost/token").unwrap();
        metadata.token_endpoint = Some(endpoint.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlNonHttpsScheme(field, url)) => (field, url)
        );
        assert_eq!(field, "token_endpoint");
        assert_eq!(url, endpoint);

        // Err - Fragment
        let endpoint = Url::parse("https://localhost/token#fragment").unwrap();
        metadata.token_endpoint = Some(endpoint.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlWithFragment(field, url)) => (field, url)
        );
        assert_eq!(field, "token_endpoint");
        assert_eq!(url, endpoint);

        // Ok - Query
        metadata.token_endpoint = Some(Url::parse("https://localhost/token?query").unwrap());
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_jwks_uri() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Err - Missing
        metadata.jwks_uri = None;
        assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::MissingJwksUri)
        );

        // Err - Not https
        let endpoint = Url::parse("http://localhost/jwks").unwrap();
        metadata.jwks_uri = Some(endpoint.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlNonHttpsScheme(field, url)) => (field, url)
        );
        assert_eq!(field, "jwks_uri");
        assert_eq!(url, endpoint);

        // Ok - Query & fragment
        metadata.jwks_uri = Some(Url::parse("https://localhost/token?query#fragment").unwrap());
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_registration_endpoint() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Err - Not https
        let endpoint = Url::parse("http://localhost/registration").unwrap();
        metadata.registration_endpoint = Some(endpoint.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlNonHttpsScheme(field, url)) => (field, url)
        );
        assert_eq!(field, "registration_endpoint");
        assert_eq!(url, endpoint);

        // Ok - Missing
        metadata.registration_endpoint = None;
        metadata.clone().validate(&issuer).unwrap();

        // Ok - Query & fragment
        metadata.registration_endpoint =
            Some(Url::parse("https://localhost/registration?query#fragment").unwrap());
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_scopes_supported() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Err - No `openid`
        metadata.scopes_supported = Some(vec!["custom".to_owned()]);
        assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::ScopesMissingOpenid)
        );

        // Ok - Missing
        metadata.scopes_supported = None;
        metadata.clone().validate(&issuer).unwrap();

        // Ok - With `openid`
        metadata.scopes_supported = Some(vec!["openid".to_owned(), "custom".to_owned()]);
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_response_types_supported() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Err - Missing
        metadata.response_types_supported = None;
        assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::MissingResponseTypesSupported)
        );

        // Ok - Present
        metadata.response_types_supported =
            Some(vec![OAuthAuthorizationEndpointResponseType::Code.into()]);
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_token_endpoint_signing_alg_values_supported() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Ok - Missing
        metadata.token_endpoint_auth_signing_alg_values_supported = None;
        metadata.token_endpoint_auth_methods_supported = None;
        metadata.clone().validate(&issuer).unwrap();

        // Err - With `none`
        metadata.token_endpoint_auth_signing_alg_values_supported =
            Some(vec![JsonWebSignatureAlg::None]);
        let endpoint = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::SigningAlgValuesWithNone(endpoint)) => endpoint
        );
        assert_eq!(endpoint, "token_endpoint");

        // Ok - Other signing alg values.
        metadata.token_endpoint_auth_signing_alg_values_supported =
            Some(vec![JsonWebSignatureAlg::Rs256, JsonWebSignatureAlg::EdDsa]);
        metadata.clone().validate(&issuer).unwrap();

        // Err - `client_secret_jwt` without signing alg values.
        metadata.token_endpoint_auth_methods_supported =
            Some(vec![OAuthClientAuthenticationMethod::ClientSecretJwt]);
        metadata.token_endpoint_auth_signing_alg_values_supported = None;
        let endpoint = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::MissingAuthSigningAlgValues(endpoint)) => endpoint
        );
        assert_eq!(endpoint, "token_endpoint");

        // Ok - `client_secret_jwt` with signing alg values.
        metadata.token_endpoint_auth_signing_alg_values_supported =
            Some(vec![JsonWebSignatureAlg::Rs256]);
        metadata.clone().validate(&issuer).unwrap();

        // Err - `private_key_jwt` without signing alg values.
        metadata.token_endpoint_auth_methods_supported =
            Some(vec![OAuthClientAuthenticationMethod::PrivateKeyJwt]);
        metadata.token_endpoint_auth_signing_alg_values_supported = None;
        let endpoint = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::MissingAuthSigningAlgValues(endpoint)) => endpoint
        );
        assert_eq!(endpoint, "token_endpoint");

        // Ok - `private_key_jwt` with signing alg values.
        metadata.token_endpoint_auth_signing_alg_values_supported =
            Some(vec![JsonWebSignatureAlg::Rs256]);
        metadata.clone().validate(&issuer).unwrap();

        // Ok - Other auth methods without signing alg values.
        metadata.token_endpoint_auth_methods_supported = Some(vec![
            OAuthClientAuthenticationMethod::ClientSecretBasic,
            OAuthClientAuthenticationMethod::ClientSecretPost,
        ]);
        metadata.token_endpoint_auth_signing_alg_values_supported = None;
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_revocation_endpoint() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Ok - Missing
        metadata.revocation_endpoint = None;
        metadata.clone().validate(&issuer).unwrap();

        // Err - Not https
        let endpoint = Url::parse("http://localhost/revocation").unwrap();
        metadata.revocation_endpoint = Some(endpoint.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlNonHttpsScheme(field, url)) => (field, url)
        );
        assert_eq!(field, "revocation_endpoint");
        assert_eq!(url, endpoint);

        // Err - Fragment
        let endpoint = Url::parse("https://localhost/revocation#fragment").unwrap();
        metadata.revocation_endpoint = Some(endpoint.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlWithFragment(field, url)) => (field, url)
        );
        assert_eq!(field, "revocation_endpoint");
        assert_eq!(url, endpoint);

        // Ok - Query
        metadata.revocation_endpoint =
            Some(Url::parse("https://localhost/revocation?query").unwrap());
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_revocation_endpoint_signing_alg_values_supported() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Only check that this field is validated, algorithm checks are already
        // tested for the token endpoint.

        // Ok - Missing
        metadata.revocation_endpoint_auth_signing_alg_values_supported = None;
        metadata.revocation_endpoint_auth_methods_supported = None;
        metadata.clone().validate(&issuer).unwrap();

        // Err - With `none`
        metadata.revocation_endpoint_auth_signing_alg_values_supported =
            Some(vec![JsonWebSignatureAlg::None]);
        let endpoint = assert_matches!(
            metadata.validate(&issuer),
            Err(ProviderMetadataVerificationError::SigningAlgValuesWithNone(endpoint)) => endpoint
        );
        assert_eq!(endpoint, "revocation_endpoint");
    }

    #[test]
    fn validate_introspection_endpoint() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Ok - Missing
        metadata.introspection_endpoint = None;
        metadata.clone().validate(&issuer).unwrap();

        // Err - Not https
        let endpoint = Url::parse("http://localhost/introspection").unwrap();
        metadata.introspection_endpoint = Some(endpoint.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlNonHttpsScheme(field, url)) => (field, url)
        );
        assert_eq!(field, "introspection_endpoint");
        assert_eq!(url, endpoint);

        // Ok - Query & Fragment
        metadata.introspection_endpoint =
            Some(Url::parse("https://localhost/introspection?query#fragment").unwrap());
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_introspection_endpoint_signing_alg_values_supported() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Only check that this field is validated, algorithm checks are already
        // tested for the token endpoint.

        // Ok - Missing
        metadata.introspection_endpoint_auth_signing_alg_values_supported = None;
        metadata.introspection_endpoint_auth_methods_supported = None;
        metadata.clone().validate(&issuer).unwrap();

        // Err - With `none`
        metadata.introspection_endpoint_auth_signing_alg_values_supported =
            Some(vec![JsonWebSignatureAlg::None]);
        let endpoint = assert_matches!(
            metadata.validate(&issuer),
            Err(ProviderMetadataVerificationError::SigningAlgValuesWithNone(endpoint)) => endpoint
        );
        assert_eq!(endpoint, "introspection_endpoint");
    }

    #[test]
    fn validate_userinfo_endpoint() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Ok - Missing
        metadata.userinfo_endpoint = None;
        metadata.clone().validate(&issuer).unwrap();

        // Err - Not https
        let endpoint = Url::parse("http://localhost/userinfo").unwrap();
        metadata.userinfo_endpoint = Some(endpoint.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlNonHttpsScheme(field, url)) => (field, url)
        );
        assert_eq!(field, "userinfo_endpoint");
        assert_eq!(url, endpoint);

        // Ok - Query & Fragment
        metadata.userinfo_endpoint =
            Some(Url::parse("https://localhost/userinfo?query#fragment").unwrap());
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_subject_types_supported() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Err - Missing
        metadata.subject_types_supported = None;
        assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::MissingSubjectTypesSupported)
        );

        // Ok - Present
        metadata.subject_types_supported = Some(vec![SubjectType::Public, SubjectType::Pairwise]);
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_id_token_signing_alg_values_supported() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Err - Missing
        metadata.id_token_signing_alg_values_supported = None;
        assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::MissingIdTokenSigningAlgValuesSupported)
        );

        // Ok - Present
        metadata.id_token_signing_alg_values_supported =
            Some(vec![JsonWebSignatureAlg::Rs256, JsonWebSignatureAlg::EdDsa]);
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn validate_pushed_authorization_request_endpoint() {
        let (mut metadata, issuer) = valid_provider_metadata();

        // Ok - Missing
        metadata.pushed_authorization_request_endpoint = None;
        metadata.clone().validate(&issuer).unwrap();

        // Err - Not https
        let endpoint = Url::parse("http://localhost/par").unwrap();
        metadata.pushed_authorization_request_endpoint = Some(endpoint.clone());
        let (field, url) = assert_matches!(
            metadata.clone().validate(&issuer),
            Err(ProviderMetadataVerificationError::UrlNonHttpsScheme(field, url)) => (field, url)
        );
        assert_eq!(field, "pushed_authorization_request_endpoint");
        assert_eq!(url, endpoint);

        // Ok - Query & Fragment
        metadata.pushed_authorization_request_endpoint =
            Some(Url::parse("https://localhost/par?query#fragment").unwrap());
        metadata.validate(&issuer).unwrap();
    }

    #[test]
    fn serialize_application_type() {
        assert_eq!(
            serde_json::to_string(&ApplicationType::Web).unwrap(),
            "\"web\""
        );
        assert_eq!(
            serde_json::to_string(&ApplicationType::Native).unwrap(),
            "\"native\""
        );
    }

    #[test]
    fn deserialize_application_type() {
        assert_eq!(
            serde_json::from_str::<ApplicationType>("\"web\"").unwrap(),
            ApplicationType::Web
        );
        assert_eq!(
            serde_json::from_str::<ApplicationType>("\"native\"").unwrap(),
            ApplicationType::Native
        );
    }

    #[test]
    fn serialize_subject_type() {
        assert_eq!(
            serde_json::to_string(&SubjectType::Public).unwrap(),
            "\"public\""
        );
        assert_eq!(
            serde_json::to_string(&SubjectType::Pairwise).unwrap(),
            "\"pairwise\""
        );
    }

    #[test]
    fn deserialize_subject_type() {
        assert_eq!(
            serde_json::from_str::<SubjectType>("\"public\"").unwrap(),
            SubjectType::Public
        );
        assert_eq!(
            serde_json::from_str::<SubjectType>("\"pairwise\"").unwrap(),
            SubjectType::Pairwise
        );
    }

    #[test]
    fn serialize_claim_type() {
        assert_eq!(
            serde_json::to_string(&ClaimType::Normal).unwrap(),
            "\"normal\""
        );
        assert_eq!(
            serde_json::to_string(&ClaimType::Aggregated).unwrap(),
            "\"aggregated\""
        );
        assert_eq!(
            serde_json::to_string(&ClaimType::Distributed).unwrap(),
            "\"distributed\""
        );
    }

    #[test]
    fn deserialize_claim_type() {
        assert_eq!(
            serde_json::from_str::<ClaimType>("\"normal\"").unwrap(),
            ClaimType::Normal
        );
        assert_eq!(
            serde_json::from_str::<ClaimType>("\"aggregated\"").unwrap(),
            ClaimType::Aggregated
        );
        assert_eq!(
            serde_json::from_str::<ClaimType>("\"distributed\"").unwrap(),
            ClaimType::Distributed
        );
    }

    #[test]
    fn deserialize_auth_method_or_token_type_type() {
        assert_eq!(
            serde_json::from_str::<AuthenticationMethodOrAccessTokenType>("\"none\"").unwrap(),
            AuthenticationMethodOrAccessTokenType::AuthenticationMethod(
                OAuthClientAuthenticationMethod::None
            )
        );
        assert_eq!(
            serde_json::from_str::<AuthenticationMethodOrAccessTokenType>("\"Bearer\"").unwrap(),
            AuthenticationMethodOrAccessTokenType::AccessTokenType(OAuthAccessTokenType::Bearer)
        );
        assert_eq!(
            serde_json::from_str::<AuthenticationMethodOrAccessTokenType>("\"unknown_value\"")
                .unwrap(),
            AuthenticationMethodOrAccessTokenType::Unknown("unknown_value".to_owned())
        );
    }
}