alibi-plugins 0.10.0

Built-in authentication plugins and API metadata for Alibi
Documentation
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
//! OAuth authorization-server discovery from installed issuer and provider policy.
pub use authentication::{OAuthAuthenticatedClient, OAuthClientAuthenticationOptions};
mod access_validation;
mod authentication;
pub use client_secret::{OAuthClientSecretCipher, OAuthClientSecretHasher};
mod assertion;
mod authorization;
mod claims_request;
mod client_jwks;
mod client_secret;
mod clients;
mod metadata_document;
pub use metadata_document::{
    OAuthClientMetadata, OAuthClientRegistrationResult, RegisterClientMetadataDocumentInput,
};
mod consent;
mod continuation;
mod credentials;
mod discovery;
mod dpop;
mod extension_authentication;
mod interaction;
pub use extension_authentication::{
    OAuthClientAssertionInput, OAuthClientAuthenticationStrategy,
    OAuthExtensionClientAuthentication, OAuthVerifiedClientAssertion,
};
mod extension_claims;
pub use extension_claims::{
    OAuthExtensionClaims, OAuthTokenClaimsContributor, OAuthTokenClaimsInput,
    OAuthUserInfoClaimsContributor, OAuthUserInfoClaimsInput,
};
mod extensions;
pub use extensions::{
    OAuthExtensionGrantHandler, OAuthExtensionGrantInput, OAuthMetadataContributor,
    OAuthMetadataExtensionInput, OAuthMetadataType, OAuthProviderApi, OAuthProviderExtension,
};
mod id_token;
mod issuance;
pub use issuance::{OAuthTokenGenerator, OAuthTokenIssueParams};
mod initial_access_token;
mod introspection;
pub use initial_access_token::{
    OAuthInitialAccessTokenAuthorization, OAuthInitialAccessTokenError,
    OAuthInitialAccessTokenInput, OAuthInitialAccessTokenValidator,
};
mod logout;
mod machine;
mod post_login;
mod rate_limit;
mod refresh;
pub use rate_limit::{OAuthEndpointRateLimit, OAuthProviderRateLimits};
mod refresh_format;
pub use refresh_format::{
    OAuthDecodedRefreshToken, OAuthRefreshTokenEncryption, OAuthRefreshTokenFormatter,
};
mod resource_cache;
mod resource_policy;
mod resource_seed;
pub use resource_seed::{OAuthResourceIdentifierValidator, OAuthResourceSeedMode};
mod resources;
mod revocation;
mod select_account;
mod session_retirement;
mod signup;
pub use post_login::{
    OAuthConsentReference, OAuthConsentReferenceContext, OAuthInteractionContext,
    OAuthPostLoginConfig, OAuthPostLoginContext, OAuthPostLoginPolicy,
};
pub use select_account::{
    OAuthSelectAccountConfig, OAuthSelectAccountContext, OAuthSelectAccountPolicy,
};
pub use signup::{OAuthSignupConfig, OAuthSignupContext, OAuthSignupPolicy, OAuthSignupRedirect};
mod subject;
mod token;
mod token_storage;
pub use token_storage::OAuthTokenHasher;
mod userinfo;
use alibi_core::endpoint::{
    EndpointCall, EndpointDefinition, EndpointInput, EndpointResponse, ServerEndpoint,
};
use alibi_core::{
    AuthContext, AuthError, AuthPlugin, AuthRequest, AuthResponse, AuthResult, AuthRoute,
    AuthSchema, HttpMethod,
};
pub use assertion::consume_client_assertion;
use async_trait::async_trait;
pub use client_jwks::{
    OAuthClientMetadataAbortSignal, OAuthClientMetadataFetchOptions,
    OAuthClientMetadataFetchResponse, OAuthClientMetadataResourceFetch,
};
pub use clients::{CreateOAuthClientInput, RegisterOAuthClientInput};
pub use discovery::OAuthClientDiscovery;
use serde_json::{Value, json};

/// Actual authenticated context passed to an operator client-privilege decision.
/// The pinned hook receives no client or reference identifier.
#[derive(Debug, Clone)]
pub struct OAuthClientPrivilegeContext {
    pub action: &'static str,
    pub headers: alibi_core::Headers,
    pub user: Value,
    pub session: Value,
}
#[async_trait]
pub trait OAuthClientPrivileges: Send + Sync + std::fmt::Debug {
    async fn allowed(&self, context: &OAuthClientPrivilegeContext) -> AuthResult<bool>;
}
/// Authenticated operator input for resource catalog and client-resource link management.
#[derive(Debug, Clone)]
pub struct OAuthResourcePrivilegeContext {
    pub action: &'static str,
    pub headers: alibi_core::Headers,
    pub user: Value,
    pub session: Value,
    /// Decoded resource identifier; absent for create and list. No client identity is supplied.
    pub resource_id: Option<String>,
}
#[async_trait]
pub trait OAuthResourcePrivileges: Send + Sync + std::fmt::Debug {
    async fn allowed(&self, context: &OAuthResourcePrivilegeContext) -> AuthResult<bool>;
}
/// Application-owned client identifiers. Empty output is preserved, matching the reference.
pub trait OAuthClientIdGenerator: Send + Sync + std::fmt::Debug {
    fn generate(&self) -> AuthResult<String>;
}
/// Application-owned client credential generation. Empty output uses the default generator.
pub trait OAuthClientSecretGenerator: Send + Sync + std::fmt::Debug {
    fn generate(&self) -> AuthResult<String>;
}
/// Application redirect trust decision. URI safety remains provider-owned.
///
/// The URI is raw effective input on schema errors (the original URL query on
/// request-object or URI-resolution errors), and schema-parsed input otherwise.
/// Neither argument uses parsed URL equality. Errors deny trust rather than failing the route.
#[async_trait]
pub trait OAuthRedirectUriValidator: Send + Sync + std::fmt::Debug {
    async fn validate(
        &self,
        redirect_uri: &str,
        registered_uris: &[String],
        default_result: bool,
    ) -> AuthResult<bool>;
}
/// The original request URI and URL-supplied client identity, before schema parsing.
pub struct OAuthRequestUriInput<'a> {
    pub request_uri: &'a str,
    pub client_id: &'a str,
    /// Initialized application context, original logical query and genuine physical request.
    pub context: &'a alibi_core::CallbackContext,
}
/// Authorization parameters with JavaScript-compatible extension values.
pub type OAuthAuthorizationQuery = indexmap::IndexMap<String, alibi_core::utils::json::JsValue>;
/// Application-owned asynchronous authorization request lookup.
///
/// Resolved parameters replace the URL query, except that the original client
/// identity always wins. `None` means invalid or expired; errors propagate at
/// the endpoint boundary. Values retain JavaScript numbers, including nonfinite values.
#[async_trait]
pub trait OAuthRequestUriResolver: Send + Sync + std::fmt::Debug {
    async fn resolve(
        &self,
        input: OAuthRequestUriInput<'_>,
    ) -> AuthResult<Option<OAuthAuthorizationQuery>>;
}
/// Immutable policy shared by authorization-server metadata and grant admission.
#[derive(Clone, Debug)]
pub struct OAuthProviderConfig {
    /// Protocol quotas registered with the global rate limiter, not private API calls.
    pub rate_limit: OAuthProviderRateLimits,
    pub scopes: Vec<String>,
    pub extensions: Vec<std::sync::Arc<OAuthProviderExtension>>,
    /// Operator-owned `UserInfo` claims, applied after additive extension claims.
    /// May override ordinary profile claims, but never the authoritative subject.
    pub custom_user_info_claims: Option<std::sync::Arc<dyn OAuthUserInfoClaimsContributor>>,
    /// Operator-owned ID-token claims. Profile claims may override additive
    /// contributions; provider-owned protocol claims remain authoritative.
    pub custom_id_token_claims: Option<std::sync::Arc<dyn OAuthTokenClaimsContributor>>,
    /// Operator access claims, above per-issuance claims but below resource
    /// policy. Opaque validation re-derives them without an issuance grant.
    pub custom_access_token_claims: Option<std::sync::Arc<dyn OAuthTokenClaimsContributor>>,
    /// Application response-envelope fields, collected before token writes.
    /// Per-issuance fields take precedence; protocol response fields remain provider-owned.
    pub custom_token_response_fields: Option<std::sync::Arc<dyn OAuthTokenClaimsContributor>>,
    pub client_discoveries: Vec<std::sync::Arc<dyn OAuthClientDiscovery>>,
    /// Managed identities cached by provider instance and protected from API mutations.
    pub cached_trusted_clients: std::collections::HashSet<String>,
    /// Global client-management policy, checked before client lookup or mutation.
    /// Metadata and secret operations remain owner-controlled. Administrative
    /// scopes-only patches additionally require the configure-scopes decision.
    pub client_privileges: Option<std::sync::Arc<dyn OAuthClientPrivileges>>,
    /// Operator decision for assigning client-credentials scopes.
    /// This narrower policy does not authorize other management actions.
    /// When both policies are configured, both must allow scope assignment.
    pub client_credentials_scope_privileges: Option<std::sync::Arc<dyn OAuthClientPrivileges>>,
    pub client_id_generator: Option<std::sync::Arc<dyn OAuthClientIdGenerator>>,
    pub client_secret_generator: Option<std::sync::Arc<dyn OAuthClientSecretGenerator>>,
    /// Override registered redirect matching after provider-owned URI safety checks.
    pub validate_redirect_uri: Option<std::sync::Arc<dyn OAuthRedirectUriValidator>>,
    /// Optional request registry; absent by default (`request_uri_not_supported`).
    pub request_uri_resolver: Option<std::sync::Arc<dyn OAuthRequestUriResolver>>,
    pub client_secret_hasher: Option<std::sync::Arc<dyn OAuthClientSecretHasher>>,
    /// Application token hashing for authorization codes, access and refresh tokens.
    pub token_hasher: Option<std::sync::Arc<dyn OAuthTokenHasher>>,
    pub opaque_access_token_generator: Option<std::sync::Arc<dyn OAuthTokenGenerator>>,
    pub refresh_token_generator: Option<std::sync::Arc<dyn OAuthTokenGenerator>>,
    /// Presentation prefix for opaque access credentials; storage hashes plaintext.
    pub opaque_access_token_prefix: Option<String>,
    /// Presentation prefix for refresh credentials; storage hashes plaintext.
    pub refresh_token_prefix: Option<String>,
    /// Application-owned refresh presentation, separate from generation and hashing.
    pub refresh_token_formatter: Option<std::sync::Arc<dyn OAuthRefreshTokenFormatter>>,
    pub client_secret_cipher: Option<std::sync::Arc<dyn OAuthClientSecretCipher>>,
    /// Wire prefix matching Better Auth's `prefix.clientSecret`; stored credentials exclude it.
    pub client_secret_prefix: Option<String>,
    pub login_page: String,
    pub consent_page: String,
    pub select_account_page: Option<String>,
    pub select_account: Option<OAuthSelectAccountConfig>,
    pub signup: Option<OAuthSignupConfig>,
    pub post_login: Option<OAuthPostLoginConfig>,
    pub code_expires_in: f64,
    /// User access-token lifetime in seconds, including refresh grant issuance.
    pub access_token_expires_in: f64,
    /// Access-token lifetime for issuance without a user.
    pub m2m_access_token_expires_in: f64,
    pub id_token_expires_in: f64,
    pub refresh_token_expires_in: f64,
    /// Per-scope access-expiration ceilings. Numeric values are absolute Unix
    /// seconds (and numeric zero is ignored), matching the reference policy.
    pub scope_expirations: std::collections::HashMap<String, crate::jwt::JwtExpiration>,
    /// Maximum assertion future expiration and issued-at age, in seconds (default 300).
    pub assertion_max_lifetime: f64,
    pub refresh_token_reuse_interval: f64,
    pub allow_public_client_prelogin: bool,
    pub enforce_per_client_resources: bool,
    /// Opt-in resource-policy cache membership. Entries are process-global by
    /// identifier, including across initialized stores, matching the pinned provider.
    /// External writes remain live by default; successful admin CRUD evicts entries.
    pub cached_resources: std::collections::HashSet<String>,
    /// Configured resource identifiers or policy objects, using the provider's camelCase fields.
    pub resources: Vec<Value>,
    pub resource_seed_mode: OAuthResourceSeedMode,
    pub identifier_validator: Option<std::sync::Arc<dyn OAuthResourceIdentifierValidator>>,
    /// Optional operator decision for resource CRUD and link/unlink actions.
    /// Without a hook, any authenticated session with headers may manage resources.
    pub resource_privileges: Option<std::sync::Arc<dyn OAuthResourcePrivileges>>,
    pub advertised_scopes: Option<Vec<String>>,
    pub advertised_claims: Option<Vec<String>>,
    pub grant_types: Vec<String>,
    pub allow_dynamic_client_registration: bool,
    /// Dynamic confidential clients may omit PKCE only when explicitly false.
    /// Public and managed clients retain their existing PKCE policy.
    pub client_registration_require_pkce: Option<bool>,
    /// Baseline dynamic-registration capabilities. `None` uses provider scopes;
    /// `Some(vec![])` deliberately supplies no baseline capabilities.
    pub client_registration_default_scopes: Option<Vec<String>>,
    /// Additional dynamic-registration capabilities, unioned after the baseline.
    /// Requested registration scopes validate against, but do not narrow, this union.
    pub client_registration_allowed_scopes: Option<Vec<String>>,
    /// Server-default resource links for newly registered clients. Omitted and empty
    /// lists both supply no links; identifiers must be present in `resources`.
    pub client_registration_default_resources: Option<Vec<String>>,
    /// Additional resource identifiers that dynamic registration may explicitly request.
    /// Defaults remain admitted even when this list is empty.
    pub client_registration_allowed_resources: Option<Vec<String>>,
    /// Operator authorization for Bearer credentials presented without a genuine user session.
    pub initial_access_token_validator:
        Option<std::sync::Arc<dyn OAuthInitialAccessTokenValidator>>,
    pub allow_unauthenticated_client_registration: bool,
    pub disable_jwt_plugin: bool,
    pub pairwise_secret: Option<String>,
    pub dpop_signing_algorithms: Option<Vec<String>>,
    pub dpop_proof_max_age_seconds: Option<f64>,
}
impl Default for OAuthProviderConfig {
    fn default() -> Self {
        Self {
            rate_limit: OAuthProviderRateLimits::default(),
            extensions: Vec::new(),
            custom_user_info_claims: None,
            custom_id_token_claims: None,
            custom_access_token_claims: None,
            custom_token_response_fields: None,
            client_discoveries: Vec::new(),
            cached_trusted_clients: std::collections::HashSet::new(),
            client_privileges: None,
            client_credentials_scope_privileges: None,
            client_id_generator: None,
            client_secret_generator: None,
            validate_redirect_uri: None,
            request_uri_resolver: None,
            client_secret_hasher: None,
            client_secret_cipher: None,
            token_hasher: None,
            opaque_access_token_generator: None,
            refresh_token_generator: None,
            opaque_access_token_prefix: None,
            refresh_token_prefix: None,
            refresh_token_formatter: None,
            client_secret_prefix: None,
            login_page: "/login".into(),
            consent_page: "/consent".into(),
            select_account_page: None,
            select_account: None,
            signup: None,
            post_login: None,
            code_expires_in: 600.0,
            access_token_expires_in: 3600.0,
            m2m_access_token_expires_in: 3600.0,
            id_token_expires_in: 36_000.0,
            refresh_token_expires_in: 2_592_000.0,
            scope_expirations: std::collections::HashMap::new(),
            assertion_max_lifetime: 300.0,
            refresh_token_reuse_interval: 0.0,
            allow_public_client_prelogin: false,
            enforce_per_client_resources: true,
            cached_resources: std::collections::HashSet::new(),
            resources: Vec::new(),
            resource_seed_mode: OAuthResourceSeedMode::default(),
            identifier_validator: None,
            resource_privileges: None,
            scopes: ["openid", "profile", "email", "offline_access"]
                .map(str::to_owned)
                .into(),
            advertised_scopes: None,
            advertised_claims: None,
            grant_types: ["authorization_code", "client_credentials", "refresh_token"]
                .map(str::to_owned)
                .into(),
            allow_dynamic_client_registration: false,
            client_registration_require_pkce: None,
            client_registration_default_scopes: None,
            client_registration_allowed_scopes: None,
            client_registration_default_resources: None,
            client_registration_allowed_resources: None,
            initial_access_token_validator: None,
            allow_unauthenticated_client_registration: false,
            disable_jwt_plugin: false,
            pairwise_secret: None,
            dpop_signing_algorithms: None,
            dpop_proof_max_age_seconds: None,
        }
    }
}
#[derive(Clone, Debug, Default)]
pub struct OAuthProviderPlugin {
    config: OAuthProviderConfig,
    client_jwks: std::sync::Arc<client_jwks::Cache>,
    trusted_clients: std::sync::Arc<discovery::TrustedCache>,
}
impl OAuthProviderPlugin {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
    #[must_use]
    pub fn with_config(mut config: OAuthProviderConfig) -> Self {
        config.scopes = unique(
            config
                .scopes
                .into_iter()
                .filter(|scope| !scope.is_empty())
                .collect(),
        );
        Self {
            config,
            ..Self::default()
        }
    }
    /// Return the issuer's authorization-server configuration for trusted server callers.
    #[must_use]
    pub fn get_oauth_server_config_endpoint() -> ServerEndpoint<Value> {
        ServerEndpoint::new("oauth-provider", "getOAuthServerConfig")
    }
    /// Return `OpenID` configuration when the provider supports the openid scope.
    #[must_use]
    pub fn get_open_id_config_endpoint() -> ServerEndpoint<Value> {
        ServerEndpoint::new("oauth-provider", "getOpenIdConfig")
    }
    fn metadata<S: AuthSchema>(&self, ctx: &AuthContext<S>) -> AuthResult<Value> {
        let jwt = if self.config.disable_jwt_plugin {
            None
        } else {
            Some(
                ctx.extensions
                    .get::<super::jwt::JwtDiscoveryOptions>()
                    .ok_or_else(|| AuthError::config("jwt_config"))?,
            )
        };
        let base = format!(
            "{}{}",
            ctx.config.base_url.trim_end_matches('/'),
            ctx.config.base_path
        );
        let issuer = jwt
            .as_ref()
            .and_then(|jwt| jwt.issuer.as_deref())
            .unwrap_or(&base);
        let issuer = normalize_issuer(issuer);
        let grants = self.supported_grant_types();
        let endpoint_auth = self.supported_auth_methods(false);
        let mut token_auth = endpoint_auth.clone();
        if self.config.allow_unauthenticated_client_registration
            || !self.config.client_discoveries.is_empty()
        {
            token_auth.insert(0, "none".into());
        }
        let signing = [
            "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512",
            "EdDSA",
        ];
        let mut output: serde_json::Map<String, Value> = serde_json::from_value(json!({
            "scopes_supported":self.config.advertised_scopes.as_ref().unwrap_or(&self.config.scopes),
            "issuer":issuer,"authorization_endpoint":format!("{base}/oauth2/authorize"),"token_endpoint":format!("{base}/oauth2/token"),
            "introspection_endpoint":format!("{base}/oauth2/introspect"),"revocation_endpoint":format!("{base}/oauth2/revoke"),
            "response_types_supported":if grants.iter().any(|grant|grant=="authorization_code"){vec!["code"]}else{vec![]},
            "response_modes_supported":["query"],"grant_types_supported":grants,
            "token_endpoint_auth_methods_supported":token_auth,"token_endpoint_auth_signing_alg_values_supported":signing,
            "introspection_endpoint_auth_methods_supported":endpoint_auth,
            "introspection_endpoint_auth_signing_alg_values_supported":signing,
            "revocation_endpoint_auth_methods_supported":endpoint_auth,
            "revocation_endpoint_auth_signing_alg_values_supported":signing,
            "code_challenge_methods_supported":["S256"],"authorization_response_iss_parameter_supported":true,
            "dpop_signing_alg_values_supported":self.config.dpop_signing_algorithms.clone().unwrap_or_else(||["EdDSA","ES256","ES512","PS256","RS256"].map(str::to_owned).into()),
            "backchannel_logout_supported":!self.config.disable_jwt_plugin,"backchannel_logout_session_supported":!self.config.disable_jwt_plugin,
        }))?;
        if let Some(jwt) = jwt.as_ref() {
            _ = output.insert(
                "jwks_uri".into(),
                json!(
                    jwt.remote_url
                        .clone()
                        .unwrap_or_else(|| format!("{base}{}", jwt.jwks_path))
                ),
            );
        }
        if self.config.allow_dynamic_client_registration {
            _ = output.insert(
                "registration_endpoint".into(),
                json!(format!("{base}/oauth2/register")),
            );
        }
        if self.config.scopes.iter().any(|scope| scope == "openid") {
            _ = output.insert("claims_supported".into(), json!(self.supported_claims()));
            _ = output.insert("claims_parameter_supported".into(), json!(true));
            _ = output.insert(
                "userinfo_endpoint".into(),
                json!(format!("{base}/oauth2/userinfo")),
            );
            _ = output.insert(
                "subject_types_supported".into(),
                json!(if self
                    .config
                    .pairwise_secret
                    .as_ref()
                    .is_some_and(|secret| !secret.is_empty())
                {
                    vec!["public", "pairwise"]
                } else {
                    vec!["public"]
                }),
            );
            _ = output.insert("acr_values_supported".into(), json!(["0"]));
            _ = output.insert(
                "id_token_signing_alg_values_supported".into(),
                json!(jwt.as_ref().map_or_else(
                    || vec!["HS256".to_owned()],
                    |jwt| jwt.signing_algorithms.clone()
                )),
            );
            _ = output.insert(
                "end_session_endpoint".into(),
                json!(format!("{base}/oauth2/end-session")),
            );
            _ = output.insert("request_parameter_supported".into(), json!(false));
            _ = output.insert("request_uri_parameter_supported".into(), json!(false));
            _ = output.insert(
                "prompt_values_supported".into(),
                json!(["login", "consent", "create", "select_account", "none"]),
            );
        }
        let mut contributed = serde_json::Map::new();
        for discovery in &self.config.client_discoveries {
            contributed.extend(discovery.discovery_metadata());
        }
        contributed.extend(output);
        self.apply_metadata_extensions(ctx, Value::Object(contributed))
    }
}
fn unique(values: Vec<String>) -> Vec<String> {
    let mut result = Vec::new();
    for value in values {
        if !result.contains(&value) {
            result.push(value);
        }
    }
    result
}
fn normalize_issuer(value: &str) -> String {
    let Ok(mut url) = url::Url::parse(value) else {
        return value.into();
    };
    let loopback = url.host_str().is_some_and(|host| {
        host == "localhost" || host == "127.0.0.1" || host == "[::1]" || host == "::1"
    });
    if url.scheme() != "https" && !loopback {
        _ = url.set_scheme("https");
    }
    url.set_query(None);
    url.set_fragment(None);
    url.to_string().trim_end_matches('/').to_owned()
}
#[async_trait]
impl<S: AuthSchema> AuthPlugin<S> for OAuthProviderPlugin {
    fn name(&self) -> &'static str {
        "oauth-provider"
    }
    fn rate_limits(&self) -> Vec<alibi_core::PluginRateLimit> {
        self.config.rate_limit.rules()
    }
    fn endpoint_hooks(&self) -> Vec<&dyn alibi_core::endpoint::EndpointHook<S>> {
        vec![self]
    }
    async fn before_request(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<S>,
    ) -> AuthResult<Option<alibi_core::BeforeRequestAction>> {
        let body = req.body_as_json::<alibi_core::utils::json::JsValue>().ok();
        interaction::admit(
            body.as_ref().and_then(|body| body.get("oauth_query")),
            ctx.config.current_secret(),
            req.extensions(),
        )?
        .map(|response| {
            response
                .to_response()
                .map(alibi_core::BeforeRequestAction::Respond)
        })
        .transpose()
    }
    async fn after_request(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<S>,
        response: AuthResponse,
    ) -> AuthResult<AuthResponse> {
        let Some(mut resumed) = interaction::resume(self, req, &response.headers, ctx).await?
        else {
            return Ok(response);
        };
        resumed.merge_headers(response.headers);
        resumed.to_response()
    }
    fn allowed_media_types(&self, route: &AuthRoute) -> Vec<&'static str> {
        match route.path.as_str() {
            "/oauth2/authorize"
            | "/oauth2/end-session/confirm"
            | "/oauth2/token"
            | "/oauth2/introspect"
            | "/oauth2/revoke"
            | "/oauth2/userinfo" => vec!["application/x-www-form-urlencoded"],
            "/oauth2/end-session" => vec!["application/json", "application/x-www-form-urlencoded"],
            _ => vec!["application/json"],
        }
    }
    fn routes(&self) -> Vec<AuthRoute> {
        vec![
            AuthRoute::post(
                "/oauth2/end-session/confirm",
                "oauth2EndSessionConfirmation",
            ),
            AuthRoute::get("/oauth2/end-session", "oauth2EndSession"),
            AuthRoute::post("/oauth2/end-session", "oauth2EndSession"),
            AuthRoute::get("/oauth2/userinfo", "oauth2UserInfo"),
            AuthRoute::post("/oauth2/userinfo", "oauth2UserInfo"),
            AuthRoute::post("/oauth2/revoke", "oauth2Revoke"),
            AuthRoute::post("/oauth2/introspect", "oauth2Introspect"),
            AuthRoute::post("/oauth2/token", "oauth2Token"),
            AuthRoute::post("/oauth2/create-client", "createOAuthClient"),
            AuthRoute::get("/oauth2/get-client", "getOAuthClient"),
            AuthRoute::get("/oauth2/public-client", "getOAuthClientPublic"),
            AuthRoute::post(
                "/oauth2/public-client-prelogin",
                "getOAuthClientPublicPrelogin",
            ),
            AuthRoute::get("/oauth2/get-clients", "getOAuthClients"),
            AuthRoute::post("/oauth2/delete-client", "deleteOAuthClient"),
            AuthRoute::post("/oauth2/update-client", "updateOAuthClient"),
            AuthRoute::post("/oauth2/register", "registerOAuthClient"),
            AuthRoute::post("/oauth2/consent", "oauth2Consent"),
            AuthRoute::post("/oauth2/continue", "oauth2Continue"),
            AuthRoute::get("/oauth2/get-consents", "getOAuthConsents"),
            AuthRoute::get("/oauth2/get-consent", "getOAuthConsent"),
            AuthRoute::post("/oauth2/update-consent", "updateOAuthConsent"),
            AuthRoute::post("/oauth2/delete-consent", "deleteOAuthConsent"),
            AuthRoute::get("/oauth2/authorize", "oauth2Authorize"),
            AuthRoute::post("/oauth2/authorize", "oauth2Authorize"),
            AuthRoute::post("/oauth2/client/rotate-secret", "rotateClientSecret"),
        ]
    }
    fn server_endpoints(&self) -> Vec<EndpointDefinition> {
        vec![
            crate::endpoint::definition(
                "oauth2EndSessionConfirmation",
                "oauth2EndSessionConfirmation",
                Some("/oauth2/end-session/confirm"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "oauth2EndSession",
                "oauth2EndSession",
                Some("/oauth2/end-session"),
                HttpMethod::Get,
            ),
            crate::endpoint::definition(
                "oauth2UserInfo",
                "oauth2UserInfo",
                Some("/oauth2/userinfo"),
                HttpMethod::Get,
            ),
            crate::endpoint::definition(
                "oauth2Revoke",
                "oauth2Revoke",
                Some("/oauth2/revoke"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "oauth2Introspect",
                "oauth2Introspect",
                Some("/oauth2/introspect"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "oauth2Token",
                "oauth2Token",
                Some("/oauth2/token"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "oauth2Continue",
                "oauth2Continue",
                Some("/oauth2/continue"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "adminUnlinkClientResource",
                "adminUnlinkClientResource",
                Some("/admin/oauth2/resources/:identifier/clients/:client_id"),
                HttpMethod::Delete,
            ),
            crate::endpoint::definition(
                "adminLinkClientResource",
                "adminLinkClientResource",
                Some("/admin/oauth2/resources/:identifier/clients/:client_id"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "adminDeleteOAuthResource",
                "adminDeleteOAuthResource",
                Some("/admin/oauth2/resources/:identifier"),
                HttpMethod::Delete,
            ),
            crate::endpoint::definition(
                "adminUpdateOAuthResource",
                "adminUpdateOAuthResource",
                Some("/admin/oauth2/resources/:identifier"),
                HttpMethod::Patch,
            ),
            crate::endpoint::definition(
                "adminGetOAuthResource",
                "adminGetOAuthResource",
                Some("/admin/oauth2/resources/:identifier"),
                HttpMethod::Get,
            ),
            crate::endpoint::definition(
                "adminListOAuthResources",
                "adminListOAuthResources",
                Some("/admin/oauth2/resources"),
                HttpMethod::Get,
            ),
            crate::endpoint::definition(
                "adminCreateOAuthResource",
                "adminCreateOAuthResource",
                Some("/admin/oauth2/resources"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "deleteOAuthConsent",
                "deleteOAuthConsent",
                Some("/oauth2/delete-consent"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "updateOAuthConsent",
                "updateOAuthConsent",
                Some("/oauth2/update-consent"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "getOAuthConsent",
                "getOAuthConsent",
                Some("/oauth2/get-consent"),
                HttpMethod::Get,
            ),
            crate::endpoint::definition(
                "getOAuthConsents",
                "getOAuthConsents",
                Some("/oauth2/get-consents"),
                HttpMethod::Get,
            ),
            crate::endpoint::definition(
                "oauth2Consent",
                "oauth2Consent",
                Some("/oauth2/consent"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "getOAuthClientPublicPrelogin",
                "getOAuthClientPublicPrelogin",
                Some("/oauth2/public-client-prelogin"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "oauth2Authorize",
                "oauth2Authorize",
                Some("/oauth2/authorize"),
                HttpMethod::Get,
            ),
            crate::endpoint::definition(
                "adminUpdateOAuthClient",
                "adminUpdateOAuthClient",
                Some("/admin/oauth2/update-client"),
                HttpMethod::Patch,
            ),
            crate::endpoint::definition(
                "adminCreateOAuthClient",
                "adminCreateOAuthClient",
                Some("/admin/oauth2/create-client"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "registerOAuthClient",
                "registerOAuthClient",
                Some("/oauth2/register"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "updateOAuthClient",
                "updateOAuthClient",
                Some("/oauth2/update-client"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "rotateClientSecret",
                "rotateClientSecret",
                Some("/oauth2/client/rotate-secret"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "deleteOAuthClient",
                "deleteOAuthClient",
                Some("/oauth2/delete-client"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "getOAuthClients",
                "getOAuthClients",
                Some("/oauth2/get-clients"),
                HttpMethod::Get,
            ),
            crate::endpoint::definition(
                "getOAuthClientPublic",
                "getOAuthClientPublic",
                Some("/oauth2/public-client"),
                HttpMethod::Get,
            ),
            crate::endpoint::definition(
                "getOAuthClient",
                "getOAuthClient",
                Some("/oauth2/get-client"),
                HttpMethod::Get,
            ),
            crate::endpoint::definition(
                "createOAuthClient",
                "createOAuthClient",
                Some("/oauth2/create-client"),
                HttpMethod::Post,
            ),
            crate::endpoint::definition(
                "getOAuthServerConfig",
                "getOAuthServerConfig",
                Some("/.well-known/oauth-authorization-server"),
                HttpMethod::Get,
            ),
            crate::endpoint::definition(
                "getOpenIdConfig",
                "getOpenIdConfig",
                Some("/.well-known/openid-configuration"),
                HttpMethod::Get,
            ),
        ]
    }
    fn validate_endpoint(
        &self,
        call: &EndpointCall,
        _ctx: &AuthContext<S>,
    ) -> AuthResult<EndpointInput> {
        Ok(EndpointInput {
            body: if call.operation_id() == "oauth2EndSessionConfirmation" {
                Some(crate::endpoint::validate_fields(
                    call.body(),
                    "body",
                    &[crate::authentication_helpers::JsonField {
                        name: "action",
                        kind: crate::authentication_helpers::JsonFieldKind::OneOf(&["confirm"]),
                        required: true,
                    }],
                )?)
            } else if call.operation_id() == "oauth2EndSession" {
                logout::validate(call.body(), "body")?
            } else if call.operation_id() == "oauth2UserInfo" {
                call.body()
                    .map(|body| {
                        crate::endpoint::validate_fields(
                            Some(body),
                            "body",
                            &[crate::authentication_helpers::JsonField::string(
                                "access_token",
                                false,
                            )],
                        )
                    })
                    .transpose()?
            } else if call.operation_id() == "oauth2Continue" {
                Some(continuation::validate(call.body())?)
            } else if call.operation_id() == "adminUpdateOAuthResource" {
                Some(resources::validate_update(call.body())?)
            } else if call.operation_id() == "adminCreateOAuthResource" {
                Some(resources::validate_create(call.body())?)
            } else if call.operation_id() == "deleteOAuthConsent" {
                Some(consent::validate_id(call.body(), "body")?)
            } else if call.operation_id() == "updateOAuthConsent" {
                Some(consent::validate_update(call.body())?)
            } else if call.operation_id() == "oauth2Consent" {
                Some(consent::validate(call.body())?)
            } else if call.operation_id() == "getOAuthClientPublicPrelogin" {
                Some(clients::validate_prelogin(call.body())?)
            } else if call.operation_id() == "adminUpdateOAuthClient" {
                Some(clients::validate_admin_update(call.body())?)
            } else if call.operation_id() == "adminCreateOAuthClient" {
                Some(clients::validate_admin_create(call.body())?)
            } else if call.operation_id() == "updateOAuthClient" {
                Some(clients::validate_update(call.body())?)
            } else if matches!(
                call.operation_id(),
                "deleteOAuthClient" | "rotateClientSecret"
            ) {
                Some(clients::validate_delete(call.body())?)
            } else if call.operation_id() == "createOAuthClient" {
                Some(clients::validate(call.body())?)
            } else {
                call.body().cloned()
            },
            query: if call.operation_id() == "oauth2EndSession" {
                logout::validate(call.query(), "query")?
            } else if call.operation_id() == "getOAuthConsent" {
                Some(consent::validate_id(call.query(), "query")?)
            } else if matches!(
                call.operation_id(),
                "getOAuthClient" | "getOAuthClientPublic"
            ) {
                Some(clients::validate_read(call.query())?)
            } else {
                call.query().cloned()
            },
        })
    }
    async fn on_endpoint(
        &self,
        call: &EndpointCall,
        ctx: &AuthContext<S>,
    ) -> AuthResult<EndpointResponse> {
        if call.operation_id() == "oauth2EndSessionConfirmation" {
            return Box::pin(self.confirm_logout(call, ctx)).await;
        }
        if call.operation_id() == "oauth2EndSession" {
            return Box::pin(self.end_session(call.query(), call.body(), call, ctx)).await;
        }
        if call.operation_id() == "oauth2UserInfo" {
            return Box::pin(self.user_info(call.body(), call, ctx)).await;
        }
        if call.operation_id() == "oauth2Revoke" {
            return Box::pin(self.revoke(call.body(), call, ctx)).await;
        }
        if call.operation_id() == "oauth2Introspect" {
            return Box::pin(self.introspect(call.body(), call, ctx)).await;
        }
        if call.operation_id() == "oauth2Token" {
            return Box::pin(self.token(call.body(), call, ctx)).await;
        }
        if call.operation_id() == "oauth2Continue" {
            return Box::pin(self.continue_authorization(call.body_as()?, call, ctx)).await;
        }
        if call.operation_id() == "adminUnlinkClientResource" {
            return Box::pin(self.unlink_resource(call.params(), call, ctx)).await;
        }
        if call.operation_id() == "adminLinkClientResource" {
            return Box::pin(self.link_resource(call.params(), call, ctx)).await;
        }
        if call.operation_id() == "adminDeleteOAuthResource" {
            return Box::pin(self.delete_resource(call.params(), call, ctx)).await;
        }
        if call.operation_id() == "adminUpdateOAuthResource" {
            return Box::pin(self.update_resource(call.params(), call.body_as()?, call, ctx)).await;
        }
        if call.operation_id() == "adminGetOAuthResource" {
            return Box::pin(self.read_resource(call.params(), call, ctx)).await;
        }
        if call.operation_id() == "adminListOAuthResources" {
            return Box::pin(self.list_resources(call, ctx)).await;
        }
        if call.operation_id() == "adminCreateOAuthResource" {
            return Box::pin(self.create_resource(call.body_as()?, call, ctx)).await;
        }
        if call.operation_id() == "deleteOAuthConsent" {
            return Box::pin(self.delete_consent(call.body_as()?, call, ctx)).await;
        }
        if call.operation_id() == "updateOAuthConsent" {
            return Box::pin(self.update_consent(call.body_as()?, call, ctx)).await;
        }
        if call.operation_id() == "getOAuthConsent" {
            return Box::pin(self.read_consent(call.query_as()?, call, ctx)).await;
        }
        if call.operation_id() == "getOAuthConsents" {
            return Box::pin(self.list_consents(call, ctx)).await;
        }
        if call.operation_id() == "oauth2Consent" {
            return Box::pin(self.consent(call.body_as()?, call, ctx)).await;
        }
        if call.operation_id() == "getOAuthClientPublicPrelogin" {
            return Box::pin(self.read_prelogin_client(call.body_as()?, ctx)).await;
        }
        if call.operation_id() == "oauth2Authorize" {
            let value = if call.method() == Some(&HttpMethod::Post) {
                call.body()
            } else {
                call.query()
            };
            return Box::pin(self.authorize(value.cloned(), call, ctx)).await;
        }
        if call.operation_id() == "adminUpdateOAuthClient" {
            return Box::pin(self.update_client(call.body_as()?, call, ctx, true)).await;
        }
        if call.operation_id() == "adminCreateOAuthClient" {
            return Box::pin(self.admin_create_client(call.body_as()?, call, ctx)).await;
        }
        if call.operation_id() == "registerOAuthClient" {
            return Box::pin(self.register_client(call.body(), call, ctx)).await;
        }
        if call.operation_id() == "updateOAuthClient" {
            return Box::pin(self.update_client(call.body_as()?, call, ctx, false)).await;
        }
        if call.operation_id() == "rotateClientSecret" {
            return Box::pin(self.rotate_client_secret(call.body_as()?, call, ctx)).await;
        }
        if call.operation_id() == "deleteOAuthClient" {
            return Box::pin(self.delete_client(call.body_as()?, call, ctx)).await;
        }
        if call.operation_id() == "getOAuthClients" {
            return Box::pin(self.list_clients(call, ctx)).await;
        }
        if call.operation_id() == "getOAuthClientPublic" {
            return Box::pin(self.read_public_client(call.query_as()?, call, ctx)).await;
        }
        if call.operation_id() == "getOAuthClient" {
            return Box::pin(self.read_client(call.query_as()?, call, ctx)).await;
        }
        if call.operation_id() == "createOAuthClient" {
            return Box::pin(self.create_client(call.body_as()?, call, ctx)).await;
        }
        if call.operation_id() == "getOpenIdConfig"
            && !self.config.scopes.iter().any(|scope| scope == "openid")
        {
            return Ok(EndpointResponse::error(AuthError::Api {
                status: 404,
                code: None,
                message: String::new(),
            })
            .without_error_body()
            .with_header("Content-Type", "application/json"));
        }
        EndpointResponse::json(&self.metadata(ctx)?)
    }
    async fn on_request(
        &self,
        req: &AuthRequest,
        ctx: &AuthContext<S>,
    ) -> AuthResult<Option<AuthResponse>> {
        if req.path() == "/oauth2/end-session/confirm" && *req.method() == HttpMethod::Post {
            let action = url::form_urlencoded::parse(req.body.as_deref().unwrap_or_default())
                .find(|(key, _)| key == "action")
                .map(|(_, value)| value.into_owned());
            if action.as_deref() != Some("confirm") {
                return Ok(Some(
                    AuthError::bad_request("Invalid logout action").to_auth_response(),
                ));
            }
            return Ok(Some(
                Box::pin(self.confirm_logout(req, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/end-session"
            && matches!(req.method(), HttpMethod::Get | HttpMethod::Post)
        {
            let query = alibi_core::utils::json::parse_value(&serde_json::to_string(&req.query)?)?;
            let body = if *req.method() == HttpMethod::Post {
                Some(alibi_core::utils::json::parse_value(
                    &serde_json::to_string(
                        &url::form_urlencoded::parse(req.body.as_deref().unwrap_or_default())
                            .into_owned()
                            .collect::<std::collections::HashMap<_, _>>(),
                    )?,
                )?)
            } else {
                None
            };
            return Ok(Some(
                Box::pin(self.end_session(Some(&query), body.as_ref(), req, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/userinfo"
            && matches!(req.method(), HttpMethod::Get | HttpMethod::Post)
        {
            let body = if *req.method() == HttpMethod::Post {
                Some(req.body_as_json::<alibi_core::utils::json::JsValue>()?)
            } else {
                None
            };
            // The admitted body may now have JSON dispatch bytes. Keep it
            // separate from the genuine Request used for POST/DPoP binding.
            let call = alibi_core::endpoint::current_endpoint_call_context().unwrap_or_else(|| {
                EndpointCall::from_http_request(
                    req,
                    &AuthRoute::get("/oauth2/userinfo", "oauth2UserInfo"),
                )
            });
            return Ok(Some(
                Box::pin(self.user_info(body.as_ref(), &call, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/token" && *req.method() == HttpMethod::Post {
            // Dispatch has already decoded the admitted form body. Endpoint
            // context patches may rewrite its bytes as JSON, so reparsing those
            // bytes as a form loses the grant and every credential binding.
            let body = req.body_as_json::<alibi_core::utils::json::JsValue>()?;
            // Credential duplicate/method checks still need the original form
            // Request retained by the call, not the rewritten dispatch bytes.
            let call = alibi_core::endpoint::current_endpoint_call_context().unwrap_or_else(|| {
                EndpointCall::from_http_request(
                    req,
                    &AuthRoute::post("/oauth2/token", "oauth2Token"),
                )
            });
            let call = call.handler_context(Some(body.clone()), call.query().cloned());
            return Ok(Some(
                Box::pin(self.token(Some(&body), &call, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if matches!(req.path(), "/oauth2/introspect" | "/oauth2/revoke")
            && *req.method() == HttpMethod::Post
        {
            // Consume admitted logical input (including form values and hook
            // patches), but authenticate against the original physical Request.
            let body = req.body_as_json::<alibi_core::utils::json::JsValue>()?;
            let revoking = req.path() == "/oauth2/revoke";
            let call = alibi_core::endpoint::current_endpoint_call_context().unwrap_or_else(|| {
                EndpointCall::from_http_request(
                    req,
                    &AuthRoute::post(
                        req.path(),
                        if revoking {
                            "oauth2Revoke"
                        } else {
                            "oauth2Introspect"
                        },
                    ),
                )
            });
            let call = call.handler_context(Some(body.clone()), call.query().cloned());
            let response = if revoking {
                Box::pin(self.revoke(Some(&body), &call, ctx)).await?
            } else {
                Box::pin(self.introspect(Some(&body), &call, ctx)).await?
            };
            return Ok(Some(response.to_response()?));
        }
        if req.path() == "/oauth2/authorize"
            && matches!(req.method(), HttpMethod::Get | HttpMethod::Post)
        {
            let value = if *req.method() == HttpMethod::Post {
                req.body_as_json::<alibi_core::utils::json::JsValue>()?
            } else {
                req.query_as_js_value()
            };
            // Legacy HTTP dispatch need not carry a logical endpoint frame.
            // Build it from the admitted route and genuine transport request,
            // not by rewriting that Request to contain resolver parameters.
            let call = alibi_core::endpoint::current_endpoint_call_context().unwrap_or_else(|| {
                EndpointCall::from_http_request(
                    req,
                    &AuthRoute::get("/oauth2/authorize", "oauth2Authorize"),
                )
            });
            let call = call.handler_context(call.body().cloned(), Some(value.clone()));
            return Ok(Some(
                alibi_core::endpoint::with_endpoint_call_context(
                    call,
                    Box::pin(self.authorize(Some(value), req, ctx)),
                )
                .await?
                .to_response()?,
            ));
        }
        if req.path() == "/oauth2/register" && *req.method() == HttpMethod::Post {
            let body: alibi_core::utils::json::JsValue = req.body_as_json()?;
            return Ok(Some(
                Box::pin(self.register_client(Some(&body), req, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/update-client" && *req.method() == HttpMethod::Post {
            let body: alibi_core::utils::json::JsValue = req.body_as_json()?;
            let input =
                alibi_core::utils::json::from_value(clients::validate_update(Some(&body))?)?;
            return Ok(Some(
                Box::pin(self.update_client(input, req, ctx, false))
                    .await?
                    .to_response()?,
            ));
        }
        if matches!(
            req.path(),
            "/oauth2/delete-client" | "/oauth2/client/rotate-secret"
        ) && *req.method() == HttpMethod::Post
        {
            let body: alibi_core::utils::json::JsValue = req.body_as_json()?;
            let input =
                alibi_core::utils::json::from_value(clients::validate_delete(Some(&body))?)?;
            if req.path() == "/oauth2/client/rotate-secret" {
                return Ok(Some(
                    Box::pin(self.rotate_client_secret(input, req, ctx))
                        .await?
                        .to_response()?,
                ));
            }
            return Ok(Some(
                Box::pin(self.delete_client(input, req, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/public-client-prelogin" && *req.method() == HttpMethod::Post {
            let body = req.body_as_json()?;
            let input =
                alibi_core::utils::json::from_value(clients::validate_prelogin(Some(&body))?)?;
            return Ok(Some(
                Box::pin(self.read_prelogin_client(input, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/continue" && *req.method() == HttpMethod::Post {
            let body = req.body_as_json()?;
            let input = alibi_core::utils::json::from_value(continuation::validate(Some(&body))?)?;
            return Ok(Some(
                Box::pin(self.continue_authorization(input, req, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/consent" && *req.method() == HttpMethod::Post {
            let body = req.body_as_json()?;
            let input = alibi_core::utils::json::from_value(consent::validate(Some(&body))?)?;
            return Ok(Some(
                Box::pin(self.consent(input, req, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/delete-consent" && *req.method() == HttpMethod::Post {
            let body = req.body_as_json()?;
            let input =
                alibi_core::utils::json::from_value(consent::validate_id(Some(&body), "body")?)?;
            return Ok(Some(
                Box::pin(self.delete_consent(input, req, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/update-consent" && *req.method() == HttpMethod::Post {
            let body = req.body_as_json()?;
            let input =
                alibi_core::utils::json::from_value(consent::validate_update(Some(&body))?)?;
            return Ok(Some(
                Box::pin(self.update_consent(input, req, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/get-consent" && *req.method() == HttpMethod::Get {
            let query = alibi_core::utils::json::parse_value(&serde_json::to_string(&req.query)?)?;
            let input =
                alibi_core::utils::json::from_value(consent::validate_id(Some(&query), "query")?)?;
            return Ok(Some(
                Box::pin(self.read_consent(input, req, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/get-consents" && *req.method() == HttpMethod::Get {
            return Ok(Some(
                Box::pin(self.list_consents(req, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/get-clients" && *req.method() == HttpMethod::Get {
            return Ok(Some(
                Box::pin(self.list_clients(req, ctx)).await?.to_response()?,
            ));
        }
        if matches!(req.path(), "/oauth2/get-client" | "/oauth2/public-client")
            && *req.method() == HttpMethod::Get
        {
            let query = alibi_core::utils::json::parse_value(&serde_json::to_string(&req.query)?)?;
            let input = alibi_core::utils::json::from_value(clients::validate_read(Some(&query))?)?;
            if req.path() == "/oauth2/public-client" {
                return Ok(Some(
                    Box::pin(self.read_public_client(input, req, ctx))
                        .await?
                        .to_response()?,
                ));
            }
            return Ok(Some(
                Box::pin(self.read_client(input, req, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        if req.path() == "/oauth2/create-client" && *req.method() == HttpMethod::Post {
            let body: alibi_core::utils::json::JsValue = req.body_as_json()?;
            let input = alibi_core::utils::json::from_value(clients::validate(Some(&body))?)?;
            return Ok(Some(
                Box::pin(self.create_client(input, req, ctx))
                    .await?
                    .to_response()?,
            ));
        }
        Ok(None)
    }
    async fn on_init(&self, ctx: &mut alibi_core::AuthInitContext<S>) -> AuthResult<()> {
        self.validate_extensions()?;
        for scope in self
            .config
            .client_registration_allowed_scopes
            .iter()
            .flatten()
            .chain(
                self.config
                    .client_registration_default_scopes
                    .iter()
                    .flatten(),
            )
        {
            if !self.config.scopes.contains(scope) {
                return Err(AuthError::config(format!(
                    "clientRegistrationAllowedScope {scope} not found in scopes"
                )));
            }
        }
        if self
            .config
            .advertised_scopes
            .as_ref()
            .is_some_and(|scopes| {
                scopes
                    .iter()
                    .any(|scope| !self.config.scopes.contains(scope))
            })
        {
            return Err(AuthError::config(
                "advertisedMetadata.scopes_supported contains an unsupported scope",
            ));
        }
        let configured_resources = self
            .config
            .resources
            .iter()
            .filter_map(|resource| {
                resource
                    .as_str()
                    .or_else(|| resource.get("identifier").and_then(Value::as_str))
            })
            .collect::<std::collections::HashSet<_>>();
        for (option, identifiers) in [
            (
                "clientRegistrationDefaultResources",
                &self.config.client_registration_default_resources,
            ),
            (
                "clientRegistrationAllowedResources",
                &self.config.client_registration_allowed_resources,
            ),
        ] {
            for identifier in identifiers.iter().flatten() {
                if !configured_resources.contains(identifier.as_str()) {
                    return Err(AuthError::config(format!(
                        "{option} resource {identifier} not found in resources"
                    )));
                }
            }
        }
        if self
            .config
            .pairwise_secret
            .as_ref()
            .is_some_and(|secret| !secret.is_empty() && secret.len() < 32)
        {
            return Err(AuthError::config(
                "pairwiseSecret must be at least 32 characters long for adequate HMAC-SHA256 security",
            ));
        }
        if self
            .config
            .grant_types
            .iter()
            .any(|grant| grant == "refresh_token")
            && !self
                .config
                .grant_types
                .iter()
                .any(|grant| grant == "authorization_code")
        {
            return Err(AuthError::config(
                "refresh_token grant requires authorization_code grant",
            ));
        }
        if self.config.disable_jwt_plugin && self.config.client_secret_hasher.is_some() {
            return Err(AuthError::config(
                "unable to store hashed secrets because id tokens will be signed with secret",
            ));
        }
        if !self.config.disable_jwt_plugin && self.config.client_secret_cipher.is_some() {
            return Err(AuthError::config(
                "encryption method not recommended, please use 'hashed' or the 'hash' function",
            ));
        }
        let mut discovery_ids = std::collections::HashSet::new();
        for discovery in &self.config.client_discoveries {
            if alibi_core::utils::javascript::trim(discovery.id()).is_empty() {
                return Err(AuthError::config(
                    "OAuth Provider extension client discovery id cannot be empty",
                ));
            }
            if !discovery_ids.insert(discovery.id()) {
                return Err(AuthError::config(format!(
                    "OAuth Provider extensions register client discovery id \"{}\" more than once. Extension contributions must be disjoint.",
                    discovery.id()
                )));
            }
        }
        self.seed_resources(ctx.database.as_ref()).await?;
        ctx.extensions.insert(resource_seed::SeedState::default());
        ctx.extensions.insert(discovery::TrustedClients {
            ids: self.config.cached_trusted_clients.clone(),
            cache: self.trusted_clients.clone(),
        });
        ctx.extensions.insert(discovery::ClientDiscoveries(
            self.config.client_discoveries.clone(),
        ));
        ctx.register_session_deletion_hook(std::sync::Arc::new(
            session_retirement::TokenRetirementHook(self.clone()),
        ));
        Ok(())
    }
}