mini-static 0.38.5

A secure, async static file server with streaming, traversal protection, and connection limits.
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
use std::borrow::Cow;
use std::fs::{File, Metadata};
use std::path::{Path, PathBuf};

use crate::error::StaticError;

/// A request path resolved all the way to an opened file.
///
/// Holding the open handle is the point: containment was verified on this exact fd (see
/// [`real_path_of`]), so serving from it — rather than re-opening by path — leaves no
/// gap between the check and the bytes.
pub(crate) struct ResolvedFile {
    pub(crate) file: File,
    pub(crate) metadata: Metadata,
    pub(crate) path: PathBuf,
}

/// The real, symlink-resolved path of an already-open file, from the kernel.
///
/// This is `canonicalize()` inverted: instead of resolving a path and hoping the later
/// `open` lands on the same file, open first and ask what was opened. macOS answers via
/// `fcntl(F_GETPATH)`; Linux via the fd's `/proc` symlink. Measured at ~38% cheaper than
/// the canonicalize-then-open sequence it replaces — and immune to the path being
/// swapped between check and use, because there is no "between".
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn real_path_of(file: &File) -> std::io::Result<PathBuf> {
    use std::os::fd::AsRawFd;
    use std::os::unix::ffi::OsStrExt;

    let mut buf = [0u8; libc::PATH_MAX as usize];
    // SAFETY: `buf` is PATH_MAX bytes and F_GETPATH writes at most PATH_MAX including
    // the NUL terminator; the fd is valid for the lifetime of `file`.
    let rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETPATH, buf.as_mut_ptr()) };
    if rc != 0 {
        return Err(std::io::Error::last_os_error());
    }
    let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    Ok(PathBuf::from(std::ffi::OsStr::from_bytes(&buf[..len])))
}

#[cfg(target_os = "linux")]
fn real_path_of(file: &File) -> std::io::Result<PathBuf> {
    use std::os::fd::AsRawFd;
    std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd()))
}

/// Check that a canonicalized path stays within the server root.
///
/// Calls `canonicalize()` on the joined path and verifies the result starts with
/// `root_canon`, catching symlink escapes and traversal attempts that sneak through
/// segment-based checks.
///
/// # Arguments
///
/// * `root_canon` - The server root in canonical form.
/// * `joined` - A path that may need canonicalizing (e.g., the result of `root.join(...)`).
///
/// # Returns
///
/// - `Ok(PathBuf)` if the canonicalized path stays within root.
/// - `Err(StaticError::NotFound)` if the path doesn't exist or can't be canonicalized.
/// - `Err(StaticError::Traversal)` if the canonicalized path escapes root.
// On fd-verified platforms (macOS/iOS/Linux) only the portability fallback calls this,
// so it reads as dead there — it is the other platforms' security boundary, not debris.
#[cfg_attr(
    any(target_os = "macos", target_os = "ios", target_os = "linux"),
    allow(dead_code)
)]
pub(crate) fn canonicalize_within_root(
    root_canon: &Path,
    joined: &Path,
) -> Result<PathBuf, StaticError> {
    let canon = joined
        .canonicalize()
        .map_err(|_| StaticError::NotFound(joined.display().to_string()))?;

    if canon.starts_with(root_canon) {
        Ok(canon)
    } else {
        Err(StaticError::Traversal(joined.display().to_string()))
    }
}

/// Resolve a request path under a pre-canonicalized root.
///
/// This function assumes `root_canon` is already in canonical form — `root_canon` should be
/// the output of `root.canonicalize()` called once at server startup. Per-request resolution
/// only canonicalizes the joined path, not the root.
///
/// # Path Traversal Protection
///
/// Segment-based traversal check rejects only path segments exactly equal to `..`.
/// This allows filenames containing `..` as a substring (e.g., `jquery..min.js`) while
/// blocking traversal attempts like `../../etc/passwd`.
///
/// # Directory Handling
///
/// If the resolved path is a directory, automatically serves `index.html` from that directory
/// if it exists and doesn't escape the root.
///
/// # Symlinks
///
/// Symlinks are followed during canonicalization. After following symlinks, the final
/// canonical path must stay within the server root.
///
/// # Arguments
///
/// * `root_canon` - The server root in canonical form (should be output of `canonicalize()`).
/// * `request_path` - The HTTP request path (e.g., `/path/to/file.html`).
///
/// # Returns
///
/// - `Ok(PathBuf)` if the path resolves to a file within root.
/// - `Err(StaticError::NotFound)` if the path doesn't exist.
/// - `Err(StaticError::Traversal)` if the path attempts to escape the root.
pub fn resolve_with_canonical_root(
    root_canon: &Path,
    request_path: &str,
) -> Result<PathBuf, StaticError> {
    resolve_with_policy(root_canon, request_path, HiddenFiles::Deny)
}

/// Whether dot-prefixed request-path segments may be served.
///
/// The default is [`HiddenFiles::Deny`]: a served root is frequently a build output
/// directory, a repository working copy, or a folder someone dropped a `.env` into, and
/// serving `.git/config` or `.env` to anyone who guesses the name is a credential leak
/// that no traversal check catches — the files are legitimately *inside* the root.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HiddenFiles {
    /// Dot-prefixed segments answer as a miss.
    Deny,
    /// Dot-prefixed segments resolve like any other name.
    Serve,
}

/// The one dot-prefixed prefix served under [`HiddenFiles::Deny`]: `/.well-known/` is
/// where the web puts things that are *meant* to be fetched — ACME challenges for
/// certificate issuance, `security.txt`, app-site association files. Denying it would
/// break certificate renewal on any site served by this crate.
const WELL_KNOWN: &str = ".well-known";

/// The file a directory request resolves to.
///
/// Named because five places depended on the same literal — two here, two in the
/// trailing-slash redirect, and the content cache's directory retry. A sixth would have been
/// the one that disagreed.
pub(crate) const INDEX_FILE_NAME: &str = "index.html";

/// Whether any segment of `decoded` is a hidden name, honoring the `.well-known`
/// exception.
///
/// Scope is deliberately the *request path* only, never the served root's own
/// filesystem path — a root that itself lives under a dot-directory
/// (`~/.config/site/public`) must keep working, since the operator chose that location
/// and no request can address it.
///
/// A segment of exactly `.` is a same-directory reference (`/./index.html`), not a
/// hidden name, so it is exempt. `..` never reaches here — the traversal check rejects
/// it first.
fn has_hidden_segment(segments: &[Cow<'_, str>]) -> bool {
    segments.iter().enumerate().any(|(index, segment)| {
        let is_well_known_root = index == 0 && segment.as_ref() == WELL_KNOWN;
        segment.starts_with('.') && segment != "." && !is_well_known_root
    })
}

/// Decode a request path into its segments — this crate's only interpretation of what a
/// path *is*.
///
/// **Splitting happens before decoding**, per RFC 3986 §3.3: `/` separates segments and a
/// percent-encoded `%2F` is an ordinary character *inside* one. Decoding the whole path
/// first — which this crate did through 0.31.x — promotes `%2F` into a separator, so
/// `/admin%2Fconfig` reaches `admin/config` on disk. Containment still held, but any
/// router or middleware in front of this server correctly reads that request as a single
/// segment matching no route, so the file was served while the route guarding it was
/// never consulted. See `tests/encoded_separator.rs`.
///
/// A segment that still contains a separator after decoding is refused rather than
/// re-split — the same answer Apache gives by default (`AllowEncodedSlashes Off`).
/// Backslash is refused on every platform, not just Windows where it separates: a server
/// whose test suite runs on one OS should not behave differently on another, and a file
/// with a backslash in its name is not worth the divergence.
pub(crate) fn decode_segments(request_path: &str) -> Result<Vec<Cow<'_, str>>, StaticError> {
    let mut segments = Vec::new();
    for raw in request_path.split('/') {
        if raw.is_empty() {
            continue;
        }
        // Invalid UTF-8 falls back to the raw segment, which then matches only a file
        // literally named that — the behaviour this crate has always had.
        // Borrowed when the segment carries no percent-encoding, which is the common
        // case; `into_owned()` here allocated a `String` per segment per request and cost
        // 5-6% on the `not_modified_304` and `sidecar_hit_200` benchmarks.
        let decoded = percent_encoding::percent_decode_str(raw)
            .decode_utf8()
            .unwrap_or(Cow::Borrowed(raw));

        check_segment(&decoded, request_path)?;
        segments.push(decoded);
    }
    Ok(segments)
}

/// Refuse a decoded segment that must not reach the filesystem.
///
/// Separate from the decoding above because the two have different owners once a router
/// sits in front of this crate. **The router decides what the segments are; this decides
/// whether they are safe to open with.** A router that splits before decoding — as
/// `mini-serve` correctly does — hands over a segment that may still contain a literal
/// `/` from a `%2F`, and `Path::push` would read that as a separator, which is the
/// encoded-separator escape all over again. So this runs over segments from any source,
/// not only ones this crate decoded itself.
pub(crate) fn check_segment(decoded: &str, request_path: &str) -> Result<(), StaticError> {
    let refuse = || StaticError::Traversal(request_path.to_string());

    // Catches a NUL whether it arrived raw or as `%00`. A separate pre-check on the
    // undecoded path used to sit above the decode loop; mutation testing showed it was
    // fully subsumed — neither guard could be removed alone and be noticed — so the
    // redundant one went and this one carries the guarantee.
    if decoded.contains('/') || decoded.contains('\\') || decoded.contains('\0') {
        return Err(refuse());
    }
    if decoded == ".." {
        return Err(refuse());
    }
    Ok(())
}

/// Join decoded segments onto the root one at a time.
///
/// One at a time because `Path::join` re-reads a separator inside its argument; feeding
/// it a pre-joined string would undo the work `decode_segments` just did.
fn join_segments(root_canon: &Path, segments: &[Cow<'_, str>]) -> PathBuf {
    // `push` rather than `join`: `join` clones the whole path per segment, so folding it
    // allocated a `PathBuf` for every segment of every request.
    let mut path = root_canon.to_path_buf();
    for segment in segments {
        path.push(segment.as_ref());
    }
    path
}

/// [`resolve_with_canonical_root`] with an explicit hidden-file policy.
pub(crate) fn resolve_with_policy(
    root_canon: &Path,
    request_path: &str,
    hidden: HiddenFiles,
) -> Result<PathBuf, StaticError> {
    open_with_policy(root_canon, request_path, hidden).map(|resolved| resolved.path)
}

/// Open `joined` and prove, on the opened fd, that it lies under `root_canon`.
///
/// A directory retries with `index.html` appended — verified on its *own* fd, never
/// trusted transitively from the directory's.
///
/// Every open failure collapses to `NotFound`: differentiating errno (permission vs
/// absent vs vanished) would hand back the existence oracle the 404 path works to deny.
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "linux"))]
fn open_verified(
    root_canon: &Path,
    joined: &Path,
    request_path: &str,
) -> Result<ResolvedFile, StaticError> {
    let file = File::open(joined).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
    let real = real_path_of(&file).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
    if !real.starts_with(root_canon) {
        return Err(StaticError::Traversal(request_path.to_string()));
    }
    let metadata = file
        .metadata()
        .map_err(|_| StaticError::NotFound(request_path.to_string()))?;

    if metadata.is_dir() {
        return open_verified(root_canon, &real.join(INDEX_FILE_NAME), request_path);
    }

    Ok(ResolvedFile {
        file,
        metadata,
        path: real,
    })
}

/// Portability fallback: the canonicalize-then-open sequence this crate used through
/// 0.30.x, for platforms without a way to read an fd's real path. Slower and it
/// re-admits the check-to-open window; the property tests exercise whichever variant
/// the platform compiles.
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
fn open_verified(
    root_canon: &Path,
    joined: &Path,
    request_path: &str,
) -> Result<ResolvedFile, StaticError> {
    let canon = canonicalize_within_root(root_canon, joined)?;
    let target = if canon.is_dir() {
        let index = canon.join(INDEX_FILE_NAME);
        canonicalize_within_root(root_canon, &index)?;
        index
    } else {
        canon
    };
    let file = File::open(&target).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
    let metadata = file
        .metadata()
        .map_err(|_| StaticError::NotFound(request_path.to_string()))?;
    Ok(ResolvedFile {
        file,
        metadata,
        path: target,
    })
}

/// Open a precompressed sidecar and prove, on the opened fd, that it is a regular file
/// under `root_canon`. `None` means "decline and serve the original".
///
/// # Why this exists rather than calling [`open_verified`]
///
/// From 0.9.0 until this function, the sidecar probe opened its file with a bare
/// `File::open` and served it with **no containment check at all** — a `styles.css.br`
/// symlinked outside the root was served for `GET /styles.css` with `Accept-Encoding: br`,
/// while `GET /styles.css.br` on the same file correctly returned 404. Two doors to one
/// file, one of them unguarded, falsifying the `containment-verified-on-fd` guarantee on a
/// path its mutation test never reached. See `PLAN-sidecar.md`.
///
/// It cannot simply call [`open_verified`], because that **retries a directory** with
/// `index.html` appended: a directory named `styles.css.br` would resolve to
/// `styles.css.br/index.html` and be served as a brotli body. A sidecar is a regular file
/// or it is nothing, and `is_file()` is the one condition that says so — it also excludes
/// a FIFO, where `File::open` blocks until a writer appears and would hang the request.
///
/// Every failure returns `None` rather than an error. A sidecar is an optimisation: if it
/// cannot be served safely the original is served instead, which is what a caller with no
/// sidecar at all already does. Distinguishing "absent" from "refused" in the response
/// would hand back an existence oracle for files outside the root.
#[cfg(any(target_os = "macos", target_os = "ios", target_os = "linux"))]
pub(crate) fn open_sidecar_verified(root_canon: &Path, sidecar: &Path) -> Option<ResolvedFile> {
    let file = File::open(sidecar).ok()?;
    let real = real_path_of(&file).ok()?;
    if !real.starts_with(root_canon) {
        return None;
    }
    let metadata = file.metadata().ok()?;
    if !metadata.is_file() {
        return None;
    }
    Some(ResolvedFile {
        file,
        metadata,
        path: real,
    })
}

/// Portability fallback for [`open_sidecar_verified`], for platforms with no way to read an
/// fd's real path. Canonicalize-then-open, so it re-admits the check-to-open window that
/// the fd-based variant closes — the same tradeoff the [`open_verified`] fallback makes.
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
pub(crate) fn open_sidecar_verified(root_canon: &Path, sidecar: &Path) -> Option<ResolvedFile> {
    let canon = canonicalize_within_root(root_canon, sidecar).ok()?;
    let file = File::open(&canon).ok()?;
    let metadata = file.metadata().ok()?;
    if !metadata.is_file() {
        return None;
    }
    Some(ResolvedFile {
        file,
        metadata,
        path: canon,
    })
}

/// [`resolve_with_policy`], but yielding the opened, containment-verified file rather
/// than a path to reopen. `Server::handle_request` serves from this handle directly.
/// [`open_with_policy`], against segments a caller already split and decoded.
///
/// Every segment is still checked by [`check_segment`]: where they came from is not this
/// crate's business, but whether they can escape the root is.
pub(crate) fn open_segments<S: AsRef<str>>(
    root_canon: &Path,
    segments: &[S],
    request_path: &str,
    hidden: HiddenFiles,
) -> Result<ResolvedFile, StaticError> {
    let checked = servable_segments(segments, request_path, hidden)?;
    open_checked(root_canon, &checked, request_path, hidden)
}

/// The refusals that stand between a request's segments and any file at all.
///
/// Called by both ways of answering a request: the disk path before it opens anything, and the
/// content cache before it looks anything up. **That sharing is the point.** The content cache
/// initially skipped these and served `/.env` from memory while the disk path refused it — a
/// hidden file leaked by a performance feature, found by the differential test within a minute
/// of the cache first answering a request. One implementation cannot diverge from itself.
pub(crate) fn servable_segments<'a, S: AsRef<str>>(
    segments: &'a [S],
    request_path: &str,
    hidden: HiddenFiles,
) -> Result<Vec<Cow<'a, str>>, StaticError> {
    let checked: Vec<Cow<'a, str>> = segments
        .iter()
        .map(|segment| {
            check_segment(segment.as_ref(), request_path)?;
            Ok(Cow::Borrowed(segment.as_ref()))
        })
        .collect::<Result<_, StaticError>>()?;

    if hidden == HiddenFiles::Deny && has_hidden_segment(&checked) {
        return Err(StaticError::NotFound(request_path.to_string()));
    }
    Ok(checked)
}

pub(crate) fn open_with_policy(
    root_canon: &Path,
    request_path: &str,
    hidden: HiddenFiles,
) -> Result<ResolvedFile, StaticError> {
    let segments = decode_segments(request_path)?;
    open_checked(root_canon, &segments, request_path, hidden)
}

/// The shared tail: hidden-file policy, then open and prove containment.
fn open_checked(
    root_canon: &Path,
    segments: &[Cow<'_, str>],
    request_path: &str,
    hidden: HiddenFiles,
) -> Result<ResolvedFile, StaticError> {

    // `NotFound`, not a distinct error: a hidden file that exists and one that doesn't
    // must be indistinguishable, or the response becomes an oracle for what the root
    // contains — the same reasoning that collapses traversal into the miss message.
    if hidden == HiddenFiles::Deny && has_hidden_segment(segments) {
        return Err(StaticError::NotFound(request_path.to_string()));
    }

    open_verified(root_canon, &join_segments(root_canon, segments), request_path)
}

/// Resolve a request path under a root directory, canonicalizing the root first.
///
/// This is a convenience wrapper around `resolve_with_canonical_root()` that canonicalizes
/// the root on every call. For production use where the root is fixed at startup, prefer
/// `Server::new()` which canonicalizes the root once and reuses it for all requests.
///
/// # Arguments
///
/// * `root` - The server root directory (need not be pre-canonicalized).
/// * `request_path` - The HTTP request path (e.g., `/path/to/file.html`).
///
/// # Returns
///
/// - `Ok(PathBuf)` if the path resolves to a file within root.
/// - `Err(StaticError)` if the path is invalid, missing, or attempts traversal.
/// - `Err(StaticError::Io)` if canonicalizing the root fails.
pub fn resolve(root: &Path, request_path: &str) -> Result<PathBuf, StaticError> {
    let root_canon = root.canonicalize().map_err(StaticError::Io)?;
    resolve_with_canonical_root(&root_canon, request_path)
}