1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-30 10:32:55 +01:00

fmt with new width

This commit is contained in:
Rob Ede 2021-08-30 23:27:44 +01:00
parent c6f579790f
commit e10937103e
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
18 changed files with 54 additions and 144 deletions

View File

@ -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() {
@ -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 {
@ -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 {
@ -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);
@ -506,12 +502,11 @@ 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(());
}
@ -519,8 +514,7 @@ where
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);
}
_ => {}
}

View File

@ -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.

View File

@ -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)
@ -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 {
@ -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()
@ -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 {

View File

@ -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;
@ -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()));
}
@ -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);

View File

@ -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))
@ -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
),
}
}
@ -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();
@ -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();
@ -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));
@ -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();
@ -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;
}

View File

@ -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};
@ -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 {

View File

@ -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 {
@ -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))),
}
}
}
@ -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);
}

View File

@ -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};

View File

@ -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());
@ -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(())
@ -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();
@ -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)))

View File

@ -77,8 +77,7 @@ impl CookieSessionInner {
return Ok(());
}
let value =
serde_json::to_string(&state).map_err(CookieSessionError::Serialize)?;
let value = serde_json::to_string(&state).map_err(CookieSessionError::Serialize)?;
if value.len() > 4064 {
return Err(CookieSessionError::Overflow.into());
@ -143,9 +142,7 @@ impl CookieSessionInner {
let cookie_opt = match self.security {
CookieSecurity::Signed => jar.signed(&self.key).get(&self.name),
CookieSecurity::Private => {
jar.private(&self.key).get(&self.name)
}
CookieSecurity::Private => jar.private(&self.key).get(&self.name),
};
if let Some(cookie) = cookie_opt {
@ -528,10 +525,7 @@ mod tests {
let _ = ses.insert("counter", 100);
"test"
}))
.service(
web::resource("/test/")
.to(|| async move { "no-changes-in-session" }),
),
.service(web::resource("/test/").to(|| async move { "no-changes-in-session" })),
)
.await;

View File

@ -165,11 +165,7 @@ impl Session {
///
/// Any serializable value can be used and will be encoded as JSON in session data, hence why
/// only a reference to the value is taken.
pub fn insert(
&self,
key: impl Into<String>,
value: impl Serialize,
) -> Result<(), Error> {
pub fn insert(&self, key: impl Into<String>, value: impl Serialize) -> Result<(), Error> {
let mut inner = self.0.borrow_mut();
if inner.status != SessionStatus::Purged {
@ -199,10 +195,7 @@ impl Session {
///
/// Returns None if key was not present in session. Returns T if deserialization succeeds,
/// otherwise returns un-deserialized JSON string.
pub fn remove_as<T: DeserializeOwned>(
&self,
key: &str,
) -> Option<Result<T, String>> {
pub fn remove_as<T: DeserializeOwned>(&self, key: &str) -> Option<Result<T, String>> {
self.remove(key)
.map(|val_str| match serde_json::from_str(&val_str) {
Ok(val) => Ok(val),
@ -259,10 +252,7 @@ impl Session {
/// vec![("counter".to_string(), serde_json::to_string(&0).unwrap())],
/// );
/// ```
pub fn set_session(
req: &mut ServiceRequest,
data: impl IntoIterator<Item = (String, String)>,
) {
pub fn set_session(req: &mut ServiceRequest, data: impl IntoIterator<Item = (String, String)>) {
let session = Session::get_session(&mut *req.extensions_mut());
let mut inner = session.0.borrow_mut();
inner.state.extend(data);

View File

@ -4,10 +4,7 @@ use actix_web::{middleware, web, App, Error, HttpServer};
use actix_web_httpauth::extractors::basic::BasicAuth;
use actix_web_httpauth::middleware::HttpAuthentication;
async fn validator(
req: ServiceRequest,
_credentials: BasicAuth,
) -> Result<ServiceRequest, Error> {
async fn validator(req: ServiceRequest, _credentials: BasicAuth) -> Result<ServiceRequest, Error> {
Ok(req)
}

View File

@ -1,8 +1,6 @@
use actix_cors::Cors;
use actix_web::{dev::ServiceRequest, get, App, Error, HttpResponse, HttpServer};
use actix_web_httpauth::{
extractors::bearer::BearerAuth, middleware::HttpAuthentication,
};
use actix_web_httpauth::{extractors::bearer::BearerAuth, middleware::HttpAuthentication};
async fn ok_validator(
req: ServiceRequest,

View File

@ -108,10 +108,7 @@ impl FromRequest for BasicAuth {
type Config = Config;
type Error = AuthenticationError<Challenge>;
fn from_request(
req: &HttpRequest,
_: &mut Payload,
) -> <Self as FromRequest>::Future {
fn from_request(req: &HttpRequest, _: &mut Payload) -> <Self as FromRequest>::Future {
ready(
Authorization::<Basic>::parse(req)
.map(|auth| BasicAuth(auth.into_scheme()))

View File

@ -107,10 +107,7 @@ impl FromRequest for BearerAuth {
type Future = Ready<Result<Self, Self::Error>>;
type Error = AuthenticationError<bearer::Bearer>;
fn from_request(
req: &HttpRequest,
_payload: &mut Payload,
) -> <Self as FromRequest>::Future {
fn from_request(req: &HttpRequest, _payload: &mut Payload) -> <Self as FromRequest>::Future {
ready(
authorization::Authorization::<authorization::Bearer>::parse(req)
.map(|auth| BearerAuth(auth.into_scheme()))

View File

@ -1,9 +1,7 @@
use std::fmt;
use actix_web::error::ParseError;
use actix_web::http::header::{
Header, HeaderName, HeaderValue, IntoHeaderValue, AUTHORIZATION,
};
use actix_web::http::header::{Header, HeaderName, HeaderValue, IntoHeaderValue, AUTHORIZATION};
use actix_web::HttpMessage;
use crate::headers::authorization::scheme::Scheme;

View File

@ -1,7 +1,5 @@
use actix_web::error::ParseError;
use actix_web::http::header::{
Header, HeaderName, HeaderValue, IntoHeaderValue, WWW_AUTHENTICATE,
};
use actix_web::http::header::{Header, HeaderName, HeaderValue, IntoHeaderValue, WWW_AUTHENTICATE};
use actix_web::HttpMessage;
use super::Challenge;

View File

@ -1,8 +1,7 @@
//! HTTP Authentication middleware.
use std::{
error::Error as StdError, future::Future, marker::PhantomData, pin::Pin, rc::Rc,
sync::Arc,
error::Error as StdError, future::Future, marker::PhantomData, pin::Pin, rc::Rc, sync::Arc,
};
use actix_web::{