proa_framework_axum 0.4.2

Axum and Tokio adapter for Proa SSR applications.
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
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Per-request CSP nonce generation and a strict `Content-Security-Policy`.
//!
//! Proa can already stamp a validated [`CspNonce`] onto every script tag it
//! emits (RSJS seed state and runtime tags, the
//! streaming bootstrap, and every out-of-order boundary swap). What it cannot
//! do on its own is mint the per-response
//! random value and write the matching header, because that is HTTP-level
//! work outside the render path.
//!
//! [`CspNonceLayer`] closes that gap: it generates a 128-bit nonce per
//! request, inserts it into the request extensions where
//! [`RouteContextLayer`](crate::route::RouteContextLayer) picks it up, and
//! writes the assembled policy onto the response.
//!
//! ```rust,ignore
//! FrameworkBuilder::new()
//!     .with_strict_csp()
//!     .build();
//! ```
//!
//! That yields
//! `default-src 'self'; script-src 'nonce-…' 'strict-dynamic'; …` with no
//! script `'unsafe-inline'`. Raw `<script>` tags written by hand still need
//! their own `nonce` attribute. Components can read the request nonce with
//! [`WebContext::csp_nonce`](proa_core::WebContext::csp_nonce).

use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{ready, Context, Poll};

use axum::http::{header, HeaderName, HeaderValue, Request, Response};
use base64::engine::general_purpose::STANDARD_NO_PAD;
use base64::Engine as _;
use bytes::Bytes;
use pin_project::pin_project;
use rand::Rng as _;
use tower::{Layer, Service};

use proa_core::CspNonce;

/// Nonce entropy in bytes. CSP recommends at least 128 bits per response.
const NONCE_BYTES: usize = 16;

/// The `script-src` sources Proa always emits ahead of any application
/// additions: the request nonce, then `'strict-dynamic'` so scripts loaded
/// by an already-trusted script inherit trust instead of needing a
/// host allowlist.
const SCRIPT_SRC_PREFIX: &str = "'nonce-";
const SCRIPT_SRC_SUFFIX: &str = "' 'strict-dynamic'";

/// Non-script directives applied unless overridden with
/// [`CspPolicy::with_directive`].
///
/// `style-src` keeps `'unsafe-inline'` because inline `style` attributes are
/// common in real templates and, unlike inline script, cannot execute code.
/// Tighten it once your app has moved those styles into classes.
const DEFAULT_DIRECTIVES: &[(&str, &str)] = &[
    ("default-src", "'self'"),
    ("base-uri", "'self'"),
    ("object-src", "'none'"),
    ("frame-ancestors", "'none'"),
    ("style-src", "'self' 'unsafe-inline'"),
];

/// A strict, nonce-based Content Security Policy.
///
/// The `script-src` directive is owned by this type: it always begins with
/// the request nonce and `'strict-dynamic'`, and extra sources go through
/// [`allow_script_source`](Self::allow_script_source). Every other directive
/// can be replaced with [`with_directive`](Self::with_directive).
#[derive(Debug, Clone)]
pub struct CspPolicy {
    directives: BTreeMap<Cow<'static, str>, String>,
    /// Directives the application set explicitly, used to keep builder-level
    /// consistency warnings from firing on Proa's own defaults.
    explicit: BTreeSet<Cow<'static, str>>,
    script_src_extra: Vec<String>,
    report_only: bool,
}

impl Default for CspPolicy {
    fn default() -> Self {
        Self::strict()
    }
}

impl CspPolicy {
    /// The recommended strict policy: same-origin default, nonce plus
    /// `'strict-dynamic'` for scripts, no plugins, no framing, and a locked
    /// `base-uri`.
    pub fn strict() -> Self {
        Self {
            directives: DEFAULT_DIRECTIVES
                .iter()
                .map(|(name, value)| (Cow::Borrowed(*name), (*value).to_owned()))
                .collect(),
            explicit: BTreeSet::new(),
            script_src_extra: Vec::new(),
            report_only: false,
        }
    }

    /// Set or replace a directive, e.g.
    /// `with_directive("img-src", "'self' data: https://cdn.example")`.
    ///
    /// `script-src` cannot be set this way: replacing it would drop the
    /// nonce and silently break hydration. Use
    /// [`allow_script_source`](Self::allow_script_source) instead. Passing
    /// `"script-src"` logs a warning and leaves the policy unchanged.
    pub fn with_directive(
        mut self,
        name: impl Into<Cow<'static, str>>,
        value: impl Into<String>,
    ) -> Self {
        let name = name.into();
        if name.eq_ignore_ascii_case("script-src") {
            tracing::warn!(
                "CspPolicy::with_directive cannot set script-src; the nonce and \
                 'strict-dynamic' are managed by the layer. Use \
                 CspPolicy::allow_script_source to add sources."
            );
            return self;
        }
        self.explicit.insert(name.clone());
        self.directives.insert(name, value.into());
        self
    }

    /// Remove a directive from the policy entirely.
    pub fn without_directive(mut self, name: &str) -> Self {
        self.directives.remove(name);
        self.explicit.remove(name);
        self
    }

    /// Append an extra `script-src` source after the nonce and
    /// `'strict-dynamic'`.
    ///
    /// With `'strict-dynamic'` in play, modern browsers ignore host
    /// allowlists in `script-src`, so this is mainly for keyword sources
    /// (`'wasm-unsafe-eval'`) or as a fallback for browsers without
    /// `'strict-dynamic'` support.
    pub fn allow_script_source(mut self, source: impl Into<String>) -> Self {
        self.script_src_extra.push(source.into());
        self
    }

    /// Let pages load published files from the host that serves them in
    /// place of this server.
    ///
    /// Stylesheets, images, fonts, media, web manifests, and fetches are
    /// governed by directives that list hosts, so `origin` is appended to
    /// each of those,
    /// whether the application set the directive or it falls back to
    /// `default-src`. A directive the application set to `'none'` stays
    /// closed. `script-src` is not touched: the nonce authorizes each script
    /// tag whatever host it names, `'strict-dynamic'` extends that to the
    /// modules it imports, and browsers ignore host sources beside it.
    ///
    /// `FrameworkBuilder` calls this with the origin of `PROA_ASSET_PREFIX`.
    pub fn allow_asset_origin(mut self, origin: &str) -> Self {
        // Directive names are case-insensitive, and a policy that carries a
        // directive twice is read by its first copy. Find the application's
        // own spelling before deciding there is none.
        let spelled = |directives: &BTreeMap<Cow<'static, str>, String>, name: &str| {
            directives
                .keys()
                .find(|key| key.eq_ignore_ascii_case(name))
                .cloned()
        };
        let fallback = spelled(&self.directives, "default-src")
            .and_then(|key| self.directives.get(&key).cloned());
        // Every directive that governs a published file a page loads by URL.
        // The `-elem` forms override their parent for the tags they cover, so
        // they are extended where the application set them, never added.
        for (directive, only_if_set) in [
            ("style-src", false),
            ("style-src-elem", true),
            ("img-src", false),
            ("font-src", false),
            ("media-src", false),
            ("connect-src", false),
            ("manifest-src", false),
        ] {
            let key = spelled(&self.directives, directive);
            let own = key.as_ref().and_then(|key| self.directives.get(key));
            if own.is_some_and(|value| value.trim().eq_ignore_ascii_case("'none'")) {
                continue;
            }
            // With neither the directive nor a default, nothing is restricted.
            let Some(current) = own.or(if only_if_set { None } else { fallback.as_ref() }) else {
                continue;
            };
            if current
                .split_ascii_whitespace()
                .any(|source| source == origin || source == "*")
            {
                continue;
            }
            let value = if current.trim().eq_ignore_ascii_case("'none'") {
                origin.to_owned()
            } else {
                format!("{current} {origin}")
            };
            self.directives
                .insert(key.unwrap_or(Cow::Borrowed(directive)), value);
        }
        self
    }

    /// Send `Content-Security-Policy-Report-Only` instead of the enforcing
    /// header. Use this to observe violations before switching a live app
    /// over to enforcement.
    pub fn report_only(mut self, report_only: bool) -> Self {
        self.report_only = report_only;
        self
    }

    /// Whether this policy is observation-only. A report-only policy writes a
    /// different header, so it cannot collide with a configured static CSP
    /// and it does not actually block framing.
    pub(crate) fn is_report_only(&self) -> bool {
        self.report_only
    }

    /// Whether `frame-ancestors` still holds Proa's restrictive default.
    /// The builder uses this to flag a policy that would keep an app from
    /// being framed even though `X-Frame-Options` was deliberately relaxed.
    pub(crate) fn frame_ancestors_is_default(&self) -> bool {
        !self.explicit.contains("frame-ancestors")
            && self.directives.contains_key("frame-ancestors")
    }

    /// Split the assembled policy around the nonce value so per-request work
    /// is one exact-capacity allocation.
    fn resolve(self) -> ResolvedCsp {
        let header_name = if self.report_only {
            HeaderName::from_static("content-security-policy-report-only")
        } else {
            header::CONTENT_SECURITY_POLICY
        };

        // proa-perf-ok(scope): one-time layer construction, not a render path.
        let mut prefix = String::new();
        let mut suffix = String::new();

        // `script-src` sorts among the other directives so the emitted
        // policy stays stable and readable; everything before it lands in
        // the prefix, everything after in the suffix.
        let mut before_script = true;
        for (name, value) in &self.directives {
            if before_script && name.as_ref() > "script-src" {
                before_script = false;
            }
            let out = if before_script {
                &mut prefix
            } else {
                &mut suffix
            };
            if !out.is_empty() {
                out.push_str("; ");
            }
            out.push_str(name);
            out.push(' ');
            out.push_str(value);
        }

        if !prefix.is_empty() {
            prefix.push_str("; ");
        }
        prefix.push_str("script-src ");
        prefix.push_str(SCRIPT_SRC_PREFIX);

        let mut tail = String::from(SCRIPT_SRC_SUFFIX);
        for source in &self.script_src_extra {
            tail.push(' ');
            tail.push_str(source);
        }
        if !suffix.is_empty() {
            tail.push_str("; ");
            tail.push_str(&suffix);
        }

        ResolvedCsp {
            header_name,
            prefix: prefix.into_boxed_str(),
            suffix: tail.into_boxed_str(),
            valid: true,
        }
        .validated()
    }
}

/// Header name plus the two halves of the policy string, resolved once.
#[derive(Debug)]
struct ResolvedCsp {
    header_name: HeaderName,
    prefix: Box<str>,
    suffix: Box<str>,
    /// Cleared when the assembled policy is not a legal header value, so a
    /// malformed directive drops the header instead of panicking per request.
    valid: bool,
}

impl ResolvedCsp {
    /// Prove at construction that the policy forms a valid header value, so
    /// the per-request path cannot fail on a value the app cannot fix.
    fn validated(mut self) -> Self {
        let sample = CspNonce::new("c2FtcGxlLW5vbmNlLXZhbHVl").expect("sample nonce is base64");
        if self.header_value(&sample).is_none() {
            tracing::warn!(
                "assembled Content-Security-Policy contains characters that are \
                 illegal in a header value; the header will not be sent"
            );
            self.valid = false;
        }
        self
    }

    fn header_value(&self, nonce: &CspNonce) -> Option<HeaderValue> {
        let nonce = nonce.as_str();
        // proa-perf-ok: one exact-capacity allocation per response; a header
        // value must own its bytes, and `from_maybe_shared` avoids a second copy.
        let mut policy = String::with_capacity(self.prefix.len() + nonce.len() + self.suffix.len());
        policy.push_str(&self.prefix);
        policy.push_str(nonce);
        policy.push_str(&self.suffix);
        HeaderValue::from_maybe_shared(Bytes::from(policy)).ok()
    }
}

/// Generate a fresh 128-bit nonce for one response.
///
/// `rand::rng()` is a cryptographically secure, OS-seeded, automatically
/// reseeded generator; a predictable nonce would let an injected script
/// name it and defeat the policy.
fn fresh_nonce() -> CspNonce {
    let mut random = [0_u8; NONCE_BYTES];
    rand::rng().fill_bytes(&mut random);
    // proa-perf-ok: one small allocation per response, off the render path.
    CspNonce::new(STANDARD_NO_PAD.encode(random)).expect("base64 output is a valid CSP nonce")
}

/// Tower layer that mints a per-request [`CspNonce`] and writes the matching
/// `Content-Security-Policy` header.
///
/// The nonce goes into the request extensions before the inner service runs,
/// so it must sit outside
/// [`RouteContextLayer`](crate::route::RouteContextLayer);
/// [`FrameworkBuilder::with_strict_csp`](crate::FrameworkBuilder::with_strict_csp)
/// places it correctly. The header is only written when the response does
/// not already carry one, so a handler that sets its own policy wins.
#[derive(Debug, Clone)]
pub struct CspNonceLayer {
    resolved: Arc<ResolvedCsp>,
}

impl CspNonceLayer {
    pub fn new(policy: CspPolicy) -> Self {
        Self {
            resolved: Arc::new(policy.resolve()),
        }
    }

    /// Shorthand for [`CspPolicy::strict`].
    pub fn strict() -> Self {
        Self::new(CspPolicy::strict())
    }
}

impl Default for CspNonceLayer {
    fn default() -> Self {
        Self::strict()
    }
}

impl<S> Layer<S> for CspNonceLayer {
    type Service = CspNonceService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        CspNonceService {
            inner,
            resolved: Arc::clone(&self.resolved),
        }
    }
}

/// Tower service produced by [`CspNonceLayer`].
#[derive(Debug, Clone)]
pub struct CspNonceService<S> {
    inner: S,
    resolved: Arc<ResolvedCsp>,
}

impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for CspNonceService<S>
where
    S: Service<Request<ReqBody>, Response = Response<ResBody>>,
{
    type Response = Response<ResBody>;
    type Error = S::Error;
    type Future = CspNonceFuture<S::Future>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future {
        let nonce = fresh_nonce();
        let header = self
            .resolved
            .valid
            .then(|| self.resolved.header_value(&nonce))
            .flatten()
            .map(|value| (self.resolved.header_name.clone(), value));
        // The render path reads this back through `RouteContext`, which
        // installs it on every nested and deferred render context.
        req.extensions_mut().insert(nonce);

        CspNonceFuture {
            inner: self.inner.call(req),
            header,
        }
    }
}

/// Future returned by [`CspNonceService`].
#[pin_project]
pub struct CspNonceFuture<F> {
    #[pin]
    inner: F,
    header: Option<(HeaderName, HeaderValue)>,
}

impl<F, ResBody, E> Future for CspNonceFuture<F>
where
    F: Future<Output = Result<Response<ResBody>, E>>,
{
    type Output = Result<Response<ResBody>, E>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        let mut result = ready!(this.inner.poll(cx));
        if let Ok(response) = &mut result {
            if let Some((name, value)) = this.header.take() {
                let headers = response.headers_mut();
                if !headers.contains_key(&name) {
                    headers.insert(name, value);
                }
            }
        }
        Poll::Ready(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use std::convert::Infallible;
    use tower::{service_fn, ServiceExt};

    fn policy_string(policy: CspPolicy) -> String {
        let resolved = policy.resolve();
        let nonce = CspNonce::new("dGVzdC1ub25jZQ").unwrap();
        resolved
            .header_value(&nonce)
            .unwrap()
            .to_str()
            .unwrap()
            .to_owned()
    }

    #[test]
    fn an_asset_origin_is_added_wherever_a_host_list_decides() {
        const CDN: &str = "https://cdn.example";
        let has = |policy: &str, directive: &str| policy.split("; ").any(|part| part == directive);
        let strict = policy_string(CspPolicy::strict().allow_asset_origin(CDN));
        for directive in [
            "style-src 'self' 'unsafe-inline' https://cdn.example",
            "img-src 'self' https://cdn.example",
            "font-src 'self' https://cdn.example",
            "media-src 'self' https://cdn.example",
            "connect-src 'self' https://cdn.example",
            "manifest-src 'self' https://cdn.example",
            "script-src 'nonce-dGVzdC1ub25jZQ' 'strict-dynamic'",
        ] {
            assert!(
                has(&strict, directive),
                "missing `{directive}` in `{strict}`"
            );
        }
        assert!(!strict.contains("style-src-elem"));

        // The application's own directives are extended in place, whatever
        // their case, and one it closed stays closed.
        let custom = policy_string(
            CspPolicy::strict()
                .with_directive("Img-Src", "'self' data:")
                .with_directive("style-src-elem", "'self'")
                .with_directive("media-src", "'NONE'")
                .with_directive("font-src", "https://cdn.example")
                .allow_asset_origin(CDN),
        );
        for directive in [
            "Img-Src 'self' data: https://cdn.example",
            "style-src-elem 'self' https://cdn.example",
            "media-src 'NONE'",
            "font-src https://cdn.example",
        ] {
            assert!(
                has(&custom, directive),
                "missing `{directive}` in `{custom}`"
            );
        }
        assert_eq!(custom.to_ascii_lowercase().matches("img-src").count(), 1);

        // A default that closes everything opens only for the asset host.
        let closed = policy_string(
            CspPolicy::strict()
                .with_directive("default-src", "'none'")
                .without_directive("style-src")
                .allow_asset_origin(CDN),
        );
        assert!(has(&closed, "img-src https://cdn.example"), "{closed}");
        assert!(has(&closed, "style-src https://cdn.example"), "{closed}");
    }

    #[test]
    fn strict_policy_carries_the_nonce_and_strict_dynamic() {
        assert_eq!(
            policy_string(CspPolicy::strict()),
            "base-uri 'self'; default-src 'self'; frame-ancestors 'none'; \
             object-src 'none'; script-src 'nonce-dGVzdC1ub25jZQ' 'strict-dynamic'; \
             style-src 'self' 'unsafe-inline'"
        );
    }

    #[test]
    fn strict_policy_never_allows_unsafe_inline_script() {
        let policy = policy_string(CspPolicy::strict());
        let script_src = policy
            .split("; ")
            .find(|directive| directive.starts_with("script-src "))
            .unwrap();
        assert!(!script_src.contains("'unsafe-inline'"));
        assert!(!script_src.contains("'unsafe-eval'"));
    }

    #[test]
    fn directives_can_be_overridden_added_and_removed() {
        let policy = policy_string(
            CspPolicy::strict()
                .with_directive("style-src", "'self'")
                .with_directive("img-src", "'self' data:")
                .without_directive("frame-ancestors"),
        );
        assert!(policy.contains("style-src 'self'"));
        assert!(!policy.contains("'unsafe-inline'"));
        assert!(policy.contains("img-src 'self' data:"));
        assert!(!policy.contains("frame-ancestors"));
    }

    #[test]
    fn extra_script_sources_follow_the_nonce() {
        let policy = policy_string(CspPolicy::strict().allow_script_source("'wasm-unsafe-eval'"));
        assert!(policy
            .contains("script-src 'nonce-dGVzdC1ub25jZQ' 'strict-dynamic' 'wasm-unsafe-eval';"));
    }

    #[test]
    fn script_src_cannot_be_replaced_wholesale() {
        let policy = policy_string(CspPolicy::strict().with_directive("script-src", "'self'"));
        assert!(policy.contains("script-src 'nonce-dGVzdC1ub25jZQ' 'strict-dynamic'"));
    }

    #[test]
    fn a_directive_sorting_after_script_src_still_renders() {
        // `style-src` and anything later lands in the suffix half of the
        // split; a lost separator there would corrupt the policy.
        let policy = policy_string(CspPolicy::strict().with_directive("worker-src", "'self'"));
        assert!(policy.contains("'strict-dynamic'; style-src"));
        assert!(policy.ends_with("worker-src 'self'"));
    }

    #[test]
    fn report_only_uses_the_report_only_header_name() {
        let resolved = CspPolicy::strict().report_only(true).resolve();
        assert_eq!(resolved.header_name, "content-security-policy-report-only");
        assert!(resolved.valid);
    }

    #[test]
    fn a_malformed_directive_drops_the_header_instead_of_panicking() {
        let resolved = CspPolicy::strict()
            .with_directive("img-src", "bad\nvalue")
            .resolve();
        assert!(!resolved.valid);
    }

    #[test]
    fn frame_ancestors_default_is_distinguishable_from_an_explicit_value() {
        assert!(CspPolicy::strict().frame_ancestors_is_default());
        assert!(!CspPolicy::strict()
            .with_directive("frame-ancestors", "https://embedder.example")
            .frame_ancestors_is_default());
        assert!(!CspPolicy::strict()
            .without_directive("frame-ancestors")
            .frame_ancestors_is_default());
    }

    #[test]
    fn generated_nonces_are_unique_and_carry_128_bits() {
        let first = fresh_nonce();
        let second = fresh_nonce();
        assert_ne!(first.as_str(), second.as_str());
        // 16 bytes, base64 without padding.
        assert_eq!(first.as_str().len(), 22);
    }

    async fn call_layer<F>(layer: CspNonceLayer, handler: F) -> Response<Body>
    where
        F: Fn(Request<Body>) -> Response<Body> + Clone + Send + 'static,
    {
        let service = layer.layer(service_fn(move |req: Request<Body>| {
            let handler = handler.clone();
            async move { Ok::<_, Infallible>(handler(req)) }
        }));
        service
            .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn the_response_header_matches_the_nonce_in_the_request_extensions() {
        let response = call_layer(CspNonceLayer::strict(), |req| {
            let nonce = req
                .extensions()
                .get::<CspNonce>()
                .expect("layer installs the request nonce");
            Response::new(Body::from(nonce.as_str().to_owned()))
        })
        .await;

        let header = response
            .headers()
            .get(header::CONTENT_SECURITY_POLICY)
            .unwrap()
            .to_str()
            .unwrap()
            .to_owned();
        let body = axum::body::to_bytes(response.into_body(), 64)
            .await
            .unwrap();
        let seen_by_handler = std::str::from_utf8(&body).unwrap();

        assert!(header.contains(&format!("'nonce-{seen_by_handler}'")));
    }

    #[tokio::test]
    async fn a_handler_authored_policy_is_not_overwritten() {
        let response = call_layer(CspNonceLayer::strict(), |_req| {
            let mut response = Response::new(Body::empty());
            response.headers_mut().insert(
                header::CONTENT_SECURITY_POLICY,
                HeaderValue::from_static("default-src 'none'"),
            );
            response
        })
        .await;

        assert_eq!(
            response.headers().get(header::CONTENT_SECURITY_POLICY),
            Some(&HeaderValue::from_static("default-src 'none'"))
        );
    }
}