tachyon-web 0.0.2

A fast, Axum-compatible async web framework with native TLS, HTTP/3, Tor (.onion), and I2P (.i2p) support
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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
use crate::http::response::{Body, IntoResponse};
use bytes::Bytes;
use hyper::{
    Response, StatusCode,
    header::{
        CACHE_CONTROL, CONTENT_ENCODING, CONTENT_TYPE, ETAG, IF_NONE_MATCH, VARY,
        X_CONTENT_TYPE_OPTIONS,
    },
};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::fs;

/// Hash map keyed by asset path, using `FxHash` instead of the default
/// `SipHash`: the key set is fixed after `preload()`/`crawl_dir()`, so the
/// DoS-resistance `SipHash` provides buys nothing here, only lookup latency.
type HashMap<K, V> = rustc_hash::FxHashMap<K, V>;

/// Configuration for in-memory file caching.
///
/// Defaults: enabled, 64 MiB total cap, 2 MiB per-file cap.
#[derive(Clone, Debug)]
pub struct CacheConfig {
    /// Whether RAM caching is *permitted*. This only takes effect once
    /// [`ServeDir::preload`] is actually called — `enabled: true` alone does not
    /// populate the cache; it just means a subsequent `.preload().await` won't be a
    /// no-op. [`Router::serve_static`](crate::routing::Router::serve_static), the
    /// most common entry point, never calls `.preload()`, so caching stays off by
    /// default there even though this field defaults to `true`. Set `false` to make
    /// `.preload()` itself a no-op and always serve from disk.
    pub enabled: bool,
    /// Maximum total RAM used by the cache in bytes. Default: 64 MiB.
    pub max_total_bytes: usize,
    /// Maximum size of a single file that will be cached. Default: 2 MiB.
    pub max_file_bytes: usize,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_total_bytes: 64 * 1024 * 1024,
            max_file_bytes: 2 * 1024 * 1024,
        }
    }
}

/// Maps a file extension to a MIME type, by extension only — this never inspects
/// file content, so a `.svg` is always reported as `image/svg+xml` regardless of
/// whether it contains a `<script>`. See the `ServeDir` docs' upload-safety
/// warning before pointing a `ServeDir` at a directory that can contain files an
/// untrusted user chose the bytes of.
pub(crate) fn guess_mime_type(path: &Path) -> &'static str {
    let Some(ext) = path.extension().and_then(|s| s.to_str()) else {
        return "application/octet-stream";
    };

    if ext.eq_ignore_ascii_case("html") || ext.eq_ignore_ascii_case("htm") {
        "text/html; charset=utf-8"
    } else if ext.eq_ignore_ascii_case("css") {
        "text/css; charset=utf-8"
    } else if ext.eq_ignore_ascii_case("js") || ext.eq_ignore_ascii_case("mjs") {
        "application/javascript; charset=utf-8"
    } else if ext.eq_ignore_ascii_case("json") {
        "application/json"
    } else if ext.eq_ignore_ascii_case("wasm") {
        "application/wasm"
    } else if ext.eq_ignore_ascii_case("webmanifest") {
        "application/manifest+json"
    } else if ext.eq_ignore_ascii_case("xml") {
        "text/xml; charset=utf-8"
    } else if ext.eq_ignore_ascii_case("txt") {
        "text/plain; charset=utf-8"
    } else if ext.eq_ignore_ascii_case("csv") {
        "text/csv; charset=utf-8"
    } else if ext.eq_ignore_ascii_case("png") {
        "image/png"
    } else if ext.eq_ignore_ascii_case("jpg") || ext.eq_ignore_ascii_case("jpeg") {
        "image/jpeg"
    } else if ext.eq_ignore_ascii_case("gif") {
        "image/gif"
    } else if ext.eq_ignore_ascii_case("svg") || ext.eq_ignore_ascii_case("svgz") {
        "image/svg+xml"
    } else if ext.eq_ignore_ascii_case("ico") {
        "image/x-icon"
    } else if ext.eq_ignore_ascii_case("webp") {
        "image/webp"
    } else if ext.eq_ignore_ascii_case("avif") {
        "image/avif"
    } else if ext.eq_ignore_ascii_case("bmp") {
        "image/bmp"
    } else if ext.eq_ignore_ascii_case("woff") {
        "font/woff"
    } else if ext.eq_ignore_ascii_case("woff2") {
        "font/woff2"
    } else if ext.eq_ignore_ascii_case("ttf") {
        "font/ttf"
    } else if ext.eq_ignore_ascii_case("otf") {
        "font/otf"
    } else if ext.eq_ignore_ascii_case("mp3") {
        "audio/mpeg"
    } else if ext.eq_ignore_ascii_case("mp4") || ext.eq_ignore_ascii_case("m4v") {
        "video/mp4"
    } else if ext.eq_ignore_ascii_case("webm") {
        "video/webm"
    } else if ext.eq_ignore_ascii_case("pdf") {
        "application/pdf"
    } else if ext.eq_ignore_ascii_case("zip") {
        "application/zip"
    } else if ext.eq_ignore_ascii_case("gz") {
        "application/gzip"
    } else {
        "application/octet-stream"
    }
}

/// Validates that `candidate` lives inside `base` (path-traversal guard).
fn is_safe_path(base: &Path, candidate: &Path) -> bool {
    candidate.starts_with(base)
}

// ─── StaticAsset ──────────────────────────────────────────────────────────────

#[derive(Clone, Debug)]
struct StaticAsset {
    /// Raw (identity) content.
    content: Bytes,
    /// Pre-compressed gzip variant, if available alongside the original file.
    content_gz: Option<Bytes>,
    /// Pre-compressed brotli variant, if available alongside the original file.
    content_br: Option<Bytes>,
    /// `ETag` value: hex-encoded content length plus a cheap rolling-hash fingerprint
    /// of the content's first 8 and last 4 bytes (see `make_etag`) — not a
    /// cryptographic or full-content hash, so it's sized for change-detection, not
    /// collision resistance.
    etag: String,
    /// Pre-validated `HeaderValue` form of `etag`, computed once at crawl time so the
    /// request path only ever needs a cheap `Bytes`-backed clone instead of re-parsing
    /// (and re-validating) `etag` on every cache hit via `HeaderValue::from_str`.
    etag_header: hyper::header::HeaderValue,
    headers: hyper::HeaderMap,
}

// ─── ServeDir ─────────────────────────────────────────────────────────────────

/// High-performance static file server.
///
/// ## Nginx-like usage
///
/// ```rust,no_run
/// use tachyon_web::{Router, ServeDir};
///
/// # async fn example() -> std::io::Result<()> {
/// // Simple: serve ./public/ at /, index.html as default
/// let router: Router = Router::new()
///     .serve_static("./public");
///
/// // Advanced: with preloading
/// let sd = ServeDir::new("./public")
///     .index("index.html")
///     .preload().await?;
/// let router: Router = Router::new().serve_dir("/", sd);
/// # let _ = router;
/// # Ok(())
/// # }
/// ```
///
/// ## ⚠️ Never point this at a directory that accepts user uploads
///
/// `ServeDir` serves whatever bytes are on disk with the MIME type derived
/// from the file extension — it has no way to know
/// whether a file's *content* actually matches that extension. In particular,
/// `.svg` is served as `image/svg+xml`, and SVG is allowed to contain
/// `<script>`: if the served directory (or any subdirectory reachable through
/// it) can ever contain a file an untrusted user chose the bytes of — an
/// avatar/logo upload folder mixed into `./public/`, for example — that user
/// can plant a self-executing script that runs in your origin the moment
/// anyone views the "image" directly or via `<img>`/`<object>`. Every response
/// from `ServeDir` sets `X-Content-Type-Options: nosniff`, which stops browsers
/// from *guessing* a more dangerous type than what's declared, but it does
/// **not** stop an SVG correctly served as `image/svg+xml` from running the
/// script embedded inside it — nosniff and inline-SVG script execution are
/// orthogonal protections.
///
/// If a served directory can ever contain user-supplied files:
/// - Serve that subtree from a **separate route/directory** with
///   `Content-Disposition: attachment` (forces download, never inline render),
///   or
/// - Sanitize/strip `<script>` (and other active content) from SVGs before
///   they land in the served directory.
#[derive(Clone, Debug)]
pub struct ServeDir {
    base_path: PathBuf,
    memory_cache: Option<Arc<HashMap<String, StaticAsset>>>,
    index_file: Option<String>,
    cache_config: CacheConfig,
}

impl ServeDir {
    /// Create a `ServeDir` that reads files from disk on every request.
    ///
    /// `path` is canonicalized once, here, so later traversal checks
    /// (`is_safe_path`) compare against a symlink-resolved base. If `path`
    /// doesn't exist yet at construction time, canonicalization is skipped and
    /// `base_path` falls back to an uncanonicalized (but absolute) path —
    /// [`preload`](Self::preload) retries canonicalization once the directory
    /// exists. If you construct a `ServeDir` for a directory that doesn't exist
    /// yet and never call `preload`, and any path component involved is later a
    /// symlink, traversal checks may spuriously reject legitimate requests;
    /// prefer creating the directory before calling `new`.
    pub fn new(path: impl AsRef<Path>) -> Self {
        let base = path.as_ref().to_path_buf();
        let base = std::fs::canonicalize(&base)
            .or_else(|_| std::env::current_dir().map(|cd| cd.join(&base)))
            .unwrap_or(base);
        Self {
            base_path: base,
            memory_cache: None,
            index_file: None,
            cache_config: CacheConfig::default(),
        }
    }

    /// Configure in-memory caching behaviour.
    ///
    /// Use this to disable caching entirely (e.g. for development) or to tune RAM limits.
    #[must_use]
    pub const fn cache(mut self, config: CacheConfig) -> Self {
        self.cache_config = config;
        self
    }

    /// Serve `index_file` (e.g. `"index.html"`) when a directory or root is requested.
    /// This is equivalent to Nginx's `index` directive.
    #[must_use]
    pub fn index(mut self, file: impl Into<String>) -> Self {
        self.index_file = Some(file.into());
        self
    }

    /// Preload the entire directory tree into memory.
    ///
    /// After this call, every request is served from `Arc<Bytes>` with **zero disk I/O**.
    /// Set `cache_config.enabled = false` to skip preloading and serve directly from disk.
    ///
    /// # Errors
    ///
    /// Returns an `std::io::Error` if reading files or directories from disk fails.
    pub async fn preload(mut self) -> std::io::Result<Self> {
        if !self.cache_config.enabled {
            return Ok(self);
        }
        // `base_path` may not have been canonicalized in `new()` if the directory
        // didn't exist yet at construction time — retry now that `preload` is
        // about to walk it (and thus requires it to exist), so subsequent
        // request-time traversal checks compare against a symlink-resolved base.
        if let Ok(canonical) = fs::canonicalize(&self.base_path).await {
            self.base_path = canonical;
        }
        let mut cache = HashMap::default();
        let mut current_total = 0usize;
        Self::crawl_dir(
            &self.base_path.clone(),
            &self.base_path.clone(),
            &mut cache,
            &mut current_total,
            self.cache_config.max_file_bytes,
            self.cache_config.max_total_bytes,
        )
        .await?;
        // Also store the index file under the empty string key for root lookups.
        // `StaticAsset::content`/`content_gz`/`content_br` are `Bytes`, so this clone
        // shares the same underlying buffer rather than duplicating it — the extra
        // `HashMap` entry (key, headers, etag) is real but negligible overhead, not
        // counted against `max_total_bytes` since it isn't proportional to file size.
        if let Some(ref idx) = self.index_file
            && let Some(asset) = cache.get(idx.as_str()).cloned()
        {
            let _ = cache.insert(String::new(), asset);
        }
        self.memory_cache = Some(Arc::new(cache));
        Ok(self)
    }

    #[allow(clippy::too_many_lines)]
    async fn crawl_dir(
        base: &Path,
        current: &Path,
        cache: &mut HashMap<String, StaticAsset>,
        current_total: &mut usize,
        max_file_bytes: usize,
        max_total_bytes: usize,
    ) -> std::io::Result<()> {
        if !current.exists() {
            return Ok(());
        }
        let mut entries = fs::read_dir(current).await?;
        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();

            // Guard against symlinks planted under the served directory that point
            // outside `base` (e.g. `ln -s /etc app/static/etc`). Unlike the dynamic
            // disk-serving path, preloaded assets are served straight from the
            // in-memory cache with no per-request traversal check, so this has to be
            // enforced once, here, at crawl time — otherwise a symlink escape would
            // get cached under an innocuous-looking key and served on every request.
            match fs::canonicalize(&path).await {
                Ok(real) if real.starts_with(base) => {}
                _ => {
                    tracing::warn!(
                        path = %path.display(),
                        "Skipping cache entry that resolves outside the served directory"
                    );
                    continue;
                }
            }

            if path.is_dir() {
                Box::pin(Self::crawl_dir(
                    base,
                    &path,
                    cache,
                    current_total,
                    max_file_bytes,
                    max_total_bytes,
                ))
                .await?;
                continue;
            }

            // Skip compressed sidecar files — but only when they actually *are* a sidecar
            // of some other cached file (i.e. the uncompressed base file exists next to
            // them). A standalone downloadable archive with no uncompressed sibling (e.g.
            // `release.tar.gz`) has no base to be loaded as a variant of, so it must still
            // be crawled and cached under its own key — otherwise it 404s in preloaded mode
            // while serving fine from disk in dynamic mode.
            let path_str = path.to_string_lossy();
            if let Some(base_str) = path_str
                .strip_suffix(".gz")
                .or_else(|| path_str.strip_suffix(".br"))
                && fs::metadata(base_str).await.is_ok()
            {
                continue;
            }

            let meta = fs::metadata(&path).await?;
            if usize::try_from(meta.len()).unwrap_or(usize::MAX) > max_file_bytes {
                tracing::debug!(
                    "Skipping cache for large file: {} ({} bytes)",
                    path.display(),
                    meta.len()
                );
                continue;
            }

            // Check total RAM budget before reading. `current_total` is a running
            // accumulator updated as each asset is inserted, avoiding an O(n) rescan
            // of the whole cache (and thus O(n^2) behaviour) for every file crawled.
            if *current_total >= max_total_bytes {
                tracing::warn!("RAM cache budget exhausted; remaining files served from disk");
                break;
            }

            let content = fs::read(&path).await?;
            let relative = match path.strip_prefix(base) {
                Ok(rel) => rel
                    .to_string_lossy()
                    .trim_start_matches('/')
                    .replace('\\', "/"),
                Err(_) => continue,
            };

            // Attempt to load pre-compressed sidecar files.
            let gz_path = PathBuf::from(format!("{}.gz", path.display()));
            let br_path = PathBuf::from(format!("{}.br", path.display()));
            let content_gz = fs::read(&gz_path).await.ok().map(Bytes::from);
            let content_br = fs::read(&br_path).await.ok().map(Bytes::from);

            // Compute a fast ETag from content length + first 8 bytes.
            let etag = make_etag(&content);
            let etag_header = hyper::header::HeaderValue::from_str(&etag)
                .unwrap_or_else(|_| hyper::header::HeaderValue::from_static("\"0\""));

            let mime_type = guess_mime_type(&path);
            let mut headers = hyper::HeaderMap::new();
            let _ = headers.insert(
                CONTENT_TYPE,
                hyper::header::HeaderValue::from_static(mime_type),
            );
            // Prevent the browser from MIME-sniffing away from the declared
            // Content-Type (e.g. treating a misconfigured upload as HTML). See the
            // module-level docs for why this alone does not make it safe to serve
            // user-uploaded files (notably `.svg`) from the same directory.
            let _ = headers.insert(
                X_CONTENT_TYPE_OPTIONS,
                hyper::header::HeaderValue::from_static("nosniff"),
            );
            // Cache-Control: 1 hour for versioned assets; 5 min for HTML.
            let cc = if mime_type.starts_with("text/html") {
                "public, max-age=300"
            } else {
                "public, max-age=3600, immutable"
            };
            let _ = headers.insert(CACHE_CONTROL, hyper::header::HeaderValue::from_static(cc));
            // Vary: Accept-Encoding whenever we have compressed variants.
            if content_gz.is_some() || content_br.is_some() {
                let _ = headers.insert(
                    VARY,
                    hyper::header::HeaderValue::from_static("Accept-Encoding"),
                );
            }

            *current_total += content.len()
                + content_gz.as_ref().map_or(0, Bytes::len)
                + content_br.as_ref().map_or(0, Bytes::len);

            let _ = cache.insert(
                relative,
                StaticAsset {
                    content: Bytes::from(content),
                    content_gz,
                    content_br,
                    etag,
                    etag_header,
                    headers,
                },
            );
        }
        Ok(())
    }
}

/// Produce a lightweight `ETag` string from content: `"<len>-<first8hex>"`.
/// No crypto, no allocation-heavy hashing — pure arithmetic on existing bytes.
#[inline]
fn make_etag(content: &[u8]) -> String {
    let len = content.len();
    // Grab up to 8 bytes and fold into a u64 for a quick fingerprint.
    let mut sample: u64 = 0;
    for &b in content.iter().take(8) {
        sample = sample.wrapping_mul(31).wrapping_add(u64::from(b));
    }
    // Also mix in a few bytes from the tail for better collision resistance.
    for &b in content.iter().rev().take(4) {
        sample = sample.wrapping_mul(37).wrapping_add(u64::from(b));
    }
    format!("\"{len:x}-{sample:x}\"")
}

impl ServeDir {
    /// Serve a request; convenience wrapper with no encoding negotiation or `ETag` checking.
    ///
    /// # Errors
    ///
    /// Returns a `StatusCode` (like `404 Not Found` or `403 Forbidden`) if serving fails.
    pub async fn handle_request(&self, req_path: &str) -> Result<Response<Body>, StatusCode> {
        self.handle_request_with_encoding(req_path, "", "").await
    }

    /// Full request handler with content-encoding negotiation and `ETag` 304 support.
    ///
    /// `accept_encoding` — value of the request's `Accept-Encoding` header (empty if absent).
    /// `if_none_match` — value of `If-None-Match` for `ETag` 304 short-circuit.
    ///
    /// # Errors
    ///
    /// Returns a `StatusCode` if percent decoding fails, traversal is detected, or the file cannot be served.
    #[allow(clippy::too_many_lines)]
    pub async fn handle_request_with_encoding(
        &self,
        req_path: &str,
        accept_encoding: &str,
        if_none_match: &str,
    ) -> Result<Response<Body>, StatusCode> {
        let Some(decoded) = crate::routing::percent_decode(req_path) else {
            return Err(StatusCode::BAD_REQUEST);
        };
        let req_clean = decoded.trim_start_matches('/');

        // ── Security: reject obvious traversal before anything else ──────────
        if req_clean.contains("..") || req_clean.contains('\0') {
            return Err(StatusCode::FORBIDDEN);
        }

        // Resolve index file for empty path (root / directory requests)
        let resolved = if req_clean.is_empty() {
            self.index_file.as_deref().unwrap_or("")
        } else {
            req_clean
        };

        if resolved.is_empty() {
            return Err(StatusCode::NOT_FOUND);
        }

        // ── 1. Preloaded memory cache (zero I/O) ─────────────────────────────
        if let Some(cache) = &self.memory_cache
            && let Some(asset) = cache.get(resolved)
        {
            // ETag 304 short-circuit — zero body, minimal CPU.
            if !if_none_match.is_empty() && if_none_match == asset.etag {
                return Ok(Response::builder()
                    .status(StatusCode::NOT_MODIFIED)
                    .body(Body::empty())
                    .unwrap_or_else(|_| Response::new(Body::empty())));
            }

            // Content-negotiation: prefer br > gz > identity.
            let (body_bytes, encoding) =
                if !accept_encoding.is_empty() && accept_encoding.contains("br") {
                    asset.content_br.as_ref().map_or_else(
                        || (asset.content.clone(), None),
                        |b| (b.clone(), Some("br")),
                    )
                } else if !accept_encoding.is_empty() && accept_encoding.contains("gzip") {
                    asset.content_gz.as_ref().map_or_else(
                        || (asset.content.clone(), None),
                        |b| (b.clone(), Some("gzip")),
                    )
                } else {
                    (asset.content.clone(), None)
                };

            let mut resp = Response::new(Body::full(body_bytes));
            *resp.headers_mut() = asset.headers.clone();
            let _ = resp
                .headers_mut()
                .insert(ETAG, asset.etag_header.clone());
            if let Some(enc) = encoding {
                let enc_val = hyper::header::HeaderValue::from_static(enc);
                let _ = resp.headers_mut().insert(CONTENT_ENCODING, enc_val);
            }
            return Ok(resp);
        }
        // If preloaded but missing from cache (e.g. too large), fall through to disk!

        // ── 2. Dynamic disk mode with path-traversal hardening ───────────────
        let candidate = self.base_path.join(resolved);
        let Ok(canonical) = fs::canonicalize(&candidate).await else {
            return Err(StatusCode::NOT_FOUND);
        };

        if !is_safe_path(&self.base_path, &canonical) {
            tracing::warn!(
                path = %canonical.display(),
                base = %self.base_path.display(),
                "Rejected path traversal attempt"
            );
            return Err(StatusCode::FORBIDDEN);
        }

        let Ok(meta) = fs::metadata(&canonical).await else {
            return Err(StatusCode::NOT_FOUND);
        };

        if !meta.is_file() {
            return Err(StatusCode::NOT_FOUND);
        }

        match fs::read(&canonical).await {
            Ok(content) => {
                let mime_type = guess_mime_type(&canonical);

                // ZERO-COPY from Vec<u8> to Bytes
                let mut resp = Response::new(Body::full(Bytes::from(content)));
                let _ = resp.headers_mut().insert(
                    CONTENT_TYPE,
                    hyper::header::HeaderValue::from_static(mime_type),
                );
                let _ = resp.headers_mut().insert(
                    X_CONTENT_TYPE_OPTIONS,
                    hyper::header::HeaderValue::from_static("nosniff"),
                );

                Ok(resp)
            }
            Err(e) => {
                tracing::error!(path = %canonical.display(), error = %e, "Failed to read static file");
                Err(StatusCode::INTERNAL_SERVER_ERROR)
            }
        }
    }

    /// Build a `MethodRouter` from this `ServeDir`.
    ///
    /// The path to serve is taken from the `{path}` or `{*path}` matchit capture.
    /// This is used internally by `Router::serve_static` — you rarely need this directly.
    #[must_use]
    pub fn into_method_router<S>(self) -> crate::routing::MethodRouter<S>
    where
        S: Clone + Send + Sync + 'static,
    {
        let self_arc = std::sync::Arc::new(self);
        crate::routing::get(move |req: hyper::Request<Bytes>| {
            let this = self_arc.clone();

            async move {
                // By moving `req` into the async block FIRST, we can borrow `&str`
                // directly from its extensions or URI, achieving zero allocations!
                let path_ext = req
                    .extensions()
                    .get::<crate::routing::extract::PathParams>();

                let file_path = path_ext
                    .and_then(|p| {
                        p.0.iter()
                            .find(|(k, _)| k.as_ref() == "path" || k.as_ref() == "*path")
                            .map(|(_, v)| v.as_str())
                    })
                    .unwrap_or_else(|| req.uri().path());

                // Extract encoding negotiation headers before calling the handler.
                let accept_enc = req
                    .headers()
                    .get(hyper::header::ACCEPT_ENCODING)
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or("");
                let if_none_match = req
                    .headers()
                    .get(IF_NONE_MATCH)
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or("");

                match this
                    .handle_request_with_encoding(file_path, accept_enc, if_none_match)
                    .await
                {
                    Ok(resp) => resp,
                    Err(status) => status.into_response(),
                }
            }
        })
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]
    use super::*;
    use std::fs;

    fn make_temp_dir() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        fs::write(
            dir.path().join("index.html"),
            b"<html><script>var x=1;</script></html>",
        )
        .unwrap();
        fs::write(dir.path().join("style.css"), b"body{}").unwrap();
        fs::write(dir.path().join("app.js"), b"console.log(1)").unwrap();
        dir
    }

    #[tokio::test]
    async fn test_serve_existing_file() {
        let dir = make_temp_dir();
        let sd = ServeDir::new(dir.path()).preload().await.unwrap();
        let resp = sd.handle_request("style.css").await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let ct = resp.headers().get(CONTENT_TYPE).unwrap().to_str().unwrap();
        assert!(ct.contains("text/css"), "ct: {ct}");
    }

    #[tokio::test]
    async fn test_nosniff_header_preloaded() {
        let dir = make_temp_dir();
        let sd = ServeDir::new(dir.path()).preload().await.unwrap();
        let resp = sd.handle_request("style.css").await.unwrap();
        assert_eq!(
            resp.headers().get(X_CONTENT_TYPE_OPTIONS).unwrap(),
            "nosniff"
        );
    }

    #[tokio::test]
    async fn test_nosniff_header_dynamic() {
        let dir = make_temp_dir();
        let sd = ServeDir::new(dir.path());
        let resp = sd.handle_request("style.css").await.unwrap();
        assert_eq!(
            resp.headers().get(X_CONTENT_TYPE_OPTIONS).unwrap(),
            "nosniff"
        );
    }

    #[test]
    fn test_svg_mime_type() {
        // Documented, deliberate behavior: `.svg` is reported by extension only,
        // never by content — see the `ServeDir` docs' upload-safety warning.
        assert_eq!(guess_mime_type(Path::new("logo.svg")), "image/svg+xml");
    }

    #[tokio::test]
    async fn test_not_found() {
        let dir = make_temp_dir();
        let sd = ServeDir::new(dir.path()).preload().await.unwrap();
        assert_eq!(
            sd.handle_request("missing.txt").await.unwrap_err(),
            StatusCode::NOT_FOUND
        );
    }

    #[tokio::test]
    async fn test_index_file_on_root_request() {
        let dir = make_temp_dir();
        let sd = ServeDir::new(dir.path())
            .index("index.html")
            .preload()
            .await
            .unwrap();
        let resp = sd.handle_request("").await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let ct = resp.headers().get(CONTENT_TYPE).unwrap().to_str().unwrap();
        assert!(ct.contains("text/html"), "ct: {ct}");
    }

    #[tokio::test]
    async fn test_path_traversal_dotdot() {
        let dir = make_temp_dir();
        let sd = ServeDir::new(dir.path()).preload().await.unwrap();
        let err = sd.handle_request("../../etc/passwd").await.unwrap_err();
        assert_eq!(err, StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn test_path_traversal_dynamic_mode() {
        let dir = make_temp_dir();
        let sd = ServeDir::new(dir.path());
        let err = sd.handle_request("../../../etc/passwd").await.unwrap_err();
        assert!(err == StatusCode::FORBIDDEN || err == StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_null_byte_rejected() {
        let dir = make_temp_dir();
        let sd = ServeDir::new(dir.path()).preload().await.unwrap();
        assert_eq!(
            sd.handle_request("style\x00.css").await.unwrap_err(),
            StatusCode::FORBIDDEN
        );
    }

    #[test]
    fn test_guess_mime_types() {
        let cases = [
            ("index.html", "text/html; charset=utf-8"),
            ("style.css", "text/css; charset=utf-8"),
            ("app.js", "application/javascript; charset=utf-8"),
            ("data.json", "application/json"),
            ("file.wasm", "application/wasm"),
            ("manifest.webmanifest", "application/manifest+json"),
            ("feed.xml", "text/xml; charset=utf-8"),
            ("doc.txt", "text/plain; charset=utf-8"),
            ("sheet.csv", "text/csv; charset=utf-8"),
            ("img.png", "image/png"),
            ("pic.jpg", "image/jpeg"),
            ("anim.gif", "image/gif"),
            ("vector.svg", "image/svg+xml"),
            ("fav.ico", "image/x-icon"),
            ("pic.webp", "image/webp"),
            ("pic.avif", "image/avif"),
            ("pic.bmp", "image/bmp"),
            ("font.woff", "font/woff"),
            ("font.woff2", "font/woff2"),
            ("font.ttf", "font/ttf"),
            ("font.otf", "font/otf"),
            ("audio.mp3", "audio/mpeg"),
            ("video.mp4", "video/mp4"),
            ("video.webm", "video/webm"),
            ("doc.pdf", "application/pdf"),
            ("archive.zip", "application/zip"),
            ("archive.gz", "application/gzip"),
            ("no_ext", "application/octet-stream"),
            ("file.unknown", "application/octet-stream"),
        ];

        for (filename, expected) in cases {
            let path = Path::new(filename);
            assert_eq!(guess_mime_type(path), expected, "failed on {filename}");
        }
    }

    #[test]
    fn test_is_safe_path() {
        let base = Path::new("/var/www");
        let safe = Path::new("/var/www/index.html");
        let unsafe_path = Path::new("/var/etc/passwd");
        assert!(is_safe_path(base, safe));
        assert!(!is_safe_path(base, unsafe_path));
    }

    #[tokio::test]
    async fn test_crawl_dir_edge_cases() {
        let dir = tempfile::tempdir().unwrap();
        // Crawl non-existent path
        let mut cache = HashMap::default();
        let mut current_total = 0usize;
        let res = ServeDir::crawl_dir(
            dir.path(),
            &dir.path().join("missing"),
            &mut cache,
            &mut current_total,
            2 * 1024 * 1024,
            64 * 1024 * 1024,
        )
        .await;
        assert!(res.is_ok());

        // Crawl large file (> 5MB)
        let large_path = dir.path().join("large.txt");
        let large_content = vec![0u8; 6 * 1024 * 1024]; // 6MB
        fs::write(&large_path, large_content).unwrap();
        let sd = ServeDir::new(dir.path()).preload().await.unwrap();
        // Large file should not be preloaded in cache
        assert!(sd.memory_cache.as_ref().unwrap().get("large.txt").is_none());

        // Dynamic serving of large file should succeed
        let resp = sd.handle_request("large.txt").await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_handle_request_edge_cases() {
        let dir = make_temp_dir();
        // Dynamic mode
        let sd_dyn = ServeDir::new(dir.path());
        let resp = sd_dyn.handle_request("style.css").await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        // Invalid percent encoding
        assert_eq!(
            sd_dyn.handle_request("style%x.css").await.unwrap_err(),
            StatusCode::BAD_REQUEST
        );

        // Empty path and empty index
        let sd_no_index = ServeDir::new(dir.path());
        assert_eq!(
            sd_no_index.handle_request("").await.unwrap_err(),
            StatusCode::NOT_FOUND
        );

        // Canonicalization failure
        assert_eq!(
            sd_dyn.handle_request("nonexistent.txt").await.unwrap_err(),
            StatusCode::NOT_FOUND
        );

        // Path traversal targeting a file that actually exists on disk (so
        // canonicalization succeeds) must still be rejected.
        let sd_traversal = ServeDir::new(dir.path());
        let res = sd_traversal
            .handle_request("../../../../../../../../../etc/passwd")
            .await;
        assert!(res.is_err());
    }

    #[tokio::test]
    async fn test_into_method_router_fallback() {
        let dir = make_temp_dir();
        let sd = ServeDir::new(dir.path()).preload().await.unwrap();
        let router = sd.into_method_router::<()>();
        // 1. Without extension, fallback to URI path
        let req = hyper::Request::builder()
            .method("GET")
            .uri("/style.css")
            .body(Body::empty())
            .unwrap();
        let h = router.handlers[super::super::IDX_GET].as_ref().unwrap();
        let resp = h.call(req, Arc::new(())).await;
        assert_eq!(resp.status(), StatusCode::OK);
    }
}