rust-web-server 18.23.1

Single-binary web server and reverse proxy: automatic HTTPS (Let's Encrypt), HTTP/1.1, HTTP/2 and HTTP/3, load balancing, auth and rate limiting, configured in one TOML file. Also a Rust library: routing, middleware, MCP server, ORM, background jobs. No hyper, no Tower; HTTP/2 and HTTP/3 framing via h2 and quinn.
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
//! Built-in authentication middleware (`auth` Cargo feature).
//!
//! Enable with `features = ["auth"]` in your `Cargo.toml`. Adds `hmac` and
//! `sha2` (RustCrypto) as dependencies.
//!
//! # HTTP Basic Auth
//!
//! [`BasicAuthLayer`] validates `Authorization: Basic <base64>` credentials
//! against a caller-supplied closure. Issues a `WWW-Authenticate` challenge
//! when the header is absent.
//!
//! # JWT (HS256)
//!
//! [`JwtLayer`] verifies `Authorization: Bearer <token>` JWTs signed with
//! HMAC-SHA256. Tokens with a past `exp` claim are rejected. Use
//! [`verify_jwt`] directly in a handler if you also need the decoded
//! [`Claims`].
//!
//! # JWT (RS256 / ES256), `auth-asymmetric` feature
//!
//! [`JwtLayer::rs256`] and [`JwtLayer::es256`] verify JWTs signed with a
//! separate auth server's RSA or P-256 private key — the caller presents a
//! token, `JwtLayer` only needs the corresponding *public* key (PEM,
//! SubjectPublicKeyInfo format) to verify it. No JWKS endpoint or the full
//! `sso` feature is required; use [`crate::sso::JwksCache`] instead if you
//! need multi-key rotation via a live JWKS URL.
//!
//! # Example
//!
//! ```rust,no_run
//! use rust_web_server::app::App;
//! use rust_web_server::auth::{BasicAuthLayer, JwtLayer};
//! use rust_web_server::core::New;
//!
//! // Basic Auth
//! let app = App::new()
//!     .wrap(BasicAuthLayer::new(|user, pass| user == "admin" && pass == "secret"));
//!
//! // JWT (HS256)
//! let app = App::new()
//!     .wrap(JwtLayer::new(b"my-signing-secret"));
//! ```
//!
//! ```rust,no_run
//! # #[cfg(feature = "auth-asymmetric")] {
//! use rust_web_server::app::App;
//! use rust_web_server::auth::JwtLayer;
//! use rust_web_server::core::New;
//!
//! // JWT (RS256) — public_key_pem is a SubjectPublicKeyInfo PEM string,
//! // e.g. produced by `openssl rsa -in key.pem -pubout`.
//! let public_key_pem = "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----\n";
//! let app = App::new().wrap(JwtLayer::rs256(public_key_pem).unwrap());
//! # }
//! ```

pub mod forward;

#[cfg(test)]
mod tests;

use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};

use crate::application::Application;
use crate::error::{AppError, IntoResponse};
use crate::header::Header;
use crate::middleware::Middleware;
use crate::request::Request;
use crate::response::Response;
use crate::server::ConnectionInfo;

type HmacSha256 = Hmac<Sha256>;

// ── Base64 helpers ────────────────────────────────────────────────────────────

// Decodes standard base64 (+/) and base64url (-_) — accepts either alphabet.
// Padding characters ('=') are stripped before decoding.
fn base64_decode(input: &str) -> Option<Vec<u8>> {
    let bytes: Vec<u8> = input.bytes().filter(|&b| b != b'=').collect();
    if bytes.len() % 4 == 1 {
        return None;
    }
    let mut out = Vec::with_capacity(bytes.len() * 3 / 4);
    for chunk in bytes.chunks(4) {
        let a = b64_val(chunk[0])?;
        let b = b64_val(chunk[1])?;
        out.push((a << 2) | (b >> 4));
        if chunk.len() > 2 {
            let c = b64_val(chunk[2])?;
            out.push((b << 4) | (c >> 2));
            if chunk.len() > 3 {
                let d = b64_val(chunk[3])?;
                out.push((c << 6) | d);
            }
        }
    }
    Some(out)
}

fn b64_val(b: u8) -> Option<u8> {
    match b {
        b'A'..=b'Z' => Some(b - b'A'),
        b'a'..=b'z' => Some(b - b'a' + 26),
        b'0'..=b'9' => Some(b - b'0' + 52),
        b'+' | b'-' => Some(62),
        b'/' | b'_' => Some(63),
        _ => None,
    }
}

// URL-safe base64 encoding without padding — used for JWT signature computation.
fn base64url_encode(input: &[u8]) -> String {
    const C: &[u8; 64] =
        b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let mut out = String::with_capacity((input.len() + 2) / 3 * 4);
    for chunk in input.chunks(3) {
        let b0 = chunk[0] as usize;
        let b1 = if chunk.len() > 1 { chunk[1] as usize } else { 0 };
        let b2 = if chunk.len() > 2 { chunk[2] as usize } else { 0 };
        out.push(C[b0 >> 2] as char);
        out.push(C[((b0 & 3) << 4) | (b1 >> 4)] as char);
        if chunk.len() > 1 { out.push(C[((b1 & 0xf) << 2) | (b2 >> 6)] as char); }
        if chunk.len() > 2 { out.push(C[b2 & 0x3f] as char); }
    }
    out
}

// Standard base64 encoding with padding — used to build Basic Auth headers.
// pub(crate): reused by proxy_config's tests to build Authorization headers.
pub(crate) fn base64_encode(input: &[u8]) -> String {
    const C: &[u8; 64] =
        b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity((input.len() + 2) / 3 * 4);
    for chunk in input.chunks(3) {
        let b0 = chunk[0] as usize;
        let b1 = if chunk.len() > 1 { chunk[1] as usize } else { 0 };
        let b2 = if chunk.len() > 2 { chunk[2] as usize } else { 0 };
        out.push(C[b0 >> 2] as char);
        out.push(C[((b0 & 3) << 4) | (b1 >> 4)] as char);
        out.push(if chunk.len() > 1 { C[((b1 & 0xf) << 2) | (b2 >> 6)] as char } else { '=' });
        out.push(if chunk.len() > 2 { C[b2 & 0x3f] as char } else { '=' });
    }
    out
}

// ── Mini JSON claim extractor ─────────────────────────────────────────────────

fn extract_string_claim(json: &str, field: &str) -> Option<String> {
    let key = format!("\"{}\"", field);
    let start = json.find(key.as_str())?;
    let rest = json[start + key.len()..].trim_start();
    let rest = rest.strip_prefix(':')?.trim_start();
    let rest = rest.strip_prefix('"')?;
    Some(rest[..rest.find('"')?].to_string())
}

fn extract_u64_claim(json: &str, field: &str) -> Option<u64> {
    let key = format!("\"{}\"", field);
    let start = json.find(key.as_str())?;
    let rest = json[start + key.len()..].trim_start();
    let rest = rest.strip_prefix(':')?.trim_start();
    let end = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len());
    rest[..end].parse().ok()
}

// ── Claims ────────────────────────────────────────────────────────────────────

/// Decoded JWT payload.
///
/// Standard claims (`sub`, `exp`) are pre-extracted. For other claims, parse
/// [`Claims::raw`] with `serde_json` or the built-in json module.
pub struct Claims {
    /// The `sub` (subject) claim, if present.
    pub sub: Option<String>,
    /// The `exp` (expiration) claim as Unix seconds, if present.
    pub exp: Option<u64>,
    /// Raw UTF-8 JSON payload — inspect for custom claims.
    pub raw: String,
}

impl Claims {
    fn from_json(json: String) -> Self {
        Claims {
            sub: extract_string_claim(&json, "sub"),
            exp: extract_u64_claim(&json, "exp"),
            raw: json,
        }
    }

    /// Return `true` if the token is not yet expired at `now_secs` (Unix
    /// timestamp). Returns `true` when `exp` is absent (no expiry set).
    pub fn is_valid_at(&self, now_secs: u64) -> bool {
        self.exp.map_or(true, |exp| now_secs < exp)
    }
}

// ── JWT helpers ───────────────────────────────────────────────────────────────

fn unix_now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

/// Extract the raw token string from `Authorization: Bearer <token>`.
/// Returns `None` if the header is absent or does not start with `Bearer `.
pub fn extract_bearer_token(request: &Request) -> Option<String> {
    let h = request.header(Header::_AUTHORIZATION)?;
    h.value.strip_prefix("Bearer ").map(str::to_string)
}

/// Build a signed HS256 JWT from a JSON claims object.
///
/// Useful for generating test tokens or issuing tokens from a login handler.
///
/// ```rust,no_run
/// use rust_web_server::auth::build_jwt;
///
/// let token = build_jwt(r#"{"sub":"42","exp":9999999999}"#, b"secret");
/// ```
pub fn build_jwt(claims_json: &str, secret: &[u8]) -> String {
    let header = base64url_encode(br#"{"alg":"HS256","typ":"JWT"}"#);
    let payload = base64url_encode(claims_json.as_bytes());
    let message = format!("{}.{}", header, payload);
    let mut mac = HmacSha256::new_from_slice(secret).expect("HMAC accepts any key size");
    mac.update(message.as_bytes());
    let sig = mac.finalize().into_bytes();
    format!("{}.{}.{}", header, payload, base64url_encode(&sig))
}

/// Verify a JWT string against `secret` (HS256 only).
///
/// Returns [`Claims`] on success. Returns `None` on any failure: bad format,
/// unsupported algorithm, signature mismatch, or expired `exp` claim.
pub fn verify_jwt(token: &str, secret: &[u8]) -> Option<Claims> {
    let mut parts = token.splitn(3, '.');
    let header_b64 = parts.next()?;
    let payload_b64 = parts.next()?;
    let sig_b64 = parts.next()?;

    if sig_b64.contains('.') {
        return None; // more than 3 parts
    }

    // Verify algorithm is HS256
    let header_bytes = base64_decode(header_b64)?;
    let header_str = String::from_utf8(header_bytes).ok()?;
    if !header_str.contains("\"HS256\"") {
        return None;
    }

    // Constant-time signature verification
    let message = format!("{}.{}", header_b64, payload_b64);
    let expected = base64_decode(sig_b64)?;
    let mut mac = HmacSha256::new_from_slice(secret).ok()?;
    mac.update(message.as_bytes());
    mac.verify_slice(&expected).ok()?;

    // Decode claims
    let payload_bytes = base64_decode(payload_b64)?;
    let payload_str = String::from_utf8(payload_bytes).ok()?;
    let claims = Claims::from_json(payload_str);

    // Reject expired tokens
    if !claims.is_valid_at(unix_now()) {
        return None;
    }

    Some(claims)
}

/// Splits a JWT into its three base64url segments. Returns `None` if the
/// token doesn't have exactly three `.`-separated parts.
#[cfg(feature = "auth-asymmetric")]
fn split_jwt(token: &str) -> Option<(&str, &str, &str)> {
    let mut parts = token.splitn(3, '.');
    let header_b64 = parts.next()?;
    let payload_b64 = parts.next()?;
    let sig_b64 = parts.next()?;
    if sig_b64.contains('.') {
        return None; // more than 3 parts
    }
    Some((header_b64, payload_b64, sig_b64))
}

/// Shared tail of `verify_jwt_rs256`/`verify_jwt_es256`, run after the
/// signature has already checked out: confirms the header's `alg` matches
/// what was actually verified (so an RS256 key can't be used to wave
/// through a token whose header merely claims HS256), decodes the claims,
/// and rejects expired tokens.
#[cfg(feature = "auth-asymmetric")]
fn finish_asymmetric_verification(header_str: &str, expected_alg: &str, payload_b64: &str) -> Option<Claims> {
    if !header_str.contains(&format!("\"{}\"", expected_alg)) {
        return None;
    }
    let payload_bytes = base64_decode(payload_b64)?;
    let payload_str = String::from_utf8(payload_bytes).ok()?;
    let claims = Claims::from_json(payload_str);
    if !claims.is_valid_at(unix_now()) {
        return None;
    }
    Some(claims)
}

/// Verify a JWT signed with RS256 (RSASSA-PKCS1-v1_5 using SHA-256) against
/// an RSA public key.
///
/// Returns [`Claims`] on success. Returns `None` on any failure: bad format,
/// a header `alg` other than `"RS256"`, signature mismatch, or an expired
/// `exp` claim.
#[cfg(feature = "auth-asymmetric")]
pub fn verify_jwt_rs256(token: &str, public_key: &crate::rsa_key::RsaPublicKey) -> Option<Claims> {
    let (header_b64, payload_b64, sig_b64) = split_jwt(token)?;
    let header_str = String::from_utf8(base64_decode(header_b64)?).ok()?;

    let message = format!("{}.{}", header_b64, payload_b64);
    let signature = base64_decode(sig_b64)?;
    if !public_key.verify_pkcs1v15_sha256(message.as_bytes(), &signature) {
        return None;
    }

    finish_asymmetric_verification(&header_str, "RS256", payload_b64)
}

/// Verify a JWT signed with ES256 (ECDSA using P-256 and SHA-256) against a
/// P-256 public key.
///
/// Returns [`Claims`] on success. Returns `None` on any failure: bad format,
/// a header `alg` other than `"ES256"`, signature mismatch, or an expired
/// `exp` claim.
///
/// JWT ES256 signatures are the raw 64-byte `r || s` concatenation, not the
/// ASN.1 DER encoding OpenSSL produces by default.
#[cfg(feature = "auth-asymmetric")]
pub fn verify_jwt_es256(token: &str, public_key: &p256::ecdsa::VerifyingKey) -> Option<Claims> {
    use p256::ecdsa::signature::Verifier;
    use p256::ecdsa::Signature as EcSignature;

    let (header_b64, payload_b64, sig_b64) = split_jwt(token)?;
    let header_str = String::from_utf8(base64_decode(header_b64)?).ok()?;

    let message = format!("{}.{}", header_b64, payload_b64);
    let signature = base64_decode(sig_b64)?;
    if signature.len() != 64 {
        return None;
    }
    let sig = EcSignature::from_slice(&signature).ok()?;
    public_key.verify(message.as_bytes(), &sig).ok()?;

    finish_asymmetric_verification(&header_str, "ES256", payload_b64)
}

// ── BasicAuthLayer ────────────────────────────────────────────────────────────

/// Middleware that validates HTTP Basic Auth credentials.
///
/// Issues `401 Unauthorized` with `WWW-Authenticate: Basic realm="Protected"`
/// when the header is absent or malformed. Issues `401` (without the
/// challenge) when credentials are present but the validator returns `false`.
///
/// Passwords containing `:` are handled correctly (only the first `:` splits
/// username from password, per RFC 7617).
///
/// # Example
///
/// ```rust,no_run
/// use rust_web_server::app::App;
/// use rust_web_server::auth::BasicAuthLayer;
/// use rust_web_server::core::New;
///
/// let app = App::new().wrap(BasicAuthLayer::new(|user, pass| {
///     user == "admin" && pass == "s3cret"
/// }));
/// ```
pub struct BasicAuthLayer<F> {
    validate: F,
}

impl<F: Fn(&str, &str) -> bool + Send + Sync + 'static> BasicAuthLayer<F> {
    /// Create a layer with a `validate(username, password) -> bool` closure.
    pub fn new(validate: F) -> Self {
        BasicAuthLayer { validate }
    }
}

impl BasicAuthLayer<Box<dyn Fn(&str, &str) -> bool + Send + Sync>> {
    /// Create a layer that validates credentials against an htpasswd-style
    /// file, loaded once at construction time (not re-read per request).
    ///
    /// Each non-empty, non-comment (`#`-prefixed) line must be
    /// `username:credential`, where `credential` is one of:
    /// - a plain-text password (Apache's `htpasswd -p` format), or
    /// - `{SHA256}` followed by the base64-encoded SHA-256 digest of the
    ///   password — **this is rws's own scheme, not Apache's**.
    ///
    /// # Not supported
    ///
    /// Apache's real `{SHA}` scheme (SHA-1), `$apr1$` (iterated MD5), and
    /// bcrypt (`$2y$`/`$2b$`) are **not** supported — this crate has no
    /// third-party HTTP/crypto dependencies beyond the audited RustCrypto
    /// hash crates it already uses, and hand-rolling SHA-1/MD5/bcrypt from
    /// scratch is not a risk worth taking for a security check. A real
    /// Apache-generated htpasswd file (which defaults to bcrypt or `$apr1$`
    /// in modern `htpasswd` versions) will **not** verify against this —
    /// regenerate it with `htpasswd -p` (plain text) or write your own
    /// `{SHA256}` entries, or use [`BasicAuthLayer::new`] with your own
    /// closure (e.g. backed by the `bcrypt` crate) if you need real
    /// Apache-hash compatibility.
    ///
    /// # Errors
    ///
    /// Returns `Err` if `path` can't be read.
    ///
    /// The file is re-read when it changes (18.20.0): adding or removing a
    /// user takes effect within a second, without a restart. Several files,
    /// comma-separated, are read together (one per team, say).
    pub fn from_htpasswd_file(path: &str) -> Result<Self, String> {
        let paths: Vec<String> = path.split(',').map(str::trim).filter(|p| !p.is_empty()).map(str::to_string).collect();
        if paths.is_empty() {
            return Err("no htpasswd file given".to_string());
        }
        let users = HtpasswdUsers::load(&paths)?;
        let validate: Box<dyn Fn(&str, &str) -> bool + Send + Sync> = Box::new(move |user: &str, pass: &str| users.check(user, pass));
        Ok(BasicAuthLayer::new(validate))
    }
}

/// HS256 against the secret the token's `kid` names, else each secret.
fn verify_with_any(token: &str, secrets: &[(Option<String>, Vec<u8>)]) -> Option<Claims> {
    let kid = token.split('.').next().and_then(base64_decode).and_then(|h| String::from_utf8(h).ok()).and_then(|h| crate::mcp::json_rpc::extract_str(&h, "kid"));
    if let Some(kid) = kid.as_deref() {
        if let Some((_, secret)) = secrets.iter().find(|(k, _)| k.as_deref() == Some(kid)) {
            return verify_jwt(token, secret);
        }
    }
    secrets.iter().find_map(|(_, secret)| verify_jwt(token, secret))
}

/// htpasswd files re-read when one changes (size or mtime, looked at most
/// once a second), so adding or removing a user needs no restart. A file
/// that can't be read keeps the users read before.
struct HtpasswdUsers {
    paths: Vec<String>,
    state: std::sync::Mutex<HtpasswdState>,
}

struct HtpasswdState {
    users: HashMap<String, String>,
    stamps: Vec<Option<(u64, SystemTime)>>,
    checked: std::time::Instant,
}

impl HtpasswdUsers {
    fn load(paths: &[String]) -> Result<HtpasswdUsers, String> {
        let mut users = HashMap::new();
        let mut stamps = Vec::new();
        for path in paths {
            let contents = std::fs::read_to_string(path).map_err(|e| format!("failed to read htpasswd file '{path}': {e}"))?;
            users.extend(parse_htpasswd(&contents));
            stamps.push(stamp(path));
        }
        Ok(HtpasswdUsers { paths: paths.to_vec(), state: std::sync::Mutex::new(HtpasswdState { users, stamps, checked: std::time::Instant::now() }) })
    }

    fn check(&self, user: &str, password: &str) -> bool {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        if state.checked.elapsed() >= std::time::Duration::from_secs(1) {
            state.checked = std::time::Instant::now();
            let now: Vec<_> = self.paths.iter().map(|p| stamp(p)).collect();
            if now != state.stamps {
                let mut users = HashMap::new();
                let mut ok = true;
                for path in &self.paths {
                    match std::fs::read_to_string(path) {
                        Ok(contents) => users.extend(parse_htpasswd(&contents)),
                        Err(e) => {
                            eprintln!("basic auth: can't re-read '{path}': {e}; keeping the users read before");
                            ok = false;
                            break;
                        }
                    }
                }
                if ok {
                    state.users = users;
                    state.stamps = now;
                }
            }
        }
        state.users.get(user).is_some_and(|stored| verify_htpasswd_credential(password, stored))
    }
}

fn stamp(path: &str) -> Option<(u64, SystemTime)> {
    std::fs::metadata(path).ok().map(|m| (m.len(), m.modified().unwrap_or(UNIX_EPOCH)))
}

fn parse_htpasswd(contents: &str) -> HashMap<String, String> {
    contents
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .filter_map(|line| line.split_once(':'))
        .map(|(user, cred)| (user.to_string(), cred.to_string()))
        .collect()
}

fn verify_htpasswd_credential(password: &str, stored: &str) -> bool {
    match stored.strip_prefix("{SHA256}") {
        Some(expected_b64) => base64_encode(&Sha256::digest(password.as_bytes())) == expected_b64,
        None => stored == password,
    }
}

impl<F: Fn(&str, &str) -> bool + Send + Sync + 'static> Middleware for BasicAuthLayer<F> {
    /// Headers only: a streamed body passes through untouched.
    fn accepts_streamed_body(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
        true
    }


    fn handle(
        &self,
        request: &Request,
        connection: &ConnectionInfo,
        next: &dyn Application,
    ) -> Result<Response, String> {
        let challenge = || {
            let mut r = AppError::Unauthorized.into_response();
            r.headers.push(Header {
                name: "WWW-Authenticate".into(),
                value: "Basic realm=\"Protected\"".into(),
            });
            r
        };

        let Some(header) = request.header(Header::_AUTHORIZATION) else {
            return Ok(challenge());
        };
        let Some(encoded) = header.value.strip_prefix("Basic ") else {
            return Ok(challenge());
        };
        let Some(decoded) = base64_decode(encoded) else {
            return Ok(challenge());
        };
        let Ok(credentials) = String::from_utf8(decoded) else {
            return Ok(challenge());
        };
        let Some((user, pass)) = credentials.split_once(':') else {
            return Ok(challenge());
        };

        if (self.validate)(user, pass) {
            match crate::authz::Identity::user(user, "basic") {
                Some(identity) => crate::authz::with_identity(identity, || next.execute(request, connection)),
                None => next.execute(request, connection),
            }
        } else {
            Ok(AppError::Unauthorized.into_response())
        }
    }
}

// ── JwtLayer ──────────────────────────────────────────────────────────────────

/// Middleware that verifies `Authorization: Bearer <token>` JWTs.
///
/// [`JwtLayer::new`] verifies HMAC-SHA256 (HS256) tokens against a shared
/// secret. With the `auth-asymmetric` feature, [`JwtLayer::rs256`] and
/// [`JwtLayer::es256`] verify tokens signed by a separate auth server's
/// private key, given only its public key.
///
/// Rejects tokens with a past `exp` claim. All other validation (format,
/// algorithm, signature) is performed by [`verify_jwt`] / [`verify_jwt_rs256`]
/// / [`verify_jwt_es256`].
///
/// If a handler also needs the decoded claims, call the matching `verify_*`
/// function again inside the handler — verification is cheap.
///
/// # Example
///
/// ```rust,no_run
/// use rust_web_server::app::App;
/// use rust_web_server::auth::JwtLayer;
/// use rust_web_server::core::New;
///
/// let app = App::new().wrap(JwtLayer::new(b"my-signing-secret"));
/// ```
pub struct JwtLayer {
    verifier: JwtVerifier,
    /// The claim naming the caller's [`Identity`](crate::authz::Identity).
    identity_claim: String,
}

enum JwtVerifier {
    /// Every accepted secret, with the `kid` that names it (key rotation).
    Hs256(Vec<(Option<String>, Vec<u8>)>),
    #[cfg(feature = "auth-asymmetric")]
    Rs256(Box<crate::rsa_key::RsaPublicKey>),
    #[cfg(feature = "auth-asymmetric")]
    Es256(Box<p256::ecdsa::VerifyingKey>),
}

impl JwtLayer {
    /// Create a layer that verifies HS256 JWTs signed with `secret`.
    pub fn new(secret: impl Into<Vec<u8>>) -> Self {
        JwtLayer { verifier: JwtVerifier::Hs256(vec![(None, secret.into())]), identity_claim: "sub".to_string() }
    }

    /// Create a layer that verifies HS256 JWTs signed with any of `secrets`
    /// (18.20.0): rotate by adding the new secret, keeping the old one until
    /// the tokens it signed have expired, then removing it.
    pub fn secrets<I, S>(secrets: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<Vec<u8>>,
    {
        let list = secrets.into_iter().map(|s| (None, s.into())).filter(|(_, s): &(Option<String>, Vec<u8>)| !s.is_empty()).collect();
        JwtLayer { verifier: JwtVerifier::Hs256(list), identity_claim: "sub".to_string() }
    }

    /// Also accept HS256 tokens signed with `secret`; a token whose header
    /// says `"kid": kid` is checked against this secret only.
    pub fn secret_with_kid(mut self, kid: impl Into<String>, secret: impl Into<Vec<u8>>) -> Self {
        // The only kind without `auth-asymmetric`.
        #[allow(irrefutable_let_patterns)]
        if let JwtVerifier::Hs256(list) = &mut self.verifier {
            list.push((Some(kid.into()), secret.into()));
        }
        self
    }

    /// Create a layer that verifies RS256 JWTs against an RSA public key.
    ///
    /// `public_key_pem` is a `-----BEGIN PUBLIC KEY-----` block
    /// (SubjectPublicKeyInfo — `openssl rsa -in key.pem -pubout`,
    /// `openssl req -pubkey`) or a `-----BEGIN RSA PUBLIC KEY-----` (PKCS#1)
    /// block; 2048–8192-bit keys.
    ///
    /// # Errors
    ///
    /// Returns `Err` if `public_key_pem` is not a valid PEM-encoded RSA
    /// public key.
    #[cfg(feature = "auth-asymmetric")]
    pub fn rs256(public_key_pem: &str) -> Result<Self, String> {
        let key = crate::rsa_key::RsaPublicKey::from_public_key_pem(public_key_pem)
            .map_err(|e| format!("invalid RSA public key: {e}"))?;
        Ok(JwtLayer { verifier: JwtVerifier::Rs256(Box::new(key)), identity_claim: "sub".to_string() })
    }

    /// Create a layer that verifies ES256 JWTs against a P-256 public key.
    ///
    /// `public_key_pem` must be in SubjectPublicKeyInfo PEM format (the
    /// `-----BEGIN PUBLIC KEY-----` block produced by, e.g.,
    /// `openssl ec -in key.pem -pubout`).
    ///
    /// # Errors
    ///
    /// Returns `Err` if `public_key_pem` is not a valid PEM-encoded P-256
    /// public key.
    #[cfg(feature = "auth-asymmetric")]
    pub fn es256(public_key_pem: &str) -> Result<Self, String> {
        use p256::pkcs8::DecodePublicKey;
        let key = p256::ecdsa::VerifyingKey::from_public_key_pem(public_key_pem)
            .map_err(|e| format!("invalid P-256 public key: {e}"))?;
        Ok(JwtLayer { verifier: JwtVerifier::Es256(Box::new(key)), identity_claim: "sub".to_string() })
    }
}

impl JwtLayer {
    /// The claim that names the caller's
    /// [`Identity`](crate::authz::Identity) (default `sub`; e.g. `email`).
    /// A token without it is still accepted, with no identity.
    pub fn identity_claim(mut self, claim: impl Into<String>) -> Self {
        self.identity_claim = claim.into();
        self
    }
}

impl Middleware for JwtLayer {
    /// Headers only: a streamed body passes through untouched.
    fn accepts_streamed_body(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
        true
    }


    fn handle(
        &self,
        request: &Request,
        connection: &ConnectionInfo,
        next: &dyn Application,
    ) -> Result<Response, String> {
        let claims = extract_bearer_token(request).and_then(|t| match &self.verifier {
            JwtVerifier::Hs256(secrets) => verify_with_any(&t, secrets),
            #[cfg(feature = "auth-asymmetric")]
            JwtVerifier::Rs256(key) => verify_jwt_rs256(&t, key),
            #[cfg(feature = "auth-asymmetric")]
            JwtVerifier::Es256(key) => verify_jwt_es256(&t, key),
        });
        match claims {
            Some(claims) => match crate::authz::Identity::from_claims(&claims.raw, &self.identity_claim, "jwt") {
                Some(identity) => crate::authz::with_identity(identity, || next.execute(request, connection)),
                None => next.execute(request, connection),
            },
            None => Ok(AppError::Unauthorized.into_response()),
        }
    }
}