1use std::path::{Component, Path, PathBuf};
4use std::time::UNIX_EPOCH;
5
6use bytes::Bytes;
7use http::{Method, StatusCode, header};
8use percent_encoding::percent_decode_str;
9
10use crate::context::Context;
11use crate::handler::BoxFuture;
12use crate::middleware::{Middleware, Next};
13use crate::response::Response;
14
15pub struct Static {
29 source: Source,
30 prefix: String,
31}
32
33enum Source {
34 Dir(PathBuf),
35 Embedded(&'static [EmbeddedFile]),
36}
37
38#[derive(Debug)]
40pub struct EmbeddedFile {
41 pub path: &'static str,
43 pub bytes: &'static [u8],
44 pub etag: &'static str,
46}
47
48impl Static {
49 pub fn new(root: impl Into<PathBuf>) -> Self {
50 Self {
51 source: Source::Dir(root.into()),
52 prefix: "/".into(),
53 }
54 }
55
56 pub fn embedded(files: &'static [EmbeddedFile]) -> Self {
58 Self {
59 source: Source::Embedded(files),
60 prefix: "/".into(),
61 }
62 }
63
64 pub fn at(mut self, prefix: &str) -> Self {
66 self.prefix = format!("/{}", prefix.trim_matches('/'));
67 self
68 }
69
70 fn relative(&self, path: &str) -> Option<PathBuf> {
73 let rest = path.strip_prefix(&self.prefix)?;
74 if !(self.prefix == "/" || rest.is_empty() || rest.starts_with('/')) {
76 return None;
77 }
78 let decoded = percent_decode_str(rest).decode_utf8().ok()?;
79 let relative = Path::new(decoded.trim_start_matches('/'));
80 if relative
82 .components()
83 .any(|c| !matches!(c, Component::Normal(_)))
84 {
85 return None;
86 }
87 Some(relative.to_path_buf())
88 }
89
90 #[cfg(test)]
91 fn resolve(&self, path: &str) -> Option<PathBuf> {
92 match &self.source {
93 Source::Dir(root) => self.relative(path).map(|r| root.join(r)),
94 Source::Embedded(_) => None,
95 }
96 }
97}
98
99impl Middleware for Static {
100 fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
101 let relative = matches!(*ctx.method(), Method::GET | Method::HEAD)
102 .then(|| self.relative(ctx.path()))
103 .flatten();
104 let Some(relative) = relative else {
105 return Box::pin(next.run(ctx));
106 };
107 match &self.source {
108 Source::Dir(root) => {
109 let file = root.join(relative);
110 Box::pin(async move {
111 match serve_file(&file, &ctx).await {
112 Some(res) => res,
113 None => next.run(ctx).await,
114 }
115 })
116 }
117 Source::Embedded(files) => {
118 let wanted = relative.to_string_lossy().replace('\\', "/");
119 match files.iter().find(|f| f.path == wanted) {
120 Some(file) => {
121 let res = respond(&ctx, file.etag, Path::new(file.path), || {
122 Bytes::from_static(file.bytes)
123 });
124 Box::pin(async move { res })
125 }
126 None => Box::pin(next.run(ctx)),
127 }
128 }
129 }
130 }
131}
132
133pub struct SignedFiles;
147
148pub(crate) const SIGNED_PREFIX: &str = "/files/";
150
151pub(crate) fn signed_text(key: &str, expires: i64) -> String {
153 format!("{expires}|{key}")
154}
155
156impl Middleware for SignedFiles {
157 fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
158 let key = matches!(*ctx.method(), Method::GET | Method::HEAD)
159 .then(|| ctx.path().strip_prefix(SIGNED_PREFIX))
160 .flatten()
161 .and_then(|rest| percent_decode_str(rest).decode_utf8().ok())
162 .map(|key| key.into_owned());
163 let Some(key) = key else {
164 return Box::pin(next.run(ctx));
165 };
166 Box::pin(async move {
167 let forbidden = || Response::text("Forbidden").with_status(StatusCode::FORBIDDEN);
168 let token = ctx.uri().query().and_then(|query| {
169 query
170 .split('&')
171 .find_map(|pair| pair.strip_prefix("token="))
172 });
173 let Some(signed) = token.and_then(|t| crate::auth::read_message("file", t)) else {
174 return forbidden();
175 };
176 let Some((expires, signed_key)) = signed.split_once('|') else {
177 return forbidden();
178 };
179 let fresh = expires
180 .parse::<i64>()
181 .is_ok_and(|at| at >= crate::time::now().timestamp());
182 if signed_key != key || !fresh {
183 return forbidden();
184 }
185 match crate::storage::current().get(&key).await {
186 Ok(Some(bytes)) => Response::new(StatusCode::OK)
187 .with_body_bytes(bytes)
188 .with_header(header::CONTENT_TYPE, content_type(Path::new(&key)))
189 .with_header(header::CACHE_CONTROL, "private, no-store")
190 .with_header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
191 .with_header(header::CONTENT_SECURITY_POLICY, "sandbox"),
192 Ok(None) => Response::text("Not Found").with_status(StatusCode::NOT_FOUND),
193 Err(error) => crate::response::IntoResponse::into_response(error),
194 }
195 })
196 }
197}
198
199async fn serve_file(path: &Path, ctx: &Context) -> Option<Response> {
200 let meta = tokio::fs::metadata(path).await.ok()?;
201 if !meta.is_file() {
202 return None;
203 }
204 let modified = meta
205 .modified()
206 .ok()
207 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
208 .map_or(0, |d| d.as_secs());
209 let etag = format!("\"{:x}-{:x}\"", meta.len(), modified);
210 if ctx.header(header::IF_NONE_MATCH) == Some(etag.as_str()) {
211 return Some(not_modified(&etag));
212 }
213 let body = tokio::fs::read(path).await.ok()?;
214 Some(respond(ctx, &etag, path, || Bytes::from(body)))
215}
216
217fn not_modified(etag: &str) -> Response {
218 Response::new(StatusCode::NOT_MODIFIED).with_header(header::ETAG, etag.to_owned())
219}
220
221fn respond(ctx: &Context, etag: &str, path: &Path, body: impl FnOnce() -> Bytes) -> Response {
223 if ctx.header(header::IF_NONE_MATCH) == Some(etag) {
224 return not_modified(etag);
225 }
226 Response::new(StatusCode::OK)
227 .with_body_bytes(body())
228 .with_header(header::CONTENT_TYPE, content_type(path))
229 .with_header(header::ETAG, etag.to_owned())
230 .with_header(header::CACHE_CONTROL, "public, max-age=0, must-revalidate")
231}
232
233fn content_type(path: &Path) -> &'static str {
234 let ext = path
235 .extension()
236 .and_then(|e| e.to_str())
237 .map(str::to_ascii_lowercase);
238 match ext.as_deref() {
239 Some("html" | "htm") => "text/html; charset=utf-8",
240 Some("css") => "text/css; charset=utf-8",
241 Some("js" | "mjs") => "text/javascript; charset=utf-8",
242 Some("json" | "map") => "application/json",
243 Some("txt") => "text/plain; charset=utf-8",
244 Some("svg") => "image/svg+xml",
245 Some("png") => "image/png",
246 Some("jpg" | "jpeg") => "image/jpeg",
247 Some("gif") => "image/gif",
248 Some("webp") => "image/webp",
249 Some("avif") => "image/avif",
250 Some("ico") => "image/x-icon",
251 Some("woff") => "font/woff",
252 Some("woff2") => "font/woff2",
253 Some("wasm") => "application/wasm",
254 Some("pdf") => "application/pdf",
255 Some("xml") => "application/xml",
256 _ => "application/octet-stream",
257 }
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263
264 #[test]
265 fn resolves_only_safe_paths_under_prefix() {
266 let root = Static::new("public");
267 assert_eq!(
268 root.resolve("/app.css"),
269 Some(PathBuf::from("public/app.css"))
270 );
271 assert_eq!(root.resolve("/../secret"), None);
272 assert_eq!(root.resolve("/a/%2e%2e/%2e%2e/secret"), None);
273 assert_eq!(root.resolve("/a/..%2f..%2fsecret"), None);
274
275 let assets = Static::new("public").at("/assets/");
276 assert_eq!(
277 assets.resolve("/assets/js/app.js"),
278 Some(PathBuf::from("public/js/app.js"))
279 );
280 assert_eq!(assets.resolve("/assetsfoo"), None);
281 assert_eq!(assets.resolve("/other/app.js"), None);
282 }
283}