webserver-base 0.5.1

A Rust library which contains shared logic for all of my webserver projects.
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
//! Browser security headers, sent by default ([`SecurityHeaders::new`]). Replace the set with
//! [`WebServer::security_headers`](super::WebServer::security_headers), or turn it off with
//! [`WebServer::without_security_headers`](super::WebServer::without_security_headers) (rarely right).
//!
//! Every response gets `X-Content-Type-Options`, `Referrer-Policy` and `Permissions-Policy`.
//! An HTML response also gets `frame-ancestors`, `X-Frame-Options`, and the optional
//! [`ContentSecurityPolicy`]. An enforced policy carries `frame-ancestors` inside the one
//! `Content-Security-Policy` header; a report-only policy ignores that directive, so then
//! `frame-ancestors` stays enforced in its own header. The layer only sets headers; it never rewrites a body. A policy that
//! uses `{nonce}` gets a fresh nonce per request, which the layer hands to rendering as
//! `{{nonce}}` (see [`current_nonce`]); a template writes `nonce="{{nonce}}"` on each script it
//! trusts, so a script injected without it is blocked.

use std::collections::BTreeSet;
use std::sync::Arc;

use axum::extract::{Request, State};
use axum::http::header::{self, HeaderName, HeaderValue};
use axum::middleware::Next;
use axum::response::Response;
use uuid::Uuid;

tokio::task_local! {
    /// The nonce of the request being served, set by the layer for the handler's whole run.
    static NONCE: Arc<str>;
}

/// The current request's CSP nonce, for a template's `{{nonce}}`; empty when the request has none
/// (no policy uses `{nonce}`, or the call is off the request's task, such as a spawned one).
#[must_use]
pub fn current_nonce() -> String {
    NONCE
        .try_with(|nonce: &Arc<str>| nonce.to_string())
        .unwrap_or_default()
}

/// The placeholder in a [`ContentSecurityPolicy`] directive that becomes the response's nonce.
pub const NONCE_PLACEHOLDER: &str = "{nonce}";

const DEFAULT_REFERRER_POLICY: &str = "strict-origin-when-cross-origin";
const DEFAULT_PERMISSIONS_POLICY: &str =
    "camera=(), microphone=(), geolocation=(), payment=(), usb=()";
const DEFAULT_FRAME_ANCESTORS: &str = "'none'";

/// Whether a violation blocks the load or is only reported.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CspMode {
    /// `Content-Security-Policy-Report-Only`: nothing is blocked; the browser reports.
    ReportOnly,
    /// `Content-Security-Policy`: violations are blocked and reported.
    Enforce,
}

/// A Content-Security-Policy, built from directives.
///
/// A directive value containing [`NONCE_PLACEHOLDER`] gets this response's nonce. Templates read
/// the same value as `{{nonce}}` and write it on their own scripts; the layer does not touch the
/// body. Prefer [`SecurityHeaders::frame_ancestors`] over listing `frame-ancestors` here; if you do
/// list it, an enforced policy is merged with the server's so the stricter one holds (never
/// weaker than both applied together). A report-only policy never enforces it.
#[derive(Clone, Debug)]
pub struct ContentSecurityPolicy {
    mode: CspMode,
    directives: Vec<(String, String)>,
    report_uri: Option<String>,
}

impl ContentSecurityPolicy {
    /// An empty policy in `mode`; add directives with [`directive`](Self::directive).
    #[must_use]
    pub const fn new(mode: CspMode) -> Self {
        Self {
            mode,
            directives: Vec::new(),
            report_uri: None,
        }
    }

    /// Adds `name value`, such as `("script-src", "'self' 'nonce-{nonce}'")`.
    #[must_use]
    pub fn directive(mut self, name: &str, value: &str) -> Self {
        self.directives.push((name.to_owned(), value.to_owned()));
        self
    }

    /// Where the browser posts violation reports (`report-uri`).
    #[must_use]
    pub fn report_uri(mut self, uri: &str) -> Self {
        self.report_uri = Some(uri.to_owned());
        self
    }

    fn uses_nonce(&self) -> bool {
        self.directives
            .iter()
            .any(|(_, value): &(String, String)| value.contains(NONCE_PLACEHOLDER))
    }

    /// The policy text, with `frame_ancestors` (the server's own sources) merged in when `merge` is
    /// set. Returns the text and whether `frame-ancestors` still needs its own enforced header.
    ///
    /// Before merging, a response carried two enforced headers and the browser applied both, so
    /// the effective `frame-ancestors` was the intersection of the two. One header cannot hold two
    /// `frame-ancestors` (the browser ignores the second), so the merge never loosens that:
    /// - the site policy has none: the server's is appended;
    /// - the server's is `'none'`: it replaces the site's (nothing is stricter);
    /// - the site's is `'none'`, or lists the same sources as the server's: the site's stays;
    /// - any other pair cannot be intersected as text without parsing hosts and wildcards, so the
    ///   server's goes back into its own header and the browser intersects the two, as before.
    fn template(&self, frame_ancestors: &str, merge: bool) -> (String, bool) {
        let ours: &str = frame_ancestors.trim();
        // A `;` or `,` in any name, value or report URI could smuggle in a directive or a second
        // policy ahead of ours, and a control character hides a name from the match below until
        // `clean` strips it, so such a policy is never merged.
        let smuggles = |text: &str| text.contains([';', ',']) || text.chars().any(char::is_control);
        let merge: bool = merge
            && !smuggles(ours)
            && !self
                .directives
                .iter()
                .any(|(name, value): &(String, String)| smuggles(name) || smuggles(value))
            && !self.report_uri.as_deref().is_some_and(smuggles);
        let mut separate: bool = !merge;
        let mut parts: Vec<String> = Vec::new();
        let mut seen: bool = false;
        for (name, value) in &self.directives {
            if merge && name.trim().eq_ignore_ascii_case("frame-ancestors") {
                if seen {
                    // The browser ignores a repeated directive, so a repeat adds nothing.
                    continue;
                }
                seen = true;
                if ours == "'none'" {
                    parts.push("frame-ancestors 'none'".to_owned());
                } else if value.trim() == "'none'" || same_sources(value, ours) {
                    parts.push(format!("{name} {value}"));
                } else {
                    separate = true;
                    parts.push(format!("{name} {value}"));
                }
                continue;
            }
            parts.push(format!("{name} {value}"));
        }
        if merge && !seen {
            parts.push(format!("frame-ancestors {ours}"));
        }
        if let Some(uri) = &self.report_uri {
            parts.push(format!("report-uri {uri}"));
        }
        (parts.join("; "), separate)
    }

    const fn header_name(&self) -> HeaderName {
        match self.mode {
            CspMode::ReportOnly => header::CONTENT_SECURITY_POLICY_REPORT_ONLY,
            CspMode::Enforce => header::CONTENT_SECURITY_POLICY,
        }
    }
}

/// The security headers a server sends. [`new`](Self::new) is the strict default every
/// [`WebServer`](super::WebServer) uses unless the site replaces it.
#[derive(Clone, Debug)]
pub struct SecurityHeaders {
    referrer_policy: String,
    permissions_policy: String,
    frame_ancestors: String,
    csp: Option<ContentSecurityPolicy>,
}

impl Default for SecurityHeaders {
    fn default() -> Self {
        Self::new()
    }
}

impl SecurityHeaders {
    /// `nosniff`, `strict-origin-when-cross-origin`, camera, microphone, geolocation, payment and
    /// USB denied, and no framing by anyone.
    #[must_use]
    pub fn new() -> Self {
        Self {
            referrer_policy: DEFAULT_REFERRER_POLICY.to_owned(),
            permissions_policy: DEFAULT_PERMISSIONS_POLICY.to_owned(),
            frame_ancestors: DEFAULT_FRAME_ANCESTORS.to_owned(),
            csp: None,
        }
    }

    /// Replaces the `Referrer-Policy` value.
    #[must_use]
    pub fn referrer_policy(mut self, value: &str) -> Self {
        value.clone_into(&mut self.referrer_policy);
        self
    }

    /// Replaces the `Permissions-Policy` value.
    #[must_use]
    pub fn permissions_policy(mut self, value: &str) -> Self {
        value.clone_into(&mut self.permissions_policy);
        self
    }

    /// Replaces the `frame-ancestors` sources (default `'none'`). `X-Frame-Options` follows for
    /// `'none'` (`DENY`) and `'self'` (`SAMEORIGIN`), and is omitted otherwise.
    #[must_use]
    pub fn frame_ancestors(mut self, sources: &str) -> Self {
        sources.clone_into(&mut self.frame_ancestors);
        self
    }

    /// Adds a Content-Security-Policy to every HTML response.
    #[must_use]
    pub fn content_security_policy(mut self, policy: ContentSecurityPolicy) -> Self {
        self.csp = Some(policy);
        self
    }

    pub(super) fn build(self) -> Arc<Built> {
        let frame_options: Option<HeaderValue> = match self.frame_ancestors.trim() {
            "'none'" => Some(HeaderValue::from_static("DENY")),
            "'self'" => Some(HeaderValue::from_static("SAMEORIGIN")),
            _ => None,
        };
        let mut separate_frame: bool = true;
        let csp: Option<(HeaderName, String, bool)> = self.csp.as_ref().map(|policy| {
            let merge: bool = matches!(policy.mode, CspMode::Enforce);
            let (template, separate): (String, bool) =
                policy.template(&self.frame_ancestors, merge);
            separate_frame = separate;
            (policy.header_name(), clean(&template), policy.uses_nonce())
        });
        Arc::new(Built {
            referrer_policy: value(&self.referrer_policy),
            permissions_policy: value(&self.permissions_policy),
            frame_policy: separate_frame
                .then(|| value(&format!("frame-ancestors {}", self.frame_ancestors))),
            frame_options,
            csp,
        })
    }
}

/// Whether two `frame-ancestors` source lists name the same sources, in any order. Sources are
/// compared exactly: CSP paths are case-sensitive.
fn same_sources(a: &str, b: &str) -> bool {
    let set =
        |text: &str| -> BTreeSet<String> { text.split_whitespace().map(str::to_owned).collect() };
    set(a) == set(b)
}

/// `text` without control characters, which no header value can carry.
fn clean(text: &str) -> String {
    text.chars().filter(|c: &char| !c.is_control()).collect()
}

fn value(text: &str) -> HeaderValue {
    HeaderValue::from_str(&clean(text)).unwrap_or_else(|_| HeaderValue::from_static(""))
}

/// [`SecurityHeaders`] with every value turned into a header value once, at boot.
pub(super) struct Built {
    referrer_policy: HeaderValue,
    permissions_policy: HeaderValue,
    frame_policy: Option<HeaderValue>,
    frame_options: Option<HeaderValue>,
    csp: Option<(HeaderName, String, bool)>,
}

const X_FRAME_OPTIONS: HeaderName = HeaderName::from_static("x-frame-options");
const PERMISSIONS_POLICY: HeaderName = HeaderName::from_static("permissions-policy");

/// `router` with the security layer, when configured.
pub(super) fn apply(router: axum::Router, security: Option<SecurityHeaders>) -> axum::Router {
    let Some(security) = security else {
        return router;
    };
    router.layer(axum::middleware::from_fn_with_state(
        security.build(),
        layer,
    ))
}

async fn layer(State(built): State<Arc<Built>>, request: Request, next: Next) -> Response {
    let uses_nonce: bool = built.csp.as_ref().is_some_and(|(_, _, uses)| *uses);
    let (nonce, mut response): (Option<String>, Response) = if uses_nonce {
        let nonce: String = Uuid::new_v4().simple().to_string();
        let response: Response = NONCE
            .scope(Arc::from(nonce.as_str()), next.run(request))
            .await;
        (Some(nonce), response)
    } else {
        (None, next.run(request).await)
    };
    let headers = response.headers_mut();
    headers.insert(
        header::X_CONTENT_TYPE_OPTIONS,
        HeaderValue::from_static("nosniff"),
    );
    headers.insert(header::REFERRER_POLICY, built.referrer_policy.clone());
    headers.insert(PERMISSIONS_POLICY, built.permissions_policy.clone());

    let is_html: bool = headers
        .get(header::CONTENT_TYPE)
        .and_then(|value: &HeaderValue| value.to_str().ok())
        .is_some_and(|value: &str| {
            value
                .trim_start()
                .to_ascii_lowercase()
                .starts_with("text/html")
        });
    if !is_html {
        return response;
    }
    if let Some(frame_policy) = &built.frame_policy {
        headers.append(header::CONTENT_SECURITY_POLICY, frame_policy.clone());
    }
    if let Some(options) = &built.frame_options {
        headers.insert(X_FRAME_OPTIONS, options.clone());
    }
    let Some((name, template, _)) = &built.csp else {
        return response;
    };
    let policy: String = nonce.as_deref().map_or_else(
        || template.clone(),
        |nonce: &str| template.replace(NONCE_PLACEHOLDER, nonce),
    );
    if let Ok(value) = HeaderValue::from_str(&policy) {
        response.headers_mut().append(name.clone(), value);
    }
    response
}

#[cfg(test)]
mod tests {
    use axum::Router;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use axum::middleware::from_fn_with_state;
    use axum::response::Html;
    use axum::routing::get;
    use tower::ServiceExt;

    use super::*;

    fn app(headers: SecurityHeaders) -> Router {
        Router::new()
            .route(
                "/",
                get(|| async {
                    Html(format!(
                        "<script nonce=\"{}\">1</script><script>injected</script>",
                        current_nonce()
                    ))
                }),
            )
            .route("/api", get(|| async { "{}" }))
            .layer(from_fn_with_state(headers.build(), layer))
    }

    async fn get_path(app: &Router, path: &str) -> Response {
        app.clone()
            .oneshot(Request::get(path).body(Body::empty()).expect("a request"))
            .await
            .expect("infallible")
    }

    fn header_of<'a>(response: &'a Response, name: &str) -> Vec<&'a str> {
        response
            .headers()
            .get_all(name)
            .iter()
            .map(|value: &HeaderValue| value.to_str().expect("ascii"))
            .collect()
    }

    #[tokio::test]
    async fn an_html_page_gets_every_header_and_a_nonce_matching_its_scripts() {
        let policy: ContentSecurityPolicy = ContentSecurityPolicy::new(CspMode::ReportOnly)
            .directive("script-src", "'self' 'nonce-{nonce}'")
            .report_uri("/r");
        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
        let response: Response = get_path(&app, "/").await;
        assert_eq!(StatusCode::OK, response.status());
        assert_eq!(
            vec!["nosniff"],
            header_of(&response, "x-content-type-options")
        );
        assert_eq!(
            vec!["strict-origin-when-cross-origin"],
            header_of(&response, "referrer-policy")
        );
        assert_eq!(
            vec![DEFAULT_PERMISSIONS_POLICY],
            header_of(&response, "permissions-policy")
        );
        assert_eq!(vec!["DENY"], header_of(&response, "x-frame-options"));
        assert_eq!(
            vec!["frame-ancestors 'none'"],
            header_of(&response, "content-security-policy")
        );
        // Report-only cannot carry an enforced directive: two headers, frame-ancestors enforced.
        let report: Vec<&str> = header_of(&response, "content-security-policy-report-only");
        let nonce: String = report[0]
            .strip_prefix("script-src 'self' 'nonce-")
            .and_then(|rest: &str| rest.strip_suffix("'; report-uri /r"))
            .expect("the nonce is in the policy")
            .to_owned();
        assert_eq!(32, nonce.len());
        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        // The layer never rewrites the body: a script a template injected stays without a nonce.
        assert_eq!(
            format!("<script nonce=\"{nonce}\">1</script><script>injected</script>"),
            String::from_utf8_lossy(&body)
        );
    }

    #[tokio::test]
    async fn each_response_gets_its_own_nonce() {
        let policy: ContentSecurityPolicy =
            ContentSecurityPolicy::new(CspMode::Enforce).directive("script-src", "'nonce-{nonce}'");
        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
        let first: Response = get_path(&app, "/").await;
        let second: Response = get_path(&app, "/").await;
        let a: Vec<&str> = header_of(&first, "content-security-policy");
        let b: Vec<&str> = header_of(&second, "content-security-policy");
        assert_eq!(1, a.len());
        assert!(a[0].ends_with("; frame-ancestors 'none'"));
        assert_ne!(a[0], b[0]);
    }

    async fn enforced(site: &str, ours: &str) -> Vec<String> {
        let policy: ContentSecurityPolicy = ContentSecurityPolicy::new(CspMode::Enforce)
            .directive("default-src", "'self'")
            .directive("frame-ancestors", site);
        let app: Router = app(SecurityHeaders::new()
            .frame_ancestors(ours)
            .content_security_policy(policy));
        let response: Response = get_path(&app, "/").await;
        header_of(&response, "content-security-policy")
            .into_iter()
            .map(str::to_owned)
            .collect()
    }

    #[tokio::test]
    async fn an_enforced_policy_without_frame_ancestors_gets_ours_in_one_header() {
        let policy: ContentSecurityPolicy =
            ContentSecurityPolicy::new(CspMode::Enforce).directive("default-src", "'self'");
        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
        let response: Response = get_path(&app, "/").await;
        assert_eq!(
            vec!["default-src 'self'; frame-ancestors 'none'"],
            header_of(&response, "content-security-policy")
        );
    }

    #[tokio::test]
    async fn a_sites_own_frame_ancestors_never_loosens_the_merge() {
        // Ours is 'none' (default): ours wins, one header.
        assert_eq!(
            vec!["default-src 'self'; frame-ancestors 'none'"],
            enforced("https://a.example", "'none'").await
        );
        // Site 'none' is stricter than ours: the site's stays, one header.
        assert_eq!(
            vec!["default-src 'self'; frame-ancestors 'none'"],
            enforced("'none'", "'self'").await
        );
        // Same sources in another order: one header.
        assert_eq!(
            vec!["default-src 'self'; frame-ancestors 'self' https://a.example"],
            enforced("'self' https://a.example", "https://a.example 'self'").await
        );
        // Anything else cannot be intersected as text: both stay enforced, as before the merge.
        assert_eq!(
            vec![
                "frame-ancestors 'self'",
                "default-src 'self'; frame-ancestors https://a.example"
            ],
            enforced("https://a.example", "'self'").await
        );
    }

    #[tokio::test]
    async fn source_paths_are_compared_case_sensitively() {
        assert_eq!(
            vec![
                "frame-ancestors https://a.example/x",
                "default-src 'self'; frame-ancestors https://a.example/X"
            ],
            enforced("https://a.example/X", "https://a.example/x").await
        );
    }

    #[tokio::test]
    async fn a_semicolon_or_comma_in_the_policy_is_never_merged() {
        for smuggled in ["'self'; frame-ancestors *", "'self', frame-ancestors *"] {
            let policy: ContentSecurityPolicy =
                ContentSecurityPolicy::new(CspMode::Enforce).directive("default-src", smuggled);
            let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
            let response: Response = get_path(&app, "/").await;
            let headers: Vec<&str> = header_of(&response, "content-security-policy");
            assert!(
                headers.contains(&"frame-ancestors 'none'"),
                "{smuggled}: {headers:?}"
            );
            assert_eq!(2, headers.len(), "{smuggled}: {headers:?}");
        }
    }

    #[tokio::test]
    async fn a_control_character_in_a_directive_name_is_never_merged() {
        let policy: ContentSecurityPolicy =
            ContentSecurityPolicy::new(CspMode::Enforce).directive("frame-ancestors\u{1}", "*");
        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
        let response: Response = get_path(&app, "/").await;
        let headers: Vec<&str> = header_of(&response, "content-security-policy");
        assert!(headers.contains(&"frame-ancestors 'none'"), "{headers:?}");
        assert_eq!(2, headers.len(), "{headers:?}");
    }

    #[tokio::test]
    async fn a_report_only_policy_keeps_frame_ancestors_enforced_in_its_own_header() {
        let policy: ContentSecurityPolicy =
            ContentSecurityPolicy::new(CspMode::ReportOnly).directive("default-src", "'self'");
        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
        let response: Response = get_path(&app, "/").await;
        assert_eq!(
            vec!["frame-ancestors 'none'"],
            header_of(&response, "content-security-policy")
        );
        assert_eq!(
            vec!["default-src 'self'"],
            header_of(&response, "content-security-policy-report-only")
        );
    }

    #[tokio::test]
    async fn a_non_html_response_gets_only_the_always_on_headers() {
        let policy: ContentSecurityPolicy =
            ContentSecurityPolicy::new(CspMode::Enforce).directive("default-src", "'self'");
        let app: Router = app(SecurityHeaders::new().content_security_policy(policy));
        let response: Response = get_path(&app, "/api").await;
        assert_eq!(
            vec!["nosniff"],
            header_of(&response, "x-content-type-options")
        );
        assert!(response.headers().get("content-security-policy").is_none());
        assert!(response.headers().get("x-frame-options").is_none());
    }

    #[test]
    fn control_characters_are_removed_from_a_header_value() {
        let built = SecurityHeaders::new()
            .referrer_policy("no-ref\nerrer")
            .build();
        assert_eq!("no-referrer", built.referrer_policy);
    }

    #[test]
    fn the_default_permissions_policy_has_no_interest_cohort() {
        assert!(!DEFAULT_PERMISSIONS_POLICY.contains("interest-cohort"));
    }
}