Skip to main content

mini_static/
resolve.rs

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