mirror of
https://git.asonix.dog/asonix/http-signature-normalization.git
synced 2024-06-12 02:09:32 +00:00
Compare commits
22 commits
http-signa
...
main
Author | SHA1 | Date | |
---|---|---|---|
3d7b620bc0 | |||
07413815d5 | |||
c38072e65d | |||
47d28c6f47 | |||
47d07e7f1f | |||
b89acf7918 | |||
bf8e0e5f69 | |||
369a1e8a96 | |||
6e0a6fa3a2 | |||
f0dc14d5f1 | |||
92a73f0313 | |||
e8588efda7 | |||
6acd291315 | |||
ef266eed95 | |||
c1d36000dd | |||
ec73fe55c9 | |||
ff0290a488 | |||
ce2d14824e | |||
bbafc22d08 | |||
8750783667 | |||
ea964decc8 | |||
1f23b72140 |
|
@ -26,5 +26,5 @@ subtle = { version = "2.4.1", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = { version = "4", features = ["macros"] }
|
actix-web = { version = "4", features = ["macros"] }
|
||||||
openssl = "0.10.43"
|
openssl = { version = "0.10.43", features = ["vendored"] }
|
||||||
thiserror = "1"
|
thiserror = "1"
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
[package]
|
[package]
|
||||||
name = "http-signature-normalization-actix"
|
name = "http-signature-normalization-actix"
|
||||||
description = "An HTTP Signatures library that leaves the signing to you"
|
description = "An HTTP Signatures library that leaves the signing to you"
|
||||||
version = "0.9.1"
|
version = "0.11.1"
|
||||||
authors = ["asonix <asonix@asonix.dog>"]
|
authors = ["asonix <asonix@asonix.dog>"]
|
||||||
license = "AGPL-3.0"
|
license = "AGPL-3.0"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
|
@ -12,30 +12,33 @@ edition = "2021"
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
[features]
|
[features]
|
||||||
default = ["server", "sha-2", "sha-3"]
|
default = ["server", "sha-2", "sha-3"]
|
||||||
client = ["awc"]
|
client = ["dep:awc"]
|
||||||
digest = ["base64"]
|
digest = ["dep:base64"]
|
||||||
server = ["actix-web"]
|
server = ["dep:actix-web"]
|
||||||
sha-2 = ["digest", "sha2"]
|
sha-2 = ["digest", "dep:sha2"]
|
||||||
sha-3 = ["digest", "sha3"]
|
sha-3 = ["digest", "dep:sha3"]
|
||||||
|
ring = ["digest", "dep:ring"]
|
||||||
|
|
||||||
[[example]]
|
[[example]]
|
||||||
name = "server"
|
name = "server"
|
||||||
required-features = ["server", "sha-2"]
|
required-features = ["server", "ring"]
|
||||||
|
|
||||||
[[example]]
|
[[example]]
|
||||||
name = "client"
|
name = "client"
|
||||||
required-features = ["client", "sha-2"]
|
required-features = ["client", "ring"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-http = { version = "3.0.2", default-features = false }
|
actix-http = { version = "3.0.2", default-features = false }
|
||||||
actix-rt = "2.6.0"
|
actix-rt = "2.6.0"
|
||||||
actix-web = { version = "4.0.0", default-features = false, optional = true }
|
actix-web = { version = "4.0.0", default-features = false, optional = true }
|
||||||
awc = { version = "3.0.0", default-features = false, optional = true }
|
awc = { version = "3.0.0", default-features = false, optional = true }
|
||||||
base64 = { version = "0.13", optional = true }
|
base64 = { version = "0.22", optional = true }
|
||||||
futures-util = { version = "0.3", default-features = false }
|
futures-core = "0.3.28"
|
||||||
http-signature-normalization = { version = "0.7.0", path = ".." }
|
http-signature-normalization = { version = "0.7.0", path = ".." }
|
||||||
|
ring = { version = "0.17.5", optional = true }
|
||||||
sha2 = { version = "0.10", optional = true }
|
sha2 = { version = "0.10", optional = true }
|
||||||
sha3 = { version = "0.10", optional = true }
|
sha3 = { version = "0.10", optional = true }
|
||||||
|
streem = "0.2.0"
|
||||||
thiserror = "1.0"
|
thiserror = "1.0"
|
||||||
tokio = { version = "1", default-features = false, features = ["sync"] }
|
tokio = { version = "1", default-features = false, features = ["sync"] }
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
|
@ -44,7 +47,7 @@ tracing-futures = "0.2"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-rt = "2.6.0"
|
actix-rt = "2.6.0"
|
||||||
tracing-actix-web = { version = "0.6.0" }
|
tracing-actix-web = { version = "0.7.0" }
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
use actix_rt::task::JoinError;
|
use actix_rt::task::JoinError;
|
||||||
use awc::Client;
|
use awc::Client;
|
||||||
use http_signature_normalization_actix::prelude::*;
|
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||||
use sha2::{Digest, Sha256};
|
use http_signature_normalization_actix::{digest::ring::Sha256, prelude::*, Canceled};
|
||||||
use tracing::{error, info};
|
use tracing::{error, info};
|
||||||
use tracing_error::ErrorLayer;
|
use tracing_error::ErrorLayer;
|
||||||
use tracing_subscriber::{layer::SubscriberExt, EnvFilter};
|
use tracing_subscriber::{layer::SubscriberExt, EnvFilter};
|
||||||
|
@ -15,7 +15,7 @@ async fn request(config: Config) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
.append_header(("Accept", "text/plain"))
|
.append_header(("Accept", "text/plain"))
|
||||||
.signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
|
.signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
|
||||||
info!("Signing String\n{}", s);
|
info!("Signing String\n{}", s);
|
||||||
Ok(base64::encode(s)) as Result<_, MyError>
|
Ok(STANDARD.encode(s)) as Result<_, MyError>
|
||||||
})
|
})
|
||||||
.await?
|
.await?
|
||||||
.send()
|
.send()
|
||||||
|
@ -45,7 +45,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
|
||||||
tracing::subscriber::set_global_default(subscriber)?;
|
tracing::subscriber::set_global_default(subscriber)?;
|
||||||
|
|
||||||
let config = Config::default().require_header("accept").require_digest();
|
let config = Config::new().require_header("accept").require_digest();
|
||||||
|
|
||||||
request(config.clone()).await?;
|
request(config.clone()).await?;
|
||||||
request(config.mastodon_compat()).await?;
|
request(config.mastodon_compat()).await?;
|
||||||
|
@ -75,3 +75,9 @@ impl From<JoinError> for MyError {
|
||||||
MyError::Canceled
|
MyError::Canceled
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<Canceled> for MyError {
|
||||||
|
fn from(_: Canceled) -> Self {
|
||||||
|
MyError::Canceled
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
use actix_web::{http::StatusCode, web, App, HttpRequest, HttpResponse, HttpServer, ResponseError};
|
use actix_web::{http::StatusCode, web, App, HttpRequest, HttpResponse, HttpServer, ResponseError};
|
||||||
use http_signature_normalization_actix::prelude::*;
|
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||||
use sha2::{Digest, Sha256};
|
use http_signature_normalization_actix::{digest::ring::Sha256, prelude::*};
|
||||||
use std::future::{ready, Ready};
|
use std::future::{ready, Ready};
|
||||||
use tracing::info;
|
use tracing::info;
|
||||||
use tracing_actix_web::TracingLogger;
|
use tracing_actix_web::TracingLogger;
|
||||||
|
@ -30,7 +30,7 @@ impl SignatureVerify for MyVerify {
|
||||||
return ready(Err(MyError::Key));
|
return ready(Err(MyError::Key));
|
||||||
}
|
}
|
||||||
|
|
||||||
let decoded = match base64::decode(&signature) {
|
let decoded = match STANDARD.decode(&signature) {
|
||||||
Ok(decoded) => decoded,
|
Ok(decoded) => decoded,
|
||||||
Err(_) => return ready(Err(MyError::Decode)),
|
Err(_) => return ready(Err(MyError::Decode)),
|
||||||
};
|
};
|
||||||
|
@ -63,7 +63,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
|
||||||
tracing::subscriber::set_global_default(subscriber)?;
|
tracing::subscriber::set_global_default(subscriber)?;
|
||||||
|
|
||||||
let config = Config::default().require_header("accept").require_digest();
|
let config = Config::new().require_header("accept").require_digest();
|
||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
|
|
|
@ -1,5 +1,7 @@
|
||||||
//! Types for setting up Digest middleware verification
|
//! Types for setting up Digest middleware verification
|
||||||
|
|
||||||
|
use crate::{Canceled, DefaultSpawner, Spawn};
|
||||||
|
|
||||||
use super::{DigestPart, DigestVerify};
|
use super::{DigestPart, DigestVerify};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
body::MessageBody,
|
body::MessageBody,
|
||||||
|
@ -8,16 +10,14 @@ use actix_web::{
|
||||||
http::{header::HeaderValue, StatusCode},
|
http::{header::HeaderValue, StatusCode},
|
||||||
web, FromRequest, HttpMessage, HttpRequest, HttpResponse, ResponseError,
|
web, FromRequest, HttpMessage, HttpRequest, HttpResponse, ResponseError,
|
||||||
};
|
};
|
||||||
use futures_util::{
|
use futures_core::{future::LocalBoxFuture, Stream};
|
||||||
future::LocalBoxFuture,
|
|
||||||
stream::{Stream, StreamExt},
|
|
||||||
};
|
|
||||||
use std::{
|
use std::{
|
||||||
future::{ready, Ready},
|
future::{ready, Ready},
|
||||||
pin::Pin,
|
pin::Pin,
|
||||||
task::{Context, Poll},
|
task::{Context, Poll},
|
||||||
};
|
};
|
||||||
use tokio::sync::mpsc;
|
use streem::{from_fn::Yielder, IntoStreamer};
|
||||||
|
use tokio::sync::{mpsc, oneshot};
|
||||||
use tracing::{debug, Span};
|
use tracing::{debug, Span};
|
||||||
use tracing_error::SpanTrace;
|
use tracing_error::SpanTrace;
|
||||||
|
|
||||||
|
@ -42,10 +42,10 @@ pub struct DigestVerified;
|
||||||
/// .route("/unprotected", web::post().to(|| "No verification required"))
|
/// .route("/unprotected", web::post().to(|| "No verification required"))
|
||||||
/// })
|
/// })
|
||||||
/// ```
|
/// ```
|
||||||
pub struct VerifyDigest<T>(bool, T);
|
pub struct VerifyDigest<T, Spawner = DefaultSpawner>(Spawner, bool, T);
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct VerifyMiddleware<T, S>(S, bool, T);
|
pub struct VerifyMiddleware<T, Spawner, S>(S, Spawner, bool, T);
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
#[error("Error verifying digest")]
|
#[error("Error verifying digest")]
|
||||||
|
@ -85,10 +85,10 @@ enum VerifyErrorKind {
|
||||||
struct RxStream<T>(mpsc::Receiver<T>);
|
struct RxStream<T>(mpsc::Receiver<T>);
|
||||||
|
|
||||||
impl<T> Stream for RxStream<T> {
|
impl<T> Stream for RxStream<T> {
|
||||||
type Item = T;
|
type Item = Result<T, PayloadError>;
|
||||||
|
|
||||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||||
Pin::new(&mut self.0).poll_recv(cx)
|
Pin::new(&mut self.0).poll_recv(cx).map(|opt| opt.map(Ok))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -98,7 +98,22 @@ where
|
||||||
{
|
{
|
||||||
/// Produce a new VerifyDigest with a user-provided [`Digestverify`] type
|
/// Produce a new VerifyDigest with a user-provided [`Digestverify`] type
|
||||||
pub fn new(verify_digest: T) -> Self {
|
pub fn new(verify_digest: T) -> Self {
|
||||||
VerifyDigest(true, verify_digest)
|
VerifyDigest(DefaultSpawner, true, verify_digest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, Spawner> VerifyDigest<T, Spawner>
|
||||||
|
where
|
||||||
|
T: DigestVerify + Clone,
|
||||||
|
{
|
||||||
|
/// Set the spawner used for verifying bytes in the request
|
||||||
|
///
|
||||||
|
/// By default this value uses `actix_web::web::block`
|
||||||
|
pub fn spawner<NewSpawner>(self, spawner: NewSpawner) -> VerifyDigest<T, NewSpawner>
|
||||||
|
where
|
||||||
|
NewSpawner: Spawn,
|
||||||
|
{
|
||||||
|
VerifyDigest(spawner, self.1, self.2)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Mark verifying the Digest as optional
|
/// Mark verifying the Digest as optional
|
||||||
|
@ -106,53 +121,68 @@ where
|
||||||
/// If a digest is present in the request, it will be verified, but it is not required to be
|
/// If a digest is present in the request, it will be verified, but it is not required to be
|
||||||
/// present
|
/// present
|
||||||
pub fn optional(self) -> Self {
|
pub fn optional(self) -> Self {
|
||||||
VerifyDigest(false, self.1)
|
VerifyDigest(self.0, false, self.2)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct VerifiedReceiver {
|
||||||
|
rx: Option<oneshot::Receiver<()>>,
|
||||||
|
}
|
||||||
|
|
||||||
impl FromRequest for DigestVerified {
|
impl FromRequest for DigestVerified {
|
||||||
type Error = VerifyError;
|
type Error = VerifyError;
|
||||||
type Future = Ready<Result<Self, Self::Error>>;
|
type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>;
|
||||||
|
|
||||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||||
let res = req
|
let res = req
|
||||||
.extensions()
|
.extensions_mut()
|
||||||
.get::<Self>()
|
.get_mut::<VerifiedReceiver>()
|
||||||
.copied()
|
.and_then(|r| r.rx.take())
|
||||||
.ok_or_else(|| VerifyError::new(&Span::current(), VerifyErrorKind::Extension));
|
.ok_or_else(|| VerifyError::new(&Span::current(), VerifyErrorKind::Extension));
|
||||||
|
|
||||||
if res.is_err() {
|
if res.is_err() {
|
||||||
debug!("Failed to fetch DigestVerified from request");
|
debug!("Failed to fetch DigestVerified from request");
|
||||||
}
|
}
|
||||||
|
|
||||||
ready(res)
|
Box::pin(async move {
|
||||||
|
res?.await
|
||||||
|
.map_err(|_| VerifyError::new(&Span::current(), VerifyErrorKind::Dropped))
|
||||||
|
.map(|()| DigestVerified)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S, B> Transform<S, ServiceRequest> for VerifyDigest<T>
|
impl<T, Spawner, S, B> Transform<S, ServiceRequest> for VerifyDigest<T, Spawner>
|
||||||
where
|
where
|
||||||
T: DigestVerify + Clone + Send + 'static,
|
T: DigestVerify + Clone + Send + 'static,
|
||||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
Spawner: Spawn + Clone + 'static,
|
||||||
{
|
{
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = actix_web::Error;
|
type Error = actix_web::Error;
|
||||||
type Transform = VerifyMiddleware<T, S>;
|
type Transform = VerifyMiddleware<T, Spawner, S>;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||||
|
|
||||||
fn new_transform(&self, service: S) -> Self::Future {
|
fn new_transform(&self, service: S) -> Self::Future {
|
||||||
ready(Ok(VerifyMiddleware(service, self.0, self.1.clone())))
|
ready(Ok(VerifyMiddleware(
|
||||||
|
service,
|
||||||
|
self.0.clone(),
|
||||||
|
self.1,
|
||||||
|
self.2.clone(),
|
||||||
|
)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S, B> Service<ServiceRequest> for VerifyMiddleware<T, S>
|
impl<T, Spawner, S, B> Service<ServiceRequest> for VerifyMiddleware<T, Spawner, S>
|
||||||
where
|
where
|
||||||
T: DigestVerify + Clone + Send + 'static,
|
T: DigestVerify + Clone + Send + 'static,
|
||||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
Spawner: Spawn + Clone + 'static,
|
||||||
{
|
{
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = actix_web::Error;
|
type Error = actix_web::Error;
|
||||||
|
@ -165,7 +195,7 @@ where
|
||||||
fn call(&self, mut req: ServiceRequest) -> Self::Future {
|
fn call(&self, mut req: ServiceRequest) -> Self::Future {
|
||||||
let span = tracing::info_span!(
|
let span = tracing::info_span!(
|
||||||
"Verify digest",
|
"Verify digest",
|
||||||
digest.required = tracing::field::display(&self.1),
|
digest.required = tracing::field::display(&self.2),
|
||||||
);
|
);
|
||||||
|
|
||||||
if let Some(digest) = req.headers().get("Digest") {
|
if let Some(digest) = req.headers().get("Digest") {
|
||||||
|
@ -177,23 +207,24 @@ where
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let spawner = self.1.clone();
|
||||||
|
let digest = self.3.clone();
|
||||||
|
let (verify_tx, verify_rx) = oneshot::channel();
|
||||||
|
|
||||||
let payload = req.take_payload();
|
let payload = req.take_payload();
|
||||||
|
|
||||||
let (tx, rx) = mpsc::channel(1);
|
|
||||||
let f1 = span.in_scope(|| verify_payload(vec, self.2.clone(), payload, tx));
|
|
||||||
|
|
||||||
let payload: Pin<Box<dyn Stream<Item = Result<web::Bytes, PayloadError>> + 'static>> =
|
let payload: Pin<Box<dyn Stream<Item = Result<web::Bytes, PayloadError>> + 'static>> =
|
||||||
Box::pin(RxStream(rx).map(Ok));
|
Box::pin(streem::try_from_fn(|yielder| async move {
|
||||||
|
verify_payload(yielder, spawner, vec, digest, payload, verify_tx).await
|
||||||
|
}));
|
||||||
req.set_payload(payload.into());
|
req.set_payload(payload.into());
|
||||||
req.extensions_mut().insert(DigestVerified);
|
|
||||||
|
|
||||||
let f2 = self.0.call(req);
|
req.extensions_mut().insert(VerifiedReceiver {
|
||||||
|
rx: Some(verify_rx),
|
||||||
|
});
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(self.0.call(req))
|
||||||
let (_, res) = futures_util::future::join(f1, f2).await;
|
} else if self.2 {
|
||||||
res
|
|
||||||
})
|
|
||||||
} else if self.1 {
|
|
||||||
Box::pin(ready(Err(VerifyError::new(
|
Box::pin(ready(Err(VerifyError::new(
|
||||||
&span,
|
&span,
|
||||||
VerifyErrorKind::MissingDigest,
|
VerifyErrorKind::MissingDigest,
|
||||||
|
@ -205,37 +236,79 @@ where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(name = "Verify Payload", skip(verify_digest, payload, tx))]
|
fn canceled_error(error: Canceled) -> PayloadError {
|
||||||
async fn verify_payload<T>(
|
PayloadError::Io(std::io::Error::new(std::io::ErrorKind::Other, error))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verified_error(error: VerifyError) -> PayloadError {
|
||||||
|
PayloadError::Io(std::io::Error::new(std::io::ErrorKind::Other, error))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn verify_payload<T, Spawner>(
|
||||||
|
yielder: Yielder<Result<web::Bytes, PayloadError>>,
|
||||||
|
spawner: Spawner,
|
||||||
vec: Vec<DigestPart>,
|
vec: Vec<DigestPart>,
|
||||||
mut verify_digest: T,
|
mut verify_digest: T,
|
||||||
mut payload: Payload,
|
payload: Payload,
|
||||||
tx: mpsc::Sender<web::Bytes>,
|
verify_tx: oneshot::Sender<()>,
|
||||||
) -> Result<(), actix_web::Error>
|
) -> Result<(), PayloadError>
|
||||||
where
|
where
|
||||||
T: DigestVerify + Clone + Send + 'static,
|
T: DigestVerify + Clone + Send + 'static,
|
||||||
|
Spawner: Spawn,
|
||||||
{
|
{
|
||||||
while let Some(res) = payload.next().await {
|
let mut payload = payload.into_streamer();
|
||||||
let bytes = res?;
|
|
||||||
let bytes2 = bytes.clone();
|
|
||||||
verify_digest = web::block(move || {
|
|
||||||
verify_digest.update(bytes2.as_ref());
|
|
||||||
Ok(verify_digest) as Result<T, VerifyError>
|
|
||||||
})
|
|
||||||
.await??;
|
|
||||||
|
|
||||||
tx.send(bytes)
|
let mut error = None;
|
||||||
.await
|
|
||||||
.map_err(|_| VerifyError::new(&Span::current(), VerifyErrorKind::Dropped))?;
|
while let Some(bytes) = payload.try_next().await? {
|
||||||
|
if error.is_none() {
|
||||||
|
let bytes2 = bytes.clone();
|
||||||
|
let mut verify_digest2 = verify_digest.clone();
|
||||||
|
|
||||||
|
let task = spawner.spawn_blocking(move || {
|
||||||
|
verify_digest2.update(bytes2.as_ref());
|
||||||
|
Ok(verify_digest2) as Result<T, VerifyError>
|
||||||
|
});
|
||||||
|
|
||||||
|
yielder.yield_ok(bytes).await;
|
||||||
|
|
||||||
|
match task.await {
|
||||||
|
Ok(Ok(digest)) => {
|
||||||
|
verify_digest = digest;
|
||||||
|
}
|
||||||
|
Ok(Err(e)) => {
|
||||||
|
error = Some(verified_error(e));
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
error = Some(canceled_error(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
yielder.yield_ok(bytes).await;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let verified =
|
if let Some(error) = error {
|
||||||
web::block(move || Ok(verify_digest.verify(&vec)) as Result<_, VerifyError>).await??;
|
return Err(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
let verified = spawner
|
||||||
|
.spawn_blocking(move || Ok(verify_digest.verify(&vec)) as Result<_, VerifyError>)
|
||||||
|
.await
|
||||||
|
.map_err(canceled_error)?
|
||||||
|
.map_err(verified_error)?;
|
||||||
|
|
||||||
if verified {
|
if verified {
|
||||||
|
if verify_tx.send(()).is_err() {
|
||||||
|
debug!("handler dropped");
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
Err(VerifyError::new(&Span::current(), VerifyErrorKind::Verify).into())
|
Err(verified_error(VerifyError::new(
|
||||||
|
&Span::current(),
|
||||||
|
VerifyErrorKind::Verify,
|
||||||
|
)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -5,6 +5,8 @@
|
||||||
|
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
pub mod middleware;
|
pub mod middleware;
|
||||||
|
#[cfg(feature = "ring")]
|
||||||
|
pub mod ring;
|
||||||
#[cfg(feature = "sha-2")]
|
#[cfg(feature = "sha-2")]
|
||||||
mod sha2;
|
mod sha2;
|
||||||
#[cfg(feature = "sha-3")]
|
#[cfg(feature = "sha-3")]
|
||||||
|
|
198
actix/src/digest/ring.rs
Normal file
198
actix/src/digest/ring.rs
Normal file
|
@ -0,0 +1,198 @@
|
||||||
|
//! Types for creating digests with the `ring` cryptography library
|
||||||
|
|
||||||
|
use crate::digest::DigestName;
|
||||||
|
|
||||||
|
/// A Sha256 digest backed by ring
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Sha256 {
|
||||||
|
ctx: ring::digest::Context,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Sha384 digest backed by ring
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Sha384 {
|
||||||
|
ctx: ring::digest::Context,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Sha512 digest backed by ring
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Sha512 {
|
||||||
|
ctx: ring::digest::Context,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sha256 {
|
||||||
|
/// Create a new empty digest
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract the context
|
||||||
|
pub fn into_inner(self) -> ring::digest::Context {
|
||||||
|
self.ctx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Sha256 {
|
||||||
|
fn default() -> Self {
|
||||||
|
Sha256 {
|
||||||
|
ctx: ring::digest::Context::new(&ring::digest::SHA256),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sha384 {
|
||||||
|
/// Create a new empty digest
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract the context
|
||||||
|
pub fn into_inner(self) -> ring::digest::Context {
|
||||||
|
self.ctx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Sha384 {
|
||||||
|
fn default() -> Self {
|
||||||
|
Sha384 {
|
||||||
|
ctx: ring::digest::Context::new(&ring::digest::SHA384),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sha512 {
|
||||||
|
/// Create a new empty digest
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract the context
|
||||||
|
pub fn into_inner(self) -> ring::digest::Context {
|
||||||
|
self.ctx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Sha512 {
|
||||||
|
fn default() -> Self {
|
||||||
|
Sha512 {
|
||||||
|
ctx: ring::digest::Context::new(&ring::digest::SHA512),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DigestName for Sha256 {
|
||||||
|
const NAME: &'static str = "SHA-256";
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DigestName for Sha384 {
|
||||||
|
const NAME: &'static str = "SHA-384";
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DigestName for Sha512 {
|
||||||
|
const NAME: &'static str = "SHA-512";
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "client")]
|
||||||
|
mod client {
|
||||||
|
use super::*;
|
||||||
|
use crate::digest::DigestCreate;
|
||||||
|
use base64::prelude::*;
|
||||||
|
|
||||||
|
fn create(mut context: ring::digest::Context, input: &[u8]) -> String {
|
||||||
|
context.update(input);
|
||||||
|
let digest = context.finish();
|
||||||
|
BASE64_STANDARD.encode(digest.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DigestCreate for Sha256 {
|
||||||
|
fn compute(&mut self, input: &[u8]) -> String {
|
||||||
|
create(self.ctx.clone(), input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DigestCreate for Sha384 {
|
||||||
|
fn compute(&mut self, input: &[u8]) -> String {
|
||||||
|
create(self.ctx.clone(), input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DigestCreate for Sha512 {
|
||||||
|
fn compute(&mut self, input: &[u8]) -> String {
|
||||||
|
create(self.ctx.clone(), input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "server")]
|
||||||
|
mod server {
|
||||||
|
use super::*;
|
||||||
|
use crate::digest::{DigestPart, DigestVerify};
|
||||||
|
use base64::prelude::*;
|
||||||
|
use tracing::{debug, warn};
|
||||||
|
|
||||||
|
fn verify(context: ring::digest::Context, name: &str, parts: &[DigestPart]) -> bool {
|
||||||
|
if let Some(part) = parts
|
||||||
|
.iter()
|
||||||
|
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
|
||||||
|
{
|
||||||
|
debug!("Verifying digest type, {}", name);
|
||||||
|
let digest = context.finish();
|
||||||
|
let encoded = BASE64_STANDARD.encode(digest.as_ref());
|
||||||
|
|
||||||
|
return part.digest == encoded;
|
||||||
|
}
|
||||||
|
warn!("No matching digest algorithm found for {}", name);
|
||||||
|
warn!(
|
||||||
|
"Provided: [{}]",
|
||||||
|
parts.iter().fold(String::new(), |mut acc, item| {
|
||||||
|
if acc.is_empty() {
|
||||||
|
} else {
|
||||||
|
acc.push_str(", ");
|
||||||
|
}
|
||||||
|
acc.push_str(&item.algorithm);
|
||||||
|
acc
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DigestVerify for Sha256 {
|
||||||
|
fn update(&mut self, part: &[u8]) {
|
||||||
|
self.ctx.update(part);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||||
|
let alg = self.ctx.algorithm();
|
||||||
|
let ctx = std::mem::replace(&mut self.ctx, ring::digest::Context::new(alg));
|
||||||
|
|
||||||
|
verify(ctx, Self::NAME, parts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DigestVerify for Sha384 {
|
||||||
|
fn update(&mut self, part: &[u8]) {
|
||||||
|
self.ctx.update(part);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||||
|
let alg = self.ctx.algorithm();
|
||||||
|
let ctx = std::mem::replace(&mut self.ctx, ring::digest::Context::new(alg));
|
||||||
|
|
||||||
|
verify(ctx, Self::NAME, parts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DigestVerify for Sha512 {
|
||||||
|
fn update(&mut self, part: &[u8]) {
|
||||||
|
self.ctx.update(part);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify(&mut self, parts: &[DigestPart]) -> bool {
|
||||||
|
let alg = self.ctx.algorithm();
|
||||||
|
let ctx = std::mem::replace(&mut self.ctx, ring::digest::Context::new(alg));
|
||||||
|
|
||||||
|
verify(ctx, Self::NAME, parts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -21,13 +21,14 @@ impl DigestName for Sha512 {
|
||||||
mod client {
|
mod client {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::digest::DigestCreate;
|
use crate::digest::DigestCreate;
|
||||||
|
use base64::prelude::*;
|
||||||
|
|
||||||
fn create<D: sha2::Digest + sha2::digest::FixedOutputReset>(
|
fn create<D: sha2::Digest + sha2::digest::FixedOutputReset>(
|
||||||
digest: &mut D,
|
digest: &mut D,
|
||||||
input: &[u8],
|
input: &[u8],
|
||||||
) -> String {
|
) -> String {
|
||||||
sha2::Digest::update(digest, input);
|
sha2::Digest::update(digest, input);
|
||||||
base64::encode(&digest.finalize_reset())
|
BASE64_STANDARD.encode(&digest.finalize_reset())
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DigestCreate for Sha224 {
|
impl DigestCreate for Sha224 {
|
||||||
|
@ -59,6 +60,7 @@ mod client {
|
||||||
mod server {
|
mod server {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::digest::{DigestPart, DigestVerify};
|
use crate::digest::{DigestPart, DigestVerify};
|
||||||
|
use base64::prelude::*;
|
||||||
use tracing::{debug, warn};
|
use tracing::{debug, warn};
|
||||||
|
|
||||||
fn verify<D: sha2::Digest + sha2::digest::FixedOutputReset>(
|
fn verify<D: sha2::Digest + sha2::digest::FixedOutputReset>(
|
||||||
|
@ -71,7 +73,7 @@ mod server {
|
||||||
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
|
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
|
||||||
{
|
{
|
||||||
debug!("Verifying digest type, {}", name);
|
debug!("Verifying digest type, {}", name);
|
||||||
let encoded = base64::encode(&digest.finalize_reset());
|
let encoded = BASE64_STANDARD.encode(&digest.finalize_reset());
|
||||||
|
|
||||||
return part.digest == encoded;
|
return part.digest == encoded;
|
||||||
}
|
}
|
||||||
|
|
|
@ -40,17 +40,18 @@ impl DigestName for Sha3_512 {
|
||||||
const NAME: &'static str = "SHA3-512";
|
const NAME: &'static str = "SHA3-512";
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(features = "client")]
|
#[cfg(feature = "client")]
|
||||||
mod client {
|
mod client {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::digest::DigestCreate;
|
use crate::digest::DigestCreate;
|
||||||
|
use base64::prelude::*;
|
||||||
|
|
||||||
fn create<D: sha3::Digest + sha3::digest::FixedOutputReset>(
|
fn create<D: sha3::Digest + sha3::digest::FixedOutputReset>(
|
||||||
digest: &mut D,
|
digest: &mut D,
|
||||||
input: &[u8],
|
input: &[u8],
|
||||||
) -> String {
|
) -> String {
|
||||||
digest.update(input);
|
sha3::Digest::update(digest, input);
|
||||||
base64::encode(&digest.finalize_reset())
|
BASE64_STANDARD.encode(&digest.finalize_reset())
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DigestCreate for Sha3_224 {
|
impl DigestCreate for Sha3_224 {
|
||||||
|
@ -112,6 +113,7 @@ mod client {
|
||||||
mod server {
|
mod server {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::digest::{DigestPart, DigestVerify};
|
use crate::digest::{DigestPart, DigestVerify};
|
||||||
|
use base64::prelude::*;
|
||||||
use tracing::{debug, warn};
|
use tracing::{debug, warn};
|
||||||
|
|
||||||
fn verify<D: sha3::Digest + sha3::digest::FixedOutputReset>(
|
fn verify<D: sha3::Digest + sha3::digest::FixedOutputReset>(
|
||||||
|
@ -124,7 +126,7 @@ mod server {
|
||||||
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
|
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
|
||||||
{
|
{
|
||||||
debug!("Verifying digest type, {}", name);
|
debug!("Verifying digest type, {}", name);
|
||||||
let encoded = base64::encode(&digest.finalize_reset());
|
let encoded = BASE64_STANDARD.encode(&digest.finalize_reset());
|
||||||
|
|
||||||
return part.digest == encoded;
|
return part.digest == encoded;
|
||||||
}
|
}
|
||||||
|
|
132
actix/src/lib.rs
132
actix/src/lib.rs
|
@ -257,7 +257,7 @@ pub mod verify {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "client")]
|
#[cfg(feature = "client")]
|
||||||
pub use self::client::{Canceled, PrepareSignError, Sign, Spawn};
|
pub use self::client::{PrepareSignError, Sign};
|
||||||
|
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
pub use self::server::{PrepareVerifyError, SignatureVerify};
|
pub use self::server::{PrepareVerifyError, SignatureVerify};
|
||||||
|
@ -285,9 +285,68 @@ pub struct Config<Spawner = DefaultSpawner> {
|
||||||
#[derive(Clone, Copy, Debug, Default)]
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
pub struct DefaultSpawner;
|
pub struct DefaultSpawner;
|
||||||
|
|
||||||
|
/// An error that indicates a blocking operation panicked and cannot return a response
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Canceled;
|
||||||
|
|
||||||
|
impl std::fmt::Display for Canceled {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "Operation was canceled")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for Canceled {}
|
||||||
|
|
||||||
|
/// A trait dictating how to spawn a future onto a blocking threadpool. By default,
|
||||||
|
/// http-signature-normalization-actix will use actix_rt's built-in blocking threadpool, but this
|
||||||
|
/// can be customized
|
||||||
|
pub trait Spawn {
|
||||||
|
/// The future type returned by spawn_blocking
|
||||||
|
type Future<T>: std::future::Future<Output = Result<T, Canceled>>;
|
||||||
|
|
||||||
|
/// Spawn the blocking function onto the threadpool
|
||||||
|
fn spawn_blocking<Func, Out>(&self, func: Func) -> Self::Future<Out>
|
||||||
|
where
|
||||||
|
Func: FnOnce() -> Out + Send + 'static,
|
||||||
|
Out: Send + 'static;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The future returned by DefaultSpawner when spawning blocking operations on the actix_rt
|
||||||
|
/// blocking threadpool
|
||||||
|
pub struct DefaultSpawnerFuture<Out> {
|
||||||
|
inner: actix_rt::task::JoinHandle<Out>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Spawn for DefaultSpawner {
|
||||||
|
type Future<T> = DefaultSpawnerFuture<T>;
|
||||||
|
|
||||||
|
fn spawn_blocking<Func, Out>(&self, func: Func) -> Self::Future<Out>
|
||||||
|
where
|
||||||
|
Func: FnOnce() -> Out + Send + 'static,
|
||||||
|
Out: Send + 'static,
|
||||||
|
{
|
||||||
|
DefaultSpawnerFuture {
|
||||||
|
inner: actix_rt::task::spawn_blocking(func),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Out> std::future::Future for DefaultSpawnerFuture<Out> {
|
||||||
|
type Output = Result<Out, Canceled>;
|
||||||
|
|
||||||
|
fn poll(
|
||||||
|
mut self: std::pin::Pin<&mut Self>,
|
||||||
|
cx: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Self::Output> {
|
||||||
|
let res = std::task::ready!(std::pin::Pin::new(&mut self.inner).poll(cx));
|
||||||
|
|
||||||
|
std::task::Poll::Ready(res.map_err(|_| Canceled))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(feature = "client")]
|
#[cfg(feature = "client")]
|
||||||
mod client {
|
mod client {
|
||||||
use super::{Config, DefaultSpawner, RequiredError};
|
use super::{Config, RequiredError, Spawn};
|
||||||
use actix_http::header::{InvalidHeaderValue, ToStrError};
|
use actix_http::header::{InvalidHeaderValue, ToStrError};
|
||||||
use actix_rt::task::JoinError;
|
use actix_rt::task::JoinError;
|
||||||
use std::{fmt::Display, future::Future, pin::Pin};
|
use std::{fmt::Display, future::Future, pin::Pin};
|
||||||
|
@ -354,65 +413,6 @@ mod client {
|
||||||
/// Invalid Date header
|
/// Invalid Date header
|
||||||
InvalidHeader(#[from] actix_http::header::InvalidHeaderValue),
|
InvalidHeader(#[from] actix_http::header::InvalidHeaderValue),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An error that indicates a blocking operation panicked and cannot return a response
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Canceled;
|
|
||||||
|
|
||||||
impl std::fmt::Display for Canceled {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
write!(f, "Operation was canceled")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for Canceled {}
|
|
||||||
|
|
||||||
/// A trait dictating how to spawn a future onto a blocking threadpool. By default,
|
|
||||||
/// http-signature-normalization-actix will use actix_rt's built-in blocking threadpool, but this
|
|
||||||
/// can be customized
|
|
||||||
pub trait Spawn {
|
|
||||||
/// The future type returned by spawn_blocking
|
|
||||||
type Future<T>: std::future::Future<Output = Result<T, Canceled>>;
|
|
||||||
|
|
||||||
/// Spawn the blocking function onto the threadpool
|
|
||||||
fn spawn_blocking<Func, Out>(&self, func: Func) -> Self::Future<Out>
|
|
||||||
where
|
|
||||||
Func: FnOnce() -> Out + Send + 'static,
|
|
||||||
Out: Send + 'static;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The future returned by DefaultSpawner when spawning blocking operations on the actix_rt
|
|
||||||
/// blocking threadpool
|
|
||||||
pub struct DefaultSpawnerFuture<Out> {
|
|
||||||
inner: actix_rt::task::JoinHandle<Out>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Spawn for DefaultSpawner {
|
|
||||||
type Future<T> = DefaultSpawnerFuture<T>;
|
|
||||||
|
|
||||||
fn spawn_blocking<Func, Out>(&self, func: Func) -> Self::Future<Out>
|
|
||||||
where
|
|
||||||
Func: FnOnce() -> Out + Send + 'static,
|
|
||||||
Out: Send + 'static,
|
|
||||||
{
|
|
||||||
DefaultSpawnerFuture {
|
|
||||||
inner: actix_rt::task::spawn_blocking(func),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Out> std::future::Future for DefaultSpawnerFuture<Out> {
|
|
||||||
type Output = Result<Out, Canceled>;
|
|
||||||
|
|
||||||
fn poll(
|
|
||||||
mut self: std::pin::Pin<&mut Self>,
|
|
||||||
cx: &mut std::task::Context<'_>,
|
|
||||||
) -> std::task::Poll<Self::Output> {
|
|
||||||
let res = std::task::ready!(std::pin::Pin::new(&mut self.inner).poll(cx));
|
|
||||||
|
|
||||||
std::task::Poll::Ready(res.map_err(|_| Canceled))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "server")]
|
#[cfg(feature = "server")]
|
||||||
|
@ -485,6 +485,16 @@ mod server {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl actix_web::ResponseError for super::Canceled {
|
||||||
|
fn status_code(&self) -> actix_http::StatusCode {
|
||||||
|
actix_http::StatusCode::INTERNAL_SERVER_ERROR
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error_response(&self) -> actix_web::HttpResponse<actix_http::body::BoxBody> {
|
||||||
|
actix_web::HttpResponse::new(self.status_code())
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
|
|
|
@ -1,13 +1,13 @@
|
||||||
//! Types for verifying requests with Actix Web
|
//! Types for verifying requests with Actix Web
|
||||||
|
|
||||||
use crate::{Config, PrepareVerifyError, SignatureVerify};
|
use crate::{Config, PrepareVerifyError, SignatureVerify, Spawn};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
body::MessageBody,
|
body::MessageBody,
|
||||||
dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform},
|
dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform},
|
||||||
http::StatusCode,
|
http::StatusCode,
|
||||||
Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, ResponseError,
|
Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, ResponseError,
|
||||||
};
|
};
|
||||||
use futures_util::future::LocalBoxFuture;
|
use futures_core::future::LocalBoxFuture;
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashSet,
|
collections::HashSet,
|
||||||
future::{ready, Ready},
|
future::{ready, Ready},
|
||||||
|
@ -45,11 +45,11 @@ impl SignatureVerified {
|
||||||
/// .route("/unprotected", web::post().to(|| "No verification required"))
|
/// .route("/unprotected", web::post().to(|| "No verification required"))
|
||||||
/// })
|
/// })
|
||||||
/// ```
|
/// ```
|
||||||
pub struct VerifySignature<T>(T, Config, HeaderKind);
|
pub struct VerifySignature<T, Spawner>(T, Config<Spawner>, HeaderKind);
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct VerifyMiddleware<T, S>(Rc<S>, Config, HeaderKind, T);
|
pub struct VerifyMiddleware<T, Spawner, S>(Rc<S>, Config<Spawner>, HeaderKind, T);
|
||||||
|
|
||||||
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||||
enum HeaderKind {
|
enum HeaderKind {
|
||||||
|
@ -126,7 +126,7 @@ impl VerifyError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> VerifySignature<T>
|
impl<T, Spawner> VerifySignature<T, Spawner>
|
||||||
where
|
where
|
||||||
T: SignatureVerify,
|
T: SignatureVerify,
|
||||||
{
|
{
|
||||||
|
@ -135,7 +135,10 @@ where
|
||||||
///
|
///
|
||||||
/// By default, this middleware expects to verify Signature headers, and requires the presence
|
/// By default, this middleware expects to verify Signature headers, and requires the presence
|
||||||
/// of the header
|
/// of the header
|
||||||
pub fn new(verify_signature: T, config: Config) -> Self {
|
pub fn new(verify_signature: T, config: Config<Spawner>) -> Self
|
||||||
|
where
|
||||||
|
Spawner: Spawn,
|
||||||
|
{
|
||||||
VerifySignature(verify_signature, config, HeaderKind::Signature)
|
VerifySignature(verify_signature, config, HeaderKind::Signature)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -145,7 +148,7 @@ where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S, B> VerifyMiddleware<T, S>
|
impl<T, Spawner, S, B> VerifyMiddleware<T, Spawner, S>
|
||||||
where
|
where
|
||||||
T: SignatureVerify + Clone + 'static,
|
T: SignatureVerify + Clone + 'static,
|
||||||
T::Future: 'static,
|
T::Future: 'static,
|
||||||
|
@ -257,16 +260,17 @@ impl FromRequest for SignatureVerified {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S, B> Transform<S, ServiceRequest> for VerifySignature<T>
|
impl<T, Spawner, S, B> Transform<S, ServiceRequest> for VerifySignature<T, Spawner>
|
||||||
where
|
where
|
||||||
T: SignatureVerify + Clone + 'static,
|
T: SignatureVerify + Clone + 'static,
|
||||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
|
Spawner: Clone,
|
||||||
{
|
{
|
||||||
type Response = ServiceResponse<B>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = actix_web::Error;
|
type Error = actix_web::Error;
|
||||||
type Transform = VerifyMiddleware<T, S>;
|
type Transform = VerifyMiddleware<T, Spawner, S>;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||||
|
|
||||||
|
@ -280,7 +284,7 @@ where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, S, B> Service<ServiceRequest> for VerifyMiddleware<T, S>
|
impl<T, Spawner, S, B> Service<ServiceRequest> for VerifyMiddleware<T, Spawner, S>
|
||||||
where
|
where
|
||||||
T: SignatureVerify + Clone + 'static,
|
T: SignatureVerify + Clone + 'static,
|
||||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
|
||||||
|
|
12
flake.lock
12
flake.lock
|
@ -5,11 +5,11 @@
|
||||||
"systems": "systems"
|
"systems": "systems"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1689068808,
|
"lastModified": 1694529238,
|
||||||
"narHash": "sha256-6ixXo3wt24N/melDWjq70UuHQLxGV8jZvooRanIHXw0=",
|
"narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
|
||||||
"owner": "numtide",
|
"owner": "numtide",
|
||||||
"repo": "flake-utils",
|
"repo": "flake-utils",
|
||||||
"rev": "919d646de7be200f3bf08cb76ae1f09402b6f9b4",
|
"rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
@ -20,11 +20,11 @@
|
||||||
},
|
},
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1690272529,
|
"lastModified": 1700794826,
|
||||||
"narHash": "sha256-MakzcKXEdv/I4qJUtq/k/eG+rVmyOZLnYNC2w1mB59Y=",
|
"narHash": "sha256-RyJTnTNKhO0yqRpDISk03I/4A67/dp96YRxc86YOPgU=",
|
||||||
"owner": "NixOS",
|
"owner": "NixOS",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "ef99fa5c5ed624460217c31ac4271cfb5cb2502c",
|
"rev": "5a09cb4b393d58f9ed0d9ca1555016a8543c2ac8",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
[package]
|
[package]
|
||||||
name = "http-signature-normalization-reqwest"
|
name = "http-signature-normalization-reqwest"
|
||||||
description = "An HTTP Signatures library that leaves the signing to you"
|
description = "An HTTP Signatures library that leaves the signing to you"
|
||||||
version = "0.9.0"
|
version = "0.12.0"
|
||||||
authors = ["asonix <asonix@asonix.dog>"]
|
authors = ["asonix <asonix@asonix.dog>"]
|
||||||
license = "AGPL-3.0"
|
license = "AGPL-3.0"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
|
@ -11,23 +11,26 @@ edition = "2021"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
[features]
|
[features]
|
||||||
default = ["sha-2", "sha-3"]
|
default = ["sha-2", "default-spawner"]
|
||||||
middleware = ["reqwest-middleware"]
|
middleware = ["dep:reqwest-middleware"]
|
||||||
digest = ["base64", "tokio"]
|
default-spawner = ["dep:tokio"]
|
||||||
sha-2 = ["digest", "sha2"]
|
digest = ["dep:base64"]
|
||||||
sha-3 = ["digest", "sha3"]
|
ring = ["digest", "dep:ring"]
|
||||||
|
sha-2 = ["digest", "dep:sha2"]
|
||||||
|
sha-3 = ["digest", "dep:sha3"]
|
||||||
|
|
||||||
[[example]]
|
[[example]]
|
||||||
name = "client"
|
name = "client"
|
||||||
required-features = ["sha-2"]
|
required-features = ["default-spawner", "ring"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-trait = "0.1.71"
|
async-trait = "0.1.71"
|
||||||
base64 = { version = "0.13", optional = true }
|
base64 = { version = "0.22", optional = true }
|
||||||
http-signature-normalization = { version = "0.7.0", path = ".." }
|
http-signature-normalization = { version = "0.7.0", path = ".." }
|
||||||
httpdate = "1.0.2"
|
httpdate = "1.0.2"
|
||||||
reqwest = { version = "0.11", default-features = false, features = ["json"] }
|
reqwest = { version = "0.12", default-features = false, features = ["json"] }
|
||||||
reqwest-middleware = { version = "0.2.0", optional = true }
|
reqwest-middleware = { version = "0.3.0", optional = true }
|
||||||
|
ring = { version = "0.17.5", optional = true }
|
||||||
sha2 = { version = "0.10", optional = true }
|
sha2 = { version = "0.10", optional = true }
|
||||||
sha3 = { version = "0.10", optional = true }
|
sha3 = { version = "0.10", optional = true }
|
||||||
thiserror = "1.0"
|
thiserror = "1.0"
|
||||||
|
@ -36,7 +39,7 @@ tokio = { version = "1", default-features = false, features = [
|
||||||
], optional = true }
|
], optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
pretty_env_logger = "0.4"
|
pretty_env_logger = "0.5"
|
||||||
tokio = { version = "1", default-features = false, features = [
|
tokio = { version = "1", default-features = false, features = [
|
||||||
"rt-multi-thread",
|
"rt-multi-thread",
|
||||||
"macros",
|
"macros",
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
use http_signature_normalization_reqwest::prelude::*;
|
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||||
|
use http_signature_normalization_reqwest::{digest::ring::Sha256, prelude::*};
|
||||||
use reqwest::{
|
use reqwest::{
|
||||||
header::{ACCEPT, USER_AGENT},
|
header::{ACCEPT, USER_AGENT},
|
||||||
Client,
|
Client,
|
||||||
};
|
};
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
|
|
||||||
async fn request(config: Config) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
async fn request(config: Config) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||||
let digest = Sha256::new();
|
let digest = Sha256::new();
|
||||||
|
@ -16,7 +16,7 @@ async fn request(config: Config) -> Result<(), Box<dyn std::error::Error + Send
|
||||||
.header(ACCEPT, "text/plain")
|
.header(ACCEPT, "text/plain")
|
||||||
.signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
|
.signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
|
||||||
println!("Signing String\n{}", s);
|
println!("Signing String\n{}", s);
|
||||||
Ok(base64::encode(s)) as Result<_, MyError>
|
Ok(STANDARD.encode(s)) as Result<_, MyError>
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
|
|
@ -1,7 +1,9 @@
|
||||||
use crate::{Config, Sign, SignError};
|
use crate::{Config, Sign, SignError, Spawn};
|
||||||
use reqwest::{Body, Request, RequestBuilder};
|
use reqwest::{Body, Request, RequestBuilder};
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
|
#[cfg(feature = "ring")]
|
||||||
|
pub mod ring;
|
||||||
#[cfg(feature = "sha-2")]
|
#[cfg(feature = "sha-2")]
|
||||||
mod sha2;
|
mod sha2;
|
||||||
#[cfg(feature = "sha-3")]
|
#[cfg(feature = "sha-3")]
|
||||||
|
@ -23,9 +25,9 @@ pub trait DigestCreate {
|
||||||
/// a malicious entity
|
/// a malicious entity
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
pub trait SignExt: Sign {
|
pub trait SignExt: Sign {
|
||||||
async fn authorization_signature_with_digest<F, E, K, D, V>(
|
async fn authorization_signature_with_digest<F, E, K, S, D, V>(
|
||||||
self,
|
self,
|
||||||
config: Config,
|
config: Config<S>,
|
||||||
key_id: K,
|
key_id: K,
|
||||||
digest: D,
|
digest: D,
|
||||||
v: V,
|
v: V,
|
||||||
|
@ -37,11 +39,12 @@ pub trait SignExt: Sign {
|
||||||
K: Display + Send + 'static,
|
K: Display + Send + 'static,
|
||||||
D: DigestCreate + Send + 'static,
|
D: DigestCreate + Send + 'static,
|
||||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||||
|
S: Spawn + Send + Sync,
|
||||||
Self: Sized;
|
Self: Sized;
|
||||||
|
|
||||||
async fn signature_with_digest<F, E, K, D, V>(
|
async fn signature_with_digest<F, E, K, S, D, V>(
|
||||||
self,
|
self,
|
||||||
config: Config,
|
config: Config<S>,
|
||||||
key_id: K,
|
key_id: K,
|
||||||
digest: D,
|
digest: D,
|
||||||
v: V,
|
v: V,
|
||||||
|
@ -53,14 +56,15 @@ pub trait SignExt: Sign {
|
||||||
K: Display + Send + 'static,
|
K: Display + Send + 'static,
|
||||||
D: DigestCreate + Send + 'static,
|
D: DigestCreate + Send + 'static,
|
||||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||||
|
S: Spawn + Send + Sync,
|
||||||
Self: Sized;
|
Self: Sized;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SignExt for RequestBuilder {
|
impl SignExt for RequestBuilder {
|
||||||
async fn authorization_signature_with_digest<F, E, K, D, V>(
|
async fn authorization_signature_with_digest<F, E, K, S, D, V>(
|
||||||
self,
|
self,
|
||||||
config: Config,
|
config: Config<S>,
|
||||||
key_id: K,
|
key_id: K,
|
||||||
mut digest: D,
|
mut digest: D,
|
||||||
v: V,
|
v: V,
|
||||||
|
@ -72,13 +76,16 @@ impl SignExt for RequestBuilder {
|
||||||
K: Display + Send + 'static,
|
K: Display + Send + 'static,
|
||||||
D: DigestCreate + Send + 'static,
|
D: DigestCreate + Send + 'static,
|
||||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||||
|
S: Spawn + Send + Sync,
|
||||||
{
|
{
|
||||||
let (v, digest) = tokio::task::spawn_blocking(move || {
|
let (v, digest) = config
|
||||||
let digest = digest.compute(v.as_ref());
|
.spawner
|
||||||
(v, digest)
|
.spawn_blocking(move || {
|
||||||
})
|
let digest = digest.compute(v.as_ref());
|
||||||
.await
|
(v, digest)
|
||||||
.map_err(|_| SignError::Canceled)?;
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| SignError::Canceled)?;
|
||||||
|
|
||||||
let mut req = self
|
let mut req = self
|
||||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||||
|
@ -90,9 +97,9 @@ impl SignExt for RequestBuilder {
|
||||||
Ok(req)
|
Ok(req)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn signature_with_digest<F, E, K, D, V>(
|
async fn signature_with_digest<F, E, K, S, D, V>(
|
||||||
self,
|
self,
|
||||||
config: Config,
|
config: Config<S>,
|
||||||
key_id: K,
|
key_id: K,
|
||||||
mut digest: D,
|
mut digest: D,
|
||||||
v: V,
|
v: V,
|
||||||
|
@ -104,13 +111,16 @@ impl SignExt for RequestBuilder {
|
||||||
K: Display + Send + 'static,
|
K: Display + Send + 'static,
|
||||||
D: DigestCreate + Send + 'static,
|
D: DigestCreate + Send + 'static,
|
||||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||||
|
S: Spawn + Send + Sync,
|
||||||
{
|
{
|
||||||
let (v, digest) = tokio::task::spawn_blocking(move || {
|
let (v, digest) = config
|
||||||
let digest = digest.compute(v.as_ref());
|
.spawner
|
||||||
(v, digest)
|
.spawn_blocking(move || {
|
||||||
})
|
let digest = digest.compute(v.as_ref());
|
||||||
.await
|
(v, digest)
|
||||||
.map_err(|_| SignError::Canceled)?;
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| SignError::Canceled)?;
|
||||||
|
|
||||||
let mut req = self
|
let mut req = self
|
||||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||||
|
@ -125,16 +135,16 @@ impl SignExt for RequestBuilder {
|
||||||
|
|
||||||
#[cfg(feature = "middleware")]
|
#[cfg(feature = "middleware")]
|
||||||
mod middleware {
|
mod middleware {
|
||||||
use super::{Config, DigestCreate, Sign, SignError, SignExt};
|
use super::{Config, DigestCreate, Sign, SignError, SignExt, Spawn};
|
||||||
use reqwest::{Body, Request};
|
use reqwest::{Body, Request};
|
||||||
use reqwest_middleware::RequestBuilder;
|
use reqwest_middleware::RequestBuilder;
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SignExt for RequestBuilder {
|
impl SignExt for RequestBuilder {
|
||||||
async fn authorization_signature_with_digest<F, E, K, D, V>(
|
async fn authorization_signature_with_digest<F, E, K, S, D, V>(
|
||||||
self,
|
self,
|
||||||
config: Config,
|
config: Config<S>,
|
||||||
key_id: K,
|
key_id: K,
|
||||||
mut digest: D,
|
mut digest: D,
|
||||||
v: V,
|
v: V,
|
||||||
|
@ -146,14 +156,17 @@ mod middleware {
|
||||||
K: Display + Send + 'static,
|
K: Display + Send + 'static,
|
||||||
D: DigestCreate + Send + 'static,
|
D: DigestCreate + Send + 'static,
|
||||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||||
|
S: Spawn + Send + Sync,
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
{
|
{
|
||||||
let (v, digest) = tokio::task::spawn_blocking(move || {
|
let (v, digest) = config
|
||||||
let digest = digest.compute(v.as_ref());
|
.spawner
|
||||||
(v, digest)
|
.spawn_blocking(move || {
|
||||||
})
|
let digest = digest.compute(v.as_ref());
|
||||||
.await
|
(v, digest)
|
||||||
.map_err(|_| SignError::Canceled)?;
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| SignError::Canceled)?;
|
||||||
|
|
||||||
let mut req = self
|
let mut req = self
|
||||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||||
|
@ -165,9 +178,9 @@ mod middleware {
|
||||||
Ok(req)
|
Ok(req)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn signature_with_digest<F, E, K, D, V>(
|
async fn signature_with_digest<F, E, K, S, D, V>(
|
||||||
self,
|
self,
|
||||||
config: Config,
|
config: Config<S>,
|
||||||
key_id: K,
|
key_id: K,
|
||||||
mut digest: D,
|
mut digest: D,
|
||||||
v: V,
|
v: V,
|
||||||
|
@ -179,14 +192,17 @@ mod middleware {
|
||||||
K: Display + Send + 'static,
|
K: Display + Send + 'static,
|
||||||
D: DigestCreate + Send + 'static,
|
D: DigestCreate + Send + 'static,
|
||||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||||
|
S: Spawn + Send + Sync,
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
{
|
{
|
||||||
let (v, digest) = tokio::task::spawn_blocking(move || {
|
let (v, digest) = config
|
||||||
let digest = digest.compute(v.as_ref());
|
.spawner
|
||||||
(v, digest)
|
.spawn_blocking(move || {
|
||||||
})
|
let digest = digest.compute(v.as_ref());
|
||||||
.await
|
(v, digest)
|
||||||
.map_err(|_| SignError::Canceled)?;
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|_| SignError::Canceled)?;
|
||||||
|
|
||||||
let mut req = self
|
let mut req = self
|
||||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||||
|
|
113
reqwest/src/digest/ring.rs
Normal file
113
reqwest/src/digest/ring.rs
Normal file
|
@ -0,0 +1,113 @@
|
||||||
|
//! Types for creating digests with the `ring` cryptography library
|
||||||
|
|
||||||
|
use super::DigestCreate;
|
||||||
|
|
||||||
|
/// A Sha256 digest backed by ring
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Sha256 {
|
||||||
|
ctx: ring::digest::Context,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Sha384 digest backed by ring
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Sha384 {
|
||||||
|
ctx: ring::digest::Context,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Sha512 digest backed by ring
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Sha512 {
|
||||||
|
ctx: ring::digest::Context,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sha256 {
|
||||||
|
/// Create a new empty digest
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract the context
|
||||||
|
pub fn into_inner(self) -> ring::digest::Context {
|
||||||
|
self.ctx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Sha256 {
|
||||||
|
fn default() -> Self {
|
||||||
|
Sha256 {
|
||||||
|
ctx: ring::digest::Context::new(&ring::digest::SHA256),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sha384 {
|
||||||
|
/// Create a new empty digest
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract the context
|
||||||
|
pub fn into_inner(self) -> ring::digest::Context {
|
||||||
|
self.ctx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Sha384 {
|
||||||
|
fn default() -> Self {
|
||||||
|
Sha384 {
|
||||||
|
ctx: ring::digest::Context::new(&ring::digest::SHA384),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sha512 {
|
||||||
|
/// Create a new empty digest
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract the context
|
||||||
|
pub fn into_inner(self) -> ring::digest::Context {
|
||||||
|
self.ctx
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Sha512 {
|
||||||
|
fn default() -> Self {
|
||||||
|
Sha512 {
|
||||||
|
ctx: ring::digest::Context::new(&ring::digest::SHA512),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create(mut context: ring::digest::Context, input: &[u8]) -> String {
|
||||||
|
use base64::prelude::*;
|
||||||
|
|
||||||
|
context.update(input);
|
||||||
|
let digest = context.finish();
|
||||||
|
BASE64_STANDARD.encode(digest.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DigestCreate for Sha256 {
|
||||||
|
const NAME: &'static str = "SHA-256";
|
||||||
|
|
||||||
|
fn compute(&mut self, input: &[u8]) -> String {
|
||||||
|
create(self.ctx.clone(), input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DigestCreate for Sha384 {
|
||||||
|
const NAME: &'static str = "SHA-384";
|
||||||
|
|
||||||
|
fn compute(&mut self, input: &[u8]) -> String {
|
||||||
|
create(self.ctx.clone(), input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DigestCreate for Sha512 {
|
||||||
|
const NAME: &'static str = "SHA-512";
|
||||||
|
|
||||||
|
fn compute(&mut self, input: &[u8]) -> String {
|
||||||
|
create(self.ctx.clone(), input)
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,3 +1,4 @@
|
||||||
|
use base64::prelude::*;
|
||||||
use sha2::{Sha224, Sha256, Sha384, Sha512};
|
use sha2::{Sha224, Sha256, Sha384, Sha512};
|
||||||
|
|
||||||
use super::DigestCreate;
|
use super::DigestCreate;
|
||||||
|
@ -7,7 +8,7 @@ fn create<D: sha2::Digest + sha2::digest::FixedOutputReset>(
|
||||||
input: &[u8],
|
input: &[u8],
|
||||||
) -> String {
|
) -> String {
|
||||||
sha2::Digest::update(digest, input);
|
sha2::Digest::update(digest, input);
|
||||||
base64::encode(&digest.finalize_reset())
|
BASE64_STANDARD.encode(&digest.finalize_reset())
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DigestCreate for Sha224 {
|
impl DigestCreate for Sha224 {
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
|
use base64::prelude::*;
|
||||||
use sha3::{
|
use sha3::{
|
||||||
Keccak224, Keccak256, Keccak256Full, Keccak384, Keccak512, Sha3_224, Sha3_256, Sha3_384,
|
Keccak224, Keccak256, Keccak256Full, Keccak384, Keccak512, Sha3_224, Sha3_256, Sha3_384,
|
||||||
Sha3_512,
|
Sha3_512,
|
||||||
|
@ -10,7 +11,7 @@ fn create<D: sha3::Digest + sha3::digest::FixedOutputReset>(
|
||||||
input: &[u8],
|
input: &[u8],
|
||||||
) -> String {
|
) -> String {
|
||||||
sha3::Digest::update(digest, input);
|
sha3::Digest::update(digest, input);
|
||||||
base64::encode(&digest.finalize_reset())
|
BASE64_STANDARD.encode(&digest.finalize_reset())
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DigestCreate for Sha3_224 {
|
impl DigestCreate for Sha3_224 {
|
||||||
|
|
|
@ -18,16 +18,23 @@ pub mod digest;
|
||||||
pub mod prelude {
|
pub mod prelude {
|
||||||
pub use crate::{Config, Sign, SignError};
|
pub use crate::{Config, Sign, SignError};
|
||||||
|
|
||||||
|
#[cfg(feature = "default-spawner")]
|
||||||
|
pub use crate::default_spawner::DefaultSpawner;
|
||||||
|
|
||||||
#[cfg(feature = "digest")]
|
#[cfg(feature = "digest")]
|
||||||
pub use crate::digest::{DigestCreate, SignExt};
|
pub use crate::digest::{DigestCreate, SignExt};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "default-spawner")]
|
||||||
|
pub use default_spawner::DefaultSpawner;
|
||||||
|
|
||||||
|
#[cfg(feature = "default-spawner")]
|
||||||
#[derive(Clone, Debug, Default)]
|
#[derive(Clone, Debug, Default)]
|
||||||
/// Configuration for signing and verifying signatures
|
/// Configuration for signing and verifying signatures
|
||||||
///
|
///
|
||||||
/// By default, the config is set up to create and verify signatures that expire after 10 seconds,
|
/// By default, the config is set up to create and verify signatures that expire after 10 seconds,
|
||||||
/// and use the `(created)` and `(expires)` fields that were introduced in draft 11
|
/// and use the `(created)` and `(expires)` fields that were introduced in draft 11
|
||||||
pub struct Config {
|
pub struct Config<Spawner = DefaultSpawner> {
|
||||||
/// The inner config type
|
/// The inner config type
|
||||||
config: http_signature_normalization::Config,
|
config: http_signature_normalization::Config,
|
||||||
|
|
||||||
|
@ -36,15 +43,115 @@ pub struct Config {
|
||||||
|
|
||||||
/// Whether to set the Date header
|
/// Whether to set the Date header
|
||||||
set_date: bool,
|
set_date: bool,
|
||||||
|
|
||||||
|
/// How to spawn blocking tasks
|
||||||
|
spawner: Spawner,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "default-spawner"))]
|
||||||
|
#[derive(Clone, Debug, Default)]
|
||||||
|
/// Configuration for signing and verifying signatures
|
||||||
|
///
|
||||||
|
/// By default, the config is set up to create and verify signatures that expire after 10 seconds,
|
||||||
|
/// and use the `(created)` and `(expires)` fields that were introduced in draft 11
|
||||||
|
pub struct Config<Spawner> {
|
||||||
|
/// The inner config type
|
||||||
|
config: http_signature_normalization::Config,
|
||||||
|
|
||||||
|
/// Whether to set the Host header
|
||||||
|
set_host: bool,
|
||||||
|
|
||||||
|
/// Whether to set the Date header
|
||||||
|
set_date: bool,
|
||||||
|
|
||||||
|
/// How to spawn blocking tasks
|
||||||
|
spawner: Spawner,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "default-spawner")]
|
||||||
|
mod default_spawner {
|
||||||
|
use super::{Canceled, Config, Spawn};
|
||||||
|
|
||||||
|
impl Config<DefaultSpawner> {
|
||||||
|
/// Create a new config with the default spawner
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A default implementation of Spawner for spawning blocking operations
|
||||||
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
|
pub struct DefaultSpawner;
|
||||||
|
|
||||||
|
/// The future returned by DefaultSpawner when spawning blocking operations on the tokio
|
||||||
|
/// blocking threadpool
|
||||||
|
pub struct DefaultSpawnerFuture<Out> {
|
||||||
|
inner: tokio::task::JoinHandle<Out>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Spawn for DefaultSpawner {
|
||||||
|
type Future<T> = DefaultSpawnerFuture<T> where T: Send;
|
||||||
|
|
||||||
|
fn spawn_blocking<Func, Out>(&self, func: Func) -> Self::Future<Out>
|
||||||
|
where
|
||||||
|
Func: FnOnce() -> Out + Send + 'static,
|
||||||
|
Out: Send + 'static,
|
||||||
|
{
|
||||||
|
DefaultSpawnerFuture {
|
||||||
|
inner: tokio::task::spawn_blocking(func),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Out> std::future::Future for DefaultSpawnerFuture<Out> {
|
||||||
|
type Output = Result<Out, Canceled>;
|
||||||
|
|
||||||
|
fn poll(
|
||||||
|
mut self: std::pin::Pin<&mut Self>,
|
||||||
|
cx: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Self::Output> {
|
||||||
|
let res = std::task::ready!(std::pin::Pin::new(&mut self.inner).poll(cx));
|
||||||
|
|
||||||
|
std::task::Poll::Ready(res.map_err(|_| Canceled))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An error that indicates a blocking operation panicked and cannot return a response
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Canceled;
|
||||||
|
|
||||||
|
impl std::fmt::Display for Canceled {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "Operation was canceled")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for Canceled {}
|
||||||
|
|
||||||
|
/// A trait dictating how to spawn a future onto a blocking threadpool. By default,
|
||||||
|
/// http-signature-normalization-actix will use tokio's built-in blocking threadpool, but this
|
||||||
|
/// can be customized
|
||||||
|
pub trait Spawn {
|
||||||
|
/// The future type returned by spawn_blocking
|
||||||
|
type Future<T>: std::future::Future<Output = Result<T, Canceled>> + Send
|
||||||
|
where
|
||||||
|
T: Send;
|
||||||
|
|
||||||
|
/// Spawn the blocking function onto the threadpool
|
||||||
|
fn spawn_blocking<Func, Out>(&self, func: Func) -> Self::Future<Out>
|
||||||
|
where
|
||||||
|
Func: FnOnce() -> Out + Send + 'static,
|
||||||
|
Out: Send + 'static;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A trait implemented by the reqwest RequestBuilder type to add an HTTP Signature to the request
|
/// A trait implemented by the reqwest RequestBuilder type to add an HTTP Signature to the request
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
pub trait Sign {
|
pub trait Sign {
|
||||||
/// Add an Authorization Signature to the request
|
/// Add an Authorization Signature to the request
|
||||||
async fn authorization_signature<F, E, K>(
|
async fn authorization_signature<F, E, K, S>(
|
||||||
self,
|
self,
|
||||||
config: &Config,
|
config: &Config<S>,
|
||||||
key_id: K,
|
key_id: K,
|
||||||
f: F,
|
f: F,
|
||||||
) -> Result<Request, E>
|
) -> Result<Request, E>
|
||||||
|
@ -52,15 +159,17 @@ pub trait Sign {
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||||
K: Display + Send;
|
K: Display + Send,
|
||||||
|
S: Spawn + Send + Sync;
|
||||||
|
|
||||||
/// Add a Signature to the request
|
/// Add a Signature to the request
|
||||||
async fn signature<F, E, K>(self, config: &Config, key_id: K, f: F) -> Result<Request, E>
|
async fn signature<F, E, K, S>(self, config: &Config<S>, key_id: K, f: F) -> Result<Request, E>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||||
K: Display + Send;
|
K: Display + Send,
|
||||||
|
S: Spawn + Send + Sync;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error)]
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
@ -88,9 +197,15 @@ pub enum SignError {
|
||||||
Canceled,
|
Canceled,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Config {
|
impl<Spawner> Config<Spawner> {
|
||||||
pub fn new() -> Self {
|
/// Create a new config with the provided spawner
|
||||||
Default::default()
|
pub fn new_with_spawner(spawner: Spawner) -> Self {
|
||||||
|
Config {
|
||||||
|
config: Default::default(),
|
||||||
|
set_host: Default::default(),
|
||||||
|
set_date: Default::default(),
|
||||||
|
spawner,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This method can be used to include the Host header in the HTTP Signature without
|
/// This method can be used to include the Host header in the HTTP Signature without
|
||||||
|
@ -100,6 +215,7 @@ impl Config {
|
||||||
config: self.config,
|
config: self.config,
|
||||||
set_host: true,
|
set_host: true,
|
||||||
set_date: self.set_date,
|
set_date: self.set_date,
|
||||||
|
spawner: self.spawner,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -112,6 +228,7 @@ impl Config {
|
||||||
config: self.config.mastodon_compat(),
|
config: self.config.mastodon_compat(),
|
||||||
set_host: true,
|
set_host: true,
|
||||||
set_date: true,
|
set_date: true,
|
||||||
|
spawner: self.spawner,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -123,6 +240,7 @@ impl Config {
|
||||||
config: self.config.require_digest(),
|
config: self.config.require_digest(),
|
||||||
set_host: self.set_host,
|
set_host: self.set_host,
|
||||||
set_date: self.set_date,
|
set_date: self.set_date,
|
||||||
|
spawner: self.spawner,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -135,6 +253,7 @@ impl Config {
|
||||||
config: self.config.dont_use_created_field(),
|
config: self.config.dont_use_created_field(),
|
||||||
set_host: self.set_host,
|
set_host: self.set_host,
|
||||||
set_date: self.set_date,
|
set_date: self.set_date,
|
||||||
|
spawner: self.spawner,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -144,6 +263,7 @@ impl Config {
|
||||||
config: self.config.set_expiration(expiries_after),
|
config: self.config.set_expiration(expiries_after),
|
||||||
set_host: self.set_host,
|
set_host: self.set_host,
|
||||||
set_date: self.set_date,
|
set_date: self.set_date,
|
||||||
|
spawner: self.spawner,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -153,15 +273,25 @@ impl Config {
|
||||||
config: self.config.require_header(header),
|
config: self.config.require_header(header),
|
||||||
set_host: self.set_host,
|
set_host: self.set_host,
|
||||||
set_date: self.set_date,
|
set_date: self.set_date,
|
||||||
|
spawner: self.spawner,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_spawner<NewSpawner: Spawn>(self, spawner: NewSpawner) -> Config<NewSpawner> {
|
||||||
|
Config {
|
||||||
|
config: self.config,
|
||||||
|
set_host: self.set_host,
|
||||||
|
set_date: self.set_date,
|
||||||
|
spawner,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl Sign for RequestBuilder {
|
impl Sign for RequestBuilder {
|
||||||
async fn authorization_signature<F, E, K>(
|
async fn authorization_signature<F, E, K, S>(
|
||||||
self,
|
self,
|
||||||
config: &Config,
|
config: &Config<S>,
|
||||||
key_id: K,
|
key_id: K,
|
||||||
f: F,
|
f: F,
|
||||||
) -> Result<Request, E>
|
) -> Result<Request, E>
|
||||||
|
@ -169,6 +299,7 @@ impl Sign for RequestBuilder {
|
||||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||||
K: Display + Send,
|
K: Display + Send,
|
||||||
|
S: Spawn + Send + Sync,
|
||||||
{
|
{
|
||||||
let mut request = self.build()?;
|
let mut request = self.build()?;
|
||||||
let signed = prepare(&mut request, config, key_id, f).await?;
|
let signed = prepare(&mut request, config, key_id, f).await?;
|
||||||
|
@ -182,11 +313,12 @@ impl Sign for RequestBuilder {
|
||||||
Ok(request)
|
Ok(request)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn signature<F, E, K>(self, config: &Config, key_id: K, f: F) -> Result<Request, E>
|
async fn signature<F, E, K, S>(self, config: &Config<S>, key_id: K, f: F) -> Result<Request, E>
|
||||||
where
|
where
|
||||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||||
K: Display + Send,
|
K: Display + Send,
|
||||||
|
S: Spawn + Send + Sync,
|
||||||
{
|
{
|
||||||
let mut request = self.build()?;
|
let mut request = self.build()?;
|
||||||
let signed = prepare(&mut request, config, key_id, f).await?;
|
let signed = prepare(&mut request, config, key_id, f).await?;
|
||||||
|
@ -202,11 +334,17 @@ impl Sign for RequestBuilder {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn prepare<F, E, K>(req: &mut Request, config: &Config, key_id: K, f: F) -> Result<Signed, E>
|
async fn prepare<F, E, K, S>(
|
||||||
|
req: &mut Request,
|
||||||
|
config: &Config<S>,
|
||||||
|
key_id: K,
|
||||||
|
f: F,
|
||||||
|
) -> Result<Signed, E>
|
||||||
where
|
where
|
||||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||||
E: From<SignError> + Send + 'static,
|
E: From<SignError> + Send + 'static,
|
||||||
K: Display + Send,
|
K: Display + Send,
|
||||||
|
S: Spawn,
|
||||||
{
|
{
|
||||||
if config.set_date && !req.headers().contains_key("date") {
|
if config.set_date && !req.headers().contains_key("date") {
|
||||||
req.headers_mut().insert(
|
req.headers_mut().insert(
|
||||||
|
@ -249,7 +387,9 @@ where
|
||||||
.map_err(SignError::from)?;
|
.map_err(SignError::from)?;
|
||||||
|
|
||||||
let key_string = key_id.to_string();
|
let key_string = key_id.to_string();
|
||||||
let signed = tokio::task::spawn_blocking(move || unsigned.sign(key_string, f))
|
let signed = config
|
||||||
|
.spawner
|
||||||
|
.spawn_blocking(move || unsigned.sign(key_string, f))
|
||||||
.await
|
.await
|
||||||
.map_err(|_| SignError::Canceled)??;
|
.map_err(|_| SignError::Canceled)??;
|
||||||
Ok(signed)
|
Ok(signed)
|
||||||
|
@ -257,16 +397,16 @@ where
|
||||||
|
|
||||||
#[cfg(feature = "middleware")]
|
#[cfg(feature = "middleware")]
|
||||||
mod middleware {
|
mod middleware {
|
||||||
use super::{prepare, Config, Sign, SignError};
|
use super::{prepare, Config, Sign, SignError, Spawn};
|
||||||
use reqwest::Request;
|
use reqwest::Request;
|
||||||
use reqwest_middleware::RequestBuilder;
|
use reqwest_middleware::RequestBuilder;
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl Sign for RequestBuilder {
|
impl Sign for RequestBuilder {
|
||||||
async fn authorization_signature<F, E, K>(
|
async fn authorization_signature<F, E, K, S>(
|
||||||
self,
|
self,
|
||||||
config: &Config,
|
config: &Config<S>,
|
||||||
key_id: K,
|
key_id: K,
|
||||||
f: F,
|
f: F,
|
||||||
) -> Result<Request, E>
|
) -> Result<Request, E>
|
||||||
|
@ -274,6 +414,7 @@ mod middleware {
|
||||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||||
K: Display + Send,
|
K: Display + Send,
|
||||||
|
S: Spawn + Send + Sync,
|
||||||
{
|
{
|
||||||
let mut request = self.build()?;
|
let mut request = self.build()?;
|
||||||
let signed = prepare(&mut request, config, key_id, f).await?;
|
let signed = prepare(&mut request, config, key_id, f).await?;
|
||||||
|
@ -287,11 +428,17 @@ mod middleware {
|
||||||
Ok(request)
|
Ok(request)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn signature<F, E, K>(self, config: &Config, key_id: K, f: F) -> Result<Request, E>
|
async fn signature<F, E, K, S>(
|
||||||
|
self,
|
||||||
|
config: &Config<S>,
|
||||||
|
key_id: K,
|
||||||
|
f: F,
|
||||||
|
) -> Result<Request, E>
|
||||||
where
|
where
|
||||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||||
K: Display + Send,
|
K: Display + Send,
|
||||||
|
S: Spawn + Send + Sync,
|
||||||
{
|
{
|
||||||
let mut request = self.build()?;
|
let mut request = self.build()?;
|
||||||
let signed = prepare(&mut request, config, key_id, f).await?;
|
let signed = prepare(&mut request, config, key_id, f).await?;
|
||||||
|
|
Loading…
Reference in a new issue