structured-proxy 8.1.4

Universal gRPC→REST transcoding proxy — config-driven, works with any gRPC service
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
//! Auth middleware tests: token handling, route policies, claim forwarding,
//! and the two verifier sources (built-in and injected).

use super::*;

use crate::config::{AuthConfig, ForwardAuthConfig, JwtConfig, RoutePolicyConfig};
use axum::http::Request as HttpRequest;
use axum::http::StatusCode;
use tower::ServiceExt;

#[test]
fn bearer_token_parsing() {
    let mut h = HeaderMap::new();
    h.insert("authorization", "Bearer abc.def.ghi".parse().unwrap());
    assert_eq!(bearer_token(&h), Some("abc.def.ghi"));

    let mut h2 = HeaderMap::new();
    h2.insert("authorization", "Basic xyz".parse().unwrap());
    assert_eq!(bearer_token(&h2), None);
    assert_eq!(bearer_token(&HeaderMap::new()), None);
}

#[test]
fn extract_roles_reads_array_and_dotted_path() {
    let claims = serde_json::json!({
        "roles": ["admin", "billing"],
        "realm_access": { "roles": ["nested"] }
    });
    assert!(extract_roles(&claims, "roles").contains("admin"));
    assert!(extract_roles(&claims, "realm_access.roles").contains("nested"));
    assert!(extract_roles(&claims, "missing").is_empty());
}

#[test]
fn inject_claim_headers_renders_scalars() {
    let claims = serde_json::json!({ "sub": "u-1", "n": 7, "obj": {"x": 1} });
    let mapping = HashMap::from([
        ("sub".to_string(), "x-user-id".to_string()),
        ("n".to_string(), "x-n".to_string()),
        ("obj".to_string(), "x-obj".to_string()),
    ]);
    let mut headers = HeaderMap::new();
    inject_claim_headers(&mut headers, &claims, &mapping);
    assert_eq!(headers["x-user-id"], "u-1");
    assert_eq!(headers["x-n"], "7");
    // Object claim is skipped (not a scalar).
    assert!(!headers.contains_key("x-obj"));
}

// --- shared harness ---

/// A router whose routes echo the `x-user` header the upstream would receive,
/// behind the auth middleware.
fn app(auth: Arc<Auth>) -> axum::Router {
    let echo = |headers: HeaderMap| async move {
        headers
            .get("x-user")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("")
            .to_string()
    };
    axum::Router::new()
        .route("/secure", axum::routing::get(echo))
        .route("/open", axum::routing::get(echo))
        .layer(axum::middleware::from_fn_with_state(auth, middleware))
}

async fn body_string(resp: axum::response::Response) -> String {
    let bytes = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
    String::from_utf8(bytes.to_vec()).unwrap()
}

/// An `auth.jwt` block carrying only the claim-forwarding settings: no key
/// source, since an injected verifier owns its own keys.
fn jwt_claims_only() -> JwtConfig {
    JwtConfig {
        jwks_uri: None,
        jwks_max_age_secs: 300,
        issuer: None,
        audience: None,
        public_key_pem_file: None,
        claims_headers: HashMap::from([("sub".to_string(), "x-user".to_string())]),
        roles_claim: "roles".into(),
        cache: Default::default(),
    }
}

/// Policies for `/secure`: auth required, plus `roles` when given.
fn secure_policy(roles: &[&str]) -> ForwardAuthConfig {
    ForwardAuthConfig {
        enabled: true,
        path: "/auth/verify".into(),
        policies: vec![RoutePolicyConfig {
            path: "/secure".into(),
            methods: vec!["*".into()],
            require_auth: true,
            required_roles: roles.iter().map(|s| s.to_string()).collect(),
        }],
        login_url: None,
        applications_path: None,
    }
}

// --- injected verifier (no crypto backend needed) ---

/// A verifier that accepts exactly one token and answers with fixed claims, so
/// the middleware can be exercised in a build with no JWT crypto at all.
struct StubVerifier {
    accepts: &'static str,
    claims: Value,
}

#[async_trait::async_trait]
impl TokenVerifier for StubVerifier {
    async fn verify(&self, token: &str) -> Option<Value> {
        (token == self.accepts).then(|| self.claims.clone())
    }
}

fn auth_with_stub(roles: &[&str], jwt: Option<JwtConfig>) -> Arc<Auth> {
    let cfg = AuthConfig {
        mode: "jwt".into(),
        jwt,
        forward_auth: Some(secure_policy(roles)),
        authz: None,
        scope: None,
    };
    let stub = StubVerifier {
        accepts: "good-token",
        claims: serde_json::json!({ "sub": "stub-user", "roles": ["admin"] }),
    };
    Auth::build(&cfg, Some(Arc::new(stub))).unwrap().unwrap()
}

#[test]
fn a_claim_cannot_be_forwarded_as_a_client_address_header() {
    // The proxy writes these from the resolved client address; a claim mapped
    // onto one would replace that address on the way upstream.
    for header in ["x-forwarded-for", "X-Real-IP", "forwarded"] {
        let mut jwt = jwt_claims_only();
        jwt.claims_headers = HashMap::from([("sub".to_string(), header.to_string())]);
        let cfg = AuthConfig {
            mode: "jwt".into(),
            jwt: Some(jwt),
            forward_auth: None,
            authz: None,
            scope: None,
        };
        let stub = StubVerifier {
            accepts: "good-token",
            claims: serde_json::json!({ "sub": "stub-user" }),
        };
        let Err(err) = Auth::build(&cfg, Some(Arc::new(stub))) else {
            panic!("{header}: a claim mapped onto a client-address header must be refused");
        };
        assert!(err.contains(header), "{header}: {err}");
    }
}

#[tokio::test]
async fn injected_verifier_decides_authentication() {
    let auth = auth_with_stub(&[], Some(jwt_claims_only()));

    // The token the injected verifier accepts passes, and its claims are
    // forwarded through the configured claims_headers mapping.
    let resp = app(auth.clone())
        .oneshot(
            HttpRequest::get("/secure")
                .header("authorization", "Bearer good-token")
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    assert_eq!(body_string(resp).await, "stub-user");

    // Anything else is rejected: a verifier returning None is a 401, never a
    // pass-through.
    let resp = app(auth)
        .oneshot(
            HttpRequest::get("/secure")
                .header("authorization", "Bearer other-token")
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn injected_verifier_claims_drive_role_policy() {
    // Roles come from the injected verifier's claims, so the policy applies the
    // same way it does to built-in verification.
    let resp = app(auth_with_stub(&["admin"], Some(jwt_claims_only())))
        .oneshot(
            HttpRequest::get("/secure")
                .header("authorization", "Bearer good-token")
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let resp = app(auth_with_stub(&["superuser"], Some(jwt_claims_only())))
        .oneshot(
            HttpRequest::get("/secure")
                .header("authorization", "Bearer good-token")
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::FORBIDDEN);
}

#[tokio::test]
async fn injected_verifier_works_without_a_jwt_block() {
    // `auth.jwt` exists only to configure keys and claim forwarding; with an
    // injected verifier and no claim headers, it can be omitted entirely.
    let auth = auth_with_stub(&["admin"], None);
    let resp = app(auth)
        .oneshot(
            HttpRequest::get("/secure")
                .header("authorization", "Bearer good-token")
                .body(axum::body::Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    // The role policy still applies (default roles_claim), and no claim header
    // is injected because none was configured.
    assert_eq!(resp.status(), StatusCode::OK);
    assert_eq!(body_string(resp).await, "");
}

/// A verifier that accepts every token and counts its calls.
struct CountingVerifier(std::sync::atomic::AtomicUsize);

#[async_trait::async_trait]
impl TokenVerifier for CountingVerifier {
    async fn verify(&self, _token: &str) -> Option<Value> {
        self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        Some(serde_json::json!({ "sub": "counted", "exp": 9_999_999_999u64 }))
    }
}

#[tokio::test]
async fn injected_verifier_is_called_on_every_request() {
    // The claims cache belongs to the built-in verifier; an injected one owns
    // its policy (introspection, revocation) and sees every request.
    let verifier = Arc::new(CountingVerifier(Default::default()));
    let cfg = AuthConfig {
        mode: "jwt".into(),
        jwt: Some(jwt_claims_only()),
        forward_auth: Some(secure_policy(&[])),
        authz: None,
        scope: None,
    };
    let auth = Auth::build(&cfg, Some(verifier.clone())).unwrap().unwrap();
    for _ in 0..3 {
        let resp = app(auth.clone())
            .oneshot(
                HttpRequest::get("/secure")
                    .header("authorization", "Bearer same-token")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }
    assert_eq!(verifier.0.load(std::sync::atomic::Ordering::Relaxed), 3);
}

#[test]
fn injected_verifier_supersedes_a_configured_key_source() {
    // A config that also names a key source is accepted (the verifier wins);
    // it must not fail the build, nor read the non-existent PEM file.
    let cfg = AuthConfig {
        mode: "jwt".into(),
        jwt: Some(JwtConfig {
            public_key_pem_file: Some("/nonexistent/key.pem".into()),
            ..jwt_claims_only()
        }),
        forward_auth: None,
        authz: None,
        scope: None,
    };
    let stub = StubVerifier {
        accepts: "good-token",
        claims: serde_json::json!({}),
    };
    assert!(Auth::build(&cfg, Some(Arc::new(stub))).unwrap().is_some());
}

#[test]
fn no_auth_when_mode_is_not_jwt() {
    let cfg = AuthConfig {
        mode: "none".into(),
        jwt: None,
        forward_auth: None,
        authz: None,
        scope: None,
    };
    assert!(Auth::build(&cfg, None).unwrap().is_none());
}

/// Without a crypto backend there is no built-in verifier, so a JWT config that
/// supplies none must fail loudly rather than silently accept every token.
#[cfg(not(feature = "builtin_jwt"))]
#[test]
fn jwt_mode_without_a_verifier_is_rejected() {
    let cfg = AuthConfig {
        mode: "jwt".into(),
        jwt: Some(jwt_claims_only()),
        forward_auth: None,
        authz: None,
        scope: None,
    };
    let Err(err) = Auth::build(&cfg, None) else {
        panic!("a jwt config with no verifier must not build");
    };
    assert!(
        err.contains("with_token_verifier"),
        "unexpected error: {err}"
    );
}

// --- built-in verifier: end-to-end JWT validation + policy enforcement ---

#[cfg(feature = "builtin_jwt")]
mod builtin {
    use super::*;
    use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
    use std::sync::atomic::{AtomicU32, Ordering};

    // Ed25519 test keypair (generated for tests only; not a secret).
    const TEST_PRIV_PEM: &str = "-----BEGIN PRIVATE KEY-----\n\
        MC4CAQAwBQYDK2VwBCIEIEVVO7H+T5tERRn/dzukOc8i9iYEKKtPh//qcrES+dCt\n\
        -----END PRIVATE KEY-----\n";
    const TEST_PUB_PEM: &str = "-----BEGIN PUBLIC KEY-----\n\
        MCowBQYDK2VwAyEARCMxEnaM2/dblLuPNgBZpTvSUXO5ir+XQ1nyzJm4CFw=\n\
        -----END PUBLIC KEY-----\n";

    fn temp_pub_pem() -> std::path::PathBuf {
        static N: AtomicU32 = AtomicU32::new(0);
        let path = std::env::temp_dir().join(format!(
            "sp_auth_{}_{}.pem",
            std::process::id(),
            N.fetch_add(1, Ordering::Relaxed)
        ));
        std::fs::write(&path, TEST_PUB_PEM).unwrap();
        path
    }

    fn sign(claims: serde_json::Value) -> String {
        let key = EncodingKey::from_ed_pem(TEST_PRIV_PEM.as_bytes()).unwrap();
        encode(&Header::new(Algorithm::EdDSA), &claims, &key).unwrap()
    }

    fn future_exp() -> i64 {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
        now + 3600
    }

    fn auth_with_policy(roles: &[&str]) -> Arc<Auth> {
        let cfg = AuthConfig {
            mode: "jwt".into(),
            jwt: Some(JwtConfig {
                issuer: Some("test-iss".into()),
                audience: Some("test-aud".into()),
                public_key_pem_file: Some(temp_pub_pem()),
                ..jwt_claims_only()
            }),
            forward_auth: Some(secure_policy(roles)),
            authz: None,
            scope: None,
        };
        Auth::build(&cfg, None).unwrap().unwrap()
    }

    #[tokio::test]
    async fn strips_client_supplied_claim_headers() {
        // A client forges x-user on an unprotected route with no token; the
        // proxy must not forward the forged value to the upstream.
        let app = app(auth_with_policy(&[]));
        let resp = app
            .oneshot(
                HttpRequest::get("/open")
                    .header("x-user", "forged-admin")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
        assert_eq!(body_string(resp).await, "");
    }

    #[tokio::test]
    async fn unauthenticated_role_check_is_401_not_403() {
        // Policy requires a role but not auth; a request with no token is
        // unauthenticated, so it must get 401, not 403.
        let cfg = AuthConfig {
            mode: "jwt".into(),
            jwt: Some(JwtConfig {
                jwks_uri: None,
                jwks_max_age_secs: 300,
                issuer: None,
                audience: None,
                public_key_pem_file: Some(temp_pub_pem()),
                claims_headers: HashMap::new(),
                roles_claim: "roles".into(),
                cache: Default::default(),
            }),
            forward_auth: Some(ForwardAuthConfig {
                policies: vec![RoutePolicyConfig {
                    path: "/secure".into(),
                    methods: vec!["*".into()],
                    require_auth: false,
                    required_roles: vec!["admin".into()],
                }],
                ..secure_policy(&[])
            }),
            authz: None,
            scope: None,
        };
        let auth = Auth::build(&cfg, None).unwrap().unwrap();
        let resp = app(auth)
            .oneshot(
                HttpRequest::get("/secure")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn rejects_missing_token_on_protected_route() {
        let app = app(auth_with_policy(&[]));
        let resp = app
            .oneshot(
                HttpRequest::get("/secure")
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn accepts_valid_token_and_injects_claim_header() {
        let app = app(auth_with_policy(&["admin"]));
        let token = sign(serde_json::json!({
            "iss": "test-iss", "aud": "test-aud", "exp": future_exp(),
            "sub": "user-42", "roles": ["admin"]
        }));
        let resp = app
            .oneshot(
                HttpRequest::get("/secure")
                    .header("authorization", format!("Bearer {token}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
        let body = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
        // The sub claim was forwarded to the handler as x-user.
        assert_eq!(&body[..], b"user-42");
    }

    #[tokio::test]
    async fn forbids_when_required_role_missing() {
        let app = app(auth_with_policy(&["admin"]));
        let token = sign(serde_json::json!({
            "iss": "test-iss", "aud": "test-aud", "exp": future_exp(),
            "sub": "user-42", "roles": ["viewer"]
        }));
        let resp = app
            .oneshot(
                HttpRequest::get("/secure")
                    .header("authorization", format!("Bearer {token}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn rejects_expired_and_wrong_issuer() {
        let app = app(auth_with_policy(&[]));
        let expired = sign(serde_json::json!({
            "iss": "test-iss", "aud": "test-aud", "exp": 1, "sub": "u", "roles": ["admin"]
        }));
        let resp = app
            .clone()
            .oneshot(
                HttpRequest::get("/secure")
                    .header("authorization", format!("Bearer {expired}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

        let wrong_iss = sign(serde_json::json!({
            "iss": "evil", "aud": "test-aud", "exp": future_exp(), "sub": "u", "roles": ["admin"]
        }));
        let resp = app
            .oneshot(
                HttpRequest::get("/secure")
                    .header("authorization", format!("Bearer {wrong_iss}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    async fn request(app: &axum::Router, token: &str) -> (StatusCode, String) {
        let resp = app
            .clone()
            .oneshot(
                HttpRequest::get("/secure")
                    .header("authorization", format!("Bearer {token}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let status = resp.status();
        (status, body_string(resp).await)
    }

    #[tokio::test]
    async fn repeated_token_is_verified_once_and_answers_the_same() {
        // The second request is served from the cache: same user header, same
        // status, and the signature checked only for the first.
        let auth = auth_with_policy(&["admin"]);
        let app = app(auth.clone());
        let token = sign(serde_json::json!({
            "iss": "test-iss", "aud": "test-aud", "exp": future_exp(),
            "sub": "user-42", "roles": ["admin"]
        }));
        assert_eq!(
            request(&app, &token).await,
            (StatusCode::OK, "user-42".into())
        );
        assert_eq!(auth.cached_tokens(), 1);
        assert_eq!(
            request(&app, &token).await,
            (StatusCode::OK, "user-42".into())
        );
        assert_eq!(auth.cached_tokens(), 1);
        assert_eq!(verifications(&auth), 1);
    }

    fn verifications(auth: &Auth) -> usize {
        auth.builtin_verifications.load(Ordering::Relaxed)
    }

    #[tokio::test]
    async fn oversized_tokens_are_verified_every_time() {
        let cfg = AuthConfig {
            mode: "jwt".into(),
            jwt: Some(JwtConfig {
                issuer: Some("test-iss".into()),
                audience: Some("test-aud".into()),
                public_key_pem_file: Some(temp_pub_pem()),
                cache: crate::config::parse_yaml("max_token_bytes: 64").unwrap(),
                ..jwt_claims_only()
            }),
            forward_auth: Some(secure_policy(&[])),
            authz: None,
            scope: None,
        };
        let auth = Auth::build(&cfg, None).unwrap().unwrap();
        let app = app(auth.clone());
        let token = sign(serde_json::json!({
            "iss": "test-iss", "aud": "test-aud", "exp": future_exp(), "sub": "user-42"
        }));
        assert!(token.len() > 64);
        for _ in 0..2 {
            assert_eq!(
                request(&app, &token).await,
                (StatusCode::OK, "user-42".into())
            );
        }
        assert_eq!(auth.cached_tokens(), 0);
        assert_eq!(verifications(&auth), 2);
    }

    #[tokio::test]
    async fn cached_claims_still_face_the_role_policy() {
        // Caching skips the signature check, never the policy: a cached token
        // without the role is refused every time.
        let auth = auth_with_policy(&["admin"]);
        let app = app(auth.clone());
        let token = sign(serde_json::json!({
            "iss": "test-iss", "aud": "test-aud", "exp": future_exp(),
            "sub": "user-42", "roles": ["viewer"]
        }));
        assert_eq!(request(&app, &token).await.0, StatusCode::FORBIDDEN);
        assert_eq!(auth.cached_tokens(), 1);
        assert_eq!(request(&app, &token).await.0, StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn rejected_tokens_are_never_cached() {
        let auth = auth_with_policy(&[]);
        let app = app(auth.clone());
        let expired = sign(serde_json::json!({
            "iss": "test-iss", "aud": "test-aud", "exp": 1, "sub": "u"
        }));
        let wrong_issuer = sign(serde_json::json!({
            "iss": "evil", "aud": "test-aud", "exp": future_exp(), "sub": "u"
        }));
        for token in [expired.as_str(), wrong_issuer.as_str(), "not.a.jwt"] {
            assert_eq!(request(&app, token).await.0, StatusCode::UNAUTHORIZED);
        }
        assert_eq!(auth.cached_tokens(), 0);
    }

    #[tokio::test]
    async fn cache_can_be_switched_off() {
        let cfg = AuthConfig {
            mode: "jwt".into(),
            jwt: Some(JwtConfig {
                issuer: Some("test-iss".into()),
                audience: Some("test-aud".into()),
                public_key_pem_file: Some(temp_pub_pem()),
                cache: crate::config::parse_yaml("enabled: false").unwrap(),
                ..jwt_claims_only()
            }),
            forward_auth: Some(secure_policy(&[])),
            authz: None,
            scope: None,
        };
        let auth = Auth::build(&cfg, None).unwrap().unwrap();
        let app = app(auth.clone());
        let token = sign(serde_json::json!({
            "iss": "test-iss", "aud": "test-aud", "exp": future_exp(), "sub": "user-42"
        }));
        for _ in 0..2 {
            assert_eq!(
                request(&app, &token).await,
                (StatusCode::OK, "user-42".into())
            );
        }
        assert_eq!(auth.cached_tokens(), 0);
        assert_eq!(verifications(&auth), 2);
    }

    #[test]
    fn jwks_max_age_below_the_refresh_interval_is_a_config_error() {
        // Refreshes are at least 60 s apart, so a shorter age could not keep
        // the removal bound it promises.
        let jwks = |max_age| AuthConfig {
            mode: "jwt".into(),
            jwt: Some(JwtConfig {
                jwks_uri: Some("http://127.0.0.1:1/jwks".into()),
                jwks_max_age_secs: max_age,
                ..jwt_claims_only()
            }),
            forward_auth: None,
            authz: None,
            scope: None,
        };
        let Err(err) = Auth::build(&jwks(59), None) else {
            panic!("a JWKS age below 60 s must be rejected");
        };
        assert!(err.contains("jwks_max_age_secs"), "{err}");
        assert!(Auth::build(&jwks(60), None).is_ok());
    }

    #[test]
    fn zero_sized_cache_is_a_config_error() {
        let cfg = AuthConfig {
            mode: "jwt".into(),
            jwt: Some(JwtConfig {
                public_key_pem_file: Some(temp_pub_pem()),
                cache: crate::config::parse_yaml("max_entries: 0").unwrap(),
                ..jwt_claims_only()
            }),
            forward_auth: None,
            authz: None,
            scope: None,
        };
        let Err(err) = Auth::build(&cfg, None) else {
            panic!("a zero-sized cache must be rejected");
        };
        assert!(err.contains("max_entries"), "{err}");
    }

    #[test]
    fn built_in_verifier_requires_a_key_source() {
        // No jwks_uri and no PEM: the built-in verifier has nothing to verify
        // against, which is a config error, not a permissive default.
        let cfg = AuthConfig {
            mode: "jwt".into(),
            jwt: Some(jwt_claims_only()),
            forward_auth: None,
            authz: None,
            scope: None,
        };
        let Err(err) = Auth::build(&cfg, None) else {
            panic!("a built-in verifier with no key source must not build");
        };
        assert!(err.contains("jwks_uri"), "unexpected error: {err}");
    }

    /// A build with both crypto backends linked (feature unification, or
    /// `--all-features`) must verify tokens like any other. `jsonwebtoken` can
    /// then not pick a provider from its own features and installs one that
    /// panics on first use, so the verifier has to select one itself.
    #[cfg(all(feature = "rust_crypto", feature = "aws_lc_rs"))]
    #[tokio::test]
    async fn verifies_with_both_crypto_backends_linked() {
        let app = app(auth_with_policy(&["admin"]));
        let token = sign(serde_json::json!({
            "iss": "test-iss", "aud": "test-aud", "exp": future_exp(),
            "sub": "user-42", "roles": ["admin"]
        }));
        let resp = app
            .oneshot(
                HttpRequest::get("/secure")
                    .header("authorization", format!("Bearer {token}"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
    }
}