diff --git a/src/middleware/https_redirector.rs b/src/middleware/https_redirector.rs index 6345ee6..277f015 100644 --- a/src/middleware/https_redirector.rs +++ b/src/middleware/https_redirector.rs @@ -22,42 +22,45 @@ impl Middleware for HttpsRedirector { request: Request, context: &Context<'_>, ) -> Result, Response> { - match context.client_scheme { - server::Scheme::HTTP => { - let host_authority = parse_host_header(&request)?; + if let server::Scheme::HTTP = context.client_scheme { + let host_authority = parse_host_header(&request)?; - let (parts, _body) = request.into_parts(); - let uri_parts = parts.uri.into_parts(); - let authority = uri_parts.authority.unwrap_or(host_authority); - let path_and_query = uri_parts.path_and_query.ok_or_else(internal_server_error)?; - let https_uri = Uri::builder() - .scheme(Scheme::HTTPS) - .authority(authority) - .path_and_query(path_and_query) - .build() - .map_err(handle_internal_server_error)?; + let (parts, _body) = request.into_parts(); + let uri_parts = parts.uri.into_parts(); + let authority = uri_parts.authority.unwrap_or(host_authority); + let path_and_query = uri_parts.path_and_query.ok_or_else(internal_server_error)?; + let https_uri = Uri::builder() + .scheme(Scheme::HTTPS) + .authority(authority) + .path_and_query(path_and_query) + .build() + .map_err(handle_internal_server_error)?; - let response = Response::builder() + debug!("Redirecting to {}", https_uri); + + return Err( + Response::builder() .status(StatusCode::MOVED_PERMANENTLY) .header(LOCATION, https_uri.to_string()) .body(Body::empty()) - .map_err(handle_internal_server_error)?; - - debug!("Redirecting to {}", https_uri); - - Err(response) - } - _ => Ok(request), + .map_err(handle_internal_server_error)? + ); } + + Ok(request) } } fn parse_host_header(request: &Request) -> Result> { - let host = request - .headers() - .get(HOST) - .ok_or_else(|| bad_request("missing host header"))? - .to_str() - .map_err(|error| bad_request(error.to_string()))?; - Authority::try_from(host).map_err(|_error| bad_request("invalid host header")) -} \ No newline at end of file + request + .headers() + .get(HOST) + .ok_or_else(|| bad_request("Missing Host header".to_string())) + .and_then(|host| { + host.to_str() + .map_err(|_| bad_request("Failed to parse Host header".to_string())) + }) + .and_then(|host_str| { + Authority::try_from(host_str).map_err(|_| bad_request("Invalid Host header".to_string())) + }) +}