rustango 0.66.0

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
//! Static file serving: read files from a directory and send them with
//! `Content-Type`, `Cache-Control` and `Last-Modified`, and answer 304
//! to `If-Modified-Since`.
//!
//! Each file gets a strong `ETag` from its size and mtime, which
//! [`crate::etag::EtagLayer`] keeps, so `If-Range` resumes match it.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::static_files::{StaticFiles, static_router};
//!
//! // Mount /static/* over ./assets
//! let app = axum::Router::new()
//!     .nest("/static", static_router(StaticFiles::new("./assets")));
//! ```
//!
//! ## Security
//!
//! - Path traversal gets a 404. The path is normalised before it is
//!   joined to the root, so a `..` segment cannot read above the root,
//!   URL-encoded or not.
//! - A symlink out of the root gets a 404 too: the resolved path is
//!   checked against the root. [`StaticFiles::no_canonicalize`] turns
//!   that check off, so use it only on a directory layout you trust.
//! - A name starting with `.` gets a 404 unless
//!   [`StaticFiles::serve_hidden`] is on, in the request and in the
//!   resolved path, so a link or a Windows 8.3 name (`ENV~1`) cannot reach
//!   `.env`. With [`StaticFiles::no_canonicalize`] only the request is
//!   checked.
//! - Mount user uploads with [`StaticFiles::user_content`](crate::static_files::StaticFiles::user_content): HTML, SVG
//!   and XML then download instead of running script on your origin, and
//!   JS, CSS and WASM go out untyped so no page here can load them.
//!
//! ## Caching
//!
//! `Cache-Control` defaults to `public, max-age=3600`; change it with
//! [`StaticFiles::cache_control`]. `Last-Modified` comes from the
//! file's mtime, and a matching `If-Modified-Since` gets a 304 with no
//! body.
//!
//! Bodies stream from disk, and a single `Range: bytes=` span gets a 206.
//!
//! ## Hashed names, SRI and embedded files
//!
//! [`AssetManifest`](crate::static_files::AssetManifest) gives every file a content-hashed name and an SRI
//! hash for templates; [`StaticFiles::manifest`](crate::static_files::StaticFiles::manifest) serves those names
//! `immutable`. [`embed_static!`](crate::embed_static) compiles a
//! directory into the binary, served by [`StaticFiles::embedded`](crate::static_files::StaticFiles::embedded).
//!
//! [`StaticFiles::no_canonicalize`]: crate::static_files::StaticFiles::no_canonicalize
//! [`StaticFiles::serve_hidden`]: crate::static_files::StaticFiles::serve_hidden
//! [`StaticFiles::cache_control`]: crate::static_files::StaticFiles::cache_control

use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use axum::body::Body;
use axum::extract::{Path as PathExt, State};
use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode};
use axum::response::Response;
use axum::routing::get;
use axum::Router;

mod assets;
pub use assets::{Asset, AssetManifest, EmbeddedDir};

/// `Cache-Control` for a content-hashed name: a year, never revalidated.
const HASHED_CACHE_CONTROL: &str = "public, max-age=31536000, immutable";

/// Static file server config.
#[derive(Clone, Debug)]
pub struct StaticFiles {
    root: PathBuf,
    cache_control: String,
    serve_hidden: bool,
    canonicalize: bool,
    user_content: bool,
    /// Files compiled into the binary; `root` is unused then.
    embedded: Option<EmbeddedDir>,
    /// Hashed names to serve as well as the plain ones.
    manifest: Option<Arc<AssetManifest>>,
}

impl StaticFiles {
    /// New server rooted at `dir`, caching `public, max-age=3600`.
    #[must_use]
    pub fn new(dir: impl Into<PathBuf>) -> Self {
        Self {
            root: dir.into(),
            cache_control: "public, max-age=3600".into(),
            serve_hidden: false,
            canonicalize: true,
            user_content: false,
            embedded: None,
            manifest: None,
        }
    }

    /// Serve files compiled into the binary by
    /// [`embed_static!`](crate::embed_static), for a one-file image:
    ///
    /// ```no_run
    /// # use rustango::static_files::{static_router, EmbeddedDir, StaticFiles};
    /// # fn app(assets: EmbeddedDir) -> axum::Router {
    /// // static ASSETS: EmbeddedDir = rustango::embed_static!("static");
    /// axum::Router::new().nest("/static", static_router(StaticFiles::embedded(assets)))
    /// # }
    /// ```
    #[must_use]
    pub fn embedded(dir: EmbeddedDir) -> Self {
        Self {
            embedded: Some(dir),
            ..Self::new(PathBuf::new())
        }
    }

    /// Also serve each file under its hashed name from `manifest`, with
    /// `Cache-Control: public, max-age=31536000, immutable`. The plain
    /// names keep [`Self::cache_control`].
    #[must_use]
    pub fn manifest(mut self, manifest: AssetManifest) -> Self {
        self.manifest = Some(Arc::new(manifest));
        self
    }

    /// The directory files are served from.
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Serve files users uploaded: HTML, SVG and XML go out as
    /// `attachment`, JS, CSS and WASM as an untyped `attachment`, and
    /// every response carries `nosniff` (#1849).
    #[must_use]
    pub fn user_content(mut self) -> Self {
        self.user_content = true;
        self
    }

    /// Override the `Cache-Control` header value.
    #[must_use]
    pub fn cache_control(mut self, v: impl Into<String>) -> Self {
        self.cache_control = v.into();
        self
    }

    /// Set `Cache-Control: public, max-age=<secs>, immutable`. Use it
    /// for hashed file names like `app.a3f8b2.js`, where new content
    /// always means a new URL.
    #[must_use]
    pub fn immutable(mut self, max_age: Duration) -> Self {
        self.cache_control = format!("public, max-age={}, immutable", max_age.as_secs());
        self
    }

    /// Allow files whose name starts with `.`. Off by default.
    #[must_use]
    pub fn serve_hidden(mut self, on: bool) -> Self {
        self.serve_hidden = on;
        self
    }

    /// Turn off the check that stops a symlink leading out of `root`.
    /// Only do this on a directory layout you have checked yourself: the
    /// hidden-file check then sees only the requested name, so on Windows
    /// an 8.3 name such as `ENV~1` can serve `.env`.
    #[must_use]
    pub fn no_canonicalize(mut self) -> Self {
        self.canonicalize = false;
        self
    }
}

/// Warn when a plain static mount looks like it serves user uploads,
/// where HTML or SVG would run on the app origin (#1849).
#[cfg_attr(not(any(feature = "manage", feature = "tenancy")), allow(dead_code))]
pub(crate) fn warn_if_uploads_prefix(prefix: &str) {
    let p = prefix.to_ascii_lowercase();
    if p.contains("upload") || p.contains("media") {
        tracing::warn!(
            target: "rustango::static_files",
            prefix,
            "static mount looks like user uploads; mount it with `with_uploads` so HTML and SVG \
             download instead of running on this origin"
        );
    }
}

/// Router that serves everything under `files.root`. Mount it with
/// `.nest("/static", static_router(...))`.
#[must_use]
pub fn static_router(files: StaticFiles) -> Router {
    let root = if files.canonicalize && files.embedded.is_none() {
        std::fs::canonicalize(&files.root).ok()
    } else {
        None
    };
    let by_hashed = files
        .manifest
        .as_ref()
        .map(|m| m.by_hashed())
        .unwrap_or_default();
    let embedded = files
        .embedded
        .iter()
        .flat_map(|d| d.files().iter())
        .map(|&(path, bytes)| (path, (bytes, content_etag(bytes))))
        .collect();
    Router::new()
        .route("/{*path}", get(serve))
        .with_state(Arc::new(Mount {
            files,
            root: std::sync::RwLock::new(root.map(|r| (r, std::time::Instant::now()))),
            by_hashed,
            embedded,
        }))
}

/// A mount plus its canonical root, cached rather than resolved per request (#1531).
struct Mount {
    files: StaticFiles,
    root: std::sync::RwLock<Option<(PathBuf, std::time::Instant)>>,
    /// Hashed name → plain name, from [`StaticFiles::manifest`].
    by_hashed: HashMap<String, String>,
    /// Embedded path → (bytes, ETag), from [`StaticFiles::embedded`].
    embedded: HashMap<&'static str, (&'static [u8], String)>,
}

/// How long a cached root is trusted before it is resolved again, so a
/// re-pointed root symlink cannot keep serving the old target's tree.
const ROOT_TTL: Duration = if cfg!(test) {
    Duration::from_millis(50)
} else {
    Duration::from_secs(1)
};

/// An open file, checked to be a regular file under the root.
struct Opened {
    path: PathBuf,
    source: Source,
    len: u64,
    mtime: Option<u64>,
    etag: Option<String>,
}

/// Where an [`Opened`] body comes from.
enum Source {
    File(std::fs::File),
    Embedded(&'static [u8]),
}

/// Strong validator from the content, for embedded files (no mtime).
fn content_etag(bytes: &[u8]) -> String {
    use sha2::Digest as _;
    let d = sha2::Sha256::digest(bytes);
    let hex: String = d[..8].iter().map(|b| format!("{b:02x}")).collect();
    format!("\"{hex}\"")
}

/// Strong validator from size and mtime, so a `206` and its `200` share it.
/// No mtime, no validator: size alone can't tell two versions apart.
fn file_etag(len: u64, mtime: Option<u64>) -> Option<String> {
    mtime.map(|m| format!("\"{m:x}-{len:x}\""))
}

async fn serve(
    State(mount): State<Arc<Mount>>,
    PathExt(rel): PathExt<String>,
    headers: HeaderMap,
    method: Method,
) -> Response {
    // A hashed name serves its plain file, cached for good.
    let (rel, cache_control) = match mount.by_hashed.get(&rel) {
        Some(plain) => (plain.clone(), HASHED_CACHE_CONTROL),
        None => (rel, mount.files.cache_control.as_str()),
    };
    let opened = if mount.files.embedded.is_some() {
        match mount.embedded.get(rel.as_str()) {
            Some(&(bytes, ref etag)) => Opened {
                path: PathBuf::from(&rel),
                source: Source::Embedded(bytes),
                len: bytes.len() as u64,
                mtime: None,
                etag: Some(etag.clone()),
            },
            None => return not_found(),
        }
    } else {
        // Every filesystem call runs off the async workers (#1531).
        let m = Arc::clone(&mount);
        match tokio::task::spawn_blocking(move || open_file(&m, &rel)).await {
            Ok(Some(o)) => o,
            Ok(None) | Err(_) => return not_found(),
        }
    };
    let files = &mount.files;
    let Opened {
        path,
        source,
        len,
        mtime,
        etag,
    } = opened;
    let etag = etag.as_deref();
    // `If-None-Match` wins over `If-Modified-Since` (RFC 9110 §13.1.3).
    if let Some(inm) = headers.get(header::IF_NONE_MATCH) {
        let inm = inm.to_str().unwrap_or("");
        if etag.is_some_and(|e| crate::etag::if_none_match(inm, e)) {
            return not_modified(mtime, etag, cache_control);
        }
    } else if let Some(secs) = mtime {
        if let Some(ims) = headers.get(header::IF_MODIFIED_SINCE) {
            if let Some(client_secs) = parse_http_date(ims.to_str().unwrap_or("")) {
                if secs <= client_secs {
                    return not_modified(mtime, etag, cache_control);
                }
            }
        }
    }

    let last_modified = mtime.map(format_http_date);
    let range = match requested_range(&headers, etag, last_modified.as_deref(), len) {
        Ok(r) => r,
        Err(()) => return range_not_satisfiable(len),
    };
    let (start, count) = range.unwrap_or((0, len));

    let body = match source {
        _ if method == Method::HEAD => Body::empty(),
        Source::Embedded(bytes) => {
            // `requested_range` keeps the span inside `len`.
            let from = usize::try_from(start).unwrap_or(bytes.len());
            let to = usize::try_from(start + count).unwrap_or(bytes.len());
            Body::from(&bytes[from..to])
        }
        Source::File(file) => {
            use tokio::io::{AsyncReadExt as _, AsyncSeekExt as _};
            let mut file = tokio::fs::File::from_std(file);
            if start > 0 && file.seek(std::io::SeekFrom::Start(start)).await.is_err() {
                return not_found();
            }
            // Streamed, so memory per request is one read buffer, not the file.
            Body::new(KnownLen {
                inner: Body::from_stream(tokio_util::io::ReaderStream::new(file.take(count))),
                len: count,
            })
        }
    };

    let mut mime = mime_for(&path);
    if files.user_content && loads_as_code(&mime) {
        mime = HeaderValue::from_static("application/octet-stream");
    }
    let status = if range.is_some() {
        StatusCode::PARTIAL_CONTENT
    } else {
        StatusCode::OK
    };
    let mut resp = Response::builder()
        .status(status)
        .body(body)
        .unwrap_or_else(|_| Response::new(Body::empty()));
    let h = resp.headers_mut();
    if files.user_content {
        h.insert(
            header::X_CONTENT_TYPE_OPTIONS,
            HeaderValue::from_static("nosniff"),
        );
        if runs_script(&mime) || mime == "application/octet-stream" {
            h.insert(
                header::CONTENT_DISPOSITION,
                HeaderValue::from_static("attachment"),
            );
        }
    }
    h.insert(header::CONTENT_TYPE, mime);
    if !cache_control.is_empty() {
        if let Ok(v) = HeaderValue::from_str(cache_control) {
            h.insert(header::CACHE_CONTROL, v);
        }
    }
    h.insert(header::ACCEPT_RANGES, HeaderValue::from_static("bytes"));
    h.insert(header::CONTENT_LENGTH, HeaderValue::from(count));
    if range.is_some() {
        let cr = format!("bytes {start}-{}/{len}", start + count - 1);
        if let Ok(v) = HeaderValue::from_str(&cr) {
            h.insert(header::CONTENT_RANGE, v);
        }
    }
    if let Some(v) = last_modified.and_then(|s| HeaderValue::from_str(&s).ok()) {
        h.insert(header::LAST_MODIFIED, v);
    }
    if let Some(v) = etag.and_then(|e| HeaderValue::from_str(e).ok()) {
        h.insert(header::ETAG, v);
    }
    resp
}

/// A streamed body that still reports its exact size, so a size-aware
/// layer such as `CompressionLayer` treats it like a buffered one.
struct KnownLen {
    inner: Body,
    len: u64,
}

impl http_body::Body for KnownLen {
    type Data = axum::body::Bytes;
    type Error = axum::Error;

    fn poll_frame(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
        std::pin::Pin::new(&mut self.inner).poll_frame(cx)
    }

    fn size_hint(&self) -> http_body::SizeHint {
        http_body::SizeHint::with_exact(self.len)
    }
}

/// Resolve, open and stat `rel`. Blocking: call it from `spawn_blocking`.
fn open_file(mount: &Mount, rel: &str) -> Option<Opened> {
    let path = resolve_path(mount, rel)?;
    let file = std::fs::File::open(&path).ok()?;
    // Stat the open handle, so the checked file is the one served.
    let meta = file.metadata().ok()?;
    if !meta.is_file() {
        return None;
    }
    let mtime = meta
        .modified()
        .ok()
        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
        .map(|d| d.as_secs());
    let len = meta.len();
    Some(Opened {
        path,
        source: Source::File(file),
        len,
        mtime,
        etag: file_etag(len, mtime),
    })
}

/// The single `Range: bytes=` span to serve, as `(start, count)`.
///
/// `Ok(None)` serves the whole file: no header, several ranges, a
/// stale `If-Range`, a malformed spec, or a unit we don't know. `Err`
/// is a 416: a valid range that starts past the end.
fn requested_range(
    headers: &HeaderMap,
    etag: Option<&str>,
    last_modified: Option<&str>,
    len: u64,
) -> Result<Option<(u64, u64)>, ()> {
    let Some(spec) = headers.get(header::RANGE).and_then(|v| v.to_str().ok()) else {
        return Ok(None);
    };
    if let Some(if_range) = headers.get(header::IF_RANGE) {
        let v = if_range.to_str().unwrap_or_default().trim();
        // An entity tag compares strongly, so a weak one never matches.
        let fresh = if v.starts_with('"') || v.starts_with("W/") {
            Some(v) == etag
        } else {
            Some(v) == last_modified
        };
        if !fresh {
            return Ok(None);
        }
    }
    let Some(spec) = spec.trim().strip_prefix("bytes=") else {
        return Ok(None);
    };
    if spec.contains(',') {
        return Ok(None);
    }
    let Some((a, b)) = spec.trim().split_once('-') else {
        return Ok(None);
    };
    let (start, end) = match (a.trim(), b.trim()) {
        ("", "") => return Ok(None),
        // `bytes=-N`: the last N bytes.
        ("", n) => {
            // Malformed specs are ignored, not refused (RFC 9110 §14.2).
            let Ok(n) = n.parse::<u64>() else {
                return Ok(None);
            };
            if n == 0 || len == 0 {
                return Err(());
            }
            (len.saturating_sub(n), len - 1)
        }
        (a, b) => {
            let (Ok(start), Ok(last)) = (
                a.parse::<u64>(),
                if b.is_empty() {
                    Ok(u64::MAX)
                } else {
                    b.parse::<u64>()
                },
            ) else {
                return Ok(None);
            };
            if last < start {
                return Ok(None);
            }
            if start >= len {
                return Err(());
            }
            (start, last.min(len - 1))
        }
    };
    Ok(Some((start, end - start + 1)))
}

fn range_not_satisfiable(len: u64) -> Response {
    Response::builder()
        .status(StatusCode::RANGE_NOT_SATISFIABLE)
        .header(header::CONTENT_RANGE, format!("bytes */{len}"))
        .body(Body::empty())
        .unwrap_or_else(|_| Response::new(Body::empty()))
}

fn resolve_path(mount: &Mount, rel: &str) -> Option<PathBuf> {
    let files = &mount.files;
    // 1. An empty path is never valid.
    if rel.is_empty() {
        return None;
    }
    let rel_path = Path::new(rel);

    // 2. Normalise before joining: drop `.`, and reject `..`, a root or a
    //    drive prefix. This is what blocks path traversal.
    let mut normalized = PathBuf::new();
    for c in rel_path.components() {
        match c {
            Component::Normal(s) => {
                if !files.serve_hidden {
                    if let Some(name) = s.to_str() {
                        if name.starts_with('.') {
                            return None;
                        }
                    }
                }
                normalized.push(s);
            }
            Component::CurDir => {}
            Component::ParentDir | Component::Prefix(_) | Component::RootDir => return None,
        }
    }
    if normalized.as_os_str().is_empty() {
        return None;
    }

    let joined = files.root.join(&normalized);

    // 3. Resolve the real path, so a symlink cannot lead out of the root.
    if files.canonicalize {
        let canon = std::fs::canonicalize(&joined).ok()?;
        let cached = mount.root.read().ok().and_then(|r| r.clone());
        let root = match cached {
            Some((root, at)) if at.elapsed() < ROOT_TTL && canon.starts_with(&root) => root,
            // Stale, missing, or a re-pointed root symlink: resolve it again.
            // A root that no longer resolves serves nothing.
            _ => {
                let root_canon = std::fs::canonicalize(&files.root).ok();
                if let Ok(mut w) = mount.root.write() {
                    *w = root_canon.clone().map(|r| (r, std::time::Instant::now()));
                }
                root_canon.filter(|r| canon.starts_with(r))?
            }
        };
        // The resolved name, not just the requested one: a link, or a Windows
        // 8.3 name such as `ENV~1`, can reach `.env`.
        if !files.serve_hidden && has_hidden_component(&canon, &root) {
            return None;
        }
        return Some(canon);
    }
    Some(joined)
}

/// Whether a component of `path` below `root` starts with a dot.
fn has_hidden_component(path: &Path, root: &Path) -> bool {
    path.strip_prefix(root).map_or(true, |rel| {
        rel.components()
            .any(|c| matches!(c, Component::Normal(s) if s.to_string_lossy().starts_with('.')))
    })
}

fn not_found() -> Response {
    Response::builder()
        .status(StatusCode::NOT_FOUND)
        .header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
        .body(Body::from("404 Not Found"))
        .unwrap_or_else(|_| Response::new(Body::empty()))
}

fn not_modified(mtime: Option<u64>, etag: Option<&str>, cache_control: &str) -> Response {
    let mut resp = Response::builder()
        .status(StatusCode::NOT_MODIFIED)
        .body(Body::empty())
        .unwrap_or_else(|_| Response::new(Body::empty()));
    let h = resp.headers_mut();
    if !cache_control.is_empty() {
        if let Ok(v) = HeaderValue::from_str(cache_control) {
            h.insert(header::CACHE_CONTROL, v);
        }
    }
    if let Some(v) = mtime.and_then(|s| HeaderValue::from_str(&format_http_date(s)).ok()) {
        h.insert(header::LAST_MODIFIED, v);
    }
    if let Some(v) = etag.and_then(|e| HeaderValue::from_str(e).ok()) {
        h.insert(header::ETAG, v);
    }
    resp
}

/// MIME type for a file extension, or `application/octet-stream`.
fn mime_for(path: &Path) -> HeaderValue {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .map(str::to_ascii_lowercase);
    let s: &'static str = match ext.as_deref() {
        Some("html" | "htm") => "text/html; charset=utf-8",
        Some("css") => "text/css; charset=utf-8",
        Some("js" | "mjs") => "application/javascript; charset=utf-8",
        Some("json") => "application/json; charset=utf-8",
        Some("xml") => "application/xml; charset=utf-8",
        Some("txt" | "md") => "text/plain; charset=utf-8",
        Some("svg") => "image/svg+xml",
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("webp") => "image/webp",
        Some("ico") => "image/x-icon",
        Some("avif") => "image/avif",
        Some("woff") => "font/woff",
        Some("woff2") => "font/woff2",
        Some("ttf") => "font/ttf",
        Some("otf") => "font/otf",
        Some("wasm") => "application/wasm",
        Some("pdf") => "application/pdf",
        Some("mp4") => "video/mp4",
        Some("webm") => "video/webm",
        Some("mp3") => "audio/mpeg",
        Some("ogg") => "audio/ogg",
        Some("zip") => "application/zip",
        Some("map") => "application/json; charset=utf-8",
        _ => "application/octet-stream",
    };
    HeaderValue::from_static(s)
}

/// A type a browser renders with script when opened directly.
fn runs_script(mime: &HeaderValue) -> bool {
    let m = mime.to_str().unwrap_or_default();
    ["text/html", "image/svg+xml", "application/xml"]
        .iter()
        .any(|t| m.starts_with(t))
}

/// A type a page on this origin can load and run by `<script>`, `<link>`
/// or `WebAssembly`; nosniff only blocks that when the type is wrong.
fn loads_as_code(mime: &HeaderValue) -> bool {
    let m = mime.to_str().unwrap_or_default();
    ["application/javascript", "text/css", "application/wasm"]
        .iter()
        .any(|t| m.starts_with(t))
}

/// Format unix seconds as an IMF-fixdate (RFC 7231), the HTTP date
/// format.
fn format_http_date(secs: u64) -> String {
    let dt = chrono::DateTime::<chrono::Utc>::from_timestamp(i64::try_from(secs).unwrap_or(0), 0)
        .unwrap_or_else(chrono::Utc::now);
    // chrono's RFC 2822 output ends in "+0000"; HTTP wants "GMT". Same
    // shape otherwise, so write the format out by hand.
    dt.format("%a, %d %b %Y %H:%M:%S GMT").to_string()
}

/// Parse an IMF-fixdate back into unix seconds. Any other format
/// gives `None`.
fn parse_http_date(s: &str) -> Option<u64> {
    let dt = chrono::DateTime::parse_from_rfc2822(s)
        .or_else(|_| {
            chrono::NaiveDateTime::parse_from_str(s, "%a, %d %b %Y %H:%M:%S GMT").map(|n| {
                chrono::DateTime::from_naive_utc_and_offset(
                    n,
                    chrono::FixedOffset::east_opt(0).unwrap(),
                )
            })
        })
        .ok()?;
    let ts = dt.timestamp();
    if ts < 0 {
        None
    } else {
        Some(u64::try_from(ts).ok()?)
    }
}

// Keeps the `SystemTime` import used, so `-D warnings` stays happy.
const _: fn() = || {
    let _ = SystemTime::UNIX_EPOCH;
};

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::Request;
    use std::io::Write;
    use tempfile::TempDir;
    use tower::ServiceExt;

    fn write_file(dir: &TempDir, rel: &str, body: &[u8]) -> PathBuf {
        let p = dir.path().join(rel);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        let mut f = std::fs::File::create(&p).unwrap();
        f.write_all(body).unwrap();
        p
    }

    fn server(dir: &TempDir) -> Router {
        static_router(StaticFiles::new(dir.path().to_path_buf()))
    }

    #[tokio::test]
    async fn serves_existing_file_with_correct_content_type() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "style.css", b"body{}");

        let resp = server(&dir)
            .oneshot(
                Request::builder()
                    .uri("/style.css")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
        assert_eq!(
            resp.headers()
                .get(header::CONTENT_TYPE)
                .unwrap()
                .to_str()
                .unwrap(),
            "text/css; charset=utf-8"
        );
        assert!(resp.headers().get(header::CACHE_CONTROL).is_some());
        let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16)
            .await
            .unwrap();
        assert_eq!(&bytes[..], b"body{}");
    }

    #[tokio::test]
    async fn returns_404_for_missing_file() {
        let dir = TempDir::new().unwrap();
        let resp = server(&dir)
            .oneshot(
                Request::builder()
                    .uri("/missing.txt")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), 404);
    }

    #[tokio::test]
    async fn rejects_parent_dir_traversal() {
        let dir = TempDir::new().unwrap();
        let resp = server(&dir)
            .oneshot(
                Request::builder()
                    .uri("/../etc/passwd")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), 404);
    }

    #[tokio::test]
    async fn rejects_hidden_files_by_default() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, ".env", b"SECRET=hunter2");
        let resp = server(&dir)
            .oneshot(Request::builder().uri("/.env").body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(resp.status(), 404);
    }

    /// A root that is itself a dot directory still serves: only the parts
    /// below it count.
    #[tokio::test]
    async fn a_dot_directory_root_serves() {
        let dir = TempDir::new().unwrap();
        let root = dir.path().join(".assets");
        std::fs::create_dir_all(&root).unwrap();
        std::fs::write(root.join("app.css"), b"body{}").unwrap();
        let resp = static_router(StaticFiles::new(root))
            .oneshot(
                Request::builder()
                    .uri("/app.css")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
    }

    /// `serve_hidden(true)` serves a name that resolves to a dot file too.
    #[cfg(unix)]
    #[tokio::test]
    async fn serve_hidden_serves_an_alias_of_a_hidden_file() {
        let dir = TempDir::new().unwrap();
        let secret = write_file(&dir, ".well", b"ok");
        std::os::unix::fs::symlink(&secret, dir.path().join("WELL~1")).unwrap();
        let app = static_router(StaticFiles::new(dir.path().to_path_buf()).serve_hidden(true));
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/WELL~1")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
    }

    /// A name that resolves to `.env` (a link here, an 8.3 alias on
    /// Windows) is hidden too.
    #[cfg(unix)]
    #[tokio::test]
    async fn rejects_an_alias_of_a_hidden_file() {
        let dir = TempDir::new().unwrap();
        let secret = write_file(&dir, ".env", b"SECRET=hunter2");
        std::os::unix::fs::symlink(&secret, dir.path().join("ENV~1")).unwrap();
        let resp = server(&dir)
            .oneshot(
                Request::builder()
                    .uri("/ENV~1")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), 404);
    }

    #[tokio::test]
    async fn serves_hidden_when_opted_in() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, ".well-known/x.txt", b"hi");
        let app = static_router(StaticFiles::new(dir.path().to_path_buf()).serve_hidden(true));
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/.well-known/x.txt")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
    }

    #[tokio::test]
    async fn directory_path_returns_404() {
        let dir = TempDir::new().unwrap();
        std::fs::create_dir_all(dir.path().join("sub")).unwrap();
        let resp = server(&dir)
            .oneshot(Request::builder().uri("/sub").body(Body::empty()).unwrap())
            .await
            .unwrap();
        // Directory listing is not supported, so 404.
        assert_eq!(resp.status(), 404);
    }

    #[tokio::test]
    async fn if_modified_since_returns_304_when_unchanged() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "robots.txt", b"User-agent: *\n");

        // First request: 200 + Last-Modified
        let r1 = server(&dir)
            .oneshot(
                Request::builder()
                    .uri("/robots.txt")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(r1.status(), 200);
        let last_modified = r1
            .headers()
            .get(header::LAST_MODIFIED)
            .unwrap()
            .to_str()
            .unwrap()
            .to_owned();

        // Sending that value back as If-Modified-Since gives a 304.
        let r2 = server(&dir)
            .oneshot(
                Request::builder()
                    .uri("/robots.txt")
                    .header(header::IF_MODIFIED_SINCE, &last_modified)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(r2.status(), StatusCode::NOT_MODIFIED);
        let bytes = axum::body::to_bytes(r2.into_body(), 1 << 16).await.unwrap();
        assert!(bytes.is_empty());
    }

    #[tokio::test]
    async fn head_request_returns_headers_no_body() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "x.html", b"<html></html>");
        let resp = server(&dir)
            .oneshot(
                Request::builder()
                    .method(Method::HEAD)
                    .uri("/x.html")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
        assert!(resp.headers().get(header::CONTENT_LENGTH).is_some());
        let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16)
            .await
            .unwrap();
        assert!(bytes.is_empty(), "HEAD must not return a body");
    }

    #[tokio::test]
    async fn immutable_helper_sets_correct_cache_control() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "app.a3f8b2.js", b"console.log(1)");
        let app = static_router(
            StaticFiles::new(dir.path().to_path_buf())
                .immutable(Duration::from_secs(60 * 60 * 24 * 365)),
        );
        let resp = app
            .oneshot(
                Request::builder()
                    .uri("/app.a3f8b2.js")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let cc = resp
            .headers()
            .get(header::CACHE_CONTROL)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(cc.contains("immutable"));
        assert!(cc.contains("max-age=31536000"));
    }

    #[test]
    fn mime_for_known_extensions() {
        assert_eq!(
            mime_for(Path::new("a.css")).to_str().unwrap(),
            "text/css; charset=utf-8"
        );
        assert_eq!(
            mime_for(Path::new("a.svg")).to_str().unwrap(),
            "image/svg+xml"
        );
        assert_eq!(
            mime_for(Path::new("a.unknown")).to_str().unwrap(),
            "application/octet-stream"
        );
    }

    async fn get(app: Router, uri: &str) -> Response {
        let req = Request::builder().uri(uri).body(Body::empty()).unwrap();
        app.oneshot(req).await.unwrap()
    }

    /// Uploaded HTML/SVG/XML must not run on the app origin (#1849).
    #[tokio::test]
    async fn user_content_downloads_active_types() {
        let dir = TempDir::new().unwrap();
        for f in ["x.html", "x.HTM", "x.svg", "x.xml", "x.png"] {
            write_file(&dir, f, b"<script>alert(1)</script>");
        }
        let app = static_router(StaticFiles::new(dir.path()).user_content());
        for f in ["x.html", "x.HTM", "x.svg", "x.xml"] {
            let r = get(app.clone(), &format!("/{f}")).await;
            assert_eq!(
                r.headers()[header::CONTENT_DISPOSITION],
                "attachment",
                "{f}"
            );
            assert_eq!(r.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
        }
        let r = get(app, "/x.png").await;
        assert!(r.headers().get(header::CONTENT_DISPOSITION).is_none());
        assert_eq!(r.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");

        // Plain static mounts keep serving HTML inline.
        let r = get(server(&dir), "/x.html").await;
        assert!(r.headers().get(header::CONTENT_DISPOSITION).is_none());
    }

    /// An uploaded script or stylesheet cannot be loaded by a page on
    /// this origin: it goes out untyped, as a download.
    #[tokio::test]
    async fn user_content_never_serves_code_types() {
        let dir = TempDir::new().unwrap();
        for f in ["x.js", "x.MJS", "x.css", "x.wasm"] {
            write_file(&dir, f, b"alert(1)");
        }
        let app = static_router(StaticFiles::new(dir.path()).user_content());
        for f in ["x.js", "x.MJS", "x.css", "x.wasm"] {
            let r = get(app.clone(), &format!("/{f}")).await;
            assert_eq!(
                r.headers()[header::CONTENT_TYPE],
                "application/octet-stream",
                "{f}"
            );
            assert_eq!(r.headers()[header::CONTENT_DISPOSITION], "attachment");
            assert_eq!(r.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
        }
        // A plain static mount still serves them typed.
        let r = get(server(&dir), "/x.js").await;
        assert!(r.headers()[header::CONTENT_TYPE]
            .to_str()
            .unwrap()
            .starts_with("application/javascript"));
    }

    /// What `warn_if_uploads_prefix(prefix)` logs.
    #[cfg(feature = "runtime")]
    fn prefix_logs(prefix: &str) -> String {
        let out = crate::testkit::CaptureWriter::default();
        let sub = tracing_subscriber::fmt()
            .with_writer(out.clone())
            .with_ansi(false)
            .finish();
        tracing::subscriber::with_default(sub, || warn_if_uploads_prefix(prefix));
        out.contents()
    }

    #[cfg(feature = "runtime")]
    #[test]
    fn upload_like_static_prefixes_warn() {
        for p in ["/uploads", "/Media", "/user-uploads/"] {
            assert!(prefix_logs(p).contains("with_uploads"), "{p}");
        }
        assert_eq!(prefix_logs("/static"), "");
    }

    /// #1531 — the body streams in chunks instead of one whole-file buffer.
    #[tokio::test]
    async fn large_file_streams_in_chunks() {
        use http_body_util::BodyExt as _;
        let dir = TempDir::new().unwrap();
        let big = vec![7u8; 1 << 20];
        write_file(&dir, "big.bin", &big);
        let mut body = get(server(&dir), "/big.bin").await.into_body();
        // Exact, so `CompressionLayer` still compresses a streamed asset.
        assert_eq!(http_body::Body::size_hint(&body).exact(), Some(1 << 20));
        let first = body.frame().await.unwrap().unwrap().into_data().unwrap();
        assert!(first.len() < big.len(), "first frame is the whole file");
        let rest = body.collect().await.unwrap().to_bytes();
        assert_eq!(first.len() + rest.len(), big.len());
    }

    /// The cached root follows a re-pointed root symlink (release swaps).
    #[cfg(unix)]
    #[tokio::test]
    async fn root_symlink_swap_keeps_serving() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "a/x.txt", b"a");
        write_file(&dir, "b/x.txt", b"b");
        let cur = dir.path().join("current");
        std::os::unix::fs::symlink(dir.path().join("a"), &cur).unwrap();
        let app = static_router(StaticFiles::new(&cur));
        assert_eq!(get(app.clone(), "/x.txt").await.status(), 200);
        std::fs::remove_file(&cur).unwrap();
        std::os::unix::fs::symlink(dir.path().join("b"), &cur).unwrap();
        let r = get(app, "/x.txt").await;
        assert_eq!(r.status(), 200);
        assert_eq!(
            &axum::body::to_bytes(r.into_body(), 8).await.unwrap()[..],
            b"b"
        );
    }

    async fn ranged(app: Router, range: &str) -> Response {
        let req = Request::builder()
            .uri("/r.txt")
            .header(header::RANGE, range)
            .body(Body::empty())
            .unwrap();
        app.oneshot(req).await.unwrap()
    }

    /// #1531 — single byte ranges get a 206; bad ones a 416.
    #[tokio::test]
    async fn range_requests_are_honoured() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "r.txt", b"0123456789");
        let full = get(server(&dir), "/r.txt").await;
        assert_eq!(full.headers()[header::ACCEPT_RANGES], "bytes");
        for (spec, want, cr) in [
            ("bytes=2-4", &b"234"[..], "bytes 2-4/10"),
            ("bytes=7-", b"789", "bytes 7-9/10"),
            ("bytes=-3", b"789", "bytes 7-9/10"),
            ("bytes=8-99", b"89", "bytes 8-9/10"),
        ] {
            let r = ranged(server(&dir), spec).await;
            assert_eq!(r.status(), StatusCode::PARTIAL_CONTENT, "{spec}");
            assert_eq!(r.headers()[header::CONTENT_RANGE], cr, "{spec}");
            assert_eq!(r.headers()[header::CONTENT_LENGTH], want.len().to_string());
            let b = axum::body::to_bytes(r.into_body(), 64).await.unwrap();
            assert_eq!(&b[..], want, "{spec}");
        }
        let r = ranged(server(&dir), "bytes=10-").await;
        assert_eq!(r.status(), StatusCode::RANGE_NOT_SATISFIABLE);
        assert_eq!(r.headers()[header::CONTENT_RANGE], "bytes */10");
        // Several ranges: the whole file is a valid answer.
        assert_eq!(ranged(server(&dir), "bytes=0-1,4-5").await.status(), 200);
        // Malformed specs are ignored, not refused (RFC 9110 §14.2).
        for spec in ["bytes=abc-", "bytes=5-3", "bytes=-x", "bytes=1-y"] {
            assert_eq!(ranged(server(&dir), spec).await.status(), 200, "{spec}");
        }
    }

    async fn if_range(app: Router, validator: &str) -> Response {
        let req = Request::builder()
            .uri("/r.txt")
            .header(header::RANGE, "bytes=2-4")
            .header(header::IF_RANGE, validator)
            .body(Body::empty())
            .unwrap();
        app.oneshot(req).await.unwrap()
    }

    /// `If-Range` resumes on the file's strong ETag or its Last-Modified,
    /// also behind `EtagLayer`, and a changed validator gets the whole file.
    #[tokio::test]
    async fn if_range_matches_etag_or_last_modified() {
        use crate::etag::{EtagLayer, EtagRouterExt as _};
        let dir = TempDir::new().unwrap();
        write_file(&dir, "r.txt", b"0123456789");
        let app = server(&dir).etag(EtagLayer::new());
        let full = get(app.clone(), "/r.txt").await;
        let etag = full.headers()[header::ETAG].to_str().unwrap().to_owned();
        let lm = full.headers()[header::LAST_MODIFIED]
            .to_str()
            .unwrap()
            .to_owned();

        let r = if_range(app.clone(), &etag).await;
        assert_eq!(r.status(), StatusCode::PARTIAL_CONTENT);
        // The 206 names the whole file, not a hash of the slice.
        assert_eq!(r.headers()[header::ETAG], etag.as_str());
        assert_eq!(if_range(app.clone(), &lm).await.status(), 206);

        let weak = format!("W/{etag}");
        for stale in ["\"other\"", weak.as_str(), "Thu, 01 Jan 1970 00:00:00 GMT"] {
            let r = if_range(app.clone(), stale).await;
            assert_eq!(r.status(), StatusCode::OK, "{stale}");
            assert_eq!(r.headers()[header::CONTENT_LENGTH], "10");
        }

        let req = Request::builder()
            .uri("/r.txt")
            .header(header::IF_NONE_MATCH, &etag)
            .body(Body::empty())
            .unwrap();
        assert_eq!(app.oneshot(req).await.unwrap().status(), 304);
    }

    /// The cached root expires, so a root re-pointed to a subdirectory
    /// stops serving symlinks into the old target.
    #[cfg(unix)]
    #[tokio::test]
    async fn repointed_root_drops_the_old_tree() {
        let dir = TempDir::new().unwrap();
        write_file(&dir, "a/secret.txt", b"s");
        write_file(&dir, "a/pub/x.txt", b"x");
        std::os::unix::fs::symlink(
            dir.path().join("a/secret.txt"),
            dir.path().join("a/pub/leak"),
        )
        .unwrap();
        let cur = dir.path().join("current");
        std::os::unix::fs::symlink(dir.path().join("a"), &cur).unwrap();
        let app = static_router(StaticFiles::new(&cur));
        assert_eq!(get(app.clone(), "/secret.txt").await.status(), 200);
        std::fs::remove_file(&cur).unwrap();
        std::os::unix::fs::symlink(dir.path().join("a/pub"), &cur).unwrap();
        tokio::time::sleep(ROOT_TTL * 2).await;
        assert_eq!(get(app.clone(), "/x.txt").await.status(), 200);
        assert_eq!(get(app, "/leak").await.status(), 404);
    }

    #[test]
    fn http_date_round_trips() {
        let secs = 1_714_651_200u64; // 2024-05-02T12:00:00Z
        let s = format_http_date(secs);
        let parsed = parse_http_date(&s).unwrap();
        assert_eq!(parsed, secs);
    }

    #[test]
    fn http_date_parses_rfc2822_form() {
        // chrono RFC 2822 → numeric offset, not "GMT".
        let parsed = parse_http_date("Thu, 02 May 2024 12:00:00 +0000").unwrap();
        assert_eq!(parsed, 1_714_651_200);
    }

    async fn body_of(resp: Response) -> Vec<u8> {
        http_body_util::BodyExt::collect(resp.into_body())
            .await
            .unwrap()
            .to_bytes()
            .to_vec()
    }

    #[test]
    fn hashed_names_keep_dir_and_extension() {
        assert_eq!(assets_hashed("js/app.js", "ab"), "js/app.ab.js");
        assert_eq!(assets_hashed("app.min.js", "ab"), "app.ab.min.js");
        assert_eq!(assets_hashed("LICENSE", "ab"), "LICENSE.ab");
        assert_eq!(assets_hashed(".x", "ab"), ".x.ab");
    }

    fn assets_hashed(path: &str, tag: &str) -> String {
        let m = AssetManifest::from_files([(path, &b""[..])]);
        let hashed = &m.get(path).unwrap().hashed;
        // Swap the real tag for `tag` so the shape is easy to read.
        let real: String = hashed
            .split('.')
            .find(|p| p.len() == 12 && p.bytes().all(|b| b.is_ascii_hexdigit()))
            .unwrap()
            .to_owned();
        hashed.replace(&real, tag)
    }

    /// The hashed URL serves the file `immutable`, and its SRI hash is the
    /// SHA-384 of the bytes served.
    #[tokio::test]
    async fn manifest_serves_hashed_names_with_matching_sri() {
        use base64::Engine as _;
        use sha2::Digest as _;
        let dir = TempDir::new().unwrap();
        write_file(&dir, "js/app.js", b"console.log(1)");
        write_file(&dir, ".env", b"SECRET=1");
        let manifest = AssetManifest::from_dir(dir.path())
            .unwrap()
            .prefix("/static/");
        assert!(manifest.get(".env").is_none(), "hidden files stay out");
        let url = manifest.url("js/app.js").unwrap();
        assert!(
            url.starts_with("/static/js/app.") && url.ends_with(".js"),
            "{url}"
        );
        let want_sri = format!(
            "sha384-{}",
            base64::engine::general_purpose::STANDARD
                .encode(sha2::Sha384::digest(b"console.log(1)"))
        );
        assert_eq!(manifest.integrity("js/app.js"), Some(want_sri.as_str()));

        let app = static_router(StaticFiles::new(dir.path()).manifest(manifest.clone()));
        let hashed = get(app.clone(), url.trim_start_matches("/static")).await;
        assert_eq!(hashed.status(), StatusCode::OK);
        assert_eq!(
            hashed.headers()[header::CACHE_CONTROL],
            HASHED_CACHE_CONTROL
        );
        assert_eq!(body_of(hashed).await, b"console.log(1)");
        let plain = get(app, "/js/app.js").await;
        assert_eq!(
            plain.headers()[header::CACHE_CONTROL],
            "public, max-age=3600"
        );

        let back = AssetManifest::from_json(&manifest.to_json()).unwrap();
        assert_eq!(back, manifest);
    }

    /// `embed_static!` leaves hidden files out; embedded files get an
    /// ETag, 304, ranges and 404s like files on disk.
    #[tokio::test]
    async fn embedded_files_serve_like_files_on_disk() {
        static ASSETS: EmbeddedDir = crate::embed_static!("tests/fixtures/embed_static");
        let names: Vec<&str> = ASSETS.files().iter().map(|(p, _)| *p).collect();
        assert_eq!(names, ["app.js", "css/site.css"]);
        let app = static_router(StaticFiles::embedded(ASSETS));

        let ok = get(app.clone(), "/css/site.css").await;
        assert_eq!(ok.status(), StatusCode::OK);
        assert_eq!(
            ok.headers()[header::CONTENT_TYPE],
            "text/css; charset=utf-8"
        );
        let etag = ok.headers()[header::ETAG].clone();
        assert_eq!(body_of(ok).await, b"body{margin:0}\n");

        let req = Request::builder()
            .uri("/css/site.css")
            .header(header::IF_NONE_MATCH, etag)
            .body(Body::empty())
            .unwrap();
        assert_eq!(
            app.clone().oneshot(req).await.unwrap().status(),
            StatusCode::NOT_MODIFIED
        );

        let req = Request::builder()
            .uri("/app.js")
            .header(header::RANGE, "bytes=0-6")
            .body(Body::empty())
            .unwrap();
        let part = app.clone().oneshot(req).await.unwrap();
        assert_eq!(part.status(), StatusCode::PARTIAL_CONTENT);
        assert_eq!(body_of(part).await, b"console");

        for missing in ["/.secret", "/css/../app.js", "/nope.js"] {
            assert_eq!(
                get(app.clone(), missing).await.status(),
                StatusCode::NOT_FOUND,
                "{missing}"
            );
        }

        let manifest = AssetManifest::from_embedded(&ASSETS);
        let app = static_router(StaticFiles::embedded(ASSETS).manifest(manifest.clone()));
        let hashed = format!("/{}", manifest.get("app.js").unwrap().hashed);
        let resp = get(app, &hashed).await;
        assert_eq!(resp.headers()[header::CACHE_CONTROL], HASHED_CACHE_CONTROL);
    }

    #[cfg(feature = "_tera")]
    #[test]
    fn tera_functions_render_url_and_integrity() {
        let m = AssetManifest::from_files([("app.js", &b"x"[..])]).prefix("/static");
        let mut tera = tera::Tera::default();
        m.register_tera(&mut tera);
        tera.add_raw_template(
            "t",
            r#"{{ asset_url(name="app.js") }}|{{ asset_integrity(name="app.js") }}"#,
        )
        .unwrap();
        let out = tera.render("t", &tera::Context::new()).unwrap();
        assert_eq!(
            out,
            format!(
                "{}|{}",
                m.url("app.js").unwrap(),
                m.integrity("app.js").unwrap()
            )
        );
        tera.add_raw_template("bad", r#"{{ asset_url(name="nope.js") }}"#)
            .unwrap();
        assert!(tera.render("bad", &tera::Context::new()).is_err());
    }
}