static-web-server 3.0.0-beta.3

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
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
// 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::{Request, Response, StatusCode};
use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};
use std::path::Path;

use crate::body::Body;
use crate::exts::http::{MethodExt, append_vary_accept};
use crate::fs::path::{PathExt, sanitize_path};
use crate::response::content_type_for;
use crate::{
    Error, exts::headers::Accept, fs::meta::try_markdown_variant, handler::RequestHandlerOpts,
};

/// 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,
    include_hidden: 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 !include_hidden && 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 !include_hidden
        && 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.
///
/// When the feature is enabled, HTML and markdown responses get
/// `Vary: Accept` since the same URI may resolve to either the HTML or the
/// markdown variant depending on the `Accept` request header. Both
/// representations must carry it, otherwise a shared cache could serve the
/// first cached one to every client. A markdown variant only makes sense for
/// HTML, so other assets (CSS, JS, images) don't get it and shared caches
/// don't store one copy per `Accept` value. Directory listings get it in any
/// format, since a directory may have a markdown index. Custom headers can
/// still override it.
///
/// `file_path` is the file resolved by the static files handler, `None` for
/// error and fallback pages.
pub(crate) fn post_process(
    is_markdown_variant: bool,
    is_dir_listing: bool,
    file_path: Option<&Path>,
    opts: &RequestHandlerOpts,
    mut resp: Response<Body>,
) -> Result<Response<Body>, Error> {
    if !opts.accept_markdown {
        return Ok(resp);
    }

    if !is_markdown_variant {
        if is_dir_listing || is_html(file_path, &resp) {
            append_vary_accept(&mut resp);
        }
        return Ok(resp);
    }

    append_vary_accept(&mut resp);

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

    Ok(resp)
}

/// Whether the response is an HTML representation.
///
/// The `Content-Type` decides when there is one. A `304 Not Modified` carries
/// none but must repeat the `Vary` of the `200` (RFC 9110, section 15.4.5), so
/// the file resolved by the static files handler decides for it. A
/// trailing-slash `308` carries none either and always counts: a directory with
/// only a markdown index redirects HTML clients but serves markdown ones, so
/// the selected response depends on `Accept` (RFC 9110, section 12.5.5).
#[inline]
fn is_html(file_path: Option<&Path>, resp: &Response<Body>) -> bool {
    if let Some(content_type) = resp.headers().get(http::header::CONTENT_TYPE) {
        return content_type
            .to_str()
            .ok()
            .and_then(|v| v.split(';').next())
            .is_some_and(|essence| essence.trim().eq_ignore_ascii_case("text/html"));
    }
    file_path.is_some_and(|path| {
        resp.status() == StatusCode::PERMANENT_REDIRECT || content_type_for(path) == "text/html"
    })
}

// 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);
            let result = pre_process(&req, &base, &uri, false);

            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::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(crate::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", false);

        assert!(result.is_none());
    }

    #[test]
    fn test_accepts_html_only() {
        let req = Request::builder()
            .method("GET")
            .uri("/test")
            .header("Accept", "text/html")
            .body(crate::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", false);

        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", false);

        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", false);

        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", false);

        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 unless include_hidden is enabled.
        let result = pre_process(&req, &base, "/.dotfile", false);
        assert!(result.is_none());

        // When explicitly enabled, 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", true);
        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, true).is_some());
        assert!(pre_process(&req, dir.path(), &uri, false).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", false);

        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", true);
        let excluded = pre_process(&req, &base, "/locked/a~b", false);
        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", false);
        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", false);

        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, "/", false);

        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", false).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"));
    }

    #[test]
    fn is_html_uses_content_type_when_present() {
        for (content_type, expected) in [
            ("text/html", true),
            ("text/html; charset=utf-8", true),
            ("Text/HTML ;charset=utf-8", true),
            ("text/markdown; charset=utf-8", false),
            ("text/css", false),
            ("text/html-sandboxed", false),
        ] {
            let mut resp = Response::new(crate::body::empty());
            resp.headers_mut().insert(
                http::header::CONTENT_TYPE,
                http::HeaderValue::from_static(content_type),
            );
            assert_eq!(is_html(None, &resp), expected, "{content_type}");
        }

        // The `Content-Type` wins over the resolved file, e.g. a directory
        // listing resolved to a custom non-HTML index file
        let mut resp = Response::new(crate::body::empty());
        resp.headers_mut().insert(
            http::header::CONTENT_TYPE,
            http::HeaderValue::from_static("text/html; charset=utf-8"),
        );
        assert!(is_html(Some(Path::new("/srv/dir/index.txt")), &resp));
    }

    #[test]
    fn is_html_uses_resolved_file_without_content_type() {
        let mut resp = Response::new(crate::body::empty());
        *resp.status_mut() = StatusCode::NOT_MODIFIED;
        assert!(is_html(Some(Path::new("/srv/article.html")), &resp));
        assert!(is_html(Some(Path::new("/srv/dir/index.htm")), &resp));
        assert!(!is_html(Some(Path::new("/srv/style.css")), &resp));
        assert!(!is_html(None, &resp));

        // A trailing-slash redirect counts whatever the index file
        *resp.status_mut() = StatusCode::PERMANENT_REDIRECT;
        assert!(is_html(Some(Path::new("/srv/dir/index.txt")), &resp));
        assert!(!is_html(None, &resp));
    }
}