static-web-server 2.44.2

A cross-platform, high-performance and asynchronous web server for static files-serving.
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
// SPDX-License-Identifier: MIT OR Apache-2.0
// This file is part of Static Web Server.
// See https://static-web-server.net/ for more information
// Copyright (C) 2019-present Jose Quintana <joseluisq.net>

//! Markdown content negotiation module.
//!
//! This module handles content negotiation for markdown files when the client sends
//! an Accept header that includes text/markdown.

use headers::HeaderMapExt;
use hyper::{Body, Request, Response};
use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};
use std::path::Path;

use crate::fs::path::{PathExt, sanitize_path};
use crate::{
    Error, fs::meta::try_markdown_variant, handler::RequestHandlerOpts, headers_ext::Accept,
    http_ext::MethodExt,
};

/// Escape set used when converting a resolved file path back into a URI path.
///
/// The returned URI is percent-decoded again by `sanitize_path` in the
/// static-files handler, so `%` must be escaped to keep the encode/decode
/// round-trip lossless for file names that contain it.
const URI_PATH_ESCAPE: &AsciiSet = &CONTROLS.add(b'%');

/// Pre-process a request to check if a markdown variant URI should be used.
///
/// The URI path is sanitized with the same `sanitize_path` used by the
/// static-files handler before any filesystem access, so the `metadata()`
/// probes issued by `try_markdown_variant` can never reach outside
/// `base_path`. On any failure the function returns `None` and the request
/// falls through to the static-files handler (fail closed, 404).
///
/// Symlink policy is intentionally *not* enforced here: the rewritten URI is
/// re-sanitized and passed through containment, symlink and hidden-file
/// checks in `static_files::handle`, which is the authoritative gate.
pub(crate) fn pre_process<T>(
    req: &Request<T>,
    base_path: &Path,
    uri_path: &str,
    ignore_hidden_files: bool,
) -> Option<String> {
    // Only a `GET` or `HEAD` gets a representation to negotiate
    let method = req.method();
    if !method.is_get() && !method.is_head() {
        return None;
    }

    let accepts_markdown = req
        .headers()
        .typed_get::<Accept>()
        .is_some_and(|accept| accept.accepts_markdown());
    if !accepts_markdown {
        return None;
    }

    // SECURITY: percent-decode and strip traversal components before
    // touching the filesystem.
    let file_path = sanitize_path(base_path, uri_path).ok()?;

    // `sanitize_path` only pushes `Normal` components onto `base_path`,
    // so this prefix strip cannot fail in practice.
    let relative = file_path.strip_prefix(base_path).ok()?;

    // Hidden-file policy check
    if ignore_hidden_files && relative.is_hidden() {
        tracing::debug!("markdown: skipping hidden path {:?}", relative);
        return None;
    }

    let md_path = try_markdown_variant(&file_path)?;
    let relative_md = md_path.strip_prefix(base_path).ok()?;

    // 8.3 short-name aliases such as `GIT~1` are checked on the variant found:
    // the requested path may have no entry of its own (`/guide~v2` for
    // `guide~v2.md`). A failed check counts as an alias.
    if ignore_hidden_files
        && relative_md
            .contains_short_name_alias(base_path)
            .unwrap_or(true)
    {
        tracing::debug!("markdown: skipping short-name alias {:?}", relative_md);
        return None;
    }
    tracing::debug!("markdown: found variant {:?}", md_path);

    // Convert the variant path back into a URI path, escaping `%` so the
    // static-files handler's re-decode resolves to the same file.
    let relative_md = relative_md.to_str()?;
    Some(format!(
        "/{}",
        utf8_percent_encode(relative_md, URI_PATH_ESCAPE)
    ))
}

/// Post-process the response to set the correct Content-Type for markdown files.
pub(crate) fn post_process(
    is_markdown_variant: bool,
    opts: &RequestHandlerOpts,
    mut resp: Response<Body>,
) -> Result<Response<Body>, Error> {
    if !is_markdown_variant || !opts.accept_markdown {
        return Ok(resp);
    }

    resp.headers_mut().insert(
        hyper::header::CONTENT_TYPE,
        hyper::header::HeaderValue::from_static("text/markdown; charset=utf-8"),
    );

    Ok(resp)
}

// Property-based regression test for `pre_process`
//
// These properties encode the security invariants of markdown content
// negotiation: regardless of the request tail (random bytes,
// percent-encoded escapes, dot segments, Windows drive prefixes,
// mixed slashes, embedded NULs) the resulting path MUST stay
// inside the configured `base` directory.
#[cfg(test)]
mod prop_tests {
    use super::{pre_process, sanitize_path};
    use hyper::Request;
    use proptest::prelude::*;
    use std::path::{Component, PathBuf};

    fn assert_under_base(base: &std::path::Path, full: &std::path::Path) {
        let extra = full
            .strip_prefix(base)
            .expect("sanitized path must extend base");
        for comp in extra.components() {
            match comp {
                Component::Normal(_) | Component::CurDir => {}
                Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                    panic!("pre_process leaked traversal component {comp:?} in {full:?}");
                }
            }
        }
    }

    fn build_markdown_request(uri_path: &str) -> Request<()> {
        Request::builder()
            .method("GET")
            .uri(uri_path)
            .header("Accept", "text/markdown")
            .body(())
            .unwrap()
    }

    proptest! {
        #![proptest_config(ProptestConfig {
            cases: 256, ..ProptestConfig::default()
        })]

        /// Targeted traversal patterns: many `../` segments interleaved
        /// with arbitrary content.
        #[test]
        fn prop_pre_process_resists_dot_dot_floods(
            tail in proptest::collection::vec(
                prop_oneof![
                    Just("../".to_string()),
                    Just("..\\".to_string()),
                    Just("%2e%2e/".to_string()),
                    Just("./".to_string()),
                    "[a-zA-Z0-9_.-]{1,8}".prop_map(String::from),
                ],
                0..32,
            )
        ) {
            let base = PathBuf::from("docker/public").canonicalize().unwrap_or_else(|_| PathBuf::from("docker/public"));
            let tail = tail.concat();
            let uri = format!("/{tail}");
            let req = build_markdown_request(&uri);
            // ignore_hidden_files = true (equivalent to include_hidden = false on master)
            let result = pre_process(&req, &base, &uri, true);

            if let Some(uri_path) = result {
                let sanitized = sanitize_path(&base, &uri_path).expect("returned URI must re-sanitize");
                assert_under_base(&base, &sanitized);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use hyper::{Body, Request};

    fn markdown_request(uri_path: &str) -> Request<()> {
        Request::builder()
            .method("GET")
            .uri(uri_path)
            .header("Accept", "text/markdown")
            .body(())
            .unwrap()
    }

    #[test]
    fn test_no_accept_header() {
        let req = Request::builder()
            .method("GET")
            .uri("/test")
            .body(Body::empty())
            .unwrap();

        // Without Accept header, should return None (no markdown variant)
        let base_path = std::path::Path::new("/tmp");
        let result = pre_process(&req, base_path, "/test", true);

        assert!(result.is_none());
    }

    #[test]
    fn test_accepts_html_only() {
        let req = Request::builder()
            .method("GET")
            .uri("/test")
            .header("Accept", "text/html")
            .body(Body::empty())
            .unwrap();

        // With Accept: text/html, should return None (no markdown variant)
        let base_path = std::path::Path::new("/tmp");
        let result = pre_process(&req, base_path, "/test", true);

        assert!(result.is_none());
    }

    #[test]
    fn test_accepts_markdown_no_file() {
        let req = markdown_request("/test");

        // With Accept: text/markdown but no file, should return None
        let base_path = std::path::Path::new("/tmp");
        let result = pre_process(&req, base_path, "/test", true);

        assert!(result.is_none());
    }

    #[test]
    fn test_traversal_is_sanitized() {
        let base = std::path::Path::new("tests/fixtures/markdown")
            .canonicalize()
            .unwrap();
        let req = markdown_request("/../README.md");

        // The traversal segment must be stripped, landing inside the base dir
        // where README.md does not exist as a markdown variant.
        let result = pre_process(&req, &base, "/../README.md", true);

        assert!(result.is_none());
    }

    #[test]
    fn test_percent_encoded_traversal_is_sanitized() {
        let base = std::path::Path::new("tests/fixtures/markdown")
            .canonicalize()
            .unwrap();
        let req = markdown_request("/%2e%2e/%2e%2e/README.md");

        let result = pre_process(&req, &base, "/%2e%2e/%2e%2e/README.md", true);

        assert!(result.is_none());
    }

    #[test]
    fn test_hidden_file_rejected() {
        let base = std::path::Path::new("tests/fixtures/public")
            .canonicalize()
            .unwrap();
        let req = markdown_request("/.dotfile");

        // Hidden files are rejected when ignore_hidden_files is enabled.
        let result = pre_process(&req, &base, "/.dotfile", true);
        assert!(result.is_none());

        // When ignore_hidden_files is disabled, the lookup is allowed (the
        // fixture has no markdown variant, so it still returns None, but not
        // because of the hidden check).
        let result = pre_process(&req, &base, "/.dotfile", false);
        assert!(result.is_none());
    }

    #[cfg(windows)]
    #[test]
    fn test_hidden_dir_short_name_alias_rejected() {
        use std::os::windows::process::CommandExt;

        let dir = tempfile::tempdir().unwrap();
        let hidden = dir.path().join(".hidden-dir");
        std::fs::create_dir(&hidden).unwrap();
        std::fs::write(hidden.join("page.md"), "# page").unwrap();
        let out = std::process::Command::new("cmd")
            .arg("/C")
            .raw_arg(format!(
                "for %I in (\"{}\") do @echo %~snxI",
                hidden.display()
            ))
            .output()
            .expect("unable to run cmd");
        let alias = String::from_utf8(out.stdout).unwrap().trim().to_owned();
        if alias == ".hidden-dir" {
            eprintln!("skipped: no 8.3 short names on this volume");
            return;
        }
        assert!(
            out.status.success() && alias.contains('~'),
            "unexpected short name {alias:?}"
        );
        let uri = format!("/{alias}/page");
        let req = markdown_request(&uri);

        assert!(pre_process(&req, dir.path(), &uri, false).is_some());
        assert!(pre_process(&req, dir.path(), &uri, true).is_none());
    }

    #[test]
    fn test_name_with_tilde_negotiates_variant() {
        let tmp = tempfile::tempdir().unwrap();
        let base = tmp.path().canonicalize().unwrap();
        std::fs::write(base.join("guide~v2.md"), "# guide").unwrap();
        let req = markdown_request("/guide~v2");

        let result = pre_process(&req, &base, "/guide~v2", true);

        assert_eq!(result, Some("/guide~v2.md".to_string()));
    }

    #[cfg(unix)]
    #[test]
    fn test_variant_with_tilde_in_unlistable_dir_rejected() {
        use std::fs::Permissions;
        use std::os::unix::fs::PermissionsExt;

        let tmp = tempfile::tempdir().unwrap();
        let base = tmp.path().canonicalize().unwrap();
        let locked = base.join("locked");
        std::fs::create_dir(&locked).unwrap();
        std::fs::write(locked.join("a~b.md"), "# page").unwrap();
        std::fs::set_permissions(&locked, Permissions::from_mode(0o311)).unwrap();
        let listable = std::fs::read_dir(&locked).is_ok();
        let req = markdown_request("/locked/a~b");

        let included = pre_process(&req, &base, "/locked/a~b", false);
        let excluded = pre_process(&req, &base, "/locked/a~b", true);
        std::fs::set_permissions(&locked, Permissions::from_mode(0o755)).unwrap();

        if listable {
            eprintln!("skipped: this user can list a directory without read permission");
            return;
        }
        assert_eq!(included, Some("/locked/a~b.md".to_string()));
        assert_eq!(excluded, None);
    }

    #[test]
    fn test_symlink_path_defers_to_static_handler() {
        // The markdown pre-processor doesn't enforce the symlink policy itself;
        // it returns None here (no markdown variant behind the symlink) and the
        // static-files handler applies containment/symlink checks to whatever
        // URI ultimately gets served.
        let base = std::path::Path::new("tests/fixtures/public")
            .canonicalize()
            .unwrap();
        let req = markdown_request("/symlink");

        let result = pre_process(&req, &base, "/symlink", true);
        assert!(result.is_none());
    }

    #[test]
    fn test_existing_markdown_variant_returns_uri() {
        let base = std::path::Path::new("tests/fixtures/markdown")
            .canonicalize()
            .unwrap();
        let req = markdown_request("/article");

        let result = pre_process(&req, &base, "/article", true);

        assert_eq!(result, Some("/article.html.md".to_string()));
    }

    #[test]
    fn test_directory_index_markdown_variant() {
        let base = std::path::Path::new("tests/fixtures/markdown")
            .canonicalize()
            .unwrap();
        let req = markdown_request("/");

        let result = pre_process(&req, &base, "/", true);

        assert_eq!(result, Some("/index.html.md".to_string()));
    }

    #[test]
    fn test_percent_in_filename_round_trips() {
        let tmp = tempfile::tempdir().unwrap();
        let base = tmp.path().canonicalize().unwrap();
        std::fs::write(base.join("a%2fb.html.md"), "# percent").unwrap();

        // Request decodes to the on-disk file name `a%2fb`.
        let req = markdown_request("/a%252fb");
        let result = pre_process(&req, &base, "/a%252fb", true).unwrap();

        // The returned URI must escape `%` so the static handler's re-decode
        // resolves back to the on-disk file name, not to `a/b.html.md`.
        assert_eq!(result, "/a%252fb.html.md");
        let resolved = sanitize_path(&base, &result).unwrap();
        assert_eq!(resolved, base.join("a%2fb.html.md"));
    }
}