2019-04-19 20:53:49 +00:00
|
|
|
//! `Middleware` to normalize request's URI
|
2019-11-21 08:52:33 +00:00
|
|
|
use std::task::{Context, Poll};
|
2019-04-19 20:53:49 +00:00
|
|
|
|
2019-12-05 17:35:43 +00:00
|
|
|
use actix_http::http::{PathAndQuery, Uri};
|
2019-04-19 20:53:49 +00:00
|
|
|
use actix_service::{Service, Transform};
|
2019-05-01 19:40:56 +00:00
|
|
|
use bytes::Bytes;
|
2020-05-18 02:47:20 +00:00
|
|
|
use futures_util::future::{ok, Ready};
|
2019-04-20 00:23:17 +00:00
|
|
|
use regex::Regex;
|
2019-04-19 20:53:49 +00:00
|
|
|
|
|
|
|
use crate::service::{ServiceRequest, ServiceResponse};
|
2019-04-25 18:14:32 +00:00
|
|
|
use crate::Error;
|
2019-04-19 20:53:49 +00:00
|
|
|
|
2020-08-19 11:21:52 +00:00
|
|
|
/// To be used when constructing `NormalizePath` to define it's behavior.
|
|
|
|
#[non_exhaustive]
|
|
|
|
#[derive(Clone, Copy)]
|
|
|
|
pub enum TrailingSlash {
|
|
|
|
/// Always add a trailing slash to the end of the path.
|
|
|
|
/// This will require all routes to end in a trailing slash for them to be accessible.
|
|
|
|
Always,
|
2020-09-25 11:50:59 +00:00
|
|
|
/// Only merge any present multiple trailing slashes.
|
|
|
|
///
|
|
|
|
/// Note: This option provides the best compatibility with the v2 version of this middlware.
|
|
|
|
MergeOnly,
|
2020-08-19 11:21:52 +00:00
|
|
|
/// Trim trailing slashes from the end of the path.
|
|
|
|
Trim,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for TrailingSlash {
|
|
|
|
fn default() -> Self {
|
|
|
|
TrailingSlash::Always
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-19 20:53:49 +00:00
|
|
|
#[derive(Default, Clone, Copy)]
|
|
|
|
/// `Middleware` to normalize request's URI in place
|
|
|
|
///
|
|
|
|
/// Performs following:
|
|
|
|
///
|
|
|
|
/// - Merges multiple slashes into one.
|
2020-09-25 11:50:59 +00:00
|
|
|
/// - Appends a trailing slash if one is not present, removes one if present, or keeps trailing
|
|
|
|
/// slashes as-is, depending on the supplied `TrailingSlash` variant.
|
2019-05-01 18:47:51 +00:00
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use actix_web::{web, http, middleware, App, HttpResponse};
|
|
|
|
///
|
2019-11-21 08:52:33 +00:00
|
|
|
/// # fn main() {
|
|
|
|
/// let app = App::new()
|
2020-08-19 11:21:52 +00:00
|
|
|
/// .wrap(middleware::NormalizePath::default())
|
2019-11-21 08:52:33 +00:00
|
|
|
/// .service(
|
|
|
|
/// web::resource("/test")
|
|
|
|
/// .route(web::get().to(|| HttpResponse::Ok()))
|
|
|
|
/// .route(web::method(http::Method::HEAD).to(|| HttpResponse::MethodNotAllowed()))
|
|
|
|
/// );
|
|
|
|
/// # }
|
2019-05-01 18:47:51 +00:00
|
|
|
/// ```
|
|
|
|
|
2020-08-19 11:21:52 +00:00
|
|
|
pub struct NormalizePath(TrailingSlash);
|
|
|
|
|
|
|
|
impl NormalizePath {
|
|
|
|
/// Create new `NormalizePath` middleware with the specified trailing slash style.
|
|
|
|
pub fn new(trailing_slash_style: TrailingSlash) -> Self {
|
|
|
|
NormalizePath(trailing_slash_style)
|
|
|
|
}
|
|
|
|
}
|
2019-04-19 20:53:49 +00:00
|
|
|
|
2019-05-01 18:47:51 +00:00
|
|
|
impl<S, B> Transform<S> for NormalizePath
|
2019-04-19 20:53:49 +00:00
|
|
|
where
|
2019-05-01 18:47:51 +00:00
|
|
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
|
|
|
S::Future: 'static,
|
2019-04-19 20:53:49 +00:00
|
|
|
{
|
|
|
|
type Request = ServiceRequest;
|
2019-05-01 18:47:51 +00:00
|
|
|
type Response = ServiceResponse<B>;
|
2019-04-25 18:14:32 +00:00
|
|
|
type Error = Error;
|
2019-04-19 20:53:49 +00:00
|
|
|
type InitError = ();
|
|
|
|
type Transform = NormalizePathNormalization<S>;
|
2019-11-21 08:52:33 +00:00
|
|
|
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
2019-04-19 20:53:49 +00:00
|
|
|
|
|
|
|
fn new_transform(&self, service: S) -> Self::Future {
|
2019-11-21 08:52:33 +00:00
|
|
|
ok(NormalizePathNormalization {
|
2019-04-19 20:53:49 +00:00
|
|
|
service,
|
2019-04-20 00:23:17 +00:00
|
|
|
merge_slash: Regex::new("//+").unwrap(),
|
2020-08-19 11:21:52 +00:00
|
|
|
trailing_slash_behavior: self.0,
|
2019-04-19 20:53:49 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-15 10:32:31 +00:00
|
|
|
#[doc(hidden)]
|
2019-04-19 20:53:49 +00:00
|
|
|
pub struct NormalizePathNormalization<S> {
|
|
|
|
service: S,
|
|
|
|
merge_slash: Regex,
|
2020-08-19 11:21:52 +00:00
|
|
|
trailing_slash_behavior: TrailingSlash,
|
2019-04-19 20:53:49 +00:00
|
|
|
}
|
|
|
|
|
2019-05-01 18:47:51 +00:00
|
|
|
impl<S, B> Service for NormalizePathNormalization<S>
|
2019-04-19 20:53:49 +00:00
|
|
|
where
|
2019-05-01 18:47:51 +00:00
|
|
|
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
|
|
|
S::Future: 'static,
|
2019-04-19 20:53:49 +00:00
|
|
|
{
|
|
|
|
type Request = ServiceRequest;
|
2019-05-01 18:47:51 +00:00
|
|
|
type Response = ServiceResponse<B>;
|
2019-04-25 18:14:32 +00:00
|
|
|
type Error = Error;
|
2019-04-19 20:53:49 +00:00
|
|
|
type Future = S::Future;
|
|
|
|
|
2019-12-07 18:46:51 +00:00
|
|
|
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
2019-11-21 08:52:33 +00:00
|
|
|
self.service.poll_ready(cx)
|
2019-04-19 20:53:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn call(&mut self, mut req: ServiceRequest) -> Self::Future {
|
|
|
|
let head = req.head_mut();
|
2020-05-21 08:56:53 +00:00
|
|
|
|
2020-06-17 09:54:20 +00:00
|
|
|
let original_path = head.uri.path();
|
|
|
|
|
2020-08-19 11:21:52 +00:00
|
|
|
// Either adds a string to the end (duplicates will be removed anyways) or trims all slashes from the end
|
|
|
|
let path = match self.trailing_slash_behavior {
|
|
|
|
TrailingSlash::Always => original_path.to_string() + "/",
|
2020-09-25 11:50:59 +00:00
|
|
|
TrailingSlash::MergeOnly => original_path.to_string(),
|
2020-08-19 11:21:52 +00:00
|
|
|
TrailingSlash::Trim => original_path.trim_end_matches('/').to_string(),
|
|
|
|
};
|
2020-04-04 18:26:40 +00:00
|
|
|
|
|
|
|
// normalize multiple /'s to one /
|
|
|
|
let path = self.merge_slash.replace_all(&path, "/");
|
2019-04-19 20:53:49 +00:00
|
|
|
|
2020-09-15 10:32:31 +00:00
|
|
|
// Ensure root paths are still resolvable. If resulting path is blank after previous step
|
|
|
|
// it means the path was one or more slashes. Reduce to single slash.
|
|
|
|
let path = if path.is_empty() { "/" } else { path.as_ref() };
|
|
|
|
|
2020-06-17 09:54:20 +00:00
|
|
|
// Check whether the path has been changed
|
|
|
|
//
|
|
|
|
// This check was previously implemented as string length comparison
|
|
|
|
//
|
|
|
|
// That approach fails when a trailing slash is added,
|
|
|
|
// and a duplicate slash is removed,
|
|
|
|
// since the length of the strings remains the same
|
2020-07-21 23:28:33 +00:00
|
|
|
//
|
2020-06-17 09:54:20 +00:00
|
|
|
// For example, the path "/v1//s" will be normalized to "/v1/s/"
|
2020-07-21 23:28:33 +00:00
|
|
|
// Both of the paths have the same length,
|
2020-06-17 09:54:20 +00:00
|
|
|
// so the change can not be deduced from the length comparison
|
|
|
|
if path != original_path {
|
2019-05-01 19:40:56 +00:00
|
|
|
let mut parts = head.uri.clone().into_parts();
|
|
|
|
let pq = parts.path_and_query.as_ref().unwrap();
|
|
|
|
|
|
|
|
let path = if let Some(q) = pq.query() {
|
|
|
|
Bytes::from(format!("{}?{}", path, q))
|
|
|
|
} else {
|
2019-12-05 17:35:43 +00:00
|
|
|
Bytes::copy_from_slice(path.as_bytes())
|
2019-05-01 19:40:56 +00:00
|
|
|
};
|
2019-12-05 17:35:43 +00:00
|
|
|
parts.path_and_query = Some(PathAndQuery::from_maybe_shared(path).unwrap());
|
2019-05-01 19:40:56 +00:00
|
|
|
|
|
|
|
let uri = Uri::from_parts(parts).unwrap();
|
|
|
|
req.match_info_mut().get_mut().update(&uri);
|
|
|
|
req.head_mut().uri = uri;
|
2019-04-19 20:53:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
self.service.call(req)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2019-05-12 15:34:51 +00:00
|
|
|
use actix_service::IntoService;
|
2019-04-19 20:53:49 +00:00
|
|
|
|
|
|
|
use super::*;
|
|
|
|
use crate::dev::ServiceRequest;
|
2019-11-26 05:25:50 +00:00
|
|
|
use crate::test::{call_service, init_service, TestRequest};
|
2019-05-01 19:40:56 +00:00
|
|
|
use crate::{web, App, HttpResponse};
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_wrap() {
|
|
|
|
let mut app = init_service(
|
|
|
|
App::new()
|
|
|
|
.wrap(NormalizePath::default())
|
2020-09-15 10:32:31 +00:00
|
|
|
.service(web::resource("/").to(HttpResponse::Ok))
|
2020-07-21 23:28:33 +00:00
|
|
|
.service(web::resource("/v1/something/").to(HttpResponse::Ok)),
|
2019-11-26 05:25:50 +00:00
|
|
|
)
|
|
|
|
.await;
|
|
|
|
|
2020-09-15 10:32:31 +00:00
|
|
|
let req = TestRequest::with_uri("/").to_request();
|
|
|
|
let res = call_service(&mut app, req).await;
|
|
|
|
assert!(res.status().is_success());
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/?query=test").to_request();
|
|
|
|
let res = call_service(&mut app, req).await;
|
|
|
|
assert!(res.status().is_success());
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("///").to_request();
|
|
|
|
let res = call_service(&mut app, req).await;
|
|
|
|
assert!(res.status().is_success());
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
let req = TestRequest::with_uri("/v1//something////").to_request();
|
|
|
|
let res = call_service(&mut app, req).await;
|
|
|
|
assert!(res.status().is_success());
|
2020-04-04 18:26:40 +00:00
|
|
|
|
|
|
|
let req2 = TestRequest::with_uri("//v1/something").to_request();
|
|
|
|
let res2 = call_service(&mut app, req2).await;
|
|
|
|
assert!(res2.status().is_success());
|
|
|
|
|
|
|
|
let req3 = TestRequest::with_uri("//v1//////something").to_request();
|
|
|
|
let res3 = call_service(&mut app, req3).await;
|
|
|
|
assert!(res3.status().is_success());
|
2020-06-17 09:54:20 +00:00
|
|
|
|
|
|
|
let req4 = TestRequest::with_uri("/v1//something").to_request();
|
|
|
|
let res4 = call_service(&mut app, req4).await;
|
|
|
|
assert!(res4.status().is_success());
|
2019-05-01 19:40:56 +00:00
|
|
|
}
|
2019-04-19 20:53:49 +00:00
|
|
|
|
2020-08-19 11:21:52 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn trim_trailing_slashes() {
|
|
|
|
let mut app = init_service(
|
|
|
|
App::new()
|
|
|
|
.wrap(NormalizePath(TrailingSlash::Trim))
|
2020-09-15 10:32:31 +00:00
|
|
|
.service(web::resource("/").to(HttpResponse::Ok))
|
2020-08-19 11:21:52 +00:00
|
|
|
.service(web::resource("/v1/something").to(HttpResponse::Ok)),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
|
2020-09-15 10:32:31 +00:00
|
|
|
// root paths should still work
|
|
|
|
let req = TestRequest::with_uri("/").to_request();
|
|
|
|
let res = call_service(&mut app, req).await;
|
|
|
|
assert!(res.status().is_success());
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/?query=test").to_request();
|
|
|
|
let res = call_service(&mut app, req).await;
|
|
|
|
assert!(res.status().is_success());
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("///").to_request();
|
|
|
|
let res = call_service(&mut app, req).await;
|
|
|
|
assert!(res.status().is_success());
|
|
|
|
|
2020-08-19 11:21:52 +00:00
|
|
|
let req = TestRequest::with_uri("/v1/something////").to_request();
|
|
|
|
let res = call_service(&mut app, req).await;
|
|
|
|
assert!(res.status().is_success());
|
|
|
|
|
|
|
|
let req2 = TestRequest::with_uri("/v1/something/").to_request();
|
|
|
|
let res2 = call_service(&mut app, req2).await;
|
|
|
|
assert!(res2.status().is_success());
|
|
|
|
|
|
|
|
let req3 = TestRequest::with_uri("//v1//something//").to_request();
|
|
|
|
let res3 = call_service(&mut app, req3).await;
|
|
|
|
assert!(res3.status().is_success());
|
|
|
|
|
|
|
|
let req4 = TestRequest::with_uri("//v1//something").to_request();
|
|
|
|
let res4 = call_service(&mut app, req4).await;
|
|
|
|
assert!(res4.status().is_success());
|
|
|
|
}
|
|
|
|
|
2020-09-25 11:50:59 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn keep_trailing_slash_unchange() {
|
|
|
|
let mut app = init_service(
|
|
|
|
App::new()
|
|
|
|
.wrap(NormalizePath(TrailingSlash::MergeOnly))
|
|
|
|
.service(web::resource("/").to(HttpResponse::Ok))
|
|
|
|
.service(web::resource("/v1/something").to(HttpResponse::Ok))
|
|
|
|
.service(web::resource("/v1/").to(HttpResponse::Ok)),
|
|
|
|
)
|
|
|
|
.await;
|
|
|
|
|
|
|
|
let tests = vec![
|
|
|
|
("/", true), // root paths should still work
|
|
|
|
("/?query=test", true),
|
|
|
|
("///", true),
|
|
|
|
("/v1/something////", false),
|
|
|
|
("/v1/something/", false),
|
|
|
|
("//v1//something", true),
|
|
|
|
("/v1/", true),
|
|
|
|
("/v1", false),
|
|
|
|
("/v1////", true),
|
|
|
|
("//v1//", true),
|
|
|
|
("///v1", false),
|
|
|
|
];
|
|
|
|
|
|
|
|
for (path, success) in tests {
|
|
|
|
let req = TestRequest::with_uri(path).to_request();
|
|
|
|
let res = call_service(&mut app, req).await;
|
|
|
|
assert_eq!(res.status().is_success(), success);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn test_in_place_normalization() {
|
|
|
|
let srv = |req: ServiceRequest| {
|
|
|
|
assert_eq!("/v1/something/", req.path());
|
|
|
|
ok(req.into_response(HttpResponse::Ok().finish()))
|
|
|
|
};
|
|
|
|
|
2020-08-19 11:21:52 +00:00
|
|
|
let mut normalize = NormalizePath::default()
|
2019-11-26 05:25:50 +00:00
|
|
|
.new_transform(srv.into_service())
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri("/v1//something////").to_srv_request();
|
|
|
|
let res = normalize.call(req).await.unwrap();
|
|
|
|
assert!(res.status().is_success());
|
2020-04-04 18:26:40 +00:00
|
|
|
|
|
|
|
let req2 = TestRequest::with_uri("///v1/something").to_srv_request();
|
|
|
|
let res2 = normalize.call(req2).await.unwrap();
|
|
|
|
assert!(res2.status().is_success());
|
|
|
|
|
|
|
|
let req3 = TestRequest::with_uri("//v1///something").to_srv_request();
|
|
|
|
let res3 = normalize.call(req3).await.unwrap();
|
|
|
|
assert!(res3.status().is_success());
|
2020-06-17 09:54:20 +00:00
|
|
|
|
|
|
|
let req4 = TestRequest::with_uri("/v1//something").to_srv_request();
|
|
|
|
let res4 = normalize.call(req4).await.unwrap();
|
|
|
|
assert!(res4.status().is_success());
|
2019-04-19 20:53:49 +00:00
|
|
|
}
|
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
#[actix_rt::test]
|
|
|
|
async fn should_normalize_nothing() {
|
|
|
|
const URI: &str = "/v1/something/";
|
2019-04-19 20:53:49 +00:00
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
let srv = |req: ServiceRequest| {
|
|
|
|
assert_eq!(URI, req.path());
|
|
|
|
ok(req.into_response(HttpResponse::Ok().finish()))
|
|
|
|
};
|
2019-04-19 20:53:49 +00:00
|
|
|
|
2020-08-19 11:21:52 +00:00
|
|
|
let mut normalize = NormalizePath::default()
|
2020-04-04 18:26:40 +00:00
|
|
|
.new_transform(srv.into_service())
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
let req = TestRequest::with_uri(URI).to_srv_request();
|
|
|
|
let res = normalize.call(req).await.unwrap();
|
|
|
|
assert!(res.status().is_success());
|
|
|
|
}
|
|
|
|
|
2020-05-21 08:56:53 +00:00
|
|
|
#[actix_rt::test]
|
2020-06-17 09:54:20 +00:00
|
|
|
async fn should_normalize_notrail() {
|
2020-04-04 18:26:40 +00:00
|
|
|
const URI: &str = "/v1/something";
|
|
|
|
|
|
|
|
let srv = |req: ServiceRequest| {
|
2020-06-17 09:54:20 +00:00
|
|
|
assert_eq!(URI.to_string() + "/", req.path());
|
2020-04-04 18:26:40 +00:00
|
|
|
ok(req.into_response(HttpResponse::Ok().finish()))
|
|
|
|
};
|
|
|
|
|
2020-08-19 11:21:52 +00:00
|
|
|
let mut normalize = NormalizePath::default()
|
2019-11-26 05:25:50 +00:00
|
|
|
.new_transform(srv.into_service())
|
|
|
|
.await
|
|
|
|
.unwrap();
|
2019-04-19 20:53:49 +00:00
|
|
|
|
2019-11-26 05:25:50 +00:00
|
|
|
let req = TestRequest::with_uri(URI).to_srv_request();
|
|
|
|
let res = normalize.call(req).await.unwrap();
|
|
|
|
assert!(res.status().is_success());
|
2019-04-19 20:53:49 +00:00
|
|
|
}
|
|
|
|
}
|