Skip to main content

mini_static/
resolve.rs

1use std::borrow::Cow;
2use std::fs::{File, Metadata};
3use std::path::{Path, PathBuf};
4
5use crate::error::StaticError;
6
7/// A request path resolved all the way to an opened file.
8///
9/// Holding the open handle is the point: containment was verified on this exact fd (see
10/// [`real_path_of`]), so serving from it — rather than re-opening by path — leaves no
11/// gap between the check and the bytes.
12pub(crate) struct ResolvedFile {
13    pub(crate) file: File,
14    pub(crate) metadata: Metadata,
15    pub(crate) path: PathBuf,
16}
17
18/// The real, symlink-resolved path of an already-open file, from the kernel.
19///
20/// This is `canonicalize()` inverted: instead of resolving a path and hoping the later
21/// `open` lands on the same file, open first and ask what was opened. macOS answers via
22/// `fcntl(F_GETPATH)`; Linux via the fd's `/proc` symlink. Measured at ~38% cheaper than
23/// the canonicalize-then-open sequence it replaces — and immune to the path being
24/// swapped between check and use, because there is no "between".
25#[cfg(any(target_os = "macos", target_os = "ios"))]
26fn real_path_of(file: &File) -> std::io::Result<PathBuf> {
27    use std::os::fd::AsRawFd;
28    use std::os::unix::ffi::OsStrExt;
29
30    let mut buf = [0u8; libc::PATH_MAX as usize];
31    // SAFETY: `buf` is PATH_MAX bytes and F_GETPATH writes at most PATH_MAX including
32    // the NUL terminator; the fd is valid for the lifetime of `file`.
33    let rc = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETPATH, buf.as_mut_ptr()) };
34    if rc != 0 {
35        return Err(std::io::Error::last_os_error());
36    }
37    let len = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
38    Ok(PathBuf::from(std::ffi::OsStr::from_bytes(&buf[..len])))
39}
40
41#[cfg(target_os = "linux")]
42fn real_path_of(file: &File) -> std::io::Result<PathBuf> {
43    use std::os::fd::AsRawFd;
44    std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd()))
45}
46
47/// Check that a canonicalized path stays within the server root.
48///
49/// Calls `canonicalize()` on the joined path and verifies the result starts with
50/// `root_canon`, catching symlink escapes and traversal attempts that sneak through
51/// segment-based checks.
52///
53/// # Arguments
54///
55/// * `root_canon` - The server root in canonical form.
56/// * `joined` - A path that may need canonicalizing (e.g., the result of `root.join(...)`).
57///
58/// # Returns
59///
60/// - `Ok(PathBuf)` if the canonicalized path stays within root.
61/// - `Err(StaticError::NotFound)` if the path doesn't exist or can't be canonicalized.
62/// - `Err(StaticError::Traversal)` if the canonicalized path escapes root.
63// On fd-verified platforms (macOS/iOS/Linux) only the portability fallback calls this,
64// so it reads as dead there — it is the other platforms' security boundary, not debris.
65#[cfg_attr(
66    any(target_os = "macos", target_os = "ios", target_os = "linux"),
67    allow(dead_code)
68)]
69pub(crate) fn canonicalize_within_root(
70    root_canon: &Path,
71    joined: &Path,
72) -> Result<PathBuf, StaticError> {
73    let canon = joined
74        .canonicalize()
75        .map_err(|_| StaticError::NotFound(joined.display().to_string()))?;
76
77    if canon.starts_with(root_canon) {
78        Ok(canon)
79    } else {
80        Err(StaticError::Traversal(joined.display().to_string()))
81    }
82}
83
84/// Resolve a request path under a pre-canonicalized root.
85///
86/// This function assumes `root_canon` is already in canonical form — `root_canon` should be
87/// the output of `root.canonicalize()` called once at server startup. Per-request resolution
88/// only canonicalizes the joined path, not the root.
89///
90/// # Path Traversal Protection
91///
92/// Segment-based traversal check rejects only path segments exactly equal to `..`.
93/// This allows filenames containing `..` as a substring (e.g., `jquery..min.js`) while
94/// blocking traversal attempts like `../../etc/passwd`.
95///
96/// # Directory Handling
97///
98/// If the resolved path is a directory, automatically serves `index.html` from that directory
99/// if it exists and doesn't escape the root.
100///
101/// # Symlinks
102///
103/// Symlinks are followed during canonicalization. After following symlinks, the final
104/// canonical path must stay within the server root.
105///
106/// # Arguments
107///
108/// * `root_canon` - The server root in canonical form (should be output of `canonicalize()`).
109/// * `request_path` - The HTTP request path (e.g., `/path/to/file.html`).
110///
111/// # Returns
112///
113/// - `Ok(PathBuf)` if the path resolves to a file within root.
114/// - `Err(StaticError::NotFound)` if the path doesn't exist.
115/// - `Err(StaticError::Traversal)` if the path attempts to escape the root.
116pub fn resolve_with_canonical_root(
117    root_canon: &Path,
118    request_path: &str,
119) -> Result<PathBuf, StaticError> {
120    resolve_with_policy(root_canon, request_path, HiddenFiles::Deny)
121}
122
123/// Whether dot-prefixed request-path segments may be served.
124///
125/// The default is [`HiddenFiles::Deny`]: a served root is frequently a build output
126/// directory, a repository working copy, or a folder someone dropped a `.env` into, and
127/// serving `.git/config` or `.env` to anyone who guesses the name is a credential leak
128/// that no traversal check catches — the files are legitimately *inside* the root.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum HiddenFiles {
131    /// Dot-prefixed segments answer as a miss.
132    Deny,
133    /// Dot-prefixed segments resolve like any other name.
134    Serve,
135}
136
137/// The one dot-prefixed prefix served under [`HiddenFiles::Deny`]: `/.well-known/` is
138/// where the web puts things that are *meant* to be fetched — ACME challenges for
139/// certificate issuance, `security.txt`, app-site association files. Denying it would
140/// break certificate renewal on any site served by this crate.
141const WELL_KNOWN: &str = ".well-known";
142
143/// Whether any segment of `decoded` is a hidden name, honoring the `.well-known`
144/// exception.
145///
146/// Scope is deliberately the *request path* only, never the served root's own
147/// filesystem path — a root that itself lives under a dot-directory
148/// (`~/.config/site/public`) must keep working, since the operator chose that location
149/// and no request can address it.
150///
151/// A segment of exactly `.` is a same-directory reference (`/./index.html`), not a
152/// hidden name, so it is exempt. `..` never reaches here — the traversal check rejects
153/// it first.
154fn has_hidden_segment(segments: &[Cow<'_, str>]) -> bool {
155    segments.iter().enumerate().any(|(index, segment)| {
156        let is_well_known_root = index == 0 && segment.as_ref() == WELL_KNOWN;
157        segment.starts_with('.') && segment != "." && !is_well_known_root
158    })
159}
160
161/// Decode a request path into its segments — this crate's only interpretation of what a
162/// path *is*.
163///
164/// **Splitting happens before decoding**, per RFC 3986 §3.3: `/` separates segments and a
165/// percent-encoded `%2F` is an ordinary character *inside* one. Decoding the whole path
166/// first — which this crate did through 0.31.x — promotes `%2F` into a separator, so
167/// `/admin%2Fconfig` reaches `admin/config` on disk. Containment still held, but any
168/// router or middleware in front of this server correctly reads that request as a single
169/// segment matching no route, so the file was served while the route guarding it was
170/// never consulted. See `tests/encoded_separator.rs`.
171///
172/// A segment that still contains a separator after decoding is refused rather than
173/// re-split — the same answer Apache gives by default (`AllowEncodedSlashes Off`).
174/// Backslash is refused on every platform, not just Windows where it separates: a server
175/// whose test suite runs on one OS should not behave differently on another, and a file
176/// with a backslash in its name is not worth the divergence.
177pub(crate) fn decode_segments(request_path: &str) -> Result<Vec<Cow<'_, str>>, StaticError> {
178    let mut segments = Vec::new();
179    for raw in request_path.split('/') {
180        if raw.is_empty() {
181            continue;
182        }
183        // Invalid UTF-8 falls back to the raw segment, which then matches only a file
184        // literally named that — the behaviour this crate has always had.
185        // Borrowed when the segment carries no percent-encoding, which is the common
186        // case; `into_owned()` here allocated a `String` per segment per request and cost
187        // 5-6% on the `not_modified_304` and `sidecar_hit_200` benchmarks.
188        let decoded = percent_encoding::percent_decode_str(raw)
189            .decode_utf8()
190            .unwrap_or(Cow::Borrowed(raw));
191
192        check_segment(&decoded, request_path)?;
193        segments.push(decoded);
194    }
195    Ok(segments)
196}
197
198/// Refuse a decoded segment that must not reach the filesystem.
199///
200/// Separate from the decoding above because the two have different owners once a router
201/// sits in front of this crate. **The router decides what the segments are; this decides
202/// whether they are safe to open with.** A router that splits before decoding — as
203/// `mini-serve` correctly does — hands over a segment that may still contain a literal
204/// `/` from a `%2F`, and `Path::push` would read that as a separator, which is the
205/// encoded-separator escape all over again. So this runs over segments from any source,
206/// not only ones this crate decoded itself.
207pub(crate) fn check_segment(decoded: &str, request_path: &str) -> Result<(), StaticError> {
208    let refuse = || StaticError::Traversal(request_path.to_string());
209
210    // Catches a NUL whether it arrived raw or as `%00`. A separate pre-check on the
211    // undecoded path used to sit above the decode loop; mutation testing showed it was
212    // fully subsumed — neither guard could be removed alone and be noticed — so the
213    // redundant one went and this one carries the guarantee.
214    if decoded.contains('/') || decoded.contains('\\') || decoded.contains('\0') {
215        return Err(refuse());
216    }
217    if decoded == ".." {
218        return Err(refuse());
219    }
220    Ok(())
221}
222
223/// Join decoded segments onto the root one at a time.
224///
225/// One at a time because `Path::join` re-reads a separator inside its argument; feeding
226/// it a pre-joined string would undo the work `decode_segments` just did.
227fn join_segments(root_canon: &Path, segments: &[Cow<'_, str>]) -> PathBuf {
228    // `push` rather than `join`: `join` clones the whole path per segment, so folding it
229    // allocated a `PathBuf` for every segment of every request.
230    let mut path = root_canon.to_path_buf();
231    for segment in segments {
232        path.push(segment.as_ref());
233    }
234    path
235}
236
237/// [`resolve_with_canonical_root`] with an explicit hidden-file policy.
238pub(crate) fn resolve_with_policy(
239    root_canon: &Path,
240    request_path: &str,
241    hidden: HiddenFiles,
242) -> Result<PathBuf, StaticError> {
243    open_with_policy(root_canon, request_path, hidden).map(|resolved| resolved.path)
244}
245
246/// Open `joined` and prove, on the opened fd, that it lies under `root_canon`.
247///
248/// A directory retries with `index.html` appended — verified on its *own* fd, never
249/// trusted transitively from the directory's.
250///
251/// Every open failure collapses to `NotFound`: differentiating errno (permission vs
252/// absent vs vanished) would hand back the existence oracle the 404 path works to deny.
253#[cfg(any(target_os = "macos", target_os = "ios", target_os = "linux"))]
254fn open_verified(
255    root_canon: &Path,
256    joined: &Path,
257    request_path: &str,
258) -> Result<ResolvedFile, StaticError> {
259    let file = File::open(joined).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
260    let real = real_path_of(&file).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
261    if !real.starts_with(root_canon) {
262        return Err(StaticError::Traversal(request_path.to_string()));
263    }
264    let metadata = file
265        .metadata()
266        .map_err(|_| StaticError::NotFound(request_path.to_string()))?;
267
268    if metadata.is_dir() {
269        return open_verified(root_canon, &real.join("index.html"), request_path);
270    }
271
272    Ok(ResolvedFile {
273        file,
274        metadata,
275        path: real,
276    })
277}
278
279/// Portability fallback: the canonicalize-then-open sequence this crate used through
280/// 0.30.x, for platforms without a way to read an fd's real path. Slower and it
281/// re-admits the check-to-open window; the property tests exercise whichever variant
282/// the platform compiles.
283#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
284fn open_verified(
285    root_canon: &Path,
286    joined: &Path,
287    request_path: &str,
288) -> Result<ResolvedFile, StaticError> {
289    let canon = canonicalize_within_root(root_canon, joined)?;
290    let target = if canon.is_dir() {
291        let index = canon.join("index.html");
292        canonicalize_within_root(root_canon, &index)?;
293        index
294    } else {
295        canon
296    };
297    let file = File::open(&target).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
298    let metadata = file
299        .metadata()
300        .map_err(|_| StaticError::NotFound(request_path.to_string()))?;
301    Ok(ResolvedFile {
302        file,
303        metadata,
304        path: target,
305    })
306}
307
308/// [`resolve_with_policy`], but yielding the opened, containment-verified file rather
309/// than a path to reopen. `Server::handle_request` serves from this handle directly.
310/// [`open_with_policy`], against segments a caller already split and decoded.
311///
312/// Every segment is still checked by [`check_segment`]: where they came from is not this
313/// crate's business, but whether they can escape the root is.
314pub(crate) fn open_segments<S: AsRef<str>>(
315    root_canon: &Path,
316    segments: &[S],
317    request_path: &str,
318    hidden: HiddenFiles,
319) -> Result<ResolvedFile, StaticError> {
320    let checked: Vec<Cow<'_, str>> = segments
321        .iter()
322        .map(|segment| {
323            check_segment(segment.as_ref(), request_path)?;
324            Ok(Cow::Borrowed(segment.as_ref()))
325        })
326        .collect::<Result<_, StaticError>>()?;
327    open_checked(root_canon, &checked, request_path, hidden)
328}
329
330pub(crate) fn open_with_policy(
331    root_canon: &Path,
332    request_path: &str,
333    hidden: HiddenFiles,
334) -> Result<ResolvedFile, StaticError> {
335    let segments = decode_segments(request_path)?;
336    open_checked(root_canon, &segments, request_path, hidden)
337}
338
339/// The shared tail: hidden-file policy, then open and prove containment.
340fn open_checked(
341    root_canon: &Path,
342    segments: &[Cow<'_, str>],
343    request_path: &str,
344    hidden: HiddenFiles,
345) -> Result<ResolvedFile, StaticError> {
346
347    // `NotFound`, not a distinct error: a hidden file that exists and one that doesn't
348    // must be indistinguishable, or the response becomes an oracle for what the root
349    // contains — the same reasoning that collapses traversal into the miss message.
350    if hidden == HiddenFiles::Deny && has_hidden_segment(segments) {
351        return Err(StaticError::NotFound(request_path.to_string()));
352    }
353
354    open_verified(root_canon, &join_segments(root_canon, segments), request_path)
355}
356
357/// Resolve a request path under a root directory, canonicalizing the root first.
358///
359/// This is a convenience wrapper around `resolve_with_canonical_root()` that canonicalizes
360/// the root on every call. For production use where the root is fixed at startup, prefer
361/// `Server::new()` which canonicalizes the root once and reuses it for all requests.
362///
363/// # Arguments
364///
365/// * `root` - The server root directory (need not be pre-canonicalized).
366/// * `request_path` - The HTTP request path (e.g., `/path/to/file.html`).
367///
368/// # Returns
369///
370/// - `Ok(PathBuf)` if the path resolves to a file within root.
371/// - `Err(StaticError)` if the path is invalid, missing, or attempts traversal.
372/// - `Err(StaticError::Io)` if canonicalizing the root fails.
373pub fn resolve(root: &Path, request_path: &str) -> Result<PathBuf, StaticError> {
374    let root_canon = root.canonicalize().map_err(StaticError::Io)?;
375    resolve_with_canonical_root(&root_canon, request_path)
376}