volga 0.9.1

Easy & Fast Web Framework for Rust
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
//! Tools and utils for Authorization & Authentication

#[cfg(feature = "jwt-auth")]
use {
    crate::headers::{CACHE_CONTROL, HeaderValue, WWW_AUTHENTICATE, cache_control::NO_STORE},
    crate::middleware::{HttpContext, Middleware, NextFn},
    crate::{
        App, HttpResult,
        error::Error,
        http::StatusCode,
        routing::{Route, RouteGroup},
        status,
    },
    std::{future::Future, sync::Arc},
};

#[cfg(feature = "jwt-auth")]
pub use {
    algorithm::Algorithm,
    authenticated::Authenticated,
    authorizer::{Authorizer, permissions, predicate, role, roles},
    bearer::{Bearer, BearerAuthConfig, BearerTokenService},
    claims::AuthClaims,
    decoding_key::DecodingKey,
    encoding_key::EncodingKey,
};

#[cfg(feature = "jwt-auth")]
use jsonwebtoken::errors::{Error as JwtError, ErrorKind};

#[cfg(feature = "jwt-derive")]
pub use volga_macros::Claims;

#[cfg(feature = "basic-auth")]
pub use basic::Basic;

#[cfg(feature = "jwt-auth")]
pub mod algorithm;
#[cfg(feature = "jwt-auth")]
pub mod authenticated;
#[cfg(feature = "jwt-auth")]
pub mod authorizer;
#[cfg(feature = "basic-auth")]
pub mod basic;
#[cfg(feature = "jwt-auth")]
pub mod bearer;
#[cfg(feature = "jwt-auth")]
pub mod claims;
#[cfg(feature = "jwt-auth")]
pub mod decoding_key;
#[cfg(feature = "jwt-auth")]
pub mod encoding_key;
#[cfg(feature = "jwt-auth")]
pub(crate) mod pem;

#[cfg(feature = "jwt-auth")]
impl From<JwtError> for Error {
    #[inline]
    fn from(err: JwtError) -> Self {
        let kind = err.kind();
        let status_code = map_jwt_error_to_status(kind);
        Error::from_parts(status_code, None, err)
    }
}

#[cfg(feature = "jwt-auth")]
fn map_jwt_error_to_status(err: &ErrorKind) -> StatusCode {
    use ErrorKind::*;
    match err {
        ExpiredSignature
        | InvalidToken
        | InvalidIssuer
        | InvalidAudience
        | InvalidSubject
        | InvalidSignature
        | MissingRequiredClaim(_)
        | ImmatureSignature
        | InvalidAlgorithmName
        | InvalidAlgorithm => StatusCode::UNAUTHORIZED,
        Base64(_) | Json(_) | Utf8(_) | InvalidKeyFormat => StatusCode::BAD_REQUEST,
        _ => StatusCode::INTERNAL_SERVER_ERROR,
    }
}

#[cfg(feature = "jwt-auth")]
fn build_www_authenticate(err: &ErrorKind, resource_metadata_url: Option<&str>) -> String {
    use ErrorKind::*;
    let base = match err {
        ExpiredSignature => {
            r#"Bearer error="invalid_token", error_description="Token has expired""#
        }
        InvalidSignature => {
            r#"Bearer error="invalid_token", error_description="Invalid signature""#
        }
        InvalidToken => {
            r#"Bearer error="invalid_token", error_description="Token is malformed or invalid""#
        }
        ImmatureSignature => {
            r#"Bearer error="invalid_token", error_description="Token is not valid yet (nbf)""#
        }
        MissingRequiredClaim(_) => {
            r#"Bearer error="invalid_token", error_description="Missing required claim""#
        }
        InvalidIssuer => {
            r#"Bearer error="invalid_token", error_description="Invalid issuer (iss)""#
        }
        InvalidAudience => {
            r#"Bearer error="invalid_token", error_description="Invalid audience (aud)""#
        }
        InvalidSubject => {
            r#"Bearer error="invalid_token", error_description="Invalid subject (sub)""#
        }
        InvalidAlgorithm | InvalidAlgorithmName => {
            r#"Bearer error="invalid_token", error_description="Invalid algorithm""#
        }
        Base64(_) => {
            r#"Bearer error="invalid_request", error_description="Token is not properly base64-encoded""#
        }
        Json(_) => {
            r#"Bearer error="invalid_request", error_description="Token payload is not valid JSON""#
        }
        Utf8(_) => {
            r#"Bearer error="invalid_request", error_description="Token contains invalid UTF-8 characters""#
        }
        InvalidKeyFormat => {
            r#"Bearer error="invalid_request", error_description="Invalid key format""#
        }
        _ => r#"Bearer error="server_error", error_description="Internal token processing error""#,
    };
    match resource_metadata_url {
        Some(url) => format!(r#"{base}, resource_metadata="{url}""#),
        None => base.to_string(),
    }
}

#[cfg(feature = "jwt-auth")]
impl App {
    /// Configures a web server with a Bearer Token Authentication & Authorization configuration
    ///
    /// Default: `None`
    ///
    /// # Example
    /// ```no_run
    /// use volga::App;
    ///
    /// let app = App::new()
    ///     .with_bearer_auth(|auth| auth);
    /// ```
    pub fn with_bearer_auth<F>(mut self, config: F) -> Self
    where
        F: FnOnce(BearerAuthConfig) -> BearerAuthConfig,
    {
        self.auth_config = Some(config(Default::default()));
        self
    }

    /// Adds authorization middleware for all routes
    ///
    /// # Example
    /// ```no_run
    /// use volga::{App, auth::{AuthClaims, roles}};
    /// use serde::Deserialize;
    ///
    /// #[derive(Clone, Deserialize)]
    /// struct MyClaims {
    ///     role: String
    /// }
    ///
    /// impl AuthClaims for MyClaims {
    ///     fn role(&self) -> Option<&str> {
    ///         Some(self.role.as_str())
    ///     }
    /// }
    ///
    /// let mut app = App::new()
    ///     .with_bearer_auth(|auth| auth);
    ///
    /// app.authorize::<MyClaims>(roles(["admin", "user"]));
    ///
    /// app.map_get("/hello", || async { "Hello, World!" });
    /// ```
    pub fn authorize<C: AuthClaims + Send + Sync + 'static>(
        &mut self,
        authorizer: Authorizer<C>,
    ) -> &mut Self {
        self.ensure_bearer_auth_configured();
        self.attach(Authorize::new(authorizer))
    }

    fn ensure_bearer_auth_configured(&self) {
        let config = match &self.auth_config {
            Some(config) => config,
            _ => panic!("Bearer Auth is not configured"),
        };

        config
            .decoding_key()
            .expect("Bearer Auth security key is not configured");
    }
}

#[cfg(feature = "jwt-auth")]
impl<'a> Route<'a> {
    /// Adds authorization middleware for this route
    ///
    /// # Example
    /// ```no_run
    /// use volga::{App, auth::{AuthClaims, roles}};
    /// use serde::Deserialize;
    ///
    /// #[derive(Clone, Deserialize)]
    /// struct MyClaims {
    ///     role: String
    /// }
    ///
    /// impl AuthClaims for MyClaims {
    ///     fn role(&self) -> Option<&str> {
    ///         Some(self.role.as_str())
    ///     }
    /// }
    ///
    /// let mut app = App::new()
    ///     .with_bearer_auth(|auth| auth);
    ///
    /// app.map_get("/hello", || async { "Hello, World!" })
    ///     .authorize::<MyClaims>(roles(["admin", "user"]));
    /// ```
    pub fn authorize<C: AuthClaims + Send + Sync + 'static>(
        self,
        authorizer: Authorizer<C>,
    ) -> Self {
        self.ensure_bearer_auth_configured();
        self.attach(Authorize::new(authorizer))
    }
}

#[cfg(feature = "jwt-auth")]
impl<'a> RouteGroup<'a> {
    /// Adds authorization middleware for this group of routes
    ///
    /// # Example
    /// ```no_run
    /// use volga::{App, auth::{AuthClaims, roles}};
    /// use serde::Deserialize;
    ///
    /// #[derive(Clone, Deserialize)]
    /// struct MyClaims {
    ///     role: String
    /// }
    ///
    /// impl AuthClaims for MyClaims {
    ///     fn role(&self) -> Option<&str> {
    ///         Some(self.role.as_str())
    ///     }
    /// }
    ///
    /// let mut app = App::new()
    ///     .with_bearer_auth(|auth| auth);
    ///
    /// app.group("/api", |api| {
    ///     api.authorize::<MyClaims>(roles(["admin", "user"]));
    ///     api.map_get("/hello", || async { "Hello, World!" });
    /// });
    /// ```
    pub fn authorize<C: AuthClaims + Send + Sync + 'static>(
        &mut self,
        authorizer: Authorizer<C>,
    ) -> &mut Self {
        self.app.ensure_bearer_auth_configured();
        self.attach(Authorize::new(authorizer))
    }
}

#[cfg(feature = "jwt-auth")]
struct Authorize<C>
where
    C: AuthClaims + Send + Sync + 'static,
{
    authorizer: Arc<Authorizer<C>>,
}

#[cfg(feature = "jwt-auth")]
impl<C> Authorize<C>
where
    C: AuthClaims + Send + Sync + 'static,
{
    fn new(a: Authorizer<C>) -> Self {
        Self {
            authorizer: Arc::new(a),
        }
    }
}

#[cfg(feature = "jwt-auth")]
impl<C> Middleware for Authorize<C>
where
    C: AuthClaims + Send + Sync + 'static,
{
    #[inline]
    fn call(
        &self,
        ctx: HttpContext,
        next: NextFn,
    ) -> impl Future<Output = HttpResult> + Send + 'static {
        authorize_impl(Arc::clone(&self.authorizer), ctx, next)
    }
}

#[cfg(feature = "jwt-auth")]
fn authorize_impl<C>(
    authorizer: Arc<Authorizer<C>>,
    mut ctx: HttpContext,
    next: NextFn,
) -> impl Future<Output = HttpResult>
where
    C: AuthClaims + Send + Sync + 'static,
{
    let authorizer = authorizer.clone();
    async move {
        if should_reject_for_https(&ctx)? {
            return status!(400; [
                (WWW_AUTHENTICATE, r#"Bearer error="invalid_request", error_description="HTTPS required""#)
            ]);
        }
        let bearer = resolve_bearer(&ctx)?;
        let bts: BearerTokenService = ctx.extract()?;
        let resp = match bts.decode(bearer.clone()) {
            Ok(claims) if authorizer.validate(&claims) => {
                if bts.strip_token_from_request {
                    stash_bearer(&mut ctx, bearer);
                    ctx.request_mut()
                        .headers_mut()
                        .remove(crate::headers::AUTHORIZATION);
                }
                ctx.request_mut()
                    .extensions_mut()
                    .insert(Authenticated(claims));

                next(ctx).await
            }
            Ok(_) => {
                let metadata_url = bts.resource_metadata_url.as_deref();
                status!(403; [
                    (WWW_AUTHENTICATE, authorizer::default_error_msg(metadata_url))
                ])
            }
            Err(err) => {
                let metadata_url = bts.resource_metadata_url.as_deref();
                let www_authenticate = err
                    .into_inner()
                    .downcast_ref::<JwtError>()
                    .map(|e| build_www_authenticate(e.kind(), metadata_url))
                    .unwrap_or_else(|| authorizer::default_error_msg(metadata_url));
                status!(403; [
                    (WWW_AUTHENTICATE, www_authenticate)
                ])
            }
        };
        resp.map(|mut resp| {
            resp.headers_mut()
                .insert(CACHE_CONTROL, HeaderValue::from_static(NO_STORE));
            resp
        })
    }
}

/// Returns the bearer token for this request, preferring the value stashed
/// by an outer `authorize` middleware (when `strip_token_from_request` removed
/// the `Authorization` header) over the raw header. This keeps stacked
/// `authorize` chains (e.g. group-level + route-level) working when the outer
/// step has already stripped the credential.
#[cfg(feature = "jwt-auth")]
fn resolve_bearer(ctx: &HttpContext) -> Result<Bearer, Error> {
    use crate::http::request_scope::HttpRequestScope;
    if let Some(scope) = ctx.request().extensions().get::<HttpRequestScope>()
        && let Some(bearer) = scope.bearer.as_ref()
    {
        return Ok(bearer.clone());
    }
    ctx.extract::<Bearer>()
}

/// Stashes the bearer token into the request scope so nested `authorize`
/// middlewares can recover it after the `Authorization` header is removed.
/// Idempotent: a token already present in the scope is left untouched.
#[cfg(feature = "jwt-auth")]
fn stash_bearer(ctx: &mut HttpContext, bearer: Bearer) {
    use crate::http::request_scope::HttpRequestScope;
    if let Some(scope) = ctx
        .request_mut()
        .extensions_mut()
        .get_mut::<HttpRequestScope>()
        && scope.bearer.is_none()
    {
        scope.bearer = Some(bearer);
    }
}

/// Returns `Ok(true)` when the request should be rejected because
/// `require_https` is enabled, the server isn't accepting TLS, and the
/// peer is not a loopback address.
#[cfg(feature = "jwt-auth")]
fn should_reject_for_https(ctx: &HttpContext) -> Result<bool, Error> {
    let bts: BearerTokenService = ctx.extract()?;
    if !bts.require_https || bts.tls_enabled {
        return Ok(false);
    }
    let client_ip: crate::ClientIp = ctx.extract()?;
    Ok(!client_ip.into_inner().ip().is_loopback())
}

#[cfg(all(test, feature = "jwt-auth"))]
mod tests {
    use super::*;
    use crate::http::StatusCode;
    use jsonwebtoken::errors::{Error as JwtError, ErrorKind};

    #[test]
    fn it_maps_expired_signature_to_unauthorized() {
        let status = map_jwt_error_to_status(&ErrorKind::ExpiredSignature);
        assert_eq!(status, StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn it_maps_invalid_token_to_unauthorized() {
        let status = map_jwt_error_to_status(&ErrorKind::InvalidToken);
        assert_eq!(status, StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn it_maps_invalid_issuer_to_unauthorized() {
        let status = map_jwt_error_to_status(&ErrorKind::InvalidIssuer);
        assert_eq!(status, StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn it_maps_invalid_audience_to_unauthorized() {
        let status = map_jwt_error_to_status(&ErrorKind::InvalidAudience);
        assert_eq!(status, StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn it_maps_invalid_subject_to_unauthorized() {
        let status = map_jwt_error_to_status(&ErrorKind::InvalidSubject);
        assert_eq!(status, StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn it_maps_invalid_signature_to_unauthorized() {
        let status = map_jwt_error_to_status(&ErrorKind::InvalidSignature);
        assert_eq!(status, StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn it_maps_missing_required_claim_to_unauthorized() {
        let status = map_jwt_error_to_status(&ErrorKind::MissingRequiredClaim("test".to_string()));
        assert_eq!(status, StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn it_maps_immature_signature_to_unauthorized() {
        let status = map_jwt_error_to_status(&ErrorKind::ImmatureSignature);
        assert_eq!(status, StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn it_maps_invalid_algorithm_name_to_unauthorized() {
        let status = map_jwt_error_to_status(&ErrorKind::InvalidAlgorithmName);
        assert_eq!(status, StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn it_maps_invalid_algorithm_to_unauthorized() {
        let status = map_jwt_error_to_status(&ErrorKind::InvalidAlgorithm);
        assert_eq!(status, StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn it_maps_base64_error_to_bad_request() {
        let status =
            map_jwt_error_to_status(&ErrorKind::Base64(base64::DecodeError::InvalidByte(0, 0)));
        assert_eq!(status, StatusCode::BAD_REQUEST);
    }

    #[test]
    fn it_maps_json_error_to_bad_request() {
        // Create a JSON error by attempting to deserialize invalid JSON
        let json_result: Result<serde_json::Value, _> = serde_json::from_str("invalid json");
        let json_error = json_result.unwrap_err();
        let status = map_jwt_error_to_status(&ErrorKind::Json(Arc::from(json_error)));
        assert_eq!(status, StatusCode::BAD_REQUEST);
    }

    #[test]
    fn it_maps_utf8_error_to_bad_request() {
        // Create a FromUtf8Error by attempting to convert invalid UTF-8 bytes
        let invalid_utf8_bytes = vec![0, 159, 146, 150];
        let utf8_error = String::from_utf8(invalid_utf8_bytes).unwrap_err();
        let status = map_jwt_error_to_status(&ErrorKind::Utf8(utf8_error));
        assert_eq!(status, StatusCode::BAD_REQUEST);
    }

    #[test]
    fn it_maps_invalid_key_format_to_bad_request() {
        let status = map_jwt_error_to_status(&ErrorKind::InvalidKeyFormat);
        assert_eq!(status, StatusCode::BAD_REQUEST);
    }

    #[test]
    fn it_maps_expired_signature_to_www_authenticate() {
        let www_auth = build_www_authenticate(&ErrorKind::ExpiredSignature, None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_token", error_description="Token has expired""#
        );
    }

    #[test]
    fn it_maps_invalid_signature_to_www_authenticate() {
        let www_auth = build_www_authenticate(&ErrorKind::InvalidSignature, None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_token", error_description="Invalid signature""#
        );
    }

    #[test]
    fn it_maps_invalid_token_to_www_authenticate() {
        let www_auth = build_www_authenticate(&ErrorKind::InvalidToken, None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_token", error_description="Token is malformed or invalid""#
        );
    }

    #[test]
    fn it_maps_immature_signature_to_www_authenticate() {
        let www_auth = build_www_authenticate(&ErrorKind::ImmatureSignature, None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_token", error_description="Token is not valid yet (nbf)""#
        );
    }

    #[test]
    fn it_maps_missing_required_claim_to_www_authenticate() {
        let www_auth =
            build_www_authenticate(&ErrorKind::MissingRequiredClaim("test".to_string()), None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_token", error_description="Missing required claim""#
        );
    }

    #[test]
    fn it_maps_invalid_issuer_to_www_authenticate() {
        let www_auth = build_www_authenticate(&ErrorKind::InvalidIssuer, None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_token", error_description="Invalid issuer (iss)""#
        );
    }

    #[test]
    fn it_maps_invalid_audience_to_www_authenticate() {
        let www_auth = build_www_authenticate(&ErrorKind::InvalidAudience, None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_token", error_description="Invalid audience (aud)""#
        );
    }

    #[test]
    fn it_maps_invalid_subject_to_www_authenticate() {
        let www_auth = build_www_authenticate(&ErrorKind::InvalidSubject, None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_token", error_description="Invalid subject (sub)""#
        );
    }

    #[test]
    fn it_maps_invalid_algorithm_to_www_authenticate() {
        let www_auth = build_www_authenticate(&ErrorKind::InvalidAlgorithm, None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_token", error_description="Invalid algorithm""#
        );
    }

    #[test]
    fn it_maps_invalid_algorithm_name_to_www_authenticate() {
        let www_auth = build_www_authenticate(&ErrorKind::InvalidAlgorithmName, None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_token", error_description="Invalid algorithm""#
        );
    }

    #[test]
    fn it_maps_base64_error_to_www_authenticate() {
        let www_auth = build_www_authenticate(
            &ErrorKind::Base64(base64::DecodeError::InvalidByte(0, 0)),
            None,
        );
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_request", error_description="Token is not properly base64-encoded""#
        );
    }

    #[test]
    fn it_maps_json_error_to_www_authenticate() {
        let json_result: Result<serde_json::Value, _> = serde_json::from_str("invalid json");
        let json_error = json_result.unwrap_err();
        let www_auth = build_www_authenticate(&ErrorKind::Json(Arc::from(json_error)), None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_request", error_description="Token payload is not valid JSON""#
        );
    }

    #[test]
    fn it_maps_utf8_error_to_www_authenticate() {
        let invalid_utf8_bytes = vec![0, 159, 146, 150];
        let utf8_error = String::from_utf8(invalid_utf8_bytes).unwrap_err();
        let www_auth = build_www_authenticate(&ErrorKind::Utf8(utf8_error), None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_request", error_description="Token contains invalid UTF-8 characters""#
        );
    }

    #[test]
    fn it_maps_invalid_key_format_to_www_authenticate() {
        let www_auth = build_www_authenticate(&ErrorKind::InvalidKeyFormat, None);
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_request", error_description="Invalid key format""#
        );
    }

    #[test]
    fn it_appends_resource_metadata_url_to_challenge() {
        let www_auth = build_www_authenticate(
            &ErrorKind::ExpiredSignature,
            Some("https://api.example.com/.well-known/oauth-protected-resource"),
        );
        assert_eq!(
            www_auth,
            r#"Bearer error="invalid_token", error_description="Token has expired", resource_metadata="https://api.example.com/.well-known/oauth-protected-resource""#
        );
    }

    #[test]
    fn it_default_error_msg_without_metadata_url() {
        let www_auth = authorizer::default_error_msg(None);
        assert_eq!(
            www_auth,
            r#"Bearer error="insufficient_scope" error_description="User does not have required role or permission""#
        );
    }

    #[test]
    fn it_default_error_msg_appends_metadata_url() {
        let www_auth = authorizer::default_error_msg(Some(
            "https://api.example.com/.well-known/oauth-protected-resource",
        ));
        assert_eq!(
            www_auth,
            r#"Bearer error="insufficient_scope" error_description="User does not have required role or permission", resource_metadata="https://api.example.com/.well-known/oauth-protected-resource""#
        );
    }

    #[test]
    fn it_converts_jwt_error_to_error_with_expired_signature() {
        let jwt_error = JwtError::from(ErrorKind::ExpiredSignature);
        let error: Error = jwt_error.into();

        assert_eq!(error.status, StatusCode::UNAUTHORIZED);
        assert!(error.instance.is_none());
    }

    #[test]
    fn it_converts_jwt_error_to_error_with_invalid_token() {
        let jwt_error = JwtError::from(ErrorKind::InvalidToken);
        let error: Error = jwt_error.into();

        assert_eq!(error.status, StatusCode::UNAUTHORIZED);
        assert!(error.instance.is_none());
    }

    #[test]
    fn it_converts_jwt_error_to_error_with_base64_error() {
        let jwt_error = JwtError::from(ErrorKind::Base64(base64::DecodeError::InvalidByte(0, 0)));
        let error: Error = jwt_error.into();

        assert_eq!(error.status, StatusCode::BAD_REQUEST);
        assert!(error.instance.is_none());
    }

    #[test]
    fn it_converts_jwt_error_to_error_with_json_error() {
        let json_result: Result<serde_json::Value, _> = serde_json::from_str("invalid json");
        let json_error = json_result.unwrap_err();
        let jwt_error = JwtError::from(ErrorKind::Json(Arc::from(json_error)));
        let error: Error = jwt_error.into();

        assert_eq!(error.status, StatusCode::BAD_REQUEST);
        assert!(error.instance.is_none());
    }

    #[test]
    fn it_converts_jwt_error_to_error_with_invalid_key_format() {
        let jwt_error = JwtError::from(ErrorKind::InvalidKeyFormat);
        let error: Error = jwt_error.into();

        assert_eq!(error.status, StatusCode::BAD_REQUEST);
        assert!(error.instance.is_none());
    }
}