Skip to content

Commit

Permalink
fmt with new width
Browse files Browse the repository at this point in the history
  • Loading branch information
robjtede committed Aug 30, 2021
1 parent c6f5797 commit e109371
Show file tree
Hide file tree
Showing 18 changed files with 54 additions and 144 deletions.
26 changes: 10 additions & 16 deletions actix-cors/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,7 @@ impl Cors {

Ok(_) => {
if cors.allowed_origins.is_all() {
cors.allowed_origins =
AllOrSome::Some(HashSet::with_capacity(8));
cors.allowed_origins = AllOrSome::Some(HashSet::with_capacity(8));
}

if let Some(origins) = cors.allowed_origins.as_mut() {
Expand Down Expand Up @@ -257,8 +256,7 @@ impl Cors {
match header.try_into() {
Ok(method) => {
if cors.allowed_headers.is_all() {
cors.allowed_headers =
AllOrSome::Some(HashSet::with_capacity(8));
cors.allowed_headers = AllOrSome::Some(HashSet::with_capacity(8));
}

if let AllOrSome::Some(ref mut headers) = cors.allowed_headers {
Expand Down Expand Up @@ -294,8 +292,7 @@ impl Cors {
match h.try_into() {
Ok(method) => {
if cors.allowed_headers.is_all() {
cors.allowed_headers =
AllOrSome::Some(HashSet::with_capacity(8));
cors.allowed_headers = AllOrSome::Some(HashSet::with_capacity(8));
}

if let AllOrSome::Some(ref mut headers) = cors.allowed_headers {
Expand Down Expand Up @@ -342,8 +339,7 @@ impl Cors {
Ok(header) => {
if let Some(cors) = cors(&mut self.inner, &self.error) {
if cors.expose_headers.is_all() {
cors.expose_headers =
AllOrSome::Some(HashSet::with_capacity(8));
cors.expose_headers = AllOrSome::Some(HashSet::with_capacity(8));
}
if let AllOrSome::Some(ref mut headers) = cors.expose_headers {
headers.insert(header);
Expand Down Expand Up @@ -506,21 +502,19 @@ where

let mut inner = Rc::clone(&self.inner);

if inner.supports_credentials
&& inner.send_wildcard
&& inner.allowed_origins.is_all()
{
error!("Illegal combination of CORS options: credentials can not be supported when all \
origins are allowed and `send_wildcard` is enabled.");
if inner.supports_credentials && inner.send_wildcard && inner.allowed_origins.is_all() {
error!(
"Illegal combination of CORS options: credentials can not be supported when all \
origins are allowed and `send_wildcard` is enabled."
);
return future::err(());
}

// bake allowed headers value if Some and not empty
match inner.allowed_headers.as_ref() {
Some(header_set) if !header_set.is_empty() => {
let allowed_headers_str = intersperse_header_values(header_set);
Rc::make_mut(&mut inner).allowed_headers_baked =
Some(allowed_headers_str);
Rc::make_mut(&mut inner).allowed_headers_baked = Some(allowed_headers_str);
}
_ => {}
}
Expand Down
12 changes: 3 additions & 9 deletions actix-cors/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,15 @@ pub enum CorsError {
MissingOrigin,

/// Request header `Access-Control-Request-Method` is required but is missing.
#[display(
fmt = "Request header `Access-Control-Request-Method` is required but is missing."
)]
#[display(fmt = "Request header `Access-Control-Request-Method` is required but is missing.")]
MissingRequestMethod,

/// Request header `Access-Control-Request-Method` has an invalid value.
#[display(
fmt = "Request header `Access-Control-Request-Method` has an invalid value."
)]
#[display(fmt = "Request header `Access-Control-Request-Method` has an invalid value.")]
BadRequestMethod,

/// Request header `Access-Control-Request-Headers` has an invalid value.
#[display(
fmt = "Request header `Access-Control-Request-Headers` has an invalid value."
)]
#[display(fmt = "Request header `Access-Control-Request-Headers` has an invalid value.")]
BadRequestHeaders,

/// Origin is not allowed to make this request.
Expand Down
19 changes: 4 additions & 15 deletions actix-cors/src/inner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,7 @@ impl Inner {
match req.headers().get(header::ORIGIN) {
// origin header exists and is a string
Some(origin) => {
if allowed_origins.contains(origin)
|| self.validate_origin_fns(origin, req)
{
if allowed_origins.contains(origin) || self.validate_origin_fns(origin, req) {
Ok(())
} else {
Err(CorsError::OriginNotAllowed)
Expand All @@ -102,10 +100,7 @@ impl Inner {
}

/// Only called if origin exists and always after it's validated.
pub(crate) fn access_control_allow_origin(
&self,
req: &RequestHead,
) -> Option<HeaderValue> {
pub(crate) fn access_control_allow_origin(&self, req: &RequestHead) -> Option<HeaderValue> {
let origin = req.headers().get(header::ORIGIN);

match self.allowed_origins {
Expand All @@ -129,10 +124,7 @@ impl Inner {

/// Use in preflight checks and therefore operates on header list in
/// `Access-Control-Request-Headers` not the actual header set.
pub(crate) fn validate_allowed_method(
&self,
req: &RequestHead,
) -> Result<(), CorsError> {
pub(crate) fn validate_allowed_method(&self, req: &RequestHead) -> Result<(), CorsError> {
// extract access control header and try to parse as method
let request_method = req
.headers()
Expand All @@ -154,10 +146,7 @@ impl Inner {
}
}

pub(crate) fn validate_allowed_headers(
&self,
req: &RequestHead,
) -> Result<(), CorsError> {
pub(crate) fn validate_allowed_headers(&self, req: &RequestHead) -> Result<(), CorsError> {
// return early if all headers are allowed or get ref to allowed origins set
#[allow(clippy::mutable_key_type)]
let allowed_headers = match &self.allowed_headers {
Expand Down
13 changes: 3 additions & 10 deletions actix-cors/src/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@ use actix_web::{
},
HttpResponse,
};
use futures_util::future::{
ok, Either, FutureExt as _, LocalBoxFuture, Ready, TryFutureExt as _,
};
use futures_util::future::{ok, Either, FutureExt as _, LocalBoxFuture, Ready, TryFutureExt as _};
use log::debug;

use crate::Inner;
Expand Down Expand Up @@ -53,9 +51,7 @@ impl<S> CorsMiddleware<S> {

if let Some(ref headers) = inner.allowed_headers_baked {
res.insert_header((header::ACCESS_CONTROL_ALLOW_HEADERS, headers.clone()));
} else if let Some(headers) =
req.headers().get(header::ACCESS_CONTROL_REQUEST_HEADERS)
{
} else if let Some(headers) = req.headers().get(header::ACCESS_CONTROL_REQUEST_HEADERS) {
// all headers allowed, return
res.insert_header((header::ACCESS_CONTROL_ALLOW_HEADERS, headers.clone()));
}
Expand All @@ -75,10 +71,7 @@ impl<S> CorsMiddleware<S> {
req.into_response(res)
}

fn augment_response<B>(
inner: &Inner,
mut res: ServiceResponse<B>,
) -> ServiceResponse<B> {
fn augment_response<B>(inner: &Inner, mut res: ServiceResponse<B>) -> ServiceResponse<B> {
if let Some(origin) = inner.access_control_allow_origin(res.request().head()) {
res.headers_mut()
.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
Expand Down
24 changes: 8 additions & 16 deletions actix-identity/src/cookie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,8 +439,7 @@ mod tests {
match login_timestamp {
LoginTimestampCheck::NoTimestamp => assert_eq!(cv.login_timestamp, None),
LoginTimestampCheck::NewTimestamp => assert!(
t30sec_ago <= cv.login_timestamp.unwrap()
&& cv.login_timestamp.unwrap() <= now
t30sec_ago <= cv.login_timestamp.unwrap() && cv.login_timestamp.unwrap() <= now
),
LoginTimestampCheck::OldTimestamp(old_timestamp) => {
assert_eq!(cv.login_timestamp, Some(old_timestamp))
Expand All @@ -450,8 +449,7 @@ mod tests {
match visit_timestamp {
VisitTimeStampCheck::NoTimestamp => assert_eq!(cv.visit_timestamp, None),
VisitTimeStampCheck::NewTimestamp => assert!(
t30sec_ago <= cv.visit_timestamp.unwrap()
&& cv.visit_timestamp.unwrap() <= now
t30sec_ago <= cv.visit_timestamp.unwrap() && cv.visit_timestamp.unwrap() <= now
),
}
}
Expand Down Expand Up @@ -488,12 +486,10 @@ mod tests {
})),
)
.await;
let resp =
test::call_service(&srv, TestRequest::with_uri("/index").to_request()).await;
let resp = test::call_service(&srv, TestRequest::with_uri("/index").to_request()).await;
assert_eq!(resp.status(), StatusCode::OK);

let resp =
test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
let resp = test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
assert_eq!(resp.status(), StatusCode::OK);
let c = resp.response().cookies().next().unwrap().to_owned();

Expand Down Expand Up @@ -538,8 +534,7 @@ mod tests {
)
.await;

let resp =
test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
let resp = test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
assert_eq!(resp.status(), StatusCode::OK);
assert!(resp.headers().contains_key(header::SET_COOKIE));
let c = resp.response().cookies().next().unwrap().to_owned();
Expand All @@ -565,8 +560,7 @@ mod tests {
)
.await;

let resp =
test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
let resp = test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;

assert_eq!(resp.status(), StatusCode::OK);
assert!(resp.headers().contains_key(header::SET_COOKIE));
Expand Down Expand Up @@ -628,8 +622,7 @@ mod tests {
})),
)
.await;
let resp =
test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
let resp = test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
assert_eq!(resp.status(), StatusCode::OK);
assert!(resp.headers().contains_key(header::SET_COOKIE));
let c = resp.response().cookies().next().unwrap().to_owned();
Expand All @@ -639,8 +632,7 @@ mod tests {
#[actix_rt::test]
async fn test_identity_legacy_cookie_is_set() {
let srv = create_identity_server(|c| c).await;
let mut resp =
test::call_service(&srv, TestRequest::with_uri("/").to_request()).await;
let mut resp = test::call_service(&srv, TestRequest::with_uri("/").to_request()).await;
assert_legacy_login_cookie(&mut resp, COOKIE_LOGIN);
assert_logged_in(resp, None).await;
}
Expand Down
8 changes: 2 additions & 6 deletions actix-identity/src/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ use actix_web::{
dev::{Service, ServiceRequest, ServiceResponse, Transform},
Error, HttpMessage, Result,
};
use futures_util::future::{
ready, FutureExt as _, LocalBoxFuture, Ready, TryFutureExt as _,
};
use futures_util::future::{ready, FutureExt as _, LocalBoxFuture, Ready, TryFutureExt as _};

use crate::{identity::IdentityItem, IdentityPolicy};

Expand Down Expand Up @@ -105,9 +103,7 @@ where

if let Some(id) = id {
match backend.to_response(id.id, id.changed, &mut res).await {
Ok(_) => {
Ok(res.map_body(|_, body| AnyBody::from_message(body)))
}
Ok(_) => Ok(res.map_body(|_, body| AnyBody::from_message(body))),
Err(e) => Ok(res.error_response(e)),
}
} else {
Expand Down
17 changes: 5 additions & 12 deletions actix-protobuf/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,15 @@ use actix_web::{
error::PayloadError,
http::header::{CONTENT_LENGTH, CONTENT_TYPE},
web::BytesMut,
Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, HttpResponseBuilder,
Responder, ResponseError,
Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, HttpResponseBuilder, Responder,
ResponseError,
};
use derive_more::Display;
use futures_util::{
future::{FutureExt as _, LocalBoxFuture},
stream::StreamExt as _,
};
use prost::{
DecodeError as ProtoBufDecodeError, EncodeError as ProtoBufEncodeError, Message,
};
use prost::{DecodeError as ProtoBufDecodeError, EncodeError as ProtoBufEncodeError, Message};

#[derive(Debug, Display)]
pub enum ProtoBufPayloadError {
Expand Down Expand Up @@ -153,9 +151,7 @@ impl<T: Message + Default> Responder for ProtoBuf<T> {
Ok(()) => HttpResponse::Ok()
.content_type("application/protobuf")
.body(buf),
Err(err) => HttpResponse::from_error(Error::from(
ProtoBufPayloadError::Serialize(err),
)),
Err(err) => HttpResponse::from_error(Error::from(ProtoBufPayloadError::Serialize(err))),
}
}
}
Expand Down Expand Up @@ -209,10 +205,7 @@ impl<T: Message + Default> ProtoBufMessage<T> {
impl<T: Message + Default + 'static> Future for ProtoBufMessage<T> {
type Output = Result<T, ProtoBufPayloadError>;

fn poll(
mut self: Pin<&mut Self>,
task: &mut task::Context<'_>,
) -> Poll<Self::Output> {
fn poll(mut self: Pin<&mut Self>, task: &mut task::Context<'_>) -> Poll<Self::Output> {
if let Some(ref mut fut) = self.fut {
return Pin::new(fut).poll(task);
}
Expand Down
3 changes: 1 addition & 2 deletions actix-redis/examples/authentication.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use actix_redis::RedisSession;
use actix_session::Session;
use actix_web::{
cookie, error::InternalError, middleware, web, App, Error, HttpResponse, HttpServer,
Responder,
cookie, error::InternalError, middleware, web, App, Error, HttpResponse, HttpServer, Responder,
};
use serde::{Deserialize, Serialize};

Expand Down
18 changes: 5 additions & 13 deletions actix-redis/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,9 +233,7 @@ impl Inner {
return Ok(None);
};

if let Some(cookie) =
cookies.iter().find(|&cookie| cookie.name() == self.name)
{
if let Some(cookie) = cookies.iter().find(|&cookie| cookie.name() == self.name) {
let mut jar = CookieJar::new();
jar.add_original(cookie.clone());

Expand Down Expand Up @@ -371,8 +369,8 @@ impl Inner {
cookie.set_max_age(Duration::zero());
cookie.set_expires(OffsetDateTime::now_utc() - Duration::days(365));

let val = HeaderValue::from_str(&cookie.to_string())
.map_err(error::ErrorInternalServerError)?;
let val =
HeaderValue::from_str(&cookie.to_string()).map_err(error::ErrorInternalServerError)?;
res.headers_mut().append(header::SET_COOKIE, val);

Ok(())
Expand Down Expand Up @@ -423,10 +421,7 @@ mod test {
user_id: String,
}

async fn login(
user_id: web::Json<Identity>,
session: Session,
) -> Result<HttpResponse> {
async fn login(user_id: web::Json<Identity>, session: Session) -> Result<HttpResponse> {
let id = user_id.into_inner().user_id;
session.insert("user_id", &id)?;
session.renew();
Expand Down Expand Up @@ -490,10 +485,7 @@ mod test {

let srv = actix_test::start(|| {
App::new()
.wrap(
RedisSession::new("127.0.0.1:6379", &[0; 32])
.cookie_name("test-session"),
)
.wrap(RedisSession::new("127.0.0.1:6379", &[0; 32]).cookie_name("test-session"))
.wrap(middleware::Logger::default())
.service(resource("/").route(get().to(index)))
.service(resource("/do_something").route(post().to(do_something)))
Expand Down
Loading

0 comments on commit e109371

Please sign in to comment.