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 refuse = || StaticError::Traversal(request_path.to_string());
179
180    if request_path.contains('\0') {
181        return Err(refuse());
182    }
183
184    let mut segments = Vec::new();
185    for raw in request_path.split('/') {
186        if raw.is_empty() {
187            continue;
188        }
189        // Invalid UTF-8 falls back to the raw segment, which then matches only a file
190        // literally named that — the behaviour this crate has always had.
191        // Borrowed when the segment carries no percent-encoding, which is the common
192        // case; `into_owned()` here allocated a `String` per segment per request and cost
193        // 5-6% on the `not_modified_304` and `sidecar_hit_200` benchmarks.
194        let decoded = percent_encoding::percent_decode_str(raw)
195            .decode_utf8()
196            .unwrap_or(Cow::Borrowed(raw));
197
198        // `%00` survives the raw check above and only fails much later, inside the
199        // syscall; refused here so the reason is the path rather than an open error.
200        if decoded.contains('/') || decoded.contains('\\') || decoded.contains('\0') {
201            return Err(refuse());
202        }
203        if decoded.as_ref() == ".." {
204            return Err(refuse());
205        }
206        segments.push(decoded);
207    }
208    Ok(segments)
209}
210
211/// Join decoded segments onto the root one at a time.
212///
213/// One at a time because `Path::join` re-reads a separator inside its argument; feeding
214/// it a pre-joined string would undo the work `decode_segments` just did.
215fn join_segments(root_canon: &Path, segments: &[Cow<'_, str>]) -> PathBuf {
216    // `push` rather than `join`: `join` clones the whole path per segment, so folding it
217    // allocated a `PathBuf` for every segment of every request.
218    let mut path = root_canon.to_path_buf();
219    for segment in segments {
220        path.push(segment.as_ref());
221    }
222    path
223}
224
225/// [`resolve_with_canonical_root`] with an explicit hidden-file policy.
226pub(crate) fn resolve_with_policy(
227    root_canon: &Path,
228    request_path: &str,
229    hidden: HiddenFiles,
230) -> Result<PathBuf, StaticError> {
231    open_with_policy(root_canon, request_path, hidden).map(|resolved| resolved.path)
232}
233
234/// Open `joined` and prove, on the opened fd, that it lies under `root_canon`.
235///
236/// A directory retries with `index.html` appended — verified on its *own* fd, never
237/// trusted transitively from the directory's.
238///
239/// Every open failure collapses to `NotFound`: differentiating errno (permission vs
240/// absent vs vanished) would hand back the existence oracle the 404 path works to deny.
241#[cfg(any(target_os = "macos", target_os = "ios", target_os = "linux"))]
242fn open_verified(
243    root_canon: &Path,
244    joined: &Path,
245    request_path: &str,
246) -> Result<ResolvedFile, StaticError> {
247    let file = File::open(joined).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
248    let real = real_path_of(&file).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
249    if !real.starts_with(root_canon) {
250        return Err(StaticError::Traversal(request_path.to_string()));
251    }
252    let metadata = file
253        .metadata()
254        .map_err(|_| StaticError::NotFound(request_path.to_string()))?;
255
256    if metadata.is_dir() {
257        return open_verified(root_canon, &real.join("index.html"), request_path);
258    }
259
260    Ok(ResolvedFile {
261        file,
262        metadata,
263        path: real,
264    })
265}
266
267/// Portability fallback: the canonicalize-then-open sequence this crate used through
268/// 0.30.x, for platforms without a way to read an fd's real path. Slower and it
269/// re-admits the check-to-open window; the property tests exercise whichever variant
270/// the platform compiles.
271#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
272fn open_verified(
273    root_canon: &Path,
274    joined: &Path,
275    request_path: &str,
276) -> Result<ResolvedFile, StaticError> {
277    let canon = canonicalize_within_root(root_canon, joined)?;
278    let target = if canon.is_dir() {
279        let index = canon.join("index.html");
280        canonicalize_within_root(root_canon, &index)?;
281        index
282    } else {
283        canon
284    };
285    let file = File::open(&target).map_err(|_| StaticError::NotFound(request_path.to_string()))?;
286    let metadata = file
287        .metadata()
288        .map_err(|_| StaticError::NotFound(request_path.to_string()))?;
289    Ok(ResolvedFile {
290        file,
291        metadata,
292        path: target,
293    })
294}
295
296/// [`resolve_with_policy`], but yielding the opened, containment-verified file rather
297/// than a path to reopen. `Server::handle_request` serves from this handle directly.
298pub(crate) fn open_with_policy(
299    root_canon: &Path,
300    request_path: &str,
301    hidden: HiddenFiles,
302) -> Result<ResolvedFile, StaticError> {
303    let segments = decode_segments(request_path)?;
304
305    // `NotFound`, not a distinct error: a hidden file that exists and one that doesn't
306    // must be indistinguishable, or the response becomes an oracle for what the root
307    // contains — the same reasoning that collapses traversal into the miss message.
308    if hidden == HiddenFiles::Deny && has_hidden_segment(&segments) {
309        return Err(StaticError::NotFound(request_path.to_string()));
310    }
311
312    open_verified(root_canon, &join_segments(root_canon, &segments), request_path)
313}
314
315/// Resolve a request path under a root directory, canonicalizing the root first.
316///
317/// This is a convenience wrapper around `resolve_with_canonical_root()` that canonicalizes
318/// the root on every call. For production use where the root is fixed at startup, prefer
319/// `Server::new()` which canonicalizes the root once and reuses it for all requests.
320///
321/// # Arguments
322///
323/// * `root` - The server root directory (need not be pre-canonicalized).
324/// * `request_path` - The HTTP request path (e.g., `/path/to/file.html`).
325///
326/// # Returns
327///
328/// - `Ok(PathBuf)` if the path resolves to a file within root.
329/// - `Err(StaticError)` if the path is invalid, missing, or attempts traversal.
330/// - `Err(StaticError::Io)` if canonicalizing the root fails.
331pub fn resolve(root: &Path, request_path: &str) -> Result<PathBuf, StaticError> {
332    let root_canon = root.canonicalize().map_err(StaticError::Io)?;
333    resolve_with_canonical_root(&root_canon, request_path)
334}