footing 0.6.2

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
//! Static frontend files with explicit SPA routing and cache policies.
//!
//! Enabled by `http-static`. [`StaticSite::build`] checks the deployment before
//! returning a Tower service; no routes, tasks or file reads are installed merely
//! by enabling the feature. File streaming, validators and conditional requests
//! use `tower-http`'s file services.
//!
//! # Routing contract
//!
//! Paths are relative to the service's mount point. Reserved paths always return
//! 404 from this service, even if a corresponding file exists. Asset paths serve
//! only real files. Other paths first try the filesystem, then may serve the SPA
//! entry when the target is missing or is a directory and `Accept` explicitly
//! includes `text/html` with positive quality. Missing/wildcard-only Accept does
//! not enable fallback. An existing directory never hides a same-named SPA page;
//! existing files still take precedence over fallback.
//! Declare **all** backend and asset namespaces: the service cannot infer whether
//! an unknown extensionless path is an API, asset or page. Dots in page names are
//! allowed. Prefixes match complete, case-sensitive URL segments, so `/api` does
//! not match `/apiculture`.
//!
//! [`StaticSite::with_entry`] maps `/` and the entry's own URL to an HTML file,
//! regardless of Accept. This does not enable SPA fallback: unknown paths still
//! return 404. [`StaticSite::with_spa_fallback`] independently enables fallback
//! to that entry; enabling it without an entry is a build error. With neither
//! option, only explicit file URLs are served. Subdirectories have no automatic
//! index or redirect behavior, with or without SPA fallback.
//!
//! Use Axum's `fallback_service` after registering backend routes, or
//! `nest_service` for a dedicated frontend mount. A nested API router can inherit
//! the outer fallback: reserve its prefix or give it its own fallback. Matched
//! backend responses, including their 404/405 responses, are left to that router.
//! Frontend asset URLs/base paths must be built for the mount point; HTML is never
//! rewritten. A frontend served at `/ui` should use `/ui/` as its canonical URL
//! when its HTML contains relative asset URLs; the host controls that redirect.
//!
//! # Caching and deployment
//!
//! Ordinary files and the SPA entry use `Cache-Control: no-cache`. Only explicitly
//! declared immutable asset paths use public long-lived caching. A 304 preserves
//! the selected cache policy; errors use `no-store`. SPA negotiation includes
//! `Vary: Accept`. File validators are weak so they remain valid under the host's
//! dynamic compression; responses also vary on Accept-Encoding, including 304.
//! Validators derive from size and modification time: deploy
//! changed files with updated metadata. Original files and precompressed variants
//! must have modification times at or after the Unix epoch (1970-01-01 UTC).
//! The underlying file service panics when formatting earlier modification times;
//! [`StaticSite::build`] does not validate file timestamps.
//! Files remain streamed from disk; do not
//! mutate a file while it is being served. Deploy immutable build directories and
//! rebuild the service when switching releases. Retain older versioned assets as
//! needed by clients still running a previous frontend.
//!
//! GET supports the underlying single-range file service. HEAD ignores Range;
//! requests containing If-Range receive the full representation rather than a
//! partial response. Other methods receive 405 with `Allow: GET, HEAD`.
//! Weak validators support If-None-Match revalidation, but only `If-Match: *`
//! can satisfy a strong precondition. Partial responses omit ETag, as HTTP does
//! not permit weak validators on 206 responses.
//!
//! The root directory and all symbolic-link targets must contain only publishable
//! build artifacts. URL exclusions are routing rules, **not** a filesystem sandbox
//! or authorization boundary. Authentication, compression, CSP and other security
//! headers belong to the host's existing middleware. No HTML is generated or
//! injected, and no CSP is relaxed automatically.
//!
//! # Precompressed files
//!
//! [`StaticSite::with_precompressed_br`] and
//! [`StaticSite::with_precompressed_gzip`] opt into serving existing `.br` and
//! `.gz` files. Both are disabled by default and apply to ordinary files, the
//! root entry and SPA fallback. Requests keep the original URL: `/assets/app.js`
//! can select `assets/app.js.br` according to `Accept-Encoding`, while retaining
//! the JavaScript content type and the URL's cache policy. No compression runs
//! during build or file serving, and no additional Cargo feature is needed.
//!
//! Publish the original files and their compressed variants together; each
//! variant must decode to the same content. The service does not decompress or
//! verify build artifacts. Explicitly accepted encodings are tried by quality,
//! with Brotli preferred over gzip at equal quality. Validators and lengths
//! describe the selected file; byte ranges address its encoded bytes. Keep
//! sending the same `Accept-Encoding` when revalidating a cached representation.
//!
//! Negotiation follows `tower-http`'s file-service behavior: `*` does not select
//! a compressed variant, and missing acceptable variants fall back to the
//! original file, even if `identity;q=0` was sent. This service is not a strict
//! encoding-rejection policy. The host's dynamic compression can additionally
//! compress original files; `HttpMiddlewareStack` (`http-stack`) preserves responses
//! already encoded by the file service.
//!
//! # Example
//!
//! ```no_run
//! use std::time::Duration;
//! use axum::{Router, middleware, routing::get, http::HeaderValue, response::Response};
//! use footing::http::{
//!     SecurityHeadersConfig,
//!     static_site::{StaticAssetCache, StaticSite},
//! };
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let frontend = StaticSite::new("dist")
//!     .with_entry("index.html")
//!     .with_spa_fallback(true)
//!     // Enable these when the build also produces .br and .gz files.
//!     .with_precompressed_br(true)
//!     .with_precompressed_gzip(true)
//!     // This directory must contain only content-addressed/versioned assets.
//!     .with_assets("/assets", StaticAssetCache::Immutable {
//!         max_age: Duration::from_secs(31_536_000),
//!     })
//!     .with_assets("/favicon.ico", StaticAssetCache::Revalidate)
//!     .with_reserved_path("/api")
//!     .build().await?;
//! let app = Router::new()
//!     .route("/api/health", get(|| async { "ok" }))
//!     .fallback_service(frontend);
//! let security = SecurityHeadersConfig::default()
//!     .with_content_security_policy(Some(HeaderValue::from_static(
//!         "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'",
//!     )));
//! let app = app.layer(middleware::map_response(move |mut response: Response| {
//!     let security = security.clone();
//!     async move { security.apply(response.headers_mut()); response }
//! }));
//! # let _: Router = app;
//! # Ok(())
//! # }
//! ```

use std::{
    borrow::Cow,
    convert::Infallible,
    future::Future,
    io,
    path::{Path, PathBuf},
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};

use axum::{
    body::Body,
    http::{HeaderMap, HeaderValue, Method, Request, StatusCode, header},
    response::{IntoResponse, Response},
};
use percent_encoding::percent_decode_str;
use thiserror::Error;
use tower::Service;
use tower_http::services::{ServeDir, ServeFile};

use crate::result::{ClassifyError, ErrorCode, ErrorKind};

/// Caching for a declared file-only URL prefix.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StaticAssetCache {
    /// Store the representation, but revalidate before reuse (`no-cache`).
    #[default]
    Revalidate,
    /// Publicly cache versioned assets whose URLs never change their content.
    ///
    /// Do not use for HTML, runtime configuration or non-versioned filenames.
    Immutable {
        /// Freshness lifetime, expressed as a positive whole number of seconds.
        max_age: Duration,
    },
}

impl StaticAssetCache {
    #[expect(
        clippy::expect_used,
        reason = "fixed ASCII and decimal digits form a valid header"
    )]
    fn header_value(self) -> Result<HeaderValue, StaticSiteError> {
        match self {
            Self::Revalidate => Ok(HeaderValue::from_static("no-cache")),
            Self::Immutable { max_age } => {
                if max_age.is_zero() || max_age.subsec_nanos() != 0 {
                    return Err(StaticSiteError::InvalidCacheDuration);
                }
                Ok(HeaderValue::try_from(format!(
                    "public, max-age={}, immutable",
                    max_age.as_secs()
                ))
                .expect("fixed ASCII cache directive"))
            }
        }
    }
}

/// Invalid site configuration or an unreadable deployment at startup.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum StaticSiteError {
    /// SPA fallback was enabled without configuring an HTML entry.
    #[error("SPA fallback requires an entry configured with with_entry")]
    MissingEntry,
    /// A configured URL or filesystem path violates the site's routing contract.
    #[error("invalid static site path {path:?}: {reason}")]
    InvalidPath {
        /// The rejected path.
        path: PathBuf,
        /// A description of the violated requirement.
        reason: &'static str,
    },
    /// Two declarations overlap, making their responsibilities ambiguous.
    #[error("static site paths overlap: {first:?} and {second:?}")]
    OverlappingPaths {
        /// The first declaration.
        first: String,
        /// The overlapping declaration.
        second: String,
    },
    /// Immutable caching needs a positive, whole-second lifetime.
    #[error("immutable asset max_age must be a positive whole number of seconds")]
    InvalidCacheDuration,
    /// The deployment could not be inspected or opened.
    #[error("cannot access static site path {path:?}: {source}")]
    Io {
        /// The path that could not be accessed.
        path: PathBuf,
        /// The underlying filesystem failure.
        #[source]
        source: io::Error,
    },
}

impl ClassifyError for StaticSiteError {
    fn error_kind(&self) -> ErrorKind {
        match self {
            Self::Io { .. } => ErrorKind::Dependency,
            _ => ErrorKind::Validation,
        }
    }

    fn error_code(&self) -> ErrorCode {
        ErrorCode::internal(match self {
            Self::MissingEntry => "static_site_missing_entry",
            Self::InvalidPath { .. } => "static_site_invalid_path",
            Self::OverlappingPaths { .. } => "static_site_overlapping_paths",
            Self::InvalidCacheDuration => "static_site_invalid_cache_duration",
            Self::Io { .. } => "static_site_io_failed",
        })
    }
}

/// Builds a validated file service with optional SPA routing.
///
/// Construction and setters do not access the filesystem. [`Self::build`] validates
/// all declarations and opens the configured entry before returning a service.
#[derive(Clone, Debug)]
#[must_use]
pub struct StaticSite {
    root: PathBuf,
    entry: Option<PathBuf>,
    spa_fallback: bool,
    precompressed_br: bool,
    precompressed_gzip: bool,
    assets: Vec<(String, StaticAssetCache)>,
    reserved: Vec<String>,
}

impl StaticSite {
    /// Serves explicit file URLs below `root`, initially without a root entry or SPA fallback.
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            entry: None,
            spa_fallback: false,
            precompressed_br: false,
            precompressed_gzip: false,
            assets: Vec::new(),
            reserved: Vec::new(),
        }
    }

    /// Maps `/` and the entry's own URL to this HTML file, without enabling SPA fallback.
    ///
    /// `entry` is a UTF-8 path relative to the root, without empty, `.` or `..`
    /// segments. It must not fall under a reserved or asset path. Calling this
    /// setter again replaces the previous entry. Both routes support GET, HEAD
    /// and conditional requests, independently of Accept, and use `no-cache`.
    /// The entry is checked during build even when SPA fallback is disabled.
    ///
    /// ```no_run
    /// use footing::http::static_site::StaticSite;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let homepage = StaticSite::new("dist")
    ///     .with_entry("index.html")
    ///     .build().await?;
    /// let app = axum::Router::<()>::new().fallback_service(homepage);
    /// // `/` serves index.html; unknown paths return 404.
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_entry(mut self, entry: impl Into<PathBuf>) -> Self {
        self.entry = Some(entry.into());
        self
    }

    /// Enables or disables SPA fallback to the configured HTML entry.
    ///
    /// Defaults to `false`. An entry must be set with [`Self::with_entry`] before
    /// building a service with fallback enabled; setter order does not matter.
    /// Missing paths and directories can use the entry for HTML navigation, while
    /// asset paths, reserved paths and other filesystem errors never trigger fallback.
    /// Disabling fallback preserves the root entry and explicit file routes.
    /// See the [module routing contract](self) for request and path rules.
    pub fn with_spa_fallback(mut self, enabled: bool) -> Self {
        self.spa_fallback = enabled;
        self
    }

    /// Enables or disables negotiation of existing Brotli (`.br`) variants.
    ///
    /// Defaults to `false`. Applies to static files, the configured entry and
    /// SPA fallback. Can be combined with [`Self::with_precompressed_gzip`].
    /// See the [precompressed file contract](self#precompressed-files).
    pub fn with_precompressed_br(mut self, enabled: bool) -> Self {
        self.precompressed_br = enabled;
        self
    }

    /// Enables or disables negotiation of existing gzip (`.gz`) variants.
    ///
    /// Defaults to `false`. Applies to static files, the configured entry and
    /// SPA fallback. Can be combined with [`Self::with_precompressed_br`].
    /// See the [precompressed file contract](self#precompressed-files).
    pub fn with_precompressed_gzip(mut self, enabled: bool) -> Self {
        self.precompressed_gzip = enabled;
        self
    }

    /// Declares a file-only URL prefix and its cache policy.
    ///
    /// The prefix does not rewrite paths: `/assets/app.js` resolves to
    /// `root/assets/app.js`. Exact filenames such as `/favicon.ico` are also valid.
    /// Missing files never use SPA fallback, even when Accept requests HTML.
    /// Prefixes must be literal absolute paths, without percent escapes or a
    /// trailing slash, and cannot be `/`. Overlapping declarations are rejected
    /// during build, including overlaps with reserved paths.
    pub fn with_assets(mut self, prefix: impl Into<String>, cache: StaticAssetCache) -> Self {
        self.assets.push((prefix.into(), cache));
        self
    }

    /// Excludes a backend URL prefix from all file serving and SPA fallback.
    ///
    /// Uses the same prefix syntax as [`Self::with_assets`]. Declare every backend
    /// namespace when installing this service as an application's fallback.
    pub fn with_reserved_path(mut self, prefix: impl Into<String>) -> Self {
        self.reserved.push(prefix.into());
        self
    }

    /// Validates configuration and deployment, then returns a cloneable service.
    ///
    /// Resolves the root to an absolute directory and checks that it can be read.
    /// A configured entry must be a readable regular file. SPA fallback requires
    /// an entry. Startup I/O errors retain their path and source; nothing is
    /// silently disabled.
    pub async fn build(self) -> Result<StaticSiteService, StaticSiteError> {
        if self.spa_fallback && self.entry.is_none() {
            return Err(StaticSiteError::MissingEntry);
        }
        let prefixes: Vec<_> = self
            .reserved
            .iter()
            .chain(self.assets.iter().map(|(path, _)| path))
            .collect();
        for (index, prefix) in prefixes.iter().enumerate() {
            if !valid_literal_path(prefix) || prefix.as_str() == "/" || prefix.ends_with('/') {
                return Err(invalid_path(
                    prefix.as_str(),
                    "expected a non-root literal URL prefix without a trailing slash",
                ));
            }
            for other in &prefixes[..index] {
                if matches_prefix(prefix, other) || matches_prefix(other, prefix) {
                    return Err(StaticSiteError::OverlappingPaths {
                        first: (*other).clone(),
                        second: (*prefix).clone(),
                    });
                }
            }
        }
        let entry = if let Some(entry) = &self.entry {
            let Some(relative) = entry.to_str() else {
                return Err(invalid_path(entry, "entry must be a UTF-8 relative path"));
            };
            let url = format!("/{relative}");
            if !valid_literal_path(&url) || url == "/" || url.ends_with('/') {
                return Err(invalid_path(
                    entry,
                    "entry must be a relative file path without empty or dot segments",
                ));
            }
            if let Some(prefix) = prefixes.iter().find(|prefix| matches_prefix(&url, prefix)) {
                return Err(StaticSiteError::OverlappingPaths {
                    first: (*prefix).clone(),
                    second: url,
                });
            }
            Some((entry, url))
        } else {
            None
        };
        let assets = self
            .assets
            .into_iter()
            .map(|(path, cache)| Ok((path, cache.header_value()?)))
            .collect::<Result<_, StaticSiteError>>()?;
        let root = tokio::fs::canonicalize(&self.root)
            .await
            .map_err(|source| io_error(&self.root, source))?;
        drop(
            tokio::fs::read_dir(&root)
                .await
                .map_err(|source| io_error(&root, source))?,
        );
        let entry = if let Some((relative, url)) = entry {
            let path = root.join(relative);
            if !tokio::fs::metadata(&path)
                .await
                .map_err(|source| io_error(&path, source))?
                .is_file()
            {
                return Err(invalid_path(&path, "entry must be a regular file"));
            }
            drop(
                tokio::fs::File::open(&path)
                    .await
                    .map_err(|source| io_error(&path, source))?,
            );
            let mut file = ServeFile::new_with_mime(&path, &mime::TEXT_HTML_UTF_8);
            if self.precompressed_br {
                file = file.precompressed_br();
            }
            if self.precompressed_gzip {
                file = file.precompressed_gzip();
            }
            Some(Entry {
                file,
                path,
                url,
                spa_fallback: self.spa_fallback,
            })
        } else {
            None
        };
        let mut files = ServeDir::new(&root)
            .append_index_html_on_directories(false)
            .redirect_to_trailing_slash(false);
        if self.precompressed_br {
            files = files.precompressed_br();
        }
        if self.precompressed_gzip {
            files = files.precompressed_gzip();
        }
        Ok(StaticSiteService {
            inner: Arc::new(Site {
                files,
                root,
                entry,
                assets,
                reserved: self.reserved,
            }),
        })
    }
}

/// A validated static site for Axum's `fallback_service` or `nest_service`.
///
/// Clones share immutable routing configuration. Responses stream files from
/// disk; there is no background task or in-memory file cache. Apply the host's
/// security and access-control middleware to the router as usual.
#[derive(Clone, Debug)]
pub struct StaticSiteService {
    inner: Arc<Site>,
}

#[derive(Debug)]
struct Site {
    root: PathBuf,
    files: ServeDir,
    entry: Option<Entry>,
    assets: Vec<(String, HeaderValue)>,
    reserved: Vec<String>,
}

#[derive(Debug)]
struct Entry {
    path: PathBuf,
    url: String,
    file: ServeFile,
    spa_fallback: bool,
}

impl Service<Request<Body>> for StaticSiteService {
    type Response = Response;
    type Error = Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send>>;

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

    fn call(&mut self, request: Request<Body>) -> Self::Future {
        let site = Arc::clone(&self.inner);
        Box::pin(async move { Ok(site.serve(request.map(|_| ())).await) })
    }
}

impl Site {
    async fn serve(&self, mut request: Request<()>) -> Response {
        let Some(path) = decoded_path(request.uri().path()) else {
            return error_response(StatusCode::NOT_FOUND);
        };
        if self
            .reserved
            .iter()
            .any(|prefix| matches_prefix(&path, prefix))
        {
            return error_response(StatusCode::NOT_FOUND);
        }
        if request.method() != Method::GET && request.method() != Method::HEAD {
            let mut response = error_response(StatusCode::METHOD_NOT_ALLOWED);
            response
                .headers_mut()
                .insert(header::ALLOW, HeaderValue::from_static("GET, HEAD"));
            return response;
        }
        let direct_entry = self
            .entry
            .as_ref()
            .filter(|entry| path == "/" || path == entry.url);
        let cache = self
            .assets
            .iter()
            .find(|(prefix, _)| matches_prefix(&path, prefix))
            .map(|(_, cache)| cache);
        let fallback_entry = self
            .entry
            .as_ref()
            .filter(|entry| entry.spa_fallback && cache.is_none());
        let path = path.into_owned();
        // tower-http does not implement If-Range; ignoring Range is permitted.
        // HEAD must describe the complete selected representation.
        if request.method() == Method::HEAD || request.headers().contains_key(header::IF_RANGE) {
            request.headers_mut().remove(header::RANGE);
        }
        if request.headers().contains_key(header::IF_MATCH) {
            let mut values = request.headers().get_all(header::IF_MATCH).iter();
            let wildcard = values
                .next()
                .is_some_and(|value| value.as_bytes().trim_ascii() == b"*")
                && values.next().is_none();
            // This service exposes only weak validators. A concrete If-Match
            // cannot match, even if the caller strips W/ from a previously sent
            // tag. Let the file service evaluate that false precondition after
            // checking existence, preserving its 404 and precondition ordering.
            request.headers_mut().insert(
                header::IF_MATCH,
                HeaderValue::from_static(if wildcard { "*" } else { "W/\"\"" }),
            );
        }
        normalize_if_none_match(request.headers_mut());
        if let Some(entry) = direct_entry {
            return entry.serve(request, false).await;
        }
        let fallback = fallback_entry.filter(|_| explicitly_accepts_html(request.headers()));
        let result = self.files.clone().try_call(request.clone()).await;
        let response = match (result, fallback) {
            (Err(error), Some(entry)) if error.kind() == io::ErrorKind::NotFound => {
                return entry.serve(request, true).await;
            }
            // ServeDir returns Ok(404) for missing slash-terminated paths and
            // directories. A directory may share a SPA page's path; a file with
            // a trailing slash and filesystem errors must not trigger fallback.
            (Ok(response), Some(entry)) if response.status() == StatusCode::NOT_FOUND => {
                match tokio::fs::metadata(self.root.join(&path[1..])).await {
                    Ok(metadata) if metadata.is_dir() => {
                        return entry.serve(request, true).await;
                    }
                    Err(error) if error.kind() == io::ErrorKind::NotFound => {
                        return entry.serve(request, true).await;
                    }
                    Err(error) => file_error(error),
                    Ok(_) => response.map(Body::new),
                }
            }
            (Ok(response), _) => response.map(Body::new),
            (Err(error), _) => file_error(error),
        };
        finish_response(response, cache, fallback_entry.is_some())
    }
}

#[expect(
    clippy::expect_used,
    reason = "commas preserve the validity of existing header values"
)]
fn normalize_if_none_match(headers: &mut HeaderMap) {
    // tower-http reads only the first field. Preserve the standard list
    // semantics when a client or intermediary sends multiple field lines.
    let values = headers.get_all(header::IF_NONE_MATCH);
    if values.iter().count() > 1 {
        let combined = values
            .iter()
            .map(HeaderValue::as_bytes)
            .collect::<Vec<_>>()
            .join(b", ".as_slice());
        headers.insert(
            header::IF_NONE_MATCH,
            HeaderValue::from_bytes(&combined).expect("valid header values joined with commas"),
        );
    } else if values
        .iter()
        .next()
        .is_some_and(|value| value.as_bytes().trim_ascii() == b"*")
    {
        // The file service recognizes the wildcard only without surrounding OWS.
        headers.insert(header::IF_NONE_MATCH, HeaderValue::from_static("*"));
    }
}

impl Entry {
    async fn serve(&self, request: Request<()>, vary: bool) -> Response {
        // ServeFile alone can report 200 for a directory on HEAD, or only fail
        // while streaming GET. Validate the entry's type before sending headers.
        let result = async {
            if !tokio::fs::metadata(&self.path).await?.is_file() {
                return Err(io::Error::other("static site entry is not a regular file"));
            }
            self.file.clone().try_call(request).await
        }
        .await;
        let response = match result {
            Ok(response) => response.map(Body::new),
            Err(error) => {
                tracing::error!(%error, "static site entry is unavailable");
                error_response(StatusCode::INTERNAL_SERVER_ERROR)
            }
        };
        finish_response(response, None, vary)
    }
}

fn finish_response(mut response: Response, cache: Option<&HeaderValue>, vary: bool) -> Response {
    let value = if response.status().is_success() || response.status() == StatusCode::NOT_MODIFIED {
        cache
            .cloned()
            .unwrap_or_else(|| HeaderValue::from_static("no-cache"))
    } else {
        HeaderValue::from_static("no-store")
    };
    response.headers_mut().insert(header::CACHE_CONTROL, value);
    if response.status() == StatusCode::PARTIAL_CONTENT {
        response.headers_mut().remove(header::ETAG);
    } else if let Some(etag) = response.headers_mut().get_mut(header::ETAG)
        && !etag.as_bytes().starts_with(b"W/")
    {
        *etag = weak_etag(etag);
    }
    // Compression middleware can skip 304 and HEAD; keep their validators and
    // cache keys consistent with a corresponding compressed GET response.
    // File services only vary on encoding; add our SPA negotiation without
    // duplicating the field already set by precompressed file serving.
    response.headers_mut().insert(
        header::VARY,
        HeaderValue::from_static(if vary {
            "Accept, Accept-Encoding"
        } else {
            "Accept-Encoding"
        }),
    );
    response
}

#[expect(
    clippy::expect_used,
    reason = "ASCII prefix preserves a validated header value"
)]
fn weak_etag(etag: &HeaderValue) -> HeaderValue {
    let mut bytes = Vec::with_capacity(etag.as_bytes().len() + 2);
    bytes.extend_from_slice(b"W/");
    bytes.extend_from_slice(etag.as_bytes());
    HeaderValue::from_bytes(&bytes).expect("ASCII prefix followed by a valid header value")
}

fn error_response(status: StatusCode) -> Response {
    finish_response(status.into_response(), None, false)
}

fn file_error(error: io::Error) -> Response {
    match error.kind() {
        io::ErrorKind::NotFound
        | io::ErrorKind::NotADirectory
        | io::ErrorKind::PermissionDenied => error_response(StatusCode::NOT_FOUND),
        _ => {
            tracing::error!(%error, "static site file could not be served");
            error_response(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

fn matches_prefix(path: &str, prefix: &str) -> bool {
    path == prefix
        || path
            .strip_prefix(prefix)
            .is_some_and(|rest| rest.starts_with('/'))
}

fn valid_literal_path(path: &str) -> bool {
    !path.contains(['%', '?', '#']) && valid_decoded_path(path)
}

fn decoded_path(path: &str) -> Option<Cow<'_, str>> {
    for (index, byte) in path.bytes().enumerate() {
        if byte == b'%'
            && !path
                .as_bytes()
                .get(index + 1..index + 3)
                .is_some_and(|hex| hex.iter().all(u8::is_ascii_hexdigit))
        {
            return None;
        }
    }
    let decoded = percent_decode_str(path).decode_utf8().ok()?;
    valid_decoded_path(&decoded).then_some(decoded)
}

fn valid_decoded_path(path: &str) -> bool {
    path.starts_with('/')
        && !path.contains("//")
        && !path.chars().any(|ch| ch == '\\' || ch.is_control())
        && !path.split('/').any(|segment| {
            matches!(segment, "." | "..")
                || (cfg!(windows) && (segment.contains(':') || segment.ends_with(['.', ' '])))
        })
}

fn explicitly_accepts_html(headers: &HeaderMap) -> bool {
    headers
        .get_all(header::ACCEPT)
        .iter()
        .flat_map(|value| super::header_list_items(value.as_bytes()))
        .filter_map(|value| std::str::from_utf8(value).ok())
        .filter_map(|value| value.trim().parse::<mime::Mime>().ok())
        .filter_map(|range| {
            if range.essence_str() != "text/html" {
                return None;
            }
            let mut quality = None;
            let mut parameters = 0;
            for (name, value) in range.params() {
                if name == "q" {
                    if quality.is_some() {
                        return None;
                    }
                    quality = Some(super::parse_quality(value.as_str()).unwrap_or(0));
                } else if quality.is_none() {
                    if !(name == mime::CHARSET && value == mime::UTF_8) || parameters != 0 {
                        return None;
                    }
                    parameters += 1;
                }
            }
            Some((parameters, quality.unwrap_or(1000)))
        })
        .max()
        .is_some_and(|(_, quality)| quality > 0)
}

fn invalid_path(path: impl Into<PathBuf>, reason: &'static str) -> StaticSiteError {
    StaticSiteError::InvalidPath {
        path: path.into(),
        reason,
    }
}

fn io_error(path: &Path, source: io::Error) -> StaticSiteError {
    StaticSiteError::Io {
        path: path.to_owned(),
        source,
    }
}