rust-web-server 17.54.0

An HTTP web framework, reverse proxy, and server for Rust supporting HTTP/1.1, HTTP/2, and HTTP/3. Config-driven proxy mode (rws.config.toml with [[route]] / [[upstream]]) or library crate. No third-party HTTP dependencies.
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
//! 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`].
//!
//! # 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
//! let app = App::new()
//!     .wrap(JwtLayer::new(b"my-signing-secret"));
//! ```

#[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.get_header(Header::_AUTHORIZATION.to_string())?;
    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)
}

// ── 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.
    pub fn from_htpasswd_file(path: &str) -> Result<Self, String> {
        let contents = std::fs::read_to_string(path)
            .map_err(|e| format!("failed to read htpasswd file '{path}': {e}"))?;
        let users = parse_htpasswd(&contents);

        let validate: Box<dyn Fn(&str, &str) -> bool + Send + Sync> =
            Box::new(move |user: &str, pass: &str| match users.get(user) {
                Some(stored) => verify_htpasswd_credential(pass, stored),
                None => false,
            });

        Ok(BasicAuthLayer::new(validate))
    }
}

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> {
    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".to_string(),
                value: "Basic realm=\"Protected\"".to_string(),
            });
            r
        };

        let Some(header) = request.get_header(Header::_AUTHORIZATION.to_string()) 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) {
            next.execute(request, connection)
        } else {
            Ok(AppError::Unauthorized.into_response())
        }
    }
}

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

/// Middleware that verifies `Authorization: Bearer <token>` JWTs signed with
/// HMAC-SHA256 (HS256).
///
/// Rejects tokens with a past `exp` claim. All other validation (format,
/// algorithm, signature) is performed by [`verify_jwt`].
///
/// If a handler also needs the decoded claims, call [`verify_jwt`] again
/// inside the handler — the verification is cheap (~1 µs).
///
/// # 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 {
    secret: Vec<u8>,
}

impl JwtLayer {
    /// Create a layer that verifies JWTs signed with `secret`.
    pub fn new(secret: impl Into<Vec<u8>>) -> Self {
        JwtLayer { secret: secret.into() }
    }
}

impl Middleware for JwtLayer {
    fn handle(
        &self,
        request: &Request,
        connection: &ConnectionInfo,
        next: &dyn Application,
    ) -> Result<Response, String> {
        let token = extract_bearer_token(request)
            .and_then(|t| verify_jwt(&t, &self.secret));
        match token {
            Some(_) => next.execute(request, connection),
            None => Ok(AppError::Unauthorized.into_response()),
        }
    }
}