pipi-rs 0.1.1

Pipi 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
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
//! Axum middleware for validating token header
//!
//! # Example:
//!
//! ```
//! use pipi::prelude::*;
//! use serde::Serialize;
//! use axum::extract::State;
//! use pipi::controller::extractor::auth;
//!
//! #[derive(Serialize)]
//! pub struct TestResponse {
//!     pub pid: String,
//! }
//!
//! async fn current(
//!     auth: auth::JWT,
//!     State(ctx): State<AppContext>,
//! ) -> Result<Response> {
//!     format::json(TestResponse{ pid: auth.claims.pid})
//! }
//! ```
use std::collections::HashMap;

use axum::{
    extract::{FromRef, FromRequestParts, Query},
    http::{request::Parts, HeaderMap},
};
use axum_extra::extract::cookie;
use serde::{Deserialize, Serialize};
use tracing;

use crate::{app::AppContext, auth, config::JWT as JWTConfig, errors::Error, Result as PipiResult};

#[cfg(feature = "with-db")]
use crate::model::{Authenticable, ModelError};

// ---------------------------------------
//
// JWT Auth extractor
//
// ---------------------------------------

// Define constants for token prefix and authorization header
const TOKEN_PREFIX: &str = "Bearer ";
const AUTH_HEADER: &str = "authorization";

// Define a struct to represent user authentication information serialized
// to/from JSON
#[cfg(feature = "with-db")]
#[derive(Debug, Deserialize, Serialize)]
pub struct JWTWithUser<T: Authenticable> {
    pub claims: auth::jwt::UserClaims,
    pub user: T,
}

// Implement the FromRequestParts trait for the Auth struct
#[cfg(feature = "with-db")]
impl<S, T> FromRequestParts<S> for JWTWithUser<T>
where
    AppContext: FromRef<S>,
    S: Send + Sync,
    T: Authenticable,
{
    type Rejection = Error;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Error> {
        let ctx: AppContext = AppContext::from_ref(state);

        let token = extract_token(get_jwt_from_config(&ctx)?, parts)?;

        let jwt_secret = ctx.config.get_jwt_config()?;

        match auth::jwt::JWT::new(&jwt_secret.secret).validate(&token) {
            Ok(claims) => {
                let user = T::find_by_claims_key(&ctx.db, &claims.claims.pid)
                    .await
                    .map_err(|e| match e {
                        ModelError::EntityNotFound => Error::Unauthorized("not found".to_string()),
                        ModelError::DbErr(db_err) => {
                            tracing::error!("Database error during authentication: {}", db_err);
                            Error::InternalServerError
                        }
                        _ => {
                            tracing::error!("Authentication error: {}", e);
                            Error::Unauthorized("could not authorize".to_string())
                        }
                    })?;
                Ok(Self {
                    claims: claims.claims,
                    user,
                })
            }
            Err(err) => {
                tracing::error!("JWT validation error: {}", err);
                Err(Error::Unauthorized("token is not valid".to_string()))
            }
        }
    }
}

// Define a struct to represent user authentication information serialized
// to/from JSON
#[derive(Debug, Deserialize, Serialize)]
pub struct JWT {
    pub claims: auth::jwt::UserClaims,
}

// Implement the FromRequestParts trait for the Auth struct
impl<S> FromRequestParts<S> for JWT
where
    AppContext: FromRef<S>,
    S: Send + Sync,
{
    type Rejection = Error;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Error> {
        extract_jwt_from_request_parts(parts, state)
    }
}

/// extract a [JWT] token from request parts, using a non-mutable reference to the [Parts]
///
/// # Errors
/// Return an error when JWT token not configured or when the token is not valid
pub fn extract_jwt_from_request_parts<S>(parts: &Parts, state: &S) -> Result<JWT, Error>
where
    AppContext: FromRef<S>,
    S: Send + Sync,
{
    let ctx: AppContext = AppContext::from_ref(state); // change to ctx

    let token = extract_token(get_jwt_from_config(&ctx)?, parts)?;

    let jwt_secret = ctx.config.get_jwt_config()?;

    match auth::jwt::JWT::new(&jwt_secret.secret).validate(&token) {
        Ok(claims) => Ok(JWT {
            claims: claims.claims,
        }),
        Err(err) => {
            tracing::error!("JWT validation error: {}", err);
            Err(Error::Unauthorized("token is not valid".to_string()))
        }
    }
}

/// extract JWT token from context configuration
///
/// # Errors
/// Return an error when JWT token not configured
pub fn get_jwt_from_config(ctx: &AppContext) -> PipiResult<&JWTConfig> {
    ctx.config
        .auth
        .as_ref()
        .ok_or_else(|| Error::string("auth not configured"))?
        .jwt
        .as_ref()
        .ok_or_else(|| Error::string("JWT token not configured"))
}
/// extract token from the configured jwt location settings
///
/// # Errors
///
/// Returns an error when the token cannot be extracted from any of the configured locations,
/// such as missing headers, invalid formats, or inaccessible request data.
pub fn extract_token(jwt_config: &JWTConfig, parts: &Parts) -> PipiResult<String> {
    let locations = get_jwt_locations(jwt_config.location.as_ref());

    for location in &locations {
        if let Ok(token) = extract_token_from_location(location, parts) {
            return Ok(token);
        }
    }

    // If we get here, none of the locations worked
    Err(Error::Unauthorized("Token not found in any of the configured JWT locations. Please check your auth.jwt.location configuration.".to_string()))
}

/// Get the list of JWT locations to try, with Bearer as default
fn get_jwt_locations(
    config: Option<&crate::config::JWTLocationConfig>,
) -> Vec<&crate::config::JWTLocation> {
    match config {
        Some(crate::config::JWTLocationConfig::Single(location)) => vec![location],
        Some(crate::config::JWTLocationConfig::Multiple(locations)) => locations.iter().collect(),
        None => vec![&crate::config::JWTLocation::Bearer],
    }
}

/// Extract token from a specific location
fn extract_token_from_location(
    location: &crate::config::JWTLocation,
    parts: &Parts,
) -> PipiResult<String> {
    match location {
        crate::config::JWTLocation::Query { name } => extract_token_from_query(name, parts),
        crate::config::JWTLocation::Cookie { name } => extract_token_from_cookie(name, parts),
        crate::config::JWTLocation::Bearer => extract_token_from_header(&parts.headers),
    }
}

/// Function to extract a token from the authorization header
///
/// # Errors
///
/// When token is not valid or not found
pub fn extract_token_from_header(headers: &HeaderMap) -> PipiResult<String> {
    let token = headers
        .get(AUTH_HEADER)
        .ok_or_else(|| Error::Unauthorized(format!("header {AUTH_HEADER} token not found")))?
        .to_str()
        .map_err(|err| Error::Unauthorized(err.to_string()))?
        .strip_prefix(TOKEN_PREFIX)
        .ok_or_else(|| Error::Unauthorized(format!("error strip {AUTH_HEADER} value")))?;

    Ok(token.to_string())
}

/// Extract a token value from cookie
///
/// # Errors
/// when token value from cookie is not found
pub fn extract_token_from_cookie(name: &str, parts: &Parts) -> PipiResult<String> {
    // LogoResult
    let jar: cookie::CookieJar = cookie::CookieJar::from_headers(&parts.headers);
    Ok(jar
        .get(name)
        .ok_or(Error::Unauthorized("token is not found".to_string()))?
        .to_string()
        .strip_prefix(&format!("{name}="))
        .ok_or_else(|| Error::Unauthorized("error strip value".to_string()))?
        .to_string())
}
/// Extract a token value from query
///
/// # Errors
/// when token value from cookie is not found
pub fn extract_token_from_query(name: &str, parts: &Parts) -> PipiResult<String> {
    // LogoResult
    let parameters: Query<HashMap<String, String>> =
        Query::try_from_uri(&parts.uri).map_err(|err| Error::Unauthorized(err.to_string()))?;
    parameters
        .get(name)
        .cloned()
        .ok_or_else(|| Error::Unauthorized(format!("`{name}` query parameter not found")))
}

// ---------------------------------------
//
// API Token Auth / Extractor
//
// ---------------------------------------
#[cfg(feature = "with-db")]
#[derive(Debug, Deserialize, Serialize)]
// Represents the data structure for the API token.
pub struct ApiToken<T: Authenticable> {
    pub user: T,
}

// Implementing the `FromRequestParts` trait for `ApiToken` to enable extracting
// it from the request.
#[cfg(feature = "with-db")]
impl<S, T> FromRequestParts<S> for ApiToken<T>
where
    AppContext: FromRef<S>,
    S: Send + Sync,
    T: Authenticable,
{
    type Rejection = Error;

    // Extracts `ApiToken` from the request parts.
    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Error> {
        // Extract API key from the request header.
        let api_key = extract_token_from_header(&parts.headers)?;

        // Convert the state reference to the application context.
        let state: AppContext = AppContext::from_ref(state);

        // Retrieve user information based on the API key from the database.
        let user = T::find_by_api_key(&state.db, &api_key)
            .await
            .map_err(|e| match e {
                ModelError::EntityNotFound => Error::Unauthorized("not found".to_string()),
                ModelError::DbErr(db_err) => {
                    tracing::error!("Database error during API key authentication: {}", db_err);
                    Error::InternalServerError
                }
                _ => {
                    tracing::error!("API key authentication error: {}", e);
                    Error::Unauthorized("could not authorize".to_string())
                }
            })?;

        Ok(Self { user })
    }
}

#[cfg(test)]
mod tests {

    use axum::http::{HeaderMap, HeaderValue};

    use super::*;
    use crate::config;

    #[test]
    fn test_extract_token_from_header_success() {
        let mut headers = HeaderMap::new();
        headers.insert(
            AUTH_HEADER,
            HeaderValue::from_str("Bearer valid_token_123").unwrap(),
        );

        let result = extract_token_from_header(&headers);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "valid_token_123");
    }

    #[test]
    fn test_extract_token_from_header_with_spaces() {
        let mut headers = HeaderMap::new();
        headers.insert(
            AUTH_HEADER,
            HeaderValue::from_str("Bearer  token_with_spaces  ").unwrap(),
        );

        let result = extract_token_from_header(&headers);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), " token_with_spaces  ");
    }

    #[test]
    fn test_extract_token_from_header_special_chars() {
        let mut headers = HeaderMap::new();
        headers.insert(
            AUTH_HEADER,
            HeaderValue::from_str("Bearer token-with_special.chars").unwrap(),
        );

        let result = extract_token_from_header(&headers);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "token-with_special.chars");
    }

    #[test]
    fn test_extract_token_from_header_missing_header() {
        let headers = HeaderMap::new();
        let result = extract_token_from_header(&headers);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("authorization token not found"));
    }

    #[test]
    fn test_extract_token_from_header_missing_bearer_prefix() {
        let mut headers = HeaderMap::new();
        headers.insert(
            AUTH_HEADER,
            HeaderValue::from_str("InvalidPrefix token").unwrap(),
        );

        let result = extract_token_from_header(&headers);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("error strip authorization value"));
    }

    #[test]
    fn test_extract_token_from_header_empty_value() {
        let mut headers = HeaderMap::new();
        headers.insert(AUTH_HEADER, HeaderValue::from_str("Bearer").unwrap());

        let result = extract_token_from_header(&headers);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("error strip authorization value"));
    }

    #[test]
    fn test_extract_token_from_cookie_success() {
        let request = axum::http::Request::builder()
            .header("Cookie", "test_cookie=cookie_value_123")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token_from_cookie("test_cookie", &parts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "cookie_value_123");
    }

    #[test]
    fn test_extract_token_from_cookie_special_chars() {
        let request = axum::http::Request::builder()
            .header("Cookie", "auth_token=token-with.special_chars")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token_from_cookie("auth_token", &parts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "token-with.special_chars");
    }

    #[test]
    fn test_extract_token_from_cookie_missing_cookie() {
        let request = axum::http::Request::builder().body(()).unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token_from_cookie("nonexistent", &parts);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("token is not found"));
    }

    #[test]
    fn test_extract_token_from_cookie_not_found() {
        let request = axum::http::Request::builder()
            .header("Cookie", "different_cookie=value")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token_from_cookie("nonexistent", &parts);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("token is not found"));
    }

    #[test]
    fn test_extract_token_from_query_success() {
        let request = axum::http::Request::builder()
            .uri("https://example.com?token=query_value_123&other=param")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token_from_query("token", &parts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "query_value_123");
    }

    #[test]
    fn test_extract_token_from_query_special_chars() {
        let request = axum::http::Request::builder()
            .uri("https://example.com?auth_token=token-with.special_chars")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token_from_query("auth_token", &parts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "token-with.special_chars");
    }

    #[test]
    fn test_extract_token_from_query_missing_param() {
        let request = axum::http::Request::builder()
            .uri("https://example.com?other=param")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token_from_query("nonexistent_param", &parts);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("query parameter not found"));
    }

    #[test]
    fn test_extract_token_from_query_invalid_uri() {
        let request = axum::http::Request::builder()
            .uri("not-a-valid-uri")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token_from_query("nonexistent_param", &parts);
        assert!(result.is_err());
    }

    #[test]
    fn test_get_jwt_locations_default() {
        let jwt_config = JWTConfig {
            location: None,
            secret: String::new(),
            expiration: 1,
        };

        let locations = get_jwt_locations(jwt_config.location.as_ref());
        assert_eq!(locations.len(), 1);
        assert!(matches!(locations[0], config::JWTLocation::Bearer));
    }

    #[test]
    fn test_get_jwt_locations_single_bearer() {
        let jwt_config = JWTConfig {
            location: Some(config::JWTLocationConfig::Single(
                config::JWTLocation::Bearer,
            )),
            secret: String::new(),
            expiration: 1,
        };

        let locations = get_jwt_locations(jwt_config.location.as_ref());
        assert_eq!(locations.len(), 1);
        assert!(matches!(locations[0], config::JWTLocation::Bearer));
    }

    #[test]
    fn test_get_jwt_locations_single_cookie() {
        let jwt_config = JWTConfig {
            location: Some(config::JWTLocationConfig::Single(
                config::JWTLocation::Cookie {
                    name: "auth_token".to_string(),
                },
            )),
            secret: String::new(),
            expiration: 1,
        };

        let locations = get_jwt_locations(jwt_config.location.as_ref());
        assert_eq!(locations.len(), 1);
        assert!(matches!(locations[0], config::JWTLocation::Cookie { .. }));
    }

    #[test]
    fn test_get_jwt_locations_single_query() {
        let jwt_config = JWTConfig {
            location: Some(config::JWTLocationConfig::Single(
                config::JWTLocation::Query {
                    name: "token".to_string(),
                },
            )),
            secret: String::new(),
            expiration: 1,
        };

        let locations = get_jwt_locations(jwt_config.location.as_ref());
        assert_eq!(locations.len(), 1);
        assert!(matches!(locations[0], config::JWTLocation::Query { .. }));
    }

    #[test]
    fn test_get_jwt_locations_multiple() {
        let jwt_config = JWTConfig {
            location: Some(config::JWTLocationConfig::Multiple(vec![
                config::JWTLocation::Cookie {
                    name: "auth".to_string(),
                },
                config::JWTLocation::Query {
                    name: "token".to_string(),
                },
                config::JWTLocation::Bearer,
            ])),
            secret: String::new(),
            expiration: 1,
        };

        let locations = get_jwt_locations(jwt_config.location.as_ref());
        assert_eq!(locations.len(), 3);
        assert!(matches!(locations[0], config::JWTLocation::Cookie { .. }));
        assert!(matches!(locations[1], config::JWTLocation::Query { .. }));
        assert!(matches!(locations[2], config::JWTLocation::Bearer));
    }

    #[test]
    fn test_extract_token_from_location_bearer() {
        let request = axum::http::Request::builder()
            .uri("https://example.com?token=query_value")
            .header(AUTH_HEADER, format!("{TOKEN_PREFIX} bearer_value"))
            .header("Cookie", "auth_token=cookie_value")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token_from_location(&config::JWTLocation::Bearer, &parts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), " bearer_value");
    }

    #[test]
    fn test_extract_token_from_location_cookie() {
        let request = axum::http::Request::builder()
            .uri("https://example.com?token=query_value")
            .header(AUTH_HEADER, format!("{TOKEN_PREFIX} bearer_value"))
            .header("Cookie", "auth_token=cookie_value")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token_from_location(
            &config::JWTLocation::Cookie {
                name: "auth_token".to_string(),
            },
            &parts,
        );
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "cookie_value");
    }

    #[test]
    fn test_extract_token_from_location_query() {
        let request = axum::http::Request::builder()
            .uri("https://example.com?token=query_value")
            .header(AUTH_HEADER, format!("{TOKEN_PREFIX} bearer_value"))
            .header("Cookie", "auth_token=cookie_value")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token_from_location(
            &config::JWTLocation::Query {
                name: "token".to_string(),
            },
            &parts,
        );
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "query_value");
    }

    #[test]
    fn test_extract_token_single_location_success() {
        let jwt_config = JWTConfig {
            location: Some(config::JWTLocationConfig::Single(
                config::JWTLocation::Bearer,
            )),
            secret: String::new(),
            expiration: 1,
        };

        let request = axum::http::Request::builder()
            .uri("https://example.com")
            .header(AUTH_HEADER, format!("{TOKEN_PREFIX} valid_token"))
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token(&jwt_config, &parts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), " valid_token");
    }

    #[test]
    fn test_extract_token_multiple_locations_fallback() {
        let jwt_config = JWTConfig {
            location: Some(config::JWTLocationConfig::Multiple(vec![
                config::JWTLocation::Cookie {
                    name: "nonexistent".to_string(),
                },
                config::JWTLocation::Query {
                    name: "token".to_string(),
                },
            ])),
            secret: String::new(),
            expiration: 1,
        };

        let request = axum::http::Request::builder()
            .uri("https://example.com?token=fallback_token")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token(&jwt_config, &parts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "fallback_token");
    }

    #[test]
    fn test_extract_token_all_locations_fail() {
        let jwt_config = JWTConfig {
            location: Some(config::JWTLocationConfig::Multiple(vec![
                config::JWTLocation::Cookie {
                    name: "nonexistent".to_string(),
                },
                config::JWTLocation::Query {
                    name: "missing".to_string(),
                },
            ])),
            secret: String::new(),
            expiration: 1,
        };

        let request = axum::http::Request::builder()
            .uri("https://example.com")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token(&jwt_config, &parts);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Token not found in any of the configured JWT locations"));
    }

    #[test]
    fn test_extract_from_default() {
        let jwt_config = JWTConfig {
            location: None,
            secret: String::new(),
            expiration: 1,
        };

        let request = axum::http::Request::builder()
            .uri("https://pipi.rs")
            .header(AUTH_HEADER, format!("{TOKEN_PREFIX} bearer_token_value"))
            .header("Cookie", "pipi_cookie_key=cookie_token_value")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token(&jwt_config, &parts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), " bearer_token_value");
    }

    #[test]
    fn test_extract_from_bearer() {
        let jwt_config = JWTConfig {
            location: Some(config::JWTLocationConfig::Single(
                config::JWTLocation::Bearer,
            )),
            secret: String::new(),
            expiration: 1,
        };

        let request = axum::http::Request::builder()
            .uri("pipi.rs")
            .header(AUTH_HEADER, format!("{TOKEN_PREFIX} bearer_token_value"))
            .header("Cookie", "pipi_cookie_key=cookie_token_value")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token(&jwt_config, &parts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), " bearer_token_value");
    }

    #[test]
    fn test_extract_from_cookie() {
        let jwt_config = JWTConfig {
            location: Some(config::JWTLocationConfig::Single(
                config::JWTLocation::Cookie {
                    name: "pipi_cookie_key".to_string(),
                },
            )),
            secret: String::new(),
            expiration: 1,
        };

        let request = axum::http::Request::builder()
            .uri("https://pipi.rs")
            .header(AUTH_HEADER, format!("{TOKEN_PREFIX} bearer_token_value"))
            .header("Cookie", "pipi_cookie_key=cookie_token_value")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token(&jwt_config, &parts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "cookie_token_value");
    }

    #[test]
    fn test_extract_from_query() {
        let jwt_config = JWTConfig {
            location: Some(config::JWTLocationConfig::Single(
                config::JWTLocation::Query {
                    name: "query_token".to_string(),
                },
            )),
            secret: String::new(),
            expiration: 1,
        };

        let request = axum::http::Request::builder()
            .uri("https://pipi.rs?query_token=query_token_value&test=pipi")
            .header(AUTH_HEADER, format!("{TOKEN_PREFIX} bearer_token_value"))
            .header("Cookie", "pipi_cookie_key=cookie_token_value")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token(&jwt_config, &parts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "query_token_value");
    }

    #[test]
    fn test_extract_from_multiple_locations() {
        let jwt_config = JWTConfig {
            location: Some(config::JWTLocationConfig::Multiple(vec![
                config::JWTLocation::Cookie {
                    name: "nonexistent".to_string(),
                },
                config::JWTLocation::Query {
                    name: "query_token".to_string(),
                },
            ])),
            secret: String::new(),
            expiration: 1,
        };

        let request = axum::http::Request::builder()
            .uri("https://pipi.rs?query_token=query_token_value&test=pipi")
            .header(AUTH_HEADER, format!("{TOKEN_PREFIX} bearer_token_value"))
            .header("Cookie", "pipi_cookie_key=cookie_token_value")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token(&jwt_config, &parts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "query_token_value");
    }

    #[test]
    fn test_extract_token_error_message_for_missing_token() {
        let jwt_config = JWTConfig {
            location: Some(config::JWTLocationConfig::Multiple(vec![
                config::JWTLocation::Cookie {
                    name: "nonexistent".to_string(),
                },
                config::JWTLocation::Query {
                    name: "missing".to_string(),
                },
            ])),
            secret: String::new(),
            expiration: 1,
        };

        let request = axum::http::Request::builder()
            .uri("https://pipi.rs")
            .body(())
            .unwrap();
        let (parts, ()) = request.into_parts();

        let result = extract_token(&jwt_config, &parts);
        assert!(result.is_err());
        let error_msg = result.unwrap_err().to_string();
        assert!(error_msg.contains("auth.jwt.location configuration"));
    }
}