rustauth-oauth-provider 0.3.0

OAuth 2.1 and OpenID Connect provider support for RustAuth.
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
use std::collections::{BTreeMap, BTreeSet};
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, RwLock};

use rustauth_core::db::{Session, User};
use rustauth_core::error::RustAuthError;
use rustauth_core::options::RateLimitRule;
use serde_json::{Map, Value};
use thiserror::Error;

use crate::models::SchemaClient;

type ClientReferenceFuture =
    Pin<Box<dyn Future<Output = Result<Option<String>, RustAuthError>> + Send>>;
type ClientPrivilegesFuture = Pin<Box<dyn Future<Output = Result<bool, RustAuthError>> + Send>>;
type JsonObjectFuture =
    Pin<Box<dyn Future<Output = Result<Map<String, Value>, RustAuthError>> + Send>>;
type OptionalStringFuture =
    Pin<Box<dyn Future<Output = Result<Option<String>, RustAuthError>> + Send>>;
type RequestUriFuture =
    Pin<Box<dyn Future<Output = Result<Option<Vec<(String, String)>>, RustAuthError>> + Send>>;
type StringGeneratorFuture = Pin<Box<dyn Future<Output = Result<String, RustAuthError>> + Send>>;
type BoolResolverFuture = Pin<Box<dyn Future<Output = Result<bool, RustAuthError>> + Send>>;
type RefreshTokenEncodeFuture = Pin<Box<dyn Future<Output = Result<String, RustAuthError>> + Send>>;
type RefreshTokenDecodeFuture =
    Pin<Box<dyn Future<Output = Result<RefreshTokenFormatDecodeOutput, RustAuthError>> + Send>>;

/// Input passed to the OAuth client reference resolver.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientReferenceInput {
    pub user: Option<User>,
    pub session: Option<Session>,
}

/// Async callback that resolves the non-user owner of OAuth clients.
#[derive(Clone)]
pub struct ClientReferenceResolver {
    resolver: Arc<dyn Fn(ClientReferenceInput) -> ClientReferenceFuture + Send + Sync>,
}

impl ClientReferenceResolver {
    /// Create a resolver from an async function.
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn(ClientReferenceInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Option<String>, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move |input| Box::pin(resolver(input))),
        }
    }

    pub async fn resolve(
        &self,
        input: ClientReferenceInput,
    ) -> Result<Option<String>, RustAuthError> {
        (self.resolver)(input).await
    }
}

impl std::fmt::Debug for ClientReferenceResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("ClientReferenceResolver(..)")
    }
}

impl PartialEq for ClientReferenceResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for ClientReferenceResolver {}

#[derive(Clone, Default)]
pub struct TrustedClientCache {
    clients: Arc<RwLock<BTreeMap<String, SchemaClient>>>,
}

impl TrustedClientCache {
    pub fn get(&self, client_id: &str) -> Result<Option<SchemaClient>, RustAuthError> {
        let clients = self
            .clients
            .read()
            .map_err(|_| RustAuthError::Api("trusted client cache lock poisoned".to_owned()))?;
        Ok(clients.get(client_id).cloned())
    }

    pub fn insert(&self, client: SchemaClient) -> Result<(), RustAuthError> {
        let mut clients = self
            .clients
            .write()
            .map_err(|_| RustAuthError::Api("trusted client cache lock poisoned".to_owned()))?;
        clients.insert(client.client_id.clone(), client);
        Ok(())
    }
}

impl std::fmt::Debug for TrustedClientCache {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("TrustedClientCache(..)")
    }
}

impl PartialEq for TrustedClientCache {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for TrustedClientCache {}

/// OAuth client-management action checked by [`ClientPrivilegesResolver`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClientPrivilegeAction {
    Create,
    Read,
    Update,
    Delete,
    List,
    Rotate,
}

/// Input passed to the OAuth client privileges resolver.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientPrivilegesInput {
    pub action: ClientPrivilegeAction,
    pub user: Option<User>,
    pub session: Option<Session>,
}

/// Async callback that authorizes OAuth client-management actions.
#[derive(Clone)]
pub struct ClientPrivilegesResolver {
    resolver: Arc<dyn Fn(ClientPrivilegesInput) -> ClientPrivilegesFuture + Send + Sync>,
}

impl ClientPrivilegesResolver {
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn(ClientPrivilegesInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<bool, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move |input| Box::pin(resolver(input))),
        }
    }

    pub async fn resolve(&self, input: ClientPrivilegesInput) -> Result<bool, RustAuthError> {
        (self.resolver)(input).await
    }
}

impl std::fmt::Debug for ClientPrivilegesResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("ClientPrivilegesResolver(..)")
    }
}

impl PartialEq for ClientPrivilegesResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for ClientPrivilegesResolver {}

/// Input passed to custom client secret hash callbacks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientSecretHashInput {
    pub secret: String,
}

/// Async callback that hashes client secrets before persistence.
#[derive(Clone)]
pub struct ClientSecretHashResolver {
    resolver: Arc<dyn Fn(ClientSecretHashInput) -> StringGeneratorFuture + Send + Sync>,
}

impl ClientSecretHashResolver {
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn(ClientSecretHashInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<String, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move |input| Box::pin(resolver(input))),
        }
    }

    pub async fn resolve(&self, input: ClientSecretHashInput) -> Result<String, RustAuthError> {
        (self.resolver)(input).await
    }
}

impl std::fmt::Debug for ClientSecretHashResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("ClientSecretHashResolver(..)")
    }
}

impl PartialEq for ClientSecretHashResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for ClientSecretHashResolver {}

/// Input passed to custom client secret verification callbacks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientSecretVerifyInput {
    pub secret: String,
    pub stored_hash: String,
}

/// Async callback that verifies client secrets against stored values.
#[derive(Clone)]
pub struct ClientSecretVerifyResolver {
    resolver: Arc<dyn Fn(ClientSecretVerifyInput) -> BoolResolverFuture + Send + Sync>,
}

impl ClientSecretVerifyResolver {
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn(ClientSecretVerifyInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<bool, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move |input| Box::pin(resolver(input))),
        }
    }

    pub async fn resolve(&self, input: ClientSecretVerifyInput) -> Result<bool, RustAuthError> {
        (self.resolver)(input).await
    }
}

impl std::fmt::Debug for ClientSecretVerifyResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("ClientSecretVerifyResolver(..)")
    }
}

impl PartialEq for ClientSecretVerifyResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for ClientSecretVerifyResolver {}

/// Input passed to custom OAuth token hash callbacks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenHashInput {
    pub token: String,
    pub token_type: String,
}

/// Async callback that hashes OAuth tokens before lookup or persistence.
#[derive(Clone)]
pub struct TokenHashResolver {
    resolver: Arc<dyn Fn(TokenHashInput) -> StringGeneratorFuture + Send + Sync>,
}

impl TokenHashResolver {
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn(TokenHashInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<String, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move |input| Box::pin(resolver(input))),
        }
    }

    pub async fn resolve(&self, input: TokenHashInput) -> Result<String, RustAuthError> {
        (self.resolver)(input).await
    }
}

impl std::fmt::Debug for TokenHashResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("TokenHashResolver(..)")
    }
}

impl PartialEq for TokenHashResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for TokenHashResolver {}

/// Input passed to advanced prompt redirect callbacks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PromptRedirectInput {
    pub user: User,
    pub session: Session,
    pub scopes: Vec<String>,
}

/// Async callback that may redirect an advanced prompt step to a page.
#[derive(Clone)]
pub struct PromptRedirectResolver {
    resolver: Arc<dyn Fn(PromptRedirectInput) -> OptionalStringFuture + Send + Sync>,
}

impl PromptRedirectResolver {
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn(PromptRedirectInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Option<String>, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move |input| Box::pin(resolver(input))),
        }
    }

    pub async fn resolve(
        &self,
        input: PromptRedirectInput,
    ) -> Result<Option<String>, RustAuthError> {
        (self.resolver)(input).await
    }
}

impl std::fmt::Debug for PromptRedirectResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("PromptRedirectResolver(..)")
    }
}

impl PartialEq for PromptRedirectResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for PromptRedirectResolver {}

/// Async callback that decides whether an advanced prompt step should run.
#[derive(Clone)]
pub struct PromptShouldRedirectResolver {
    resolver: Arc<dyn Fn(PromptRedirectInput) -> BoolResolverFuture + Send + Sync>,
}

impl PromptShouldRedirectResolver {
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn(PromptRedirectInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<bool, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move |input| Box::pin(resolver(input))),
        }
    }

    pub async fn resolve(&self, input: PromptRedirectInput) -> Result<bool, RustAuthError> {
        (self.resolver)(input).await
    }
}

impl std::fmt::Debug for PromptShouldRedirectResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("PromptShouldRedirectResolver(..)")
    }
}

impl PartialEq for PromptShouldRedirectResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for PromptShouldRedirectResolver {}

/// Input passed to custom ID token claim callbacks.
#[derive(Debug, Clone, PartialEq)]
pub struct CustomIdTokenClaimsInput {
    pub user: User,
    pub scopes: Vec<String>,
    pub metadata: Option<Value>,
}

/// Input passed to custom access token claim callbacks.
#[derive(Debug, Clone, PartialEq)]
pub struct CustomAccessTokenClaimsInput {
    pub user: Option<User>,
    pub reference_id: Option<String>,
    pub scopes: Vec<String>,
    pub resource: Vec<String>,
    pub metadata: Option<Value>,
}

/// Async callback that provides additional access token or introspection claims.
#[derive(Clone)]
pub struct CustomAccessTokenClaimsResolver {
    resolver: Arc<dyn Fn(CustomAccessTokenClaimsInput) -> JsonObjectFuture + Send + Sync>,
}

impl CustomAccessTokenClaimsResolver {
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn(CustomAccessTokenClaimsInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Map<String, Value>, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move |input| Box::pin(resolver(input))),
        }
    }

    pub async fn resolve(
        &self,
        input: CustomAccessTokenClaimsInput,
    ) -> Result<Map<String, Value>, RustAuthError> {
        (self.resolver)(input).await
    }
}

impl std::fmt::Debug for CustomAccessTokenClaimsResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("CustomAccessTokenClaimsResolver(..)")
    }
}

impl PartialEq for CustomAccessTokenClaimsResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for CustomAccessTokenClaimsResolver {}

/// Async callback that provides additional ID token claims.
#[derive(Clone)]
pub struct CustomIdTokenClaimsResolver {
    resolver: Arc<dyn Fn(CustomIdTokenClaimsInput) -> JsonObjectFuture + Send + Sync>,
}

impl CustomIdTokenClaimsResolver {
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn(CustomIdTokenClaimsInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Map<String, Value>, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move |input| Box::pin(resolver(input))),
        }
    }

    pub async fn resolve(
        &self,
        input: CustomIdTokenClaimsInput,
    ) -> Result<Map<String, Value>, RustAuthError> {
        (self.resolver)(input).await
    }
}

impl std::fmt::Debug for CustomIdTokenClaimsResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("CustomIdTokenClaimsResolver(..)")
    }
}

impl PartialEq for CustomIdTokenClaimsResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for CustomIdTokenClaimsResolver {}

/// Input passed to custom token response field callbacks.
#[derive(Debug, Clone, PartialEq)]
pub struct CustomTokenResponseFieldsInput {
    pub grant_type: GrantType,
    pub user: Option<User>,
    pub scopes: Vec<String>,
    pub metadata: Option<Value>,
}

/// Async callback that provides extra token response fields.
#[derive(Clone)]
pub struct CustomTokenResponseFieldsResolver {
    resolver: Arc<dyn Fn(CustomTokenResponseFieldsInput) -> JsonObjectFuture + Send + Sync>,
}

impl CustomTokenResponseFieldsResolver {
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn(CustomTokenResponseFieldsInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Map<String, Value>, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move |input| Box::pin(resolver(input))),
        }
    }

    pub async fn resolve(
        &self,
        input: CustomTokenResponseFieldsInput,
    ) -> Result<Map<String, Value>, RustAuthError> {
        (self.resolver)(input).await
    }
}

impl std::fmt::Debug for CustomTokenResponseFieldsResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("CustomTokenResponseFieldsResolver(..)")
    }
}

impl PartialEq for CustomTokenResponseFieldsResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for CustomTokenResponseFieldsResolver {}

/// Input passed to custom userinfo claim callbacks.
#[derive(Debug, Clone, PartialEq)]
pub struct CustomUserInfoClaimsInput {
    pub user: User,
    pub scopes: Vec<String>,
    pub jwt: Value,
}

/// Async callback that provides additional userinfo claims.
#[derive(Clone)]
pub struct CustomUserInfoClaimsResolver {
    resolver: Arc<dyn Fn(CustomUserInfoClaimsInput) -> JsonObjectFuture + Send + Sync>,
}

impl CustomUserInfoClaimsResolver {
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn(CustomUserInfoClaimsInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Map<String, Value>, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move |input| Box::pin(resolver(input))),
        }
    }

    pub async fn resolve(
        &self,
        input: CustomUserInfoClaimsInput,
    ) -> Result<Map<String, Value>, RustAuthError> {
        (self.resolver)(input).await
    }
}

impl std::fmt::Debug for CustomUserInfoClaimsResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("CustomUserInfoClaimsResolver(..)")
    }
}

impl PartialEq for CustomUserInfoClaimsResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for CustomUserInfoClaimsResolver {}

/// Input passed to request URI resolution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestUriResolverInput {
    pub request_uri: String,
    pub client_id: Option<String>,
}

/// Async callback that resolves pushed authorization request parameters.
#[derive(Clone)]
pub struct RequestUriResolver {
    resolver: Arc<dyn Fn(RequestUriResolverInput) -> RequestUriFuture + Send + Sync>,
}

impl RequestUriResolver {
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn(RequestUriResolverInput) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Option<Vec<(String, String)>>, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move |input| Box::pin(resolver(input))),
        }
    }

    pub async fn resolve(
        &self,
        input: RequestUriResolverInput,
    ) -> Result<Option<Vec<(String, String)>>, RustAuthError> {
        (self.resolver)(input).await
    }
}

impl std::fmt::Debug for RequestUriResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("RequestUriResolver(..)")
    }
}

impl PartialEq for RequestUriResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for RequestUriResolver {}

/// Async callback used to generate OAuth identifiers and token secrets.
#[derive(Clone)]
pub struct StringGeneratorResolver {
    resolver: Arc<dyn Fn() -> StringGeneratorFuture + Send + Sync>,
}

impl StringGeneratorResolver {
    pub fn new<F, Fut>(resolver: F) -> Self
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<String, RustAuthError>> + Send + 'static,
    {
        Self {
            resolver: Arc::new(move || Box::pin(resolver())),
        }
    }

    pub async fn generate(&self) -> Result<String, RustAuthError> {
        (self.resolver)().await
    }
}

impl std::fmt::Debug for StringGeneratorResolver {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("StringGeneratorResolver(..)")
    }
}

impl PartialEq for StringGeneratorResolver {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for StringGeneratorResolver {}

/// Input passed to custom refresh token formatters.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefreshTokenFormatEncodeInput {
    pub token: String,
    pub session_id: Option<String>,
}

/// Output returned from custom refresh token decoders.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefreshTokenFormatDecodeOutput {
    pub session_id: Option<String>,
    pub token: String,
}

/// Async callbacks that encode and decode refresh tokens returned to OAuth clients.
#[derive(Clone)]
pub struct RefreshTokenFormatter {
    encoder: Arc<dyn Fn(RefreshTokenFormatEncodeInput) -> RefreshTokenEncodeFuture + Send + Sync>,
    decoder: Arc<dyn Fn(String) -> RefreshTokenDecodeFuture + Send + Sync>,
}

impl RefreshTokenFormatter {
    pub fn new<Encode, EncodeFuture, Decode, DecodeFuture>(encoder: Encode, decoder: Decode) -> Self
    where
        Encode: Fn(RefreshTokenFormatEncodeInput) -> EncodeFuture + Send + Sync + 'static,
        EncodeFuture: Future<Output = Result<String, RustAuthError>> + Send + 'static,
        Decode: Fn(String) -> DecodeFuture + Send + Sync + 'static,
        DecodeFuture:
            Future<Output = Result<RefreshTokenFormatDecodeOutput, RustAuthError>> + Send + 'static,
    {
        Self {
            encoder: Arc::new(move |input| Box::pin(encoder(input))),
            decoder: Arc::new(move |token| Box::pin(decoder(token))),
        }
    }

    pub async fn encode(
        &self,
        input: RefreshTokenFormatEncodeInput,
    ) -> Result<String, RustAuthError> {
        (self.encoder)(input).await
    }

    pub async fn decode(
        &self,
        token: String,
    ) -> Result<RefreshTokenFormatDecodeOutput, RustAuthError> {
        (self.decoder)(token).await
    }
}

impl std::fmt::Debug for RefreshTokenFormatter {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("RefreshTokenFormatter(..)")
    }
}

impl PartialEq for RefreshTokenFormatter {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl Eq for RefreshTokenFormatter {}

/// Optional public prefixes applied to generated OAuth secrets before returning them.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OAuthTokenPrefixes {
    pub opaque_access_token: Option<String>,
    pub refresh_token: Option<String>,
    pub client_secret: Option<String>,
}

/// Supported token endpoint grant types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GrantType {
    AuthorizationCode,
    ClientCredentials,
    RefreshToken,
}

impl GrantType {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::AuthorizationCode => "authorization_code",
            Self::ClientCredentials => "client_credentials",
            Self::RefreshToken => "refresh_token",
        }
    }
}

/// OAuth token endpoint client authentication method.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TokenEndpointAuthMethod {
    None,
    ClientSecretBasic,
    ClientSecretPost,
}

impl TokenEndpointAuthMethod {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::ClientSecretBasic => "client_secret_basic",
            Self::ClientSecretPost => "client_secret_post",
        }
    }
}

/// Storage strategy for OAuth provider secrets and tokens.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SecretStorage {
    /// Choose the upstream default from the JWT plugin setting.
    Auto,
    /// Store only a hash of the value.
    Hashed,
    /// Store an encrypted value.
    Encrypted,
}

/// Per-endpoint OAuth provider rate-limit behavior.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OAuthProviderRateLimit {
    /// Use the provider's built-in default for this endpoint.
    Default,
    /// Do not contribute a plugin rate-limit rule for this endpoint.
    Disabled,
    /// Override the built-in default with a custom rule.
    Custom(RateLimitRule),
}

/// Rate-limit settings for OAuth provider endpoints.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OAuthProviderRateLimits {
    pub token: OAuthProviderRateLimit,
    pub authorize: OAuthProviderRateLimit,
    pub introspect: OAuthProviderRateLimit,
    pub revoke: OAuthProviderRateLimit,
    pub register: OAuthProviderRateLimit,
    pub userinfo: OAuthProviderRateLimit,
}

impl Default for OAuthProviderRateLimits {
    fn default() -> Self {
        Self {
            token: OAuthProviderRateLimit::Default,
            authorize: OAuthProviderRateLimit::Default,
            introspect: OAuthProviderRateLimit::Default,
            revoke: OAuthProviderRateLimit::Default,
            register: OAuthProviderRateLimit::Default,
            userinfo: OAuthProviderRateLimit::Default,
        }
    }
}

/// Metadata extension points for MCP discovery responses.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]
pub struct McpMetadataOverrides {
    #[serde(default, skip_serializing_if = "Map::is_empty")]
    pub authorization_server: Map<String, Value>,
    #[serde(default, skip_serializing_if = "Map::is_empty")]
    pub protected_resource: Map<String, Value>,
}

/// MCP profile options. When enabled, the provider exposes MCP resource metadata.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct McpOptions {
    /// Protected resource identifier (RFC 9728). Defaults to the origin of `base_url`.
    pub resource: Option<String>,
    pub metadata: McpMetadataOverrides,
}

/// Resolved MCP options stored on the plugin after validation.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct ResolvedMcpOptions {
    pub resource: Option<String>,
    pub metadata: McpMetadataOverrides,
}

/// User-facing OAuth provider plugin options.
#[derive(Clone)]
pub struct OAuthProviderOptions {
    pub scopes: Vec<String>,
    pub client_registration_default_scopes: Vec<String>,
    pub client_registration_allowed_scopes: Vec<String>,
    pub grant_types: Vec<GrantType>,
    pub login_page: String,
    pub consent_page: String,
    pub signup_page: Option<String>,
    pub select_account_page: Option<String>,
    pub post_login_page: Option<String>,
    pub signup_redirect: Option<PromptRedirectResolver>,
    pub select_account_redirect: Option<PromptRedirectResolver>,
    pub post_login_redirect: Option<PromptRedirectResolver>,
    pub signup_should_redirect: Option<PromptShouldRedirectResolver>,
    pub select_account_should_redirect: Option<PromptShouldRedirectResolver>,
    pub post_login_should_redirect: Option<PromptShouldRedirectResolver>,
    pub consent_reference_id: Option<ClientReferenceResolver>,
    pub code_expires_in: u64,
    pub access_token_expires_in: u64,
    pub m2m_access_token_expires_in: u64,
    pub id_token_expires_in: u64,
    pub refresh_token_expires_in: u64,
    pub client_credential_grant_default_scopes: Vec<String>,
    pub scope_expirations: BTreeMap<String, u64>,
    pub client_registration_client_secret_expiration: Option<u64>,
    pub allow_unauthenticated_client_registration: bool,
    pub allow_dynamic_client_registration: bool,
    pub allow_public_client_prelogin: bool,
    pub cached_trusted_clients: BTreeSet<String>,
    pub client_reference: Option<ClientReferenceResolver>,
    pub client_privileges: Option<ClientPrivilegesResolver>,
    pub custom_access_token_claims: Option<CustomAccessTokenClaimsResolver>,
    pub custom_id_token_claims: Option<CustomIdTokenClaimsResolver>,
    pub custom_token_response_fields: Option<CustomTokenResponseFieldsResolver>,
    pub custom_userinfo_claims: Option<CustomUserInfoClaimsResolver>,
    pub request_uri_resolver: Option<RequestUriResolver>,
    pub prefixes: OAuthTokenPrefixes,
    pub generate_client_id: Option<StringGeneratorResolver>,
    pub generate_client_secret: Option<StringGeneratorResolver>,
    pub generate_opaque_access_token: Option<StringGeneratorResolver>,
    pub generate_refresh_token: Option<StringGeneratorResolver>,
    pub format_refresh_token: Option<RefreshTokenFormatter>,
    pub disable_jwt_plugin: bool,
    pub store_client_secret: SecretStorage,
    pub store_tokens: SecretStorage,
    pub hash_client_secret: Option<ClientSecretHashResolver>,
    pub verify_client_secret_hash: Option<ClientSecretVerifyResolver>,
    pub hash_token: Option<TokenHashResolver>,
    pub pairwise_secret: Option<String>,
    pub advertised_scopes_supported: Vec<String>,
    pub advertised_claims_supported: Vec<String>,
    pub advertised_jwks_uri: Option<String>,
    pub advertised_id_token_signing_algorithms: Vec<String>,
    pub jwks_path: String,
    pub valid_audiences: Vec<String>,
    pub rate_limits: OAuthProviderRateLimits,
    /// Enable MCP protected-resource metadata.
    pub mcp: Option<McpOptions>,
}

impl Default for OAuthProviderOptions {
    fn default() -> Self {
        Self {
            scopes: Vec::new(),
            client_registration_default_scopes: Vec::new(),
            client_registration_allowed_scopes: Vec::new(),
            grant_types: Vec::new(),
            login_page: String::new(),
            consent_page: String::new(),
            signup_page: None,
            select_account_page: None,
            post_login_page: None,
            signup_redirect: None,
            select_account_redirect: None,
            post_login_redirect: None,
            signup_should_redirect: None,
            select_account_should_redirect: None,
            post_login_should_redirect: None,
            consent_reference_id: None,
            code_expires_in: 600,
            access_token_expires_in: 3600,
            m2m_access_token_expires_in: 3600,
            id_token_expires_in: 36000,
            refresh_token_expires_in: 2_592_000,
            client_credential_grant_default_scopes: Vec::new(),
            scope_expirations: BTreeMap::new(),
            client_registration_client_secret_expiration: None,
            allow_unauthenticated_client_registration: false,
            allow_dynamic_client_registration: false,
            allow_public_client_prelogin: false,
            cached_trusted_clients: BTreeSet::new(),
            client_reference: None,
            client_privileges: None,
            custom_access_token_claims: None,
            custom_id_token_claims: None,
            custom_token_response_fields: None,
            custom_userinfo_claims: None,
            request_uri_resolver: None,
            prefixes: OAuthTokenPrefixes::default(),
            generate_client_id: None,
            generate_client_secret: None,
            generate_opaque_access_token: None,
            generate_refresh_token: None,
            format_refresh_token: None,
            disable_jwt_plugin: false,
            store_client_secret: SecretStorage::Auto,
            store_tokens: SecretStorage::Hashed,
            hash_client_secret: None,
            verify_client_secret_hash: None,
            hash_token: None,
            pairwise_secret: None,
            advertised_scopes_supported: Vec::new(),
            advertised_claims_supported: Vec::new(),
            advertised_jwks_uri: None,
            advertised_id_token_signing_algorithms: Vec::new(),
            jwks_path: "/jwks".to_owned(),
            valid_audiences: Vec::new(),
            rate_limits: OAuthProviderRateLimits::default(),
            mcp: None,
        }
    }
}

impl OAuthProviderOptions {
    /// Disable JWT integration (opaque tokens / HS256 id_tokens without the jwt plugin).
    #[must_use]
    pub fn with_external_jwt(mut self) -> Self {
        self.disable_jwt_plugin = true;
        self
    }
}

/// Fully resolved OAuth provider options after upstream-compatible defaults.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedOAuthProviderOptions {
    pub scopes: Vec<String>,
    pub claims: Vec<String>,
    pub client_registration_allowed_scopes: Vec<String>,
    pub grant_types: Vec<GrantType>,
    pub login_page: String,
    pub consent_page: String,
    pub signup_page: Option<String>,
    pub select_account_page: Option<String>,
    pub post_login_page: Option<String>,
    pub signup_redirect: Option<PromptRedirectResolver>,
    pub select_account_redirect: Option<PromptRedirectResolver>,
    pub post_login_redirect: Option<PromptRedirectResolver>,
    pub signup_should_redirect: Option<PromptShouldRedirectResolver>,
    pub select_account_should_redirect: Option<PromptShouldRedirectResolver>,
    pub post_login_should_redirect: Option<PromptShouldRedirectResolver>,
    pub consent_reference_id: Option<ClientReferenceResolver>,
    pub code_expires_in: u64,
    pub access_token_expires_in: u64,
    pub m2m_access_token_expires_in: u64,
    pub id_token_expires_in: u64,
    pub refresh_token_expires_in: u64,
    pub client_credential_grant_default_scopes: Vec<String>,
    pub scope_expirations: BTreeMap<String, u64>,
    pub client_registration_default_scopes: Vec<String>,
    pub client_registration_client_secret_expiration: Option<u64>,
    pub allow_unauthenticated_client_registration: bool,
    pub allow_dynamic_client_registration: bool,
    pub allow_public_client_prelogin: bool,
    pub cached_trusted_clients: BTreeSet<String>,
    pub trusted_client_cache: TrustedClientCache,
    pub client_reference: Option<ClientReferenceResolver>,
    pub client_privileges: Option<ClientPrivilegesResolver>,
    pub custom_access_token_claims: Option<CustomAccessTokenClaimsResolver>,
    pub custom_id_token_claims: Option<CustomIdTokenClaimsResolver>,
    pub custom_token_response_fields: Option<CustomTokenResponseFieldsResolver>,
    pub custom_userinfo_claims: Option<CustomUserInfoClaimsResolver>,
    pub request_uri_resolver: Option<RequestUriResolver>,
    pub prefixes: OAuthTokenPrefixes,
    pub generate_client_id: Option<StringGeneratorResolver>,
    pub generate_client_secret: Option<StringGeneratorResolver>,
    pub generate_opaque_access_token: Option<StringGeneratorResolver>,
    pub generate_refresh_token: Option<StringGeneratorResolver>,
    pub format_refresh_token: Option<RefreshTokenFormatter>,
    pub disable_jwt_plugin: bool,
    pub store_client_secret: SecretStorage,
    pub store_tokens: SecretStorage,
    pub hash_client_secret: Option<ClientSecretHashResolver>,
    pub verify_client_secret_hash: Option<ClientSecretVerifyResolver>,
    pub hash_token: Option<TokenHashResolver>,
    pub pairwise_secret: Option<String>,
    pub advertised_scopes_supported: Vec<String>,
    pub advertised_claims_supported: Vec<String>,
    pub advertised_jwks_uri: Option<String>,
    pub advertised_id_token_signing_algorithms: Vec<String>,
    pub jwks_path: String,
    pub valid_audiences: Vec<String>,
    pub rate_limits: OAuthProviderRateLimits,
    pub mcp: Option<ResolvedMcpOptions>,
}

/// OAuth provider configuration errors.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum OAuthProviderConfigError {
    #[error("login_page is required")]
    MissingLoginPage,
    #[error("consent_page is required")]
    MissingConsentPage,
    #[error("clientRegistrationAllowedScope {0} not found in scopes")]
    UnknownClientRegistrationScope(String),
    #[error("clientCredentialGrantDefaultScopes {0} not found in scopes")]
    UnknownClientCredentialGrantScope(String),
    #[error("advertisedMetadata.scopes_supported {0} not found in scopes")]
    UnknownAdvertisedScope(String),
    #[error(
        "pairwiseSecret must be at least 32 characters long for adequate HMAC-SHA256 security"
    )]
    PairwiseSecretTooShort,
    #[error("refresh_token grant requires authorization_code grant")]
    RefreshTokenRequiresAuthorizationCode,
    #[error("unable to store hashed secrets because id tokens will be signed with secret")]
    HashedClientSecretsRequireJwtPlugin,
    #[error("encryption method not recommended, please use 'hashed' or the 'hash' function")]
    EncryptedClientSecretsWithJwtPlugin,
    #[error("mcp.resource must be a valid absolute URL when set")]
    InvalidMcpResource,
}