flatbed 0.0.5

Rust HTTP framework with FlatBuffer codegen, built on Hyper
Documentation
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
//! Static-file serving for `static_route!` mounts.
//!
//! A mount reads from a directory on the container filesystem at request
//! time, or from a directory embedded in the binary. Path resolution rejects
//! any `..` or absolute component in the request URL; symlinks under a
//! filesystem `dir` are followed by the OS and are not separately constrained
//! (the served directory is operator-controlled, shipped in the image).

use std::path::{Component, Path, PathBuf};

use crate::{HeaderName, HeaderValue, ResponseParts, StaticRouteInfo, StaticSource};

/// Serve a static file for `path` from the first mount that produces a hit.
///
/// Returns `None` when no mount matches, the resolved file is absent, and no
/// fallback applies.
///
/// The full file is read regardless of request method; the caller strips the
/// body for a HEAD request while preserving the `Content-Length` it implies.
pub async fn serve(routes: &[StaticRouteInfo], path: &str) -> Option<ResponseParts> {
    for route in routes {
        if let Some(parts) = serve_one(route, path).await {
            return Some(parts);
        }
    }
    None
}

async fn serve_one(route: &StaticRouteInfo, path: &str) -> Option<ResponseParts> {
    let rel = strip_mount(route.mount, path)?;
    let relative = sanitize(rel)?;

    if !relative.as_os_str().is_empty() {
        if let Some(bytes) = read(route.source, &relative).await {
            return Some(build(bytes, &relative));
        }
        if is_known_asset(&relative) {
            return None;
        }
    }

    if route
        .no_fallback
        .iter()
        .any(|prefix| rel.starts_with(prefix.trim_start_matches('/')))
    {
        return None;
    }
    let fallback = Path::new(route.fallback?);
    let bytes = read(route.source, fallback).await?;
    Some(build(bytes, fallback))
}

/// The bytes of `relative` under the mount's source, `None` when it names
/// nothing there or names a directory.
async fn read(source: StaticSource, relative: &Path) -> Option<Vec<u8>> {
    match source {
        StaticSource::Dir(dir) => read_file(&Path::new(dir).join(relative)).await,
        StaticSource::Embedded(dir) => dir.get_file(relative).map(|file| file.contents().to_vec()),
    }
}

/// Strip the mount prefix from a request path, returning the relative remainder.
///
/// The prefix must end on a path boundary, so mount `/assets` matches
/// `/assets/app.js` but not `/assetsX`.
fn strip_mount<'a>(mount: &str, path: &'a str) -> Option<&'a str> {
    let mount = mount.trim_end_matches('/');
    if mount.is_empty() {
        return Some(path.trim_start_matches('/'));
    }
    if path == mount {
        return Some("");
    }
    path.strip_prefix(mount)?.strip_prefix('/')
}

/// Resolve a relative request path to a directory-relative path, rejecting any
/// URL component that could escape the mount directory (`..`, absolute roots).
fn sanitize(rel: &str) -> Option<PathBuf> {
    let mut out = PathBuf::new();
    for component in Path::new(rel).components() {
        match component {
            Component::Normal(part) => out.push(part),
            Component::CurDir => {}
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
        }
    }
    Some(out)
}

async fn read_file(path: &Path) -> Option<Vec<u8>> {
    // `read` errors on a missing path and on a directory, so it doubles as the
    // existence/regular-file check — no separate `stat` needed.
    tokio::fs::read(path).await.ok()
}

fn build(bytes: Vec<u8>, path: &Path) -> ResponseParts {
    let mut parts = ResponseParts::ok(bytes, content_type(path));
    parts.headers.insert(
        HeaderName::from_static("cache-control"),
        HeaderValue::from_static(cache_control(path)),
    );
    parts
}

/// Files a bundler content-hashes into their filename are safe to cache
/// forever; files that keep a stable name across builds (HTML, and the
/// conventionally-unhashed `robots.txt` / `favicon.ico` / `manifest.json` /
/// sitemap set) must stay fresh.
fn cache_control(path: &Path) -> &'static str {
    match extension(path).as_deref() {
        Some("html" | "json" | "txt" | "ico" | "xml" | "webmanifest") | None => "no-cache",
        _ => "public, max-age=31536000, immutable",
    }
}

/// Whether the path names a recognized asset type (its extension maps to a
/// concrete media type).
fn is_known_asset(path: &Path) -> bool {
    content_type(path) != "application/octet-stream"
}

fn content_type(path: &Path) -> &'static str {
    match extension(path).as_deref() {
        Some("html") => "text/html; charset=utf-8",
        Some("js" | "mjs") => "text/javascript; charset=utf-8",
        Some("css") => "text/css; charset=utf-8",
        Some("json" | "map") => "application/json",
        Some("xml") => "application/xml",
        Some("webmanifest") => "application/manifest+json",
        Some("svg") => "image/svg+xml",
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("webp") => "image/webp",
        Some("ico") => "image/x-icon",
        Some("woff2") => "font/woff2",
        Some("woff") => "font/woff",
        Some("ttf") => "font/ttf",
        Some("wasm") => "application/wasm",
        Some("txt") => "text/plain; charset=utf-8",
        _ => "application/octet-stream",
    }
}

fn extension(path: &Path) -> Option<String> {
    path.extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_ascii_lowercase())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn strip_mount_root() {
        assert_eq!(strip_mount("/", "/index.html"), Some("index.html"));
        assert_eq!(strip_mount("/", "/"), Some(""));
        assert_eq!(strip_mount("/", "/assets/app.js"), Some("assets/app.js"));
    }

    #[test]
    fn strip_mount_prefix_needs_boundary() {
        assert_eq!(strip_mount("/assets", "/assets/app.js"), Some("app.js"));
        assert_eq!(strip_mount("/assets", "/assets"), Some(""));
        assert_eq!(strip_mount("/assets", "/assetsX"), None);
        assert_eq!(strip_mount("/assets", "/other"), None);
    }

    #[test]
    fn sanitize_rejects_traversal() {
        assert!(sanitize("../etc/passwd").is_none());
        assert!(sanitize("a/../../b").is_none());
        assert!(sanitize("/abs").is_none());
    }

    #[test]
    fn sanitize_allows_nested() {
        assert_eq!(
            sanitize("assets/app.js"),
            Some(PathBuf::from("assets/app.js"))
        );
        assert_eq!(sanitize("./app.js"), Some(PathBuf::from("app.js")));
        assert_eq!(sanitize(""), Some(PathBuf::new()));
    }

    #[test]
    fn content_type_by_extension() {
        assert_eq!(
            content_type(Path::new("i.html")),
            "text/html; charset=utf-8"
        );
        assert_eq!(
            content_type(Path::new("a.js")),
            "text/javascript; charset=utf-8"
        );
        assert_eq!(content_type(Path::new("a.css")), "text/css; charset=utf-8");
        assert_eq!(content_type(Path::new("f.woff2")), "font/woff2");
        assert_eq!(content_type(Path::new("x.bin")), "application/octet-stream");
    }

    #[test]
    fn cache_control_hashed_vs_stable_name() {
        // Content-hashed assets: cache forever.
        assert_eq!(
            cache_control(Path::new("app-a1b2.js")),
            "public, max-age=31536000, immutable"
        );
        assert_eq!(
            cache_control(Path::new("style-c3d4.css")),
            "public, max-age=31536000, immutable"
        );
        // Stable-name files: must stay fresh.
        for stable in [
            "index.html",
            "robots.txt",
            "favicon.ico",
            "manifest.json",
            "sitemap.xml",
            "app.webmanifest",
        ] {
            assert_eq!(cache_control(Path::new(stable)), "no-cache", "{stable}");
        }
    }

    #[test]
    fn known_asset_vs_client_route() {
        for asset in [
            "app.js",
            "index.html",
            "sitemap.xml",
            "manifest.webmanifest",
        ] {
            assert!(is_known_asset(Path::new(asset)), "{asset}");
        }
        // A dotted client-side route (e.g. /v2.0) is not an asset type.
        assert!(!is_known_asset(Path::new("v2.0")));
        assert!(!is_known_asset(Path::new("dashboard")));
    }

    /// Create a throwaway `dist` dir (unique per test name) with `index.html`
    /// and `assets/app.js`, leaking a `StaticRouteInfo` that points at it.
    fn fixture(name: &str) -> StaticRouteInfo {
        let dir =
            std::env::temp_dir().join(format!("flatbed-static-{}-{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("assets")).unwrap();
        std::fs::write(dir.join("index.html"), b"<!doctype html><h1>shell</h1>").unwrap();
        std::fs::write(dir.join("assets/app.js"), b"console.log(1)").unwrap();
        StaticRouteInfo {
            mount: "/",
            source: StaticSource::Dir(Box::leak(
                dir.to_str().unwrap().to_string().into_boxed_str(),
            )),
            fallback: Some("index.html"),
            no_fallback: &[],
        }
    }

    #[tokio::test]
    async fn serves_existing_asset_with_type() {
        let route = fixture("asset");
        let parts = serve_one(&route, "/assets/app.js").await.expect("hit");
        assert_eq!(parts.body, b"console.log(1)");
        assert_eq!(parts.content_type, "text/javascript; charset=utf-8");
    }

    #[tokio::test]
    async fn root_serves_fallback_shell() {
        let route = fixture("root");
        let parts = serve_one(&route, "/").await.expect("fallback");
        assert_eq!(parts.content_type, "text/html; charset=utf-8");
        assert!(parts.body.starts_with(b"<!doctype"));
    }

    #[tokio::test]
    async fn extensionless_miss_serves_fallback() {
        let route = fixture("nav");
        let parts = serve_one(&route, "/dashboard").await.expect("spa fallback");
        assert_eq!(parts.content_type, "text/html; charset=utf-8");
    }

    #[tokio::test]
    async fn missing_asset_is_404_not_shell() {
        let route = fixture("missasset");
        assert!(serve_one(&route, "/assets/missing-x9.js").await.is_none());
    }

    #[tokio::test]
    async fn dotted_client_route_serves_fallback() {
        let route = fixture("dotted");
        // `/v2.0` looks like it has an extension but isn't an asset type.
        let parts = serve_one(&route, "/v2.0").await.expect("spa fallback");
        assert_eq!(parts.content_type, "text/html; charset=utf-8");
    }

    #[tokio::test]
    async fn traversal_is_rejected() {
        let route = fixture("traversal");
        assert!(serve_one(&route, "/../../etc/hosts").await.is_none());
    }

    #[tokio::test]
    async fn serve_first_matching_mount_wins() {
        let base = std::env::temp_dir();
        let make = |suffix: &str, body: &[u8]| -> &'static str {
            let dir = base.join(format!("flatbed-static-{}-{suffix}", std::process::id()));
            let _ = std::fs::remove_dir_all(&dir);
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(dir.join("app.js"), body).unwrap();
            Box::leak(dir.to_str().unwrap().to_string().into_boxed_str())
        };
        let routes = [
            StaticRouteInfo {
                mount: "/",
                source: StaticSource::Dir(make("winA", b"first")),
                fallback: None,
                no_fallback: &[],
            },
            StaticRouteInfo {
                mount: "/",
                source: StaticSource::Dir(make("winB", b"second")),
                fallback: None,
                no_fallback: &[],
            },
        ];
        let parts = serve(&routes, "/app.js").await.expect("hit");
        assert_eq!(parts.body, b"first");
    }

    #[tokio::test]
    async fn no_fallback_extensionless_is_404() {
        // No fallback configured: an extensionless miss has nowhere to go.
        let route = StaticRouteInfo {
            mount: "/",
            source: StaticSource::Dir("/nonexistent"),
            fallback: None,
            no_fallback: &[],
        };
        assert!(serve_one(&route, "/dashboard").await.is_none());
    }

    #[tokio::test]
    async fn missing_fallback_file_is_404() {
        // `dir` exists but the configured fallback file does not.
        let dir = std::env::temp_dir().join(format!("flatbed-static-{}-nofb", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let route = StaticRouteInfo {
            mount: "/",
            source: StaticSource::Dir(Box::leak(
                dir.to_str().unwrap().to_string().into_boxed_str(),
            )),
            fallback: Some("index.html"),
            no_fallback: &[],
        };
        assert!(serve_one(&route, "/dashboard").await.is_none());
    }

    /// The crate's own test fixture, compiled in: `app.js` and `index.html`.
    static EMBEDDED: include_dir::Dir<'static> =
        include_dir::include_dir!("$CARGO_MANIFEST_DIR/tests/static_fixture");

    fn embedded(mount: &'static str, fallback: Option<&'static str>) -> StaticRouteInfo {
        StaticRouteInfo {
            mount,
            source: StaticSource::Embedded(&EMBEDDED),
            fallback,
            no_fallback: &[],
        }
    }

    #[tokio::test]
    async fn embedded_serves_asset_with_type_and_cache() {
        let route = embedded("/", Some("index.html"));
        let parts = serve_one(&route, "/app.js").await.expect("hit");
        assert_eq!(
            parts.body,
            std::fs::read("tests/static_fixture/app.js").unwrap()
        );
        assert_eq!(parts.content_type, "text/javascript; charset=utf-8");
        assert_eq!(
            parts.headers.get("cache-control").unwrap(),
            "public, max-age=31536000, immutable"
        );
    }

    #[tokio::test]
    async fn embedded_root_and_client_route_serve_fallback() {
        let route = embedded("/", Some("index.html"));
        for path in ["/", "/dashboard", "/v2.0"] {
            let parts = serve_one(&route, path).await.expect(path);
            assert_eq!(parts.content_type, "text/html; charset=utf-8", "{path}");
            assert!(parts.body.starts_with(b"<!doctype"), "{path}");
            assert_eq!(parts.headers.get("cache-control").unwrap(), "no-cache");
        }
    }

    #[tokio::test]
    async fn embedded_missing_asset_is_404_not_shell() {
        let route = embedded("/", Some("index.html"));
        assert!(serve_one(&route, "/assets/missing-x9.js").await.is_none());
    }

    #[tokio::test]
    async fn no_fallback_prefix_miss_is_404_and_the_rest_still_falls_back() {
        let route = StaticRouteInfo {
            mount: "/",
            source: StaticSource::Embedded(&EMBEDDED),
            fallback: Some("index.html"),
            no_fallback: &["/api/"],
        };
        assert!(serve_one(&route, "/api/nothing").await.is_none());
        assert!(serve_one(&route, "/api/deeper/nothing").await.is_none());
        // The bare prefix root is not under the prefix.
        let shell = serve_one(&route, "/api").await.expect("fallback");
        assert_eq!(shell.content_type, "text/html; charset=utf-8");
        let shell = serve_one(&route, "/dashboard").await.expect("fallback");
        assert_eq!(shell.content_type, "text/html; charset=utf-8");
        let asset = serve_one(&route, "/app.js").await.expect("asset");
        assert_eq!(asset.content_type, "text/javascript; charset=utf-8");
    }

    #[tokio::test]
    async fn no_fallback_prefix_is_relative_to_the_mount() {
        let route = StaticRouteInfo {
            mount: "/app",
            source: StaticSource::Embedded(&EMBEDDED),
            fallback: Some("index.html"),
            no_fallback: &["/api/"],
        };
        assert!(serve_one(&route, "/app/api/nothing").await.is_none());
        let shell = serve_one(&route, "/app/dashboard").await.expect("fallback");
        assert_eq!(shell.content_type, "text/html; charset=utf-8");
    }

    #[tokio::test]
    async fn embedded_no_fallback_miss_is_404() {
        let route = embedded("/static", None);
        assert!(serve_one(&route, "/static/dashboard").await.is_none());
        assert!(serve_one(&route, "/static/app.js").await.is_some());
    }

    #[tokio::test]
    async fn embedded_traversal_is_rejected() {
        let route = embedded("/", Some("index.html"));
        assert!(serve_one(&route, "/../Cargo.toml").await.is_none());
    }
}