next_rust_server/
embed.rs1#[derive(Debug, Clone, Copy)]
9pub struct EmbeddedFile {
10 pub path: &'static str,
11 pub bytes: &'static [u8],
12 pub hash: &'static str,
15 pub br: Option<&'static [u8]>,
17 pub gz: Option<&'static [u8]>,
19}
20
21#[derive(Debug, Clone, Copy, Default)]
23pub struct Embedded {
24 pub config: Option<(&'static str, bool)>,
26 pub built_at: u64,
28 pub public: &'static [EmbeddedFile],
30 pub assets: &'static [EmbeddedFile],
32 pub client: &'static [EmbeddedFile],
34}
35
36impl Embedded {
37 pub fn is_empty(&self) -> bool {
38 self.config.is_none() && self.public.is_empty() && self.assets.is_empty() && self.client.is_empty()
39 }
40}
41
42pub fn find(files: &'static [EmbeddedFile], url_path: &str) -> Option<&'static EmbeddedFile> {
45 let mut rel = String::new();
46 for raw in url_path.split('/').filter(|s| !s.is_empty()) {
47 let seg = next_rust_router::decode_segment(raw)?;
48 if seg.starts_with('.') || seg.contains(['\\', '\0', '/', ':']) {
49 return None;
50 }
51 if !rel.is_empty() {
52 rel.push('/');
53 }
54 rel.push_str(&seg);
55 }
56 if rel.is_empty() {
57 return None;
58 }
59 files.binary_search_by(|f| f.path.cmp(rel.as_str())).ok().map(|i| &files[i])
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65
66 const FILES: &[EmbeddedFile] = &[
67 EmbeddedFile { path: "favicon.svg", bytes: b"<svg/>", hash: "a", br: None, gz: None },
68 EmbeddedFile { path: "images/logo space.png", bytes: b"png", hash: "b", br: None, gz: None },
69 EmbeddedFile { path: "robots.txt", bytes: b"ok", hash: "c", br: None, gz: None },
70 ];
71
72 #[test]
73 fn lookups_follow_disk_rules() {
74 assert_eq!(find(FILES, "/favicon.svg").map(|f| f.hash), Some("a"));
75 assert_eq!(find(FILES, "/images/logo%20space.png").map(|f| f.hash), Some("b"));
76 assert_eq!(find(FILES, "//robots.txt").map(|f| f.hash), Some("c"));
77 for bad in ["/", "/images", "/../robots.txt", "/.env", "/images%2Flogo%20space.png", "/nope.txt"] {
78 assert!(find(FILES, bad).is_none(), "{bad}");
79 }
80 }
81}