4 releases

0.2.0 Jul 7, 2023
0.1.2 May 26, 2023
0.1.1 May 26, 2023
0.1.0 May 26, 2023

#631 in Filesystem

Download history 54/week @ 2024-01-04 41/week @ 2024-01-11 45/week @ 2024-01-18 17/week @ 2024-01-25 58/week @ 2024-02-01 318/week @ 2024-02-08 256/week @ 2024-02-15 298/week @ 2024-02-22 264/week @ 2024-02-29 123/week @ 2024-03-07 247/week @ 2024-03-14 95/week @ 2024-03-21 221/week @ 2024-03-28 172/week @ 2024-04-04 89/week @ 2024-04-11 153/week @ 2024-04-18

637 downloads per month

Apache-2.0

9KB
164 lines

Tower middleware to sanitize paths.

Any sort of path traversal techniques used to access the underlying filesystem will be removed from the request's paths. For example, a request with /../../passwd will become /passwd before being passed to inner services.

Example

use http::{Request, Response, StatusCode};
use hyper::Body;
use std::{iter::once, convert::Infallible};
use tower::{ServiceBuilder, Service, ServiceExt};
use tower_sanitize_path::SanitizePathLayer;

# #[tokio::main]
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
async fn handle(req: Request<Body>) -> Result<Response<Body>, Infallible> {
    // `req.uri().path()` will not be usable to traverse the filesystem
    # Ok(Response::new(Body::empty()))
}

let mut service = ServiceBuilder::new()
    // sanitize the paths
    .layer(SanitizePathLayer)
    .service_fn(handle);

// call the service
let request = Request::builder()
    // `handle` will see `/secret`
    .uri("/../../secret")
    .body(Body::empty())?;

service.ready().await?.call(request).await?;
#
# Ok(())
# }

Dependencies

~640KB
~10K SLoC