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
// Copyright 2022 Kévin Commaille.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! The error types used in this crate.

use std::{str::Utf8Error, sync::Arc};

use headers::authorization::InvalidBearerToken;
use http::{header::ToStrError, StatusCode};
use mas_http::{catch_http_codes, form_urlencoded_request, json_request, json_response};
use mas_jose::{
    claims::ClaimError,
    jwa::InvalidAlgorithm,
    jwt::{JwtDecodeError, JwtSignatureError, NoKeyWorked},
};
use oauth2_types::{
    errors::ClientErrorCode, oidc::ProviderMetadataVerificationError, pkce::CodeChallengeError,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;
pub use tower::BoxError;

/// All possible errors when using this crate.
#[derive(Debug, Error)]
#[error(transparent)]
pub enum Error {
    /// An error occurred fetching provider metadata.
    Discovery(#[from] DiscoveryError),

    /// An error occurred fetching the provider JWKS.
    Jwks(#[from] JwksError),

    /// An error occurred during client registration.
    Registration(#[from] RegistrationError),

    /// An error occurred building the authorization URL.
    Authorization(#[from] AuthorizationError),

    /// An error occurred exchanging an authorization code for an access token.
    TokenAuthorizationCode(#[from] TokenAuthorizationCodeError),

    /// An error occurred requesting an access token with client credentials.
    TokenClientCredentials(#[from] TokenRequestError),

    /// An error occurred refreshing an access token.
    TokenRefresh(#[from] TokenRefreshError),

    /// An error occurred revoking a token.
    TokenRevoke(#[from] TokenRevokeError),

    /// An error occurred requesting user info.
    UserInfo(#[from] UserInfoError),

    /// An error occurred introspecting a token.
    Introspection(#[from] IntrospectionError),

    /// An error occurred building the account management URL.
    AccountManagement(#[from] AccountManagementError),
}

/// All possible errors when fetching provider metadata.
#[derive(Debug, Error)]
pub enum DiscoveryError {
    /// An error occurred building the request's URL.
    #[error(transparent)]
    IntoUrl(#[from] url::ParseError),

    /// An error occurred building the request.
    #[error(transparent)]
    IntoHttp(#[from] http::Error),

    /// The server returned an HTTP error status code.
    #[error(transparent)]
    Http(#[from] HttpError),

    /// An error occurred deserializing the response.
    #[error(transparent)]
    FromJson(#[from] serde_json::Error),

    /// An error occurred validating the metadata.
    #[error(transparent)]
    Validation(#[from] ProviderMetadataVerificationError),

    /// An error occurred sending the request.
    #[error(transparent)]
    Service(BoxError),

    /// Discovery is disabled for this provider.
    #[error("Discovery is disabled for this provider")]
    Disabled,
}

impl<S> From<json_response::Error<S>> for DiscoveryError
where
    S: Into<DiscoveryError>,
{
    fn from(err: json_response::Error<S>) -> Self {
        match err {
            json_response::Error::Deserialize { inner } => inner.into(),
            json_response::Error::Service { inner } => inner.into(),
        }
    }
}

impl<S> From<catch_http_codes::Error<S, Option<ErrorBody>>> for DiscoveryError
where
    S: Into<BoxError>,
{
    fn from(err: catch_http_codes::Error<S, Option<ErrorBody>>) -> Self {
        match err {
            catch_http_codes::Error::HttpError { status_code, inner } => {
                Self::Http(HttpError::new(status_code, inner))
            }
            catch_http_codes::Error::Service { inner } => Self::Service(inner.into()),
        }
    }
}

/// All possible errors when registering the client.
#[derive(Debug, Error)]
pub enum RegistrationError {
    /// An error occurred building the request.
    #[error(transparent)]
    IntoHttp(#[from] http::Error),

    /// An error occurred serializing the request or deserializing the response.
    #[error(transparent)]
    Json(#[from] serde_json::Error),

    /// The server returned an HTTP error status code.
    #[error(transparent)]
    Http(#[from] HttpError),

    /// No client secret was received although one was expected because of the
    /// authentication method.
    #[error("missing client secret in response")]
    MissingClientSecret,

    /// An error occurred sending the request.
    #[error(transparent)]
    Service(BoxError),
}

impl<S> From<json_request::Error<S>> for RegistrationError
where
    S: Into<RegistrationError>,
{
    fn from(err: json_request::Error<S>) -> Self {
        match err {
            json_request::Error::Serialize { inner } => inner.into(),
            json_request::Error::Service { inner } => inner.into(),
        }
    }
}

impl<S> From<json_response::Error<S>> for RegistrationError
where
    S: Into<RegistrationError>,
{
    fn from(err: json_response::Error<S>) -> Self {
        match err {
            json_response::Error::Deserialize { inner } => inner.into(),
            json_response::Error::Service { inner } => inner.into(),
        }
    }
}

impl<S> From<catch_http_codes::Error<S, Option<ErrorBody>>> for RegistrationError
where
    S: Into<BoxError>,
{
    fn from(err: catch_http_codes::Error<S, Option<ErrorBody>>) -> Self {
        match err {
            catch_http_codes::Error::HttpError { status_code, inner } => {
                HttpError::new(status_code, inner).into()
            }
            catch_http_codes::Error::Service { inner } => Self::Service(inner.into()),
        }
    }
}

/// All possible errors when making a pushed authorization request.
#[derive(Debug, Error)]
pub enum PushedAuthorizationError {
    /// An error occurred serializing the request.
    #[error(transparent)]
    UrlEncoded(#[from] serde_urlencoded::ser::Error),

    /// An error occurred building the request.
    #[error(transparent)]
    IntoHttp(#[from] http::Error),

    /// An error occurred adding the client credentials to the request.
    #[error(transparent)]
    Credentials(#[from] CredentialsError),

    /// The server returned an HTTP error status code.
    #[error(transparent)]
    Http(#[from] HttpError),

    /// An error occurred deserializing the response.
    #[error(transparent)]
    Json(#[from] serde_json::Error),

    /// An error occurred sending the request.
    #[error(transparent)]
    Service(BoxError),
}

impl<S> From<form_urlencoded_request::Error<S>> for PushedAuthorizationError
where
    S: Into<PushedAuthorizationError>,
{
    fn from(err: form_urlencoded_request::Error<S>) -> Self {
        match err {
            form_urlencoded_request::Error::Serialize { inner } => inner.into(),
            form_urlencoded_request::Error::Service { inner } => inner.into(),
        }
    }
}

impl<S> From<json_response::Error<S>> for PushedAuthorizationError
where
    S: Into<PushedAuthorizationError>,
{
    fn from(err: json_response::Error<S>) -> Self {
        match err {
            json_response::Error::Deserialize { inner } => inner.into(),
            json_response::Error::Service { inner } => inner.into(),
        }
    }
}

impl<S> From<catch_http_codes::Error<S, Option<ErrorBody>>> for PushedAuthorizationError
where
    S: Into<BoxError>,
{
    fn from(err: catch_http_codes::Error<S, Option<ErrorBody>>) -> Self {
        match err {
            catch_http_codes::Error::HttpError { status_code, inner } => {
                HttpError::new(status_code, inner).into()
            }
            catch_http_codes::Error::Service { inner } => Self::Service(inner.into()),
        }
    }
}

/// All possible errors when authorizing the client.
#[derive(Debug, Error)]
pub enum AuthorizationError {
    /// An error occurred constructing the PKCE code challenge.
    #[error(transparent)]
    Pkce(#[from] CodeChallengeError),

    /// An error occurred serializing the request.
    #[error(transparent)]
    UrlEncoded(#[from] serde_urlencoded::ser::Error),

    /// An error occurred making the PAR request.
    #[error(transparent)]
    PushedAuthorization(#[from] PushedAuthorizationError),
}

/// All possible errors when requesting an access token.
#[derive(Debug, Error)]
pub enum TokenRequestError {
    /// An error occurred building the request.
    #[error(transparent)]
    IntoHttp(#[from] http::Error),

    /// An error occurred adding the client credentials to the request.
    #[error(transparent)]
    Credentials(#[from] CredentialsError),

    /// An error occurred serializing the request.
    #[error(transparent)]
    UrlEncoded(#[from] serde_urlencoded::ser::Error),

    /// The server returned an HTTP error status code.
    #[error(transparent)]
    Http(#[from] HttpError),

    /// An error occurred deserializing the response.
    #[error(transparent)]
    Json(#[from] serde_json::Error),

    /// An error occurred sending the request.
    #[error(transparent)]
    Service(BoxError),
}

impl<S> From<form_urlencoded_request::Error<S>> for TokenRequestError
where
    S: Into<TokenRequestError>,
{
    fn from(err: form_urlencoded_request::Error<S>) -> Self {
        match err {
            form_urlencoded_request::Error::Serialize { inner } => inner.into(),
            form_urlencoded_request::Error::Service { inner } => inner.into(),
        }
    }
}

impl<S> From<json_response::Error<S>> for TokenRequestError
where
    S: Into<TokenRequestError>,
{
    fn from(err: json_response::Error<S>) -> Self {
        match err {
            json_response::Error::Deserialize { inner } => inner.into(),
            json_response::Error::Service { inner } => inner.into(),
        }
    }
}

impl<S> From<catch_http_codes::Error<S, Option<ErrorBody>>> for TokenRequestError
where
    S: Into<BoxError>,
{
    fn from(err: catch_http_codes::Error<S, Option<ErrorBody>>) -> Self {
        match err {
            catch_http_codes::Error::HttpError { status_code, inner } => {
                HttpError::new(status_code, inner).into()
            }
            catch_http_codes::Error::Service { inner } => Self::Service(inner.into()),
        }
    }
}

/// All possible errors when exchanging a code for an access token.
#[derive(Debug, Error)]
pub enum TokenAuthorizationCodeError {
    /// An error occurred requesting the access token.
    #[error(transparent)]
    Token(#[from] TokenRequestError),

    /// An error occurred validating the ID Token.
    #[error(transparent)]
    IdToken(#[from] IdTokenError),
}

/// All possible errors when refreshing an access token.
#[derive(Debug, Error)]
pub enum TokenRefreshError {
    /// An error occurred requesting the access token.
    #[error(transparent)]
    Token(#[from] TokenRequestError),

    /// An error occurred validating the ID Token.
    #[error(transparent)]
    IdToken(#[from] IdTokenError),
}

/// All possible errors when revoking a token.
#[derive(Debug, Error)]
pub enum TokenRevokeError {
    /// An error occurred building the request.
    #[error(transparent)]
    IntoHttp(#[from] http::Error),

    /// An error occurred adding the client credentials to the request.
    #[error(transparent)]
    Credentials(#[from] CredentialsError),

    /// An error occurred serializing the request.
    #[error(transparent)]
    UrlEncoded(#[from] serde_urlencoded::ser::Error),

    /// An error occurred deserializing the error response.
    #[error(transparent)]
    Json(#[from] serde_json::Error),

    /// The server returned an HTTP error status code.
    #[error(transparent)]
    Http(#[from] HttpError),

    /// An error occurred sending the request.
    #[error(transparent)]
    Service(BoxError),
}

impl<S> From<form_urlencoded_request::Error<S>> for TokenRevokeError
where
    S: Into<TokenRevokeError>,
{
    fn from(err: form_urlencoded_request::Error<S>) -> Self {
        match err {
            form_urlencoded_request::Error::Serialize { inner } => inner.into(),
            form_urlencoded_request::Error::Service { inner } => inner.into(),
        }
    }
}

impl<S> From<catch_http_codes::Error<S, Option<ErrorBody>>> for TokenRevokeError
where
    S: Into<BoxError>,
{
    fn from(err: catch_http_codes::Error<S, Option<ErrorBody>>) -> Self {
        match err {
            catch_http_codes::Error::HttpError { status_code, inner } => {
                HttpError::new(status_code, inner).into()
            }
            catch_http_codes::Error::Service { inner } => Self::Service(inner.into()),
        }
    }
}

/// All possible errors when requesting user info.
#[derive(Debug, Error)]
pub enum UserInfoError {
    /// An error occurred getting the provider metadata.
    #[error(transparent)]
    Discovery(#[from] Arc<DiscoveryError>),

    /// The provider doesn't support requesting user info.
    #[error("missing UserInfo support")]
    MissingUserInfoSupport,

    /// No token is available to get info from.
    #[error("missing token")]
    MissingToken,

    /// No client metadata is available.
    #[error("missing client metadata")]
    MissingClientMetadata,

    /// The access token is invalid.
    #[error(transparent)]
    Token(#[from] InvalidBearerToken),

    /// An error occurred building the request.
    #[error(transparent)]
    IntoHttp(#[from] http::Error),

    /// The content-type header is missing from the response.
    #[error("missing response content-type")]
    MissingResponseContentType,

    /// The content-type header could not be decoded.
    #[error("could not decoded response content-type: {0}")]
    DecodeResponseContentType(#[from] ToStrError),

    /// The content-type is not valid.
    #[error("invalid response content-type")]
    InvalidResponseContentTypeValue,

    /// The content-type is not the one that was expected.
    #[error("unexpected response content-type {got:?}, expected {expected:?}")]
    UnexpectedResponseContentType {
        /// The expected content-type.
        expected: String,
        /// The returned content-type.
        got: String,
    },

    /// An error occurred reading the response.
    #[error(transparent)]
    FromUtf8(#[from] Utf8Error),

    /// An error occurred deserializing the JSON or error response.
    #[error(transparent)]
    Json(#[from] serde_json::Error),

    /// An error occurred verifying the Id Token.
    #[error(transparent)]
    IdToken(#[from] IdTokenError),

    /// The server returned an HTTP error status code.
    #[error(transparent)]
    Http(#[from] HttpError),

    /// An error occurred sending the request.
    #[error(transparent)]
    Service(BoxError),
}

impl<S> From<catch_http_codes::Error<S, Option<ErrorBody>>> for UserInfoError
where
    S: Into<BoxError>,
{
    fn from(err: catch_http_codes::Error<S, Option<ErrorBody>>) -> Self {
        match err {
            catch_http_codes::Error::HttpError { status_code, inner } => {
                HttpError::new(status_code, inner).into()
            }
            catch_http_codes::Error::Service { inner } => Self::Service(inner.into()),
        }
    }
}

/// All possible errors when introspecting a token.
#[derive(Debug, Error)]
pub enum IntrospectionError {
    /// An error occurred building the request.
    #[error(transparent)]
    IntoHttp(#[from] http::Error),

    /// An error occurred adding the client credentials to the request.
    #[error(transparent)]
    Credentials(#[from] CredentialsError),

    /// The access token is invalid.
    #[error(transparent)]
    Token(#[from] InvalidBearerToken),

    /// An error occurred serializing the request.
    #[error(transparent)]
    UrlEncoded(#[from] serde_urlencoded::ser::Error),

    /// An error occurred deserializing the JSON or error response.
    #[error(transparent)]
    Json(#[from] serde_json::Error),

    /// The server returned an HTTP error status code.
    #[error(transparent)]
    Http(#[from] HttpError),

    /// An error occurred sending the request.
    #[error(transparent)]
    Service(BoxError),
}

impl<S> From<form_urlencoded_request::Error<S>> for IntrospectionError
where
    S: Into<IntrospectionError>,
{
    fn from(err: form_urlencoded_request::Error<S>) -> Self {
        match err {
            form_urlencoded_request::Error::Serialize { inner } => inner.into(),
            form_urlencoded_request::Error::Service { inner } => inner.into(),
        }
    }
}

impl<S> From<json_response::Error<S>> for IntrospectionError
where
    S: Into<IntrospectionError>,
{
    fn from(err: json_response::Error<S>) -> Self {
        match err {
            json_response::Error::Deserialize { inner } => inner.into(),
            json_response::Error::Service { inner } => inner.into(),
        }
    }
}

impl<S> From<catch_http_codes::Error<S, Option<ErrorBody>>> for IntrospectionError
where
    S: Into<BoxError>,
{
    fn from(err: catch_http_codes::Error<S, Option<ErrorBody>>) -> Self {
        match err {
            catch_http_codes::Error::HttpError { status_code, inner } => {
                HttpError::new(status_code, inner).into()
            }
            catch_http_codes::Error::Service { inner } => Self::Service(inner.into()),
        }
    }
}

/// All possible errors when requesting a JWKS.
#[derive(Debug, Error)]
pub enum JwksError {
    /// An error occurred building the request.
    #[error(transparent)]
    IntoHttp(#[from] http::Error),

    /// An error occurred deserializing the response.
    #[error(transparent)]
    Json(#[from] serde_json::Error),

    /// An error occurred sending the request.
    #[error(transparent)]
    Service(BoxError),
}

impl<S> From<json_response::Error<S>> for JwksError
where
    S: Into<BoxError>,
{
    fn from(err: json_response::Error<S>) -> Self {
        match err {
            json_response::Error::Service { inner } => Self::Service(inner.into()),
            json_response::Error::Deserialize { inner } => Self::Json(inner),
        }
    }
}

/// All possible errors when verifying a JWT.
#[derive(Debug, Error)]
pub enum JwtVerificationError {
    /// An error occured decoding the JWT.
    #[error(transparent)]
    JwtDecode(#[from] JwtDecodeError),

    /// No key worked for verifying the JWT's signature.
    #[error(transparent)]
    JwtSignature(#[from] NoKeyWorked),

    /// An error occurred extracting a claim.
    #[error(transparent)]
    Claim(#[from] ClaimError),

    /// The algorithm used for signing the JWT is not the one that was
    /// requested.
    #[error("wrong signature alg")]
    WrongSignatureAlg,
}

/// All possible errors when verifying an ID token.
#[derive(Debug, Error)]
pub enum IdTokenError {
    /// No ID Token was found in the response although one was expected.
    #[error("ID token is missing")]
    MissingIdToken,

    /// The ID Token from the latest Authorization was not provided although
    /// this request expects to be verified against one.
    #[error("Authorization ID token is missing")]
    MissingAuthIdToken,

    /// An error occurred validating the ID Token's signature and basic claims.
    #[error(transparent)]
    Jwt(#[from] JwtVerificationError),

    /// An error occurred extracting a claim.
    #[error(transparent)]
    Claim(#[from] ClaimError),

    /// The subject identifier returned by the issuer is not the same as the one
    /// we got before.
    #[error("wrong subject identifier")]
    WrongSubjectIdentifier,

    /// The authentication time returned by the issuer is not the same as the
    /// one we got before.
    #[error("wrong authentication time")]
    WrongAuthTime,
}

/// An error that can be returned by an OpenID Provider.
#[derive(Debug, Clone, Error)]
#[error("{status}: {body:?}")]
pub struct HttpError {
    /// The status code of the error.
    pub status: StatusCode,

    /// The body of the error, if any.
    pub body: Option<ErrorBody>,
}

impl HttpError {
    /// Creates a new `HttpError` with the given status code and optional body.
    #[must_use]
    pub fn new(status: StatusCode, body: Option<ErrorBody>) -> Self {
        Self { status, body }
    }
}

/// The body of an error that can be returned by an OpenID Provider.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorBody {
    /// The error code.
    pub error: ClientErrorCode,

    /// Additional text description of the error for debugging.
    pub error_description: Option<String>,
}

/// All errors that can occur when adding client credentials to the request.
#[derive(Debug, Error)]
pub enum CredentialsError {
    /// Trying to use an unsupported authentication method.
    #[error("unsupported authentication method")]
    UnsupportedMethod,

    /// When authenticationg with `private_key_jwt`, no private key was found
    /// for the given algorithm.
    #[error("no private key was found for the given algorithm")]
    NoPrivateKeyFound,

    /// The signing algorithm is invalid for this authentication method.
    #[error("invalid algorithm: {0}")]
    InvalidSigningAlgorithm(#[from] InvalidAlgorithm),

    /// An error occurred when building the claims of the JWT.
    #[error(transparent)]
    JwtClaims(#[from] ClaimError),

    /// The key found cannot be used with the algorithm.
    #[error("Wrong algorithm for key")]
    JwtWrongAlgorithm,

    /// An error occurred when signing the JWT.
    #[error(transparent)]
    JwtSignature(#[from] JwtSignatureError),

    /// An error occurred with a custom signing method.
    #[error(transparent)]
    Custom(BoxError),
}

/// All errors that can occur when building the account management URL.
#[derive(Debug, Error)]
pub enum AccountManagementError {
    /// An error occurred serializing the parameters.
    #[error(transparent)]
    UrlEncoded(#[from] serde_urlencoded::ser::Error),
}