tower-serve-static 0.1.2

Tower service that serves static files.
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
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
use super::{AsyncReadBody, DEFAULT_CAPACITY};
use bytes::Bytes;
use http::{header, HeaderValue, Request, Response, StatusCode, Uri};
use http_body::Frame;
use http_body_util::{combinators::BoxBody, BodyExt, Empty};
use include_dir::{Dir, File};
use percent_encoding::percent_decode;
use std::{
    convert::Infallible,
    future::Future,
    io,
    path::{Path, PathBuf},
    pin::Pin,
    task::{Context, Poll},
};
use tower_service::Service;

/// Service that serves files from a given directory and all its sub directories.
///
/// The `Content-Type` will be guessed from the file extension.
///
/// An empty response with status `404 Not Found` will be returned if:
///
/// - The file doesn't exist
/// - Any segment of the path contains `..`
/// - Any segment of the path contains a backslash
#[derive(Clone, Debug)]
pub struct ServeDir {
    dir: &'static Dir<'static>,
    append_index_html_on_directories: bool,
    buf_chunk_size: usize,
}

impl ServeDir {
    /// Create a new [`ServeDir`].
    pub fn new(dir: &'static Dir<'static>) -> Self {
        Self {
            dir,
            append_index_html_on_directories: true,
            buf_chunk_size: DEFAULT_CAPACITY,
        }
    }

    /// If the requested path is a directory append `index.html`.
    ///
    /// This is useful for static sites.
    ///
    /// Defaults to `true`.
    pub fn append_index_html_on_directories(mut self, append: bool) -> Self {
        self.append_index_html_on_directories = append;
        self
    }

    /// Set a specific read buffer chunk size.
    ///
    /// The default capacity is 64kb.
    pub fn with_buf_chunk_size(mut self, chunk_size: usize) -> Self {
        self.buf_chunk_size = chunk_size;
        self
    }
}

impl<ReqBody> Service<Request<ReqBody>> for ServeDir {
    type Response = Response<ResponseBody>;
    type Error = Infallible;
    type Future = ResponseFuture;

    #[inline]
    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
        // build and validate the path
        let path = req.uri().path();
        let path = path.trim_start_matches('/');

        let path_decoded = if let Ok(decoded_utf8) = percent_decode(path.as_ref()).decode_utf8() {
            decoded_utf8
        } else {
            return ResponseFuture {
                inner: Some(Inner::Invalid),
            };
        };

        let mut full_path = PathBuf::new();
        for seg in path_decoded.split('/') {
            if seg.starts_with("..") || seg.contains('\\') {
                return ResponseFuture {
                    inner: Some(Inner::Invalid),
                };
            }
            full_path.push(seg);
        }

        if !req.uri().path().ends_with('/') {
            if is_dir(self.dir, &full_path) {
                let Ok(uri) = append_slash_on_path(req.uri().clone()) else {
                    return ResponseFuture {
                        inner: Some(Inner::Invalid),
                    };
                };
                let location = HeaderValue::from_str(&uri.to_string()).unwrap();
                return ResponseFuture {
                    inner: Some(Inner::Redirect(location)),
                };
            }
        } else if is_dir(self.dir, &full_path) {
            if self.append_index_html_on_directories {
                full_path.push("index.html");
            } else {
                return ResponseFuture {
                    inner: Some(Inner::NotFound),
                };
            }
        }

        let file = if let Some(file) = self.dir.get_file(&full_path) {
            file
        } else {
            return ResponseFuture {
                inner: Some(Inner::NotFound),
            };
        };

        #[cfg(feature = "metadata")]
        if super::unmodified_since_request_condition(file, &req) {
            return ResponseFuture {
                inner: Some(Inner::NotModified),
            };
        }

        let guess = mime_guess::from_path(&full_path);
        let mime = guess
            .first_raw()
            .map(HeaderValue::from_static)
            .unwrap_or_else(|| {
                HeaderValue::from_str(mime::APPLICATION_OCTET_STREAM.as_ref()).unwrap()
            });

        ResponseFuture {
            inner: Some(Inner::File(file, mime, self.buf_chunk_size)),
        }
    }
}

fn is_dir(dir: &Dir<'static>, path: &Path) -> bool {
    if path.as_os_str() == std::ffi::OsStr::new("") {
        return true;
    }
    dir.get_dir(path).is_some()
}

fn append_slash_on_path(uri: Uri) -> http::Result<Uri> {
    let http::uri::Parts {
        scheme,
        authority,
        path_and_query,
        ..
    } = uri.into_parts();

    let mut builder = Uri::builder();
    if let Some(scheme) = scheme {
        builder = builder.scheme(scheme);
    }
    if let Some(authority) = authority {
        builder = builder.authority(authority);
    }
    if let Some(path_and_query) = path_and_query {
        if let Some(query) = path_and_query.query() {
            builder = builder.path_and_query(format!("{}/?{}", path_and_query.path(), query));
        } else {
            builder = builder.path_and_query(format!("{}/", path_and_query.path()));
        }
    } else {
        builder = builder.path_and_query("/");
    }

    builder.build()
}

enum Inner {
    File(&'static File<'static>, HeaderValue, usize),
    Redirect(HeaderValue),
    NotFound,
    Invalid,
    #[cfg(feature = "metadata")]
    NotModified,
}

/// Response future of [`ServeDir`].
pub struct ResponseFuture {
    inner: Option<Inner>,
}

impl Future for ResponseFuture {
    type Output = Result<Response<ResponseBody>, Infallible>;

    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
        match self.inner.take().unwrap() {
            Inner::File(file, mime, chunk_size) => {
                let body = AsyncReadBody::with_capacity(file.contents(), chunk_size).boxed();
                let body = ResponseBody(body);

                let mut res = Response::new(body);
                res.headers_mut().insert(header::CONTENT_TYPE, mime);

                #[cfg(feature = "metadata")]
                if let Some(metadata) = file.metadata() {
                    let modified = httpdate::HttpDate::from(metadata.modified()).to_string();
                    let value = HeaderValue::from_str(&modified).expect("SystemTime format");
                    res.headers_mut().insert(header::LAST_MODIFIED, value);
                }

                Poll::Ready(Ok(res))
            }
            Inner::Redirect(location) => {
                let res = Response::builder()
                    .header(http::header::LOCATION, location)
                    .status(StatusCode::TEMPORARY_REDIRECT)
                    .body(empty_body())
                    .unwrap();

                Poll::Ready(Ok(res))
            }
            Inner::NotFound | Inner::Invalid => {
                let res = Response::builder()
                    .status(StatusCode::NOT_FOUND)
                    .body(empty_body())
                    .unwrap();

                Poll::Ready(Ok(res))
            }
            #[cfg(feature = "metadata")]
            Inner::NotModified => {
                let res = Response::builder()
                    .status(StatusCode::NOT_MODIFIED)
                    .body(empty_body())
                    .unwrap();

                Poll::Ready(Ok(res))
            }
        }
    }
}

fn empty_body() -> ResponseBody {
    let body = Empty::new().map_err(|err| match err {}).boxed();
    ResponseBody(body)
}

opaque_body! {
    /// Response body for [`ServeDir`].
    pub type ResponseBody = BoxBody<Bytes, io::Error>;
}

#[cfg(test)]
mod tests {
    #[allow(unused_imports)]
    use super::*;
    use http::{Request, StatusCode};
    use http_body::Body as HttpBody;
    use include_dir::include_dir;
    use tower::ServiceExt;

    static ASSETS_DIR: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/tests/assets");

    #[tokio::test]
    async fn basic() {
        let svc = ServeDir::new(&ASSETS_DIR);

        let req = Request::builder()
            .uri("/text.txt")
            .body(http_body_util::Empty::<Bytes>::new())
            .unwrap();
        let res = svc.oneshot(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::OK);
        assert_eq!(res.headers()["content-type"], "text/plain");
        #[cfg(not(feature = "metadata"))]
        {
            assert!(!res.headers().contains_key("last-modified"));
        }
        #[cfg(feature = "metadata")]
        {
            assert!(res.headers().contains_key("last-modified"));
        }

        let body = body_into_text(res.into_body()).await;

        let contents = std::fs::read_to_string("./tests/assets/text.txt").unwrap();
        assert_eq!(body, contents);
    }

    #[cfg(feature = "metadata")]
    #[tokio::test]
    async fn with_if_modified_since() {
        let svc = ServeDir::new(&ASSETS_DIR);

        let modified: httpdate::HttpDate = ASSETS_DIR
            .get_file("text.txt")
            .unwrap()
            .metadata()
            .unwrap()
            .modified()
            .into();

        let req = Request::builder()
            .uri("/text.txt")
            .header(
                header::IF_MODIFIED_SINCE,
                HeaderValue::from_str(&modified.to_string()).unwrap(),
            )
            .body(http_body_util::Empty::<Bytes>::new())
            .unwrap();
        let res = svc.oneshot(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::NOT_MODIFIED);
        assert!(!res.headers().contains_key("content-type"));
        assert!(!res.headers().contains_key("last-modified"));
        assert!(body_into_text(res.into_body()).await.is_empty());
    }

    #[tokio::test]
    async fn with_custom_chunk_size() {
        let svc = ServeDir::new(&ASSETS_DIR).with_buf_chunk_size(1024 * 32);

        let req = Request::builder()
            .uri("/text.txt")
            .body(http_body_util::Empty::<Bytes>::new())
            .unwrap();
        let res = svc.oneshot(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::OK);
        assert_eq!(res.headers()["content-type"], "text/plain");

        let body = body_into_text(res.into_body()).await;

        let contents = std::fs::read_to_string("./tests/assets/text.txt").unwrap();
        assert_eq!(body, contents);
    }

    #[tokio::test]
    async fn access_to_sub_dirs() {
        let svc = ServeDir::new(&ASSETS_DIR);

        let req = Request::builder()
            .uri("/subfolder/data.json")
            .body(http_body_util::Empty::<Bytes>::new())
            .unwrap();
        let res = svc.oneshot(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::OK);
        assert_eq!(res.headers()["content-type"], "application/json");

        let body = body_into_text(res.into_body()).await;

        let contents = std::fs::read_to_string("./tests/assets/subfolder/data.json").unwrap();
        assert_eq!(body, contents);
    }

    #[tokio::test]
    async fn not_found() {
        let svc = ServeDir::new(&ASSETS_DIR);

        let req = Request::builder()
            .uri("/not-found")
            .body(http_body_util::Empty::<Bytes>::new())
            .unwrap();
        let res = svc.oneshot(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::NOT_FOUND);
        assert!(res.headers().get(header::CONTENT_TYPE).is_none());

        let body = body_into_text(res.into_body()).await;
        assert!(body.is_empty());
    }

    #[tokio::test]
    async fn redirect_to_trailing_slash_on_dir() {
        let svc = ServeDir::new(&ASSETS_DIR);

        let req = Request::builder()
            .uri("/subfolder")
            .body(http_body_util::Empty::<Bytes>::new())
            .unwrap();
        let res = svc.oneshot(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::TEMPORARY_REDIRECT);

        let location = &res.headers()[http::header::LOCATION];
        assert_eq!(location, "/subfolder/");
    }

    #[tokio::test]
    async fn empty_directory_without_index() {
        let svc = ServeDir::new(&ASSETS_DIR).append_index_html_on_directories(false);

        let req = Request::new(http_body_util::Empty::<Bytes>::new());
        let res = svc.oneshot(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::NOT_FOUND);
        assert!(res.headers().get(header::CONTENT_TYPE).is_none());

        let body = body_into_text(res.into_body()).await;
        assert!(body.is_empty());
    }

    #[tokio::test]
    async fn root_path_with_index() {
        let svc = ServeDir::new(&ASSETS_DIR);

        let req = Request::builder()
            .uri("/")
            .body(http_body_util::Empty::<Bytes>::new())
            .unwrap();
        let res = svc.oneshot(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::OK);
        assert_eq!(res.headers()["content-type"], "text/html");

        let body = body_into_text(res.into_body()).await;

        let contents = std::fs::read_to_string("./tests/assets/index.html").unwrap();
        assert_eq!(body, contents);
    }

    async fn body_into_text<B>(body: B) -> String
    where
        B: HttpBody<Data = bytes::Bytes> + Unpin,
        B::Error: std::fmt::Debug,
    {
        let bytes = body.collect().await.unwrap().to_bytes(); //.await.unwrap();
        String::from_utf8(bytes.to_vec()).unwrap()
    }

    #[tokio::test]
    async fn access_cjk_percent_encoded_uri_path() {
        let svc = ServeDir::new(&ASSETS_DIR);

        let req = Request::builder()
            // percent encoding present of 你好世界.txt
            .uri("/%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C.txt")
            .body(http_body_util::Empty::<Bytes>::new())
            .unwrap();
        let res = svc.oneshot(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::OK);
        assert_eq!(res.headers()["content-type"], "text/plain");
    }

    #[tokio::test]
    async fn authority_form_uri_does_not_panic() {
        // Authority-form URIs (e.g. "localhost:8080") have authority but no scheme.
        // Per RFC 3986, a URI with authority always requires a scheme; authority-form
        // is only valid for CONNECT requests (RFC 7230 §5.3.3).
        // ServeDir should reject these gracefully instead of panicking in
        // append_slash_on_path when rebuilding the URI via Uri::from_parts.
        let svc = ServeDir::new(&ASSETS_DIR);

        let uri: Uri = "localhost:8080".parse().unwrap();
        assert!(uri.authority().is_some());
        assert!(uri.scheme().is_none());

        let req = Request::builder()
            .uri(uri)
            .body(http_body_util::Empty::<Bytes>::new())
            .unwrap();
        let res = svc.oneshot(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn access_space_percent_encoded_uri_path() {
        let svc = ServeDir::new(&ASSETS_DIR);

        let req = Request::builder()
            // percent encoding present of "filename with space.txt"
            .uri("/filename%20with%20space.txt")
            .body(http_body_util::Empty::<Bytes>::new())
            .unwrap();
        let res = svc.oneshot(req).await.unwrap();

        assert_eq!(res.status(), StatusCode::OK);
        assert_eq!(res.headers()["content-type"], "text/plain");
    }
}