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
use std::collections::HashMap;

use reqwest::{
    header::{HeaderMap, HeaderValue},
    StatusCode,
};

use crate::{
    helpers::{convert_json_to, validate_url},
    http::{default_request_interceptor, request, request_async},
    issuer::Issuer,
    jwks::Jwks,
    types::{
        ClientMetadata, ClientOptions, ClientRegistrationOptions, OidcClientError, Request,
        RequestInterceptor, Response,
    },
};

/// # Client instance
pub struct Client {
    /// Client Id
    pub client_id: String,
    /// Client secret
    pub client_secret: Option<String>,
    /// [Registration Access Token](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub registration_access_token: Option<String>,
    /// [Registration Client Uri](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub registration_client_uri: Option<String>,
    /// [Client Id Issued At](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub client_id_issued_at: Option<i64>,
    /// [Secret Expiry](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    /// Epoch Seconds
    pub client_secret_expires_at: Option<i64>,
    /// [Authentication method](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    /// used by the client for authenticating with the OP
    pub token_endpoint_auth_method: String,
    /// [Algorithm](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    /// used for signing the JWT used to authenticate
    /// the client at the token endpoint.
    pub token_endpoint_auth_signing_alg: Option<String>,
    /// [Authentication method](https://www.rfc-editor.org/rfc/rfc8414.html#section-2)
    /// used by the client for introspection endpoint
    pub introspection_endpoint_auth_method: Option<String>,
    /// [Algorithm](https://www.rfc-editor.org/rfc/rfc8414.html#section-2)
    /// used for signing the JWT used to authenticate
    /// the client at the introspection endpoint.
    pub introspection_endpoint_auth_signing_alg: Option<String>,
    /// [Authentication method](https://www.rfc-editor.org/rfc/rfc8414.html#section-2)
    /// used by the client for revocation endpoint
    pub revocation_endpoint_auth_method: Option<String>,
    /// [Algorithm](https://www.rfc-editor.org/rfc/rfc8414.html#section-2)
    /// used for signing the JWT used to authenticate
    /// the client at the revocation endpoint.
    pub revocation_endpoint_auth_signing_alg: Option<String>,
    /// The [redirect uri](https://openid.net/specs/openid-connect-http-redirect-1_0-01.html#rf_prep)
    /// where response will be sent
    pub redirect_uri: Option<String>,
    /// A list of acceptable [redirect uris](https://openid.net/specs/openid-connect-http-redirect-1_0-01.html#rf_prep)
    pub redirect_uris: Option<Vec<String>>,
    /// [Response type](https://openid.net/specs/openid-connect-http-redirect-1_0-01.html#rf_prep) supported by the client.
    pub response_type: Option<String>,
    /// List of [Response type](https://openid.net/specs/openid-connect-http-redirect-1_0-01.html#rf_prep) supported by the client
    pub response_types: Vec<String>,
    /// [Grant Types](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub grant_types: Vec<String>,
    /// [Application Type](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub application_type: Option<String>,
    /// [Contacts](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub contacts: Option<Vec<String>>,
    /// [Client Name](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub client_name: Option<String>,
    /// [Logo Uri](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub logo_uri: Option<String>,
    /// [Client Uri](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub client_uri: Option<String>,
    /// [Policy Uri](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub policy_uri: Option<String>,
    /// [Tos Uri](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub tos_uri: Option<String>,
    /// [Jwks Uri](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub jwks_uri: Option<String>,
    /// [JWKS](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub jwks: Option<Jwks>,
    /// [Sector Identifier Uri](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub sector_identifier_uri: Option<String>,
    /// [Subject Type](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub subject_type: Option<String>,
    /// [Id Token Signed Response Algorithm](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub id_token_signed_response_alg: String,
    /// [Id Token Encrypted Response Algorithm](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub id_token_encrypted_response_alg: Option<String>,
    /// [Id Token Encrypted Response Algorithm](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub id_token_encrypted_response_enc: Option<String>,
    /// [Userinfo Signed Response Algorithm](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub userinfo_signed_response_alg: Option<String>,
    /// [Userinfo Encrypted Response Algorithm](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub userinfo_encrypted_response_alg: Option<String>,
    /// [Userinfo Encrypted Response Algorithm](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub userinfo_encrypted_response_enc: Option<String>,
    /// [Request Object Signing Algorithm](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub request_object_signing_alg: Option<String>,
    /// [Request Object Encryption Algorithm](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub request_object_encryption_alg: Option<String>,
    /// [Request Object Encryption Algorithm](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub request_object_encryption_enc: Option<String>,
    /// [Default Max Age](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub default_max_age: Option<i64>,
    /// [Require Auth Time](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub require_auth_time: Option<bool>,
    /// [Default Acr Values](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub default_acr_values: Option<Vec<String>>,
    /// [Initiate Login Uri](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub initiate_login_uri: Option<String>,
    /// [Request Uris](https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata)
    pub request_uris: Option<String>,
    /// Extra key values
    pub other_fields: HashMap<String, serde_json::Value>,
    pub(crate) private_jwks: Option<Jwks>,
    pub(crate) request_interceptor: RequestInterceptor,
    pub(crate) issuer: Option<Issuer>,
    pub(crate) client_options: Option<ClientOptions>,
}

impl Client {
    pub(crate) fn default() -> Self {
        Self {
            client_id: String::new(),
            client_secret: None,
            registration_access_token: None,
            registration_client_uri: None,
            client_id_issued_at: None,
            client_secret_expires_at: None,
            token_endpoint_auth_method: "client_secret_basic".to_string(),
            token_endpoint_auth_signing_alg: None,
            introspection_endpoint_auth_method: None,
            introspection_endpoint_auth_signing_alg: None,
            revocation_endpoint_auth_method: None,
            revocation_endpoint_auth_signing_alg: None,
            redirect_uri: None,
            redirect_uris: None,
            response_type: None,
            response_types: vec!["code".to_string()],
            grant_types: vec!["authorization_code".to_string()],
            application_type: None,
            contacts: None,
            client_name: None,
            logo_uri: None,
            client_uri: None,
            policy_uri: None,
            tos_uri: None,
            jwks_uri: None,
            jwks: None,
            sector_identifier_uri: None,
            subject_type: None,
            id_token_signed_response_alg: "RS256".to_string(),
            id_token_encrypted_response_alg: None,
            id_token_encrypted_response_enc: None,
            userinfo_signed_response_alg: None,
            userinfo_encrypted_response_alg: None,
            userinfo_encrypted_response_enc: None,
            request_object_signing_alg: None,
            request_object_encryption_alg: None,
            request_object_encryption_enc: None,
            default_max_age: None,
            require_auth_time: None,
            default_acr_values: None,
            initiate_login_uri: None,
            request_uris: None,
            private_jwks: None,
            request_interceptor: Box::new(default_request_interceptor),
            issuer: None,
            other_fields: HashMap::new(),
            client_options: None,
        }
    }

    /// # Internal documentation
    /// This method is used to create an instance of [Client] by:
    ///     - [`Issuer::client()`]
    ///     - [`Client::new_with_interceptor()`]
    ///     - [`Client::from_uri_async()`],
    ///     - [`Client::from_uri()`]
    ///     - [`Client::from_uri_with_interceptor()`]
    ///     - [`Client::from_uri_with_interceptor_async()`]
    ///     - [`Client::register()`]
    ///     - [`Client::register_async()`]
    ///
    /// The `issuer` will be cloned using [`Issuer::clone_with_default_interceptor()`] method
    pub(crate) fn from_internal(
        metadata: ClientMetadata,
        issuer: Option<&Issuer>,
        interceptor: RequestInterceptor,
        jwks: Option<Jwks>,
        options: Option<ClientOptions>,
    ) -> Result<Self, OidcClientError> {
        let mut valid_client_id = true;

        if let Some(client_id) = &metadata.client_id {
            if client_id.is_empty() {
                valid_client_id = false;
            }
        } else {
            valid_client_id = false;
        }

        if !valid_client_id {
            return Err(OidcClientError::new_type_error(
                "client_id is required",
                None,
            ));
        }

        let mut client = Self {
            client_id: metadata.client_id.unwrap(),
            client_secret: metadata.client_secret,
            logo_uri: metadata.logo_uri,
            tos_uri: metadata.tos_uri,
            client_uri: metadata.client_uri,
            policy_uri: metadata.policy_uri,
            sector_identifier_uri: metadata.sector_identifier_uri,
            subject_type: metadata.subject_type,
            registration_access_token: metadata.registration_access_token,
            registration_client_uri: metadata.registration_client_uri,
            client_id_issued_at: metadata.client_id_issued_at,
            client_secret_expires_at: metadata.client_secret_expires_at,
            id_token_encrypted_response_alg: metadata.id_token_encrypted_response_alg,
            id_token_encrypted_response_enc: metadata.id_token_encrypted_response_enc,
            userinfo_signed_response_alg: metadata.userinfo_signed_response_alg,
            userinfo_encrypted_response_alg: metadata.userinfo_encrypted_response_alg,
            userinfo_encrypted_response_enc: metadata.userinfo_encrypted_response_enc,
            request_object_signing_alg: metadata.request_object_signing_alg,
            request_object_encryption_alg: metadata.request_object_encryption_alg,
            request_object_encryption_enc: metadata.request_object_encryption_enc,
            jwks_uri: metadata.jwks_uri,
            jwks: metadata.jwks,
            default_max_age: metadata.default_max_age,
            require_auth_time: metadata.require_auth_time,
            default_acr_values: metadata.default_acr_values,
            initiate_login_uri: metadata.initiate_login_uri,
            request_uris: metadata.request_uris,
            other_fields: metadata.other_fields,
            ..Client::default()
        };

        client.client_options = options;

        if client.jwks_uri.is_some() && client.jwks.is_some() {
            client.jwks = None;
        }

        if metadata.response_type.is_some() && metadata.response_types.is_some() {
            return Err(OidcClientError::new_type_error(
                "provide a response_type or response_types, not both",
                None,
            ));
        }

        if let Some(response_type) = &metadata.response_type {
            client.response_type = Some(response_type.clone());
            client.response_types = vec![response_type.clone()];
        }

        if let Some(response_types) = &metadata.response_types {
            client.response_types = response_types.clone().to_vec();
        }

        if metadata.redirect_uri.is_some() && metadata.redirect_uris.is_some() {
            return Err(OidcClientError::new_type_error(
                "provide a redirect_uri or redirect_uris, not both",
                None,
            ));
        }

        if let Some(redirect_uri) = &metadata.redirect_uri {
            client.redirect_uri = Some(redirect_uri.clone());
            client.redirect_uris = Some(vec![redirect_uri.clone()])
        }

        if let Some(redirect_uris) = &metadata.redirect_uris {
            client.redirect_uris = Some(redirect_uris.clone().to_vec());
        }

        if let Some(team) = metadata.token_endpoint_auth_method {
            client.token_endpoint_auth_method = team;
        } else if let Some(iss) = issuer {
            if let Some(teams) = &iss.token_endpoint_auth_methods_supported {
                if !teams.contains(&client.get_token_endpoint_auth_method())
                    && teams.contains(&"client_secret_post".to_string())
                {
                    client.token_endpoint_auth_method = "client_secret_post".to_string();
                }
            }
        }

        if metadata.token_endpoint_auth_signing_alg.is_some() {
            client.token_endpoint_auth_signing_alg = metadata.token_endpoint_auth_signing_alg;
        }

        client.introspection_endpoint_auth_method = metadata
            .introspection_endpoint_auth_method
            .or(Some(client.get_token_endpoint_auth_method()));

        client.introspection_endpoint_auth_signing_alg = metadata
            .introspection_endpoint_auth_signing_alg
            .or(client.get_token_endpoint_auth_signing_alg());

        client.revocation_endpoint_auth_method = metadata
            .revocation_endpoint_auth_method
            .or(Some(client.get_token_endpoint_auth_method()));

        client.revocation_endpoint_auth_signing_alg = metadata
            .revocation_endpoint_auth_signing_alg
            .or(client.get_token_endpoint_auth_signing_alg());

        if let Some(iss) = issuer {
            Self::assert_signing_alg_values_support(
                &Some(client.token_endpoint_auth_method.clone()),
                &client.token_endpoint_auth_signing_alg,
                &iss.token_endpoint_auth_methods_supported,
                "token",
            )?;

            Self::assert_signing_alg_values_support(
                &client.introspection_endpoint_auth_method,
                &client.introspection_endpoint_auth_signing_alg,
                &iss.introspection_endpoint_auth_methods_supported,
                "introspection",
            )?;

            Self::assert_signing_alg_values_support(
                &client.revocation_endpoint_auth_method,
                &client.revocation_endpoint_auth_signing_alg,
                &iss.revocation_endpoint_auth_methods_supported,
                "revocation",
            )?;

            client.issuer = Some(iss.clone_with_default_interceptor());
        }

        client.set_request_interceptor(interceptor);

        if jwks.is_some() {
            client.private_jwks = jwks;
        }

        if let Some(alg) = metadata.id_token_signed_response_alg {
            client.id_token_signed_response_alg = alg;
        }

        Ok(client)
    }

    fn assert_signing_alg_values_support(
        auth_method: &Option<String>,
        supported_alg: &Option<String>,
        issuer_supported_alg_values: &Option<Vec<String>>,
        endpoint: &str,
    ) -> Result<(), OidcClientError> {
        if let Some(am) = auth_method {
            if am.ends_with("_jwt")
                && supported_alg.is_none()
                && issuer_supported_alg_values.is_none()
            {
                return Err(OidcClientError::new_type_error(
                &format!("{0}_endpoint_auth_signing_alg_values_supported must be configured on the issuer if {0}_endpoint_auth_signing_alg is not defined on a client", endpoint),
                None
            ));
            }
        }
        Ok(())
    }
}

/// Implementation for Client Read Methods
impl Client {
    /// # Creates a client from the [Client Read Endpoint](https://openid.net/specs/openid-connect-registration-1_0.html#ReadRequest)
    /// *This is a blocking method. Checkout [`Client::from_uri_async()`] for async version*
    ///
    /// Creates a [Client] from the Client Read Endpoint.
    ///
    /// - `registration_client_uri` - The client read endpoint
    /// - `registration_access_token` - The access token to be sent with the request
    /// - `jwks` - Private [Jwks] of the client
    /// - `client_options` - The [ClientOptions]
    /// - `issuer` - [Issuer]
    /// - `interceptor` - [RequestInterceptor]
    ///
    /// ### *Example:*
    ///
    /// ```rust
    ///     let _client = Client::from_uri(
    ///         "https://auth.example.com/client/id",
    ///         None,
    ///         None,
    ///         None,
    ///         None,
    ///         None,
    ///     )
    ///     .unwrap();
    /// ```
    ///
    /// ### *Example: with all params*
    ///
    /// ```rust
    ///     let jwk = Jwk::generate_rsa_key(2048).unwrap();
    ///
    ///     let jwks = Jwks::from(vec![jwk]);
    ///
    ///     let client_options = ClientOptions {
    ///         additional_authorized_parties: Some(vec!["authParty".to_string()]),
    ///     };
    ///
    ///     let interceptor = |request: &Request| {
    ///         let mut headers = HeaderMap::new();
    ///
    ///         if request.url.contains("userinfor") || request.url.contains("token") {
    ///             headers.append("foo", HeaderValue::from_static("bar"));
    ///         }
    ///
    ///         RequestOptions {
    ///             headers,
    ///             timeout: Duration::from_millis(10000),
    ///         }
    ///     };
    ///
    ///     let issuer = Issuer::discover("https://auth.example.com", Some(Box::new(interceptor))).unwrap();
    ///
    ///     let _client = Client::from_uri(
    ///         "https://auth.example.com/client/id",
    ///         Some("token".to_string()),
    ///         Some(jwks),
    ///         Some(client_options),
    ///         Some(&issuer),
    ///         Some(Box::new(interceptor)),
    ///     )
    ///     .unwrap();
    /// ```
    ///
    pub fn from_uri(
        registration_client_uri: &str,
        registration_access_token: Option<String>,
        jwks: Option<Jwks>,
        client_options: Option<ClientOptions>,
        issuer: Option<&Issuer>,
        interceptor: Option<RequestInterceptor>,
    ) -> Result<Self, OidcClientError> {
        let mut request_interceptor = interceptor.unwrap_or(Box::new(default_request_interceptor));

        Self::jwks_only_private_keys_validation(jwks.as_ref())?;

        let req = Self::build_from_uri_request(
            registration_client_uri,
            registration_access_token.as_ref(),
        )?;

        let res = request(req, &mut request_interceptor)?;

        Self::process_from_uri_response(res, issuer, request_interceptor, jwks, client_options)
    }

    /// # Creates a client from the [Client Read Endpoint](https://openid.net/specs/openid-connect-registration-1_0.html#ReadRequest)
    /// *This is an async method. Checkout [`Client::from_uri()`] for the blocking version.*
    ///
    /// Creates a [Client] from the Client read endpoint.
    ///
    /// - `registration_client_uri` - The client read endpoint
    /// - `registration_access_token` - The access token to be sent with the request
    /// - `jwks` - Private [Jwks] of the client
    /// - `client_options` - The [ClientOptions]
    /// - `issuer` - [Issuer]
    /// - `interceptor` - [RequestInterceptor]
    ///
    /// ### *Example:*
    ///
    /// ```rust
    ///     let _client = Client::from_uri_async(
    ///         "https://auth.example.com/client/id",
    ///         None,
    ///         None,
    ///         None,
    ///         None,
    ///         None,
    ///     )
    ///     .await
    ///     .unwrap();
    /// ```
    ///
    /// ### *Example: with all params*
    ///
    /// ```rust
    ///     let jwk = Jwk::generate_rsa_key(2048).unwrap();
    ///
    ///     let jwks = Jwks::from(vec![jwk]);
    ///
    ///     let client_options = ClientOptions {
    ///         additional_authorized_parties: Some(vec!["authParty".to_string()]),
    ///     };
    ///
    ///     let interceptor = |request: &Request| {
    ///         let mut headers = HeaderMap::new();
    ///
    ///         if request.url.contains("userinfor") || request.url.contains("token") {
    ///             headers.append("foo", HeaderValue::from_static("bar"));
    ///         }
    ///
    ///         RequestOptions {
    ///             headers,
    ///             timeout: Duration::from_millis(10000),
    ///         }
    ///     };
    ///
    ///     let issuer = Issuer::discover_async("https://auth.example.com", Some(Box::new(interceptor)))
    ///         .await
    ///         .unwrap();
    ///
    ///     let _client = Client::from_uri_async(
    ///         "https://auth.example.com/client/id",
    ///         Some("token".to_string()),
    ///         Some(jwks),
    ///         Some(client_options),
    ///         Some(&issuer),
    ///         Some(Box::new(interceptor)),
    ///     )
    ///     .await
    ///     .unwrap();
    ///```
    pub async fn from_uri_async(
        registration_client_uri: &str,
        registration_access_token: Option<String>,
        jwks: Option<Jwks>,
        client_options: Option<ClientOptions>,
        issuer: Option<&Issuer>,
        interceptor: Option<RequestInterceptor>,
    ) -> Result<Self, OidcClientError> {
        let mut request_interceptor = interceptor.unwrap_or(Box::new(default_request_interceptor));

        Self::jwks_only_private_keys_validation(jwks.as_ref())?;

        let req = Self::build_from_uri_request(
            registration_client_uri,
            registration_access_token.as_ref(),
        )?;

        let res = request_async(req, &mut request_interceptor).await?;

        Self::process_from_uri_response(res, issuer, request_interceptor, jwks, client_options)
    }
}

/// Implementations for Dynamic Client Registration
impl Client {
    /// # Dynamic Client Registration
    /// *This is a blocking method. Checkout [`Client::register_async()`] for async version.*
    ///
    /// Attempts a Dynamic Client Registration using the Issuer's `registration_endpoint`
    ///
    /// - `issuer` - The [Issuer] client should be registered to.
    /// - `client_metadata` - The [ClientMetadata] to be sent using the registration request.
    /// - `register_options` - [ClientRegistrationOptions]
    /// - `interceptor` - [RequestInterceptor]
    ///
    /// ### *Example:*
    ///
    /// ```rust
    ///     let issuer = Issuer::discover("https://auth.example.com", None).unwrap();
    ///
    ///     let metadata = ClientMetadata {
    ///         client_id: Some("identifier".to_string()),
    ///         ..ClientMetadata::default()
    ///     };
    ///
    ///     let _client = Client::register(&issuer, metadata, None, None).unwrap();
    /// ```
    ///
    /// ### *Example: with all params*
    ///
    /// ```rust
    ///     let interceptor = |request: &Request| {
    ///         let mut headers = HeaderMap::new();
    ///
    ///         if request.url.contains("token") {
    ///             headers.append("foo", HeaderValue::from_static("bar"));
    ///         }
    ///
    ///         RequestOptions {
    ///             headers,
    ///             timeout: Duration::from_millis(10000),
    ///         }
    ///     };
    ///
    ///     let issuer = Issuer::discover("https://auth.example.com", Some(Box::new(interceptor))).unwrap();
    ///
    ///     let metadata = ClientMetadata {
    ///         client_id: Some("identifier".to_string()),
    ///         ..ClientMetadata::default()
    ///     };
    ///
    ///     let jwk = Jwk::generate_rsa_key(2048).unwrap();
    ///
    ///     let registration_options = ClientRegistrationOptions {
    ///         initial_access_token: Some("initial_access_token".to_string()),
    ///         jwks: Some(Jwks::from(vec![jwk])),
    ///         client_options: Default::default(),
    ///     };
    ///
    ///     let _client = Client::register(
    ///         &issuer,
    ///         metadata,
    ///         Some(registration_options),
    ///         Some(Box::new(interceptor)),
    ///     )
    ///     .unwrap();
    /// ```
    ///
    pub fn register(
        issuer: &Issuer,
        mut client_metadata: ClientMetadata,
        register_options: Option<ClientRegistrationOptions>,
        interceptor: Option<RequestInterceptor>,
    ) -> Result<Self, OidcClientError> {
        let (initial_access_token, jwks, client_options, registration_endpoint) =
            Self::registration_config_validation(issuer, &mut client_metadata, register_options)?;

        let req = Self::build_register_request(
            &registration_endpoint,
            client_metadata,
            initial_access_token,
        )?;

        let mut request_interceptor: RequestInterceptor =
            interceptor.unwrap_or(Box::new(default_request_interceptor));

        let response = request(req, &mut request_interceptor)?;

        Self::process_register_response(response, issuer, request_interceptor, jwks, client_options)
    }

    /// # Dynamic Client Registration
    /// *This is an async method. Checkout [`Client::register()`] for the blocking version.*
    ///
    /// Attempts a Dynamic Client Registration using the Issuer's `registration_endpoint`
    ///
    /// - `issuer` - The [Issuer] client should be registered to.
    /// - `client_metadata` - The [ClientMetadata] to be sent using the registration request.
    /// - `register_options` - [ClientRegistrationOptions]
    /// - `interceptor` - [RequestInterceptor]
    ///
    /// ### *Example:*
    ///
    /// ```rust
    ///     let issuer = Issuer::discover_async("https://auth.example.com", None)
    ///         .await
    ///         .unwrap();
    ///
    ///     let metadata = ClientMetadata {
    ///         client_id: Some("identifier".to_string()),
    ///         ..ClientMetadata::default()
    ///     };
    ///
    ///     let _client = Client::register_async(&issuer, metadata, None, None)
    ///         .await
    ///         .unwrap();
    /// ```
    ///
    /// ### *Example: with all params*
    ///
    /// ```rust
    ///     let interceptor = |request: &Request| {
    ///         let mut headers = HeaderMap::new();
    ///
    ///         if request.url.contains("token") {
    ///             headers.append("foo", HeaderValue::from_static("bar"));
    ///         }
    ///
    ///         RequestOptions {
    ///             headers,
    ///             timeout: Duration::from_millis(10000),
    ///         }
    ///     };
    ///
    ///     let issuer = Issuer::discover_async("https://auth.example.com", Some(Box::new(interceptor)))
    ///         .await
    ///         .unwrap();
    ///
    ///     let metadata = ClientMetadata {
    ///         client_id: Some("identifier".to_string()),
    ///         ..ClientMetadata::default()
    ///     };
    ///
    ///     let jwk = Jwk::generate_rsa_key(2048).unwrap();
    ///
    ///     let registration_options = ClientRegistrationOptions {
    ///         initial_access_token: Some("initial_access_token".to_string()),
    ///         jwks: Some(Jwks::from(vec![jwk])),
    ///         client_options: Default::default(),
    ///     };
    ///
    ///     let _client = Client::register_async(
    ///         &issuer,
    ///         metadata,
    ///         Some(registration_options),
    ///         Some(Box::new(interceptor)),
    ///     )
    ///     .await
    ///     .unwrap();
    /// ```
    ///
    pub async fn register_async(
        issuer: &Issuer,
        mut client_metadata: ClientMetadata,
        register_options: Option<ClientRegistrationOptions>,
        interceptor: Option<RequestInterceptor>,
    ) -> Result<Self, OidcClientError> {
        let (initial_access_token, jwks, client_options, registration_endpoint) =
            Self::registration_config_validation(issuer, &mut client_metadata, register_options)?;

        let req = Self::build_register_request(
            &registration_endpoint,
            client_metadata,
            initial_access_token,
        )?;

        let mut request_interceptor: RequestInterceptor =
            interceptor.unwrap_or(Box::new(default_request_interceptor));

        let response = request_async(req, &mut request_interceptor).await?;

        Self::process_register_response(response, issuer, request_interceptor, jwks, client_options)
    }
}

impl Client {
    /// Returs error if JWKS only has private keys
    pub(crate) fn jwks_only_private_keys_validation(
        jwks: Option<&Jwks>,
    ) -> Result<(), OidcClientError> {
        if let Some(jwks) = jwks {
            if !jwks.is_only_private_keys() || jwks.has_oct_keys() {
                return Err(OidcClientError::new_error(
                    "jwks must only contain private keys",
                    None,
                ));
            }
        }
        Ok(())
    }

    // Client read response

    /// Request builder for the `from_uri_internal` methods
    fn build_from_uri_request(
        registration_client_uri: &str,
        registration_access_token: Option<&String>,
    ) -> Result<Request, OidcClientError> {
        let url = validate_url(registration_client_uri)?;

        let mut headers = HeaderMap::new();
        headers.insert("Accept", HeaderValue::from_static("application/json"));

        if let Some(rat) = registration_access_token {
            let header_value = match HeaderValue::from_str(&format!("Bearer {}", rat)) {
                Ok(v) => v,
                Err(_) => {
                    return Err(OidcClientError::new_type_error(
                        &format!("registration_access_token {} is invalid", rat),
                        None,
                    ))
                }
            };
            headers.insert("Authorization", header_value);
        }

        Ok(Request {
            url: url.to_string(),
            method: reqwest::Method::GET,
            expect_body: true,
            expected: StatusCode::OK,
            bearer: true,
            headers,
            ..Request::default()
        })
    }

    /// Response processor for the `from_uri_internal` methods
    fn process_from_uri_response(
        response: Response,
        issuer: Option<&Issuer>,
        interceptor: RequestInterceptor,
        jwks: Option<Jwks>,
        client_options: Option<ClientOptions>,
    ) -> Result<Self, OidcClientError> {
        let client_metadata = convert_json_to::<ClientMetadata>(response.body.as_ref().unwrap())
            .map_err(|_| {
                OidcClientError::new_op_error(
                    "invalid client metadata".to_string(),
                    Some("error while deserializing".to_string()),
                    None,
                    None,
                    None,
                    Some(response),
                )
            })?;

        Self::from_internal(client_metadata, issuer, interceptor, jwks, client_options)
    }

    // Registration helpers

    /// Validates registration configuration
    #[allow(clippy::type_complexity)]
    fn registration_config_validation(
        issuer: &Issuer,
        mut client_metadata: &mut ClientMetadata,
        register_options: Option<ClientRegistrationOptions>,
    ) -> Result<(Option<String>, Option<Jwks>, Option<ClientOptions>, String), OidcClientError>
    {
        if issuer.registration_endpoint.is_none() {
            return Err(OidcClientError::new_type_error(
                "registration_endpoint must be configured on the issuer",
                None,
            ));
        }

        let mut initial_access_token: Option<String> = None;
        let mut jwks: Option<Jwks> = None;
        let mut client_options: Option<ClientOptions> = None;

        if let Some(options) = &register_options {
            initial_access_token = options.initial_access_token.clone();
            jwks = options.jwks.clone();
            client_options = Some(options.client_options.clone());

            if options.jwks.is_some()
                && client_metadata.jwks_uri.is_none()
                && client_metadata.jwks.is_none()
            {
                if let Some(jwks) = options.jwks.as_ref() {
                    client_metadata.jwks = Some(jwks.get_public_jwks());
                }
            }
        }

        Self::jwks_only_private_keys_validation(jwks.as_ref())?;

        Ok((
            initial_access_token,
            jwks,
            client_options,
            issuer.registration_endpoint.clone().unwrap(),
        ))
    }

    /// Internal registration request builder
    fn build_register_request(
        registration_endpoint: &str,
        registration_metadata: ClientMetadata,
        initial_access_token: Option<String>,
    ) -> Result<Request, OidcClientError> {
        let url = validate_url(registration_endpoint)?;

        let body = serde_json::to_value(registration_metadata).map_err(|_| {
            OidcClientError::new_error("client metadata is an invalid json format", None)
        })?;

        let mut headers = HeaderMap::new();
        headers.insert("Accept", HeaderValue::from_static("application/json"));

        if let Some(iat) = initial_access_token {
            let header_value = match HeaderValue::from_str(&format!("Bearer {}", iat)) {
                Ok(v) => v,
                Err(_) => {
                    return Err(OidcClientError::new_error(
                        "access token is invalid. wtf?",
                        None,
                    ))
                }
            };
            headers.insert("Authorization", header_value);
        }

        Ok(Request {
            url: url.to_string(),
            method: reqwest::Method::POST,
            expect_body: true,
            expected: StatusCode::CREATED,
            bearer: true,
            headers,
            json: Some(body),
            response_type: Some("json".to_string()),
            ..Request::default()
        })
    }

    /// Processes registration response and creates a client
    fn process_register_response(
        response: Response,
        issuer: &Issuer,
        interceptor: RequestInterceptor,
        jwks: Option<Jwks>,
        client_options: Option<ClientOptions>,
    ) -> Result<Self, OidcClientError> {
        let client_metadata = convert_json_to::<ClientMetadata>(response.body.as_ref().unwrap())
            .map_err(|_| {
                OidcClientError::new_op_error(
                    "invalid client metadata".to_string(),
                    None,
                    None,
                    None,
                    None,
                    Some(response),
                )
            })?;

        Self::from_internal(
            client_metadata,
            Some(issuer),
            interceptor,
            jwks,
            client_options,
        )
    }
}

/// Getter & Setter method implementations for Client
impl Client {
    /// Get client id
    pub fn get_client_id(&self) -> String {
        self.client_id.clone()
    }

    /// Get client secret
    pub fn get_client_secret(&self) -> Option<String> {
        self.client_secret.clone()
    }

    /// Get grant types
    pub fn get_grant_types(&self) -> Vec<String> {
        self.grant_types.to_vec()
    }

    /// Get registration access token
    pub fn get_registration_access_token(&self) -> Option<String> {
        self.registration_access_token.clone()
    }

    /// Get registration client uri
    pub fn get_registration_client_uri(&self) -> Option<String> {
        self.registration_client_uri.clone()
    }

    /// Get client id issued at. Epoch(seconds)
    pub fn get_client_id_issued_at(&self) -> Option<i64> {
        self.client_id_issued_at
    }

    /// Get client secret exprires at. Epoch(seconds)
    pub fn get_client_secret_expires_at(&self) -> Option<i64> {
        self.client_secret_expires_at
    }

    /// Get id token signed response algorithm
    pub fn get_id_token_signed_response_alg(&self) -> String {
        self.id_token_signed_response_alg.clone()
    }

    /// Get response types. See [ClientMetadata].
    pub fn get_response_types(&self) -> Vec<String> {
        self.response_types.to_vec()
    }

    /// Get token endpoint authentication method. See [ClientMetadata].
    pub fn get_token_endpoint_auth_method(&self) -> String {
        self.token_endpoint_auth_method.clone()
    }

    /// Get token endpoint authentication signing alg. See [ClientMetadata].
    pub fn get_token_endpoint_auth_signing_alg(&self) -> Option<String> {
        self.token_endpoint_auth_signing_alg.clone()
    }

    /// Get introspection endpoint authentication method. See [ClientMetadata].
    pub fn get_introspection_endpoint_auth_method(&self) -> Option<String> {
        self.introspection_endpoint_auth_method.clone()
    }

    /// Get introspection endpoint authentication signing alg. See [ClientMetadata].
    pub fn get_introspection_endpoint_auth_signing_alg(&self) -> Option<String> {
        self.introspection_endpoint_auth_signing_alg.clone()
    }

    /// Get revocation endpoint authentication method. See [ClientMetadata].
    pub fn get_revocation_endpoint_auth_method(&self) -> Option<String> {
        self.revocation_endpoint_auth_method.clone()
    }

    /// Get revocation endpoint authentication signing alg. See [ClientMetadata].
    pub fn get_revocation_endpoint_auth_signing_alg(&self) -> Option<String> {
        self.revocation_endpoint_auth_signing_alg.clone()
    }

    /// Gets a field from `other_fields`
    pub fn get_field(&self, key: &str) -> Option<&serde_json::Value> {
        self.other_fields.get(key)
    }

    /// Get redirect uri. See [ClientMetadata].
    pub fn get_redirect_uri(&self) -> Option<String> {
        self.redirect_uri.clone()
    }

    /// Get redirect uris. See [ClientMetadata].
    pub fn get_redirect_uris(&self) -> Option<Vec<String>> {
        Some(self.redirect_uris.clone()?.to_vec())
    }

    /// Get response type
    pub fn get_response_type(&self) -> Option<String> {
        self.response_type.clone()
    }

    /// Get application type
    pub fn get_application_type(&self) -> Option<String> {
        self.application_type.clone()
    }

    /// Get contacts
    pub fn get_contacts(&self) -> Option<Vec<String>> {
        Some(self.contacts.clone()?.to_vec())
    }

    /// Get client name
    pub fn get_client_name(&self) -> Option<String> {
        self.client_name.clone()
    }

    /// Get logo uri
    pub fn get_logo_uri(&self) -> Option<String> {
        self.logo_uri.clone()
    }

    /// Get client uri
    pub fn get_client_uri(&self) -> Option<String> {
        self.client_uri.clone()
    }

    /// Get policy uri
    pub fn get_policy_uri(&self) -> Option<String> {
        self.policy_uri.clone()
    }

    /// Get tos uri
    pub fn get_tos_uri(&self) -> Option<String> {
        self.tos_uri.clone()
    }

    /// Get jwks uri
    pub fn get_jwks_uri(&self) -> Option<String> {
        self.jwks_uri.clone()
    }

    /// Get sector identifier uri
    pub fn get_sector_identifier_uri(&self) -> Option<String> {
        self.sector_identifier_uri.clone()
    }

    /// Get subject type
    pub fn get_subject_type(&self) -> Option<String> {
        self.subject_type.clone()
    }

    /// Get id token encrypted response algorithm
    pub fn get_id_token_encrypted_response_alg(&self) -> Option<String> {
        self.id_token_encrypted_response_alg.clone()
    }

    /// Get id token encrypted response algorithm
    pub fn get_id_token_encrypted_response_enc(&self) -> Option<String> {
        self.id_token_encrypted_response_enc.clone()
    }

    /// Get userinfo signed response algorithm
    pub fn get_userinfo_signed_response_alg(&self) -> Option<String> {
        self.userinfo_signed_response_alg.clone()
    }

    /// Get userinfo encrypted response algorithm
    pub fn get_userinfo_encrypted_response_alg(&self) -> Option<String> {
        self.userinfo_encrypted_response_alg.clone()
    }

    /// Get userinfo encrypted response algorithm
    pub fn get_userinfo_encrypted_response_enc(&self) -> Option<String> {
        self.userinfo_encrypted_response_enc.clone()
    }

    /// Get request object signing algorithm
    pub fn get_request_object_signing_alg(&self) -> Option<String> {
        self.request_object_signing_alg.clone()
    }

    /// Get request object encryption algorithm
    pub fn get_request_object_encryption_alg(&self) -> Option<String> {
        self.request_object_encryption_alg.clone()
    }

    /// Get request object encryption algorithm
    pub fn get_request_object_encryption_enc(&self) -> Option<String> {
        self.request_object_encryption_enc.clone()
    }

    /// Get default max age
    pub fn get_default_max_age(&self) -> Option<i64> {
        self.default_max_age
    }

    /// Get require auth time
    pub fn get_require_auth_time(&self) -> Option<bool> {
        self.require_auth_time
    }

    /// Get default acr values
    pub fn get_default_acr_values(&self) -> Option<Vec<String>> {
        Some(self.default_acr_values.clone()?.to_vec())
    }

    /// Get initiate login uri
    pub fn get_initiate_login_uri(&self) -> Option<String> {
        self.initiate_login_uri.clone()
    }

    /// Get request uris
    pub fn get_request_uris(&self) -> Option<String> {
        self.request_uris.clone()
    }

    /// Get jwks
    pub fn get_jwks(&self) -> Option<Jwks> {
        self.jwks.clone()
    }

    /// Gets the issuer that the client was created with.
    pub fn get_issuer(&self) -> Option<&Issuer> {
        self.issuer.as_ref()
    }

    /// Gets the private jwks
    pub fn get_private_jwks(&self) -> Option<Jwks> {
        self.private_jwks.clone()
    }

    /// Gets the client options the client was created with
    pub fn get_client_options(&self) -> Option<ClientOptions> {
        self.client_options.clone()
    }

    pub(crate) fn set_request_interceptor(&mut self, interceptor: RequestInterceptor) {
        self.request_interceptor = interceptor;
    }
}

impl std::fmt::Debug for Client {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("client_id", &self.client_id)
            .field("client_secret", &self.client_secret)
            .field("grant_types", &self.grant_types)
            .field(
                "id_token_signed_response_alg",
                &self.id_token_signed_response_alg,
            )
            .field("response_types", &self.response_types)
            .field(
                "token_endpoint_auth_method",
                &self.token_endpoint_auth_method,
            )
            .field(
                "token_endpoint_auth_signing_alg",
                &self.token_endpoint_auth_signing_alg,
            )
            .field(
                "introspection_endpoint_auth_method",
                &self.introspection_endpoint_auth_method,
            )
            .field(
                "introspection_endpoint_auth_signing_alg",
                &self.introspection_endpoint_auth_signing_alg,
            )
            .field(
                "revocation_endpoint_auth_method",
                &self.revocation_endpoint_auth_method,
            )
            .field(
                "revocation_endpoint_auth_signing_alg",
                &self.revocation_endpoint_auth_signing_alg,
            )
            .field("redirect_uri", &self.redirect_uri)
            .field("redirect_uris", &self.redirect_uris)
            .field("response_type", &self.response_type)
            .field(
                "request_interceptor",
                &"fn(&RequestOptions) -> RequestOptions",
            )
            .field("jwks", &self.jwks)
            .field("other_fields", &self.other_fields)
            .field("issuer", &self.issuer)
            .finish()
    }
}

#[cfg(test)]
#[path = "../tests/client_test.rs"]
mod client_test;