Compare commits

...

23 commits

Author SHA1 Message Date
asonix 3d7b620bc0 actix: update version to 0.11.1 2024-04-14 20:24:21 -05:00
asonix 07413815d5 actix: Update base64 2024-04-14 20:23:46 -05:00
asonix c38072e65d Update reqwest to 0.12 2024-04-14 20:19:19 -05:00
asonix 47d28c6f47 Update ring, base64 2023-11-25 19:52:55 -06:00
asonix 47d07e7f1f Fix sha3 2023-11-25 19:47:04 -06:00
asonix b89acf7918 Update flake 2023-11-25 19:44:28 -06:00
asonix bf8e0e5f69 Update dependencies - ring is public 2023-11-25 19:43:33 -06:00
asonix 369a1e8a96 Replace spawned tasks with inline payload stream processing 2023-09-10 13:27:19 -04:00
asonix 6e0a6fa3a2 Bump version 2023-09-09 18:06:10 -04:00
asonix f0dc14d5f1 Ensure veirfy before returning DigestVerify 2023-09-09 18:05:18 -04:00
asonix 92a73f0313 clippy 2023-09-09 17:26:08 -04:00
asonix e8588efda7 Bump version 2023-09-09 17:24:16 -04:00
asonix 6acd291315 replace futures-util with streem 2023-09-09 17:17:23 -04:00
asonix ef266eed95 Vendor openssl for actix-extractor example 2023-08-17 12:35:21 -05:00
asonix c1d36000dd Use ring for reqwest example 2023-08-17 12:34:51 -05:00
asonix ec73fe55c9 Add ring 2023-08-17 12:03:38 -05:00
asonix ff0290a488 Remove tokio from digest dep 2023-08-17 11:59:07 -05:00
asonix ce2d14824e Bump version 2023-08-17 11:56:50 -05:00
asonix bbafc22d08 Allow providing custom spawners for reqwest 2023-08-17 11:56:09 -05:00
asonix 8750783667 Update examples to use ring 2023-08-04 18:01:41 -05:00
asonix ea964decc8 Add ring-backed digest types 2023-08-04 17:55:14 -05:00
asonix 1f23b72140 Enable Spawn for server, allow spawner in digest verify 2023-07-27 12:15:42 -05:00
asonix e526699c87 Properly expose spawner method on config 2023-07-26 17:49:39 -05:00
19 changed files with 809 additions and 228 deletions

View file

@ -26,5 +26,5 @@ subtle = { version = "2.4.1", optional = true }
[dev-dependencies]
actix-web = { version = "4", features = ["macros"] }
openssl = "0.10.43"
openssl = { version = "0.10.43", features = ["vendored"] }
thiserror = "1"

View file

@ -1,7 +1,7 @@
[package]
name = "http-signature-normalization-actix"
description = "An HTTP Signatures library that leaves the signing to you"
version = "0.9.0"
version = "0.11.1"
authors = ["asonix <asonix@asonix.dog>"]
license = "AGPL-3.0"
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
[features]
default = ["server", "sha-2", "sha-3"]
client = ["awc"]
digest = ["base64"]
server = ["actix-web"]
sha-2 = ["digest", "sha2"]
sha-3 = ["digest", "sha3"]
client = ["dep:awc"]
digest = ["dep:base64"]
server = ["dep:actix-web"]
sha-2 = ["digest", "dep:sha2"]
sha-3 = ["digest", "dep:sha3"]
ring = ["digest", "dep:ring"]
[[example]]
name = "server"
required-features = ["server", "sha-2"]
required-features = ["server", "ring"]
[[example]]
name = "client"
required-features = ["client", "sha-2"]
required-features = ["client", "ring"]
[dependencies]
actix-http = { version = "3.0.2", default-features = false }
actix-rt = "2.6.0"
actix-web = { version = "4.0.0", default-features = false, optional = true }
awc = { version = "3.0.0", default-features = false, optional = true }
base64 = { version = "0.13", optional = true }
futures-util = { version = "0.3", default-features = false }
base64 = { version = "0.22", optional = true }
futures-core = "0.3.28"
http-signature-normalization = { version = "0.7.0", path = ".." }
ring = { version = "0.17.5", optional = true }
sha2 = { version = "0.10", optional = true }
sha3 = { version = "0.10", optional = true }
streem = "0.2.0"
thiserror = "1.0"
tokio = { version = "1", default-features = false, features = ["sync"] }
tracing = "0.1"
@ -44,7 +47,7 @@ tracing-futures = "0.2"
[dev-dependencies]
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"] }
[package.metadata.docs.rs]

View file

@ -1,7 +1,7 @@
use actix_rt::task::JoinError;
use awc::Client;
use http_signature_normalization_actix::prelude::*;
use sha2::{Digest, Sha256};
use base64::{engine::general_purpose::STANDARD, Engine};
use http_signature_normalization_actix::{digest::ring::Sha256, prelude::*, Canceled};
use tracing::{error, info};
use tracing_error::ErrorLayer;
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"))
.signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
info!("Signing String\n{}", s);
Ok(base64::encode(s)) as Result<_, MyError>
Ok(STANDARD.encode(s)) as Result<_, MyError>
})
.await?
.send()
@ -45,7 +45,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
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.mastodon_compat()).await?;
@ -75,3 +75,9 @@ impl From<JoinError> for MyError {
MyError::Canceled
}
}
impl From<Canceled> for MyError {
fn from(_: Canceled) -> Self {
MyError::Canceled
}
}

View file

@ -1,6 +1,6 @@
use actix_web::{http::StatusCode, web, App, HttpRequest, HttpResponse, HttpServer, ResponseError};
use http_signature_normalization_actix::prelude::*;
use sha2::{Digest, Sha256};
use base64::{engine::general_purpose::STANDARD, Engine};
use http_signature_normalization_actix::{digest::ring::Sha256, prelude::*};
use std::future::{ready, Ready};
use tracing::info;
use tracing_actix_web::TracingLogger;
@ -30,7 +30,7 @@ impl SignatureVerify for MyVerify {
return ready(Err(MyError::Key));
}
let decoded = match base64::decode(&signature) {
let decoded = match STANDARD.decode(&signature) {
Ok(decoded) => decoded,
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)?;
let config = Config::default().require_header("accept").require_digest();
let config = Config::new().require_header("accept").require_digest();
HttpServer::new(move || {
App::new()

View file

@ -1,5 +1,7 @@
//! Types for setting up Digest middleware verification
use crate::{Canceled, DefaultSpawner, Spawn};
use super::{DigestPart, DigestVerify};
use actix_web::{
body::MessageBody,
@ -8,16 +10,14 @@ use actix_web::{
http::{header::HeaderValue, StatusCode},
web, FromRequest, HttpMessage, HttpRequest, HttpResponse, ResponseError,
};
use futures_util::{
future::LocalBoxFuture,
stream::{Stream, StreamExt},
};
use futures_core::{future::LocalBoxFuture, Stream};
use std::{
future::{ready, Ready},
pin::Pin,
task::{Context, Poll},
};
use tokio::sync::mpsc;
use streem::{from_fn::Yielder, IntoStreamer};
use tokio::sync::{mpsc, oneshot};
use tracing::{debug, Span};
use tracing_error::SpanTrace;
@ -42,10 +42,10 @@ pub struct DigestVerified;
/// .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)]
pub struct VerifyMiddleware<T, S>(S, bool, T);
pub struct VerifyMiddleware<T, Spawner, S>(S, Spawner, bool, T);
#[derive(Debug, thiserror::Error)]
#[error("Error verifying digest")]
@ -85,10 +85,10 @@ enum VerifyErrorKind {
struct RxStream<T>(mpsc::Receiver<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>> {
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
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
@ -106,53 +121,68 @@ where
/// If a digest is present in the request, it will be verified, but it is not required to be
/// present
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 {
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 {
let res = req
.extensions()
.get::<Self>()
.copied()
.extensions_mut()
.get_mut::<VerifiedReceiver>()
.and_then(|r| r.rx.take())
.ok_or_else(|| VerifyError::new(&Span::current(), VerifyErrorKind::Extension));
if res.is_err() {
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
T: DigestVerify + Clone + Send + 'static,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
S::Error: 'static,
B: MessageBody + 'static,
Spawner: Spawn + Clone + 'static,
{
type Response = ServiceResponse<B>;
type Error = actix_web::Error;
type Transform = VerifyMiddleware<T, S>;
type Transform = VerifyMiddleware<T, Spawner, S>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
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
T: DigestVerify + Clone + Send + 'static,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
S::Error: 'static,
B: MessageBody + 'static,
Spawner: Spawn + Clone + 'static,
{
type Response = ServiceResponse<B>;
type Error = actix_web::Error;
@ -165,7 +195,7 @@ where
fn call(&self, mut req: ServiceRequest) -> Self::Future {
let span = tracing::info_span!(
"Verify digest",
digest.required = tracing::field::display(&self.1),
digest.required = tracing::field::display(&self.2),
);
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 (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>> =
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.extensions_mut().insert(DigestVerified);
let f2 = self.0.call(req);
req.extensions_mut().insert(VerifiedReceiver {
rx: Some(verify_rx),
});
Box::pin(async move {
let (_, res) = futures_util::future::join(f1, f2).await;
res
})
} else if self.1 {
Box::pin(self.0.call(req))
} else if self.2 {
Box::pin(ready(Err(VerifyError::new(
&span,
VerifyErrorKind::MissingDigest,
@ -205,37 +236,79 @@ where
}
}
#[tracing::instrument(name = "Verify Payload", skip(verify_digest, payload, tx))]
async fn verify_payload<T>(
fn canceled_error(error: Canceled) -> PayloadError {
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>,
mut verify_digest: T,
mut payload: Payload,
tx: mpsc::Sender<web::Bytes>,
) -> Result<(), actix_web::Error>
payload: Payload,
verify_tx: oneshot::Sender<()>,
) -> Result<(), PayloadError>
where
T: DigestVerify + Clone + Send + 'static,
Spawner: Spawn,
{
while let Some(res) = payload.next().await {
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??;
let mut payload = payload.into_streamer();
tx.send(bytes)
.await
.map_err(|_| VerifyError::new(&Span::current(), VerifyErrorKind::Dropped))?;
let mut error = None;
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 =
web::block(move || Ok(verify_digest.verify(&vec)) as Result<_, VerifyError>).await??;
if let Some(error) = error {
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 verify_tx.send(()).is_err() {
debug!("handler dropped");
}
Ok(())
} else {
Err(VerifyError::new(&Span::current(), VerifyErrorKind::Verify).into())
Err(verified_error(VerifyError::new(
&Span::current(),
VerifyErrorKind::Verify,
)))
}
}

View file

@ -5,6 +5,8 @@
#[cfg(feature = "server")]
pub mod middleware;
#[cfg(feature = "ring")]
pub mod ring;
#[cfg(feature = "sha-2")]
mod sha2;
#[cfg(feature = "sha-3")]

198
actix/src/digest/ring.rs Normal file
View 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)
}
}
}

View file

@ -21,13 +21,14 @@ impl DigestName for Sha512 {
mod client {
use super::*;
use crate::digest::DigestCreate;
use base64::prelude::*;
fn create<D: sha2::Digest + sha2::digest::FixedOutputReset>(
digest: &mut D,
input: &[u8],
) -> String {
sha2::Digest::update(digest, input);
base64::encode(&digest.finalize_reset())
BASE64_STANDARD.encode(&digest.finalize_reset())
}
impl DigestCreate for Sha224 {
@ -59,6 +60,7 @@ mod client {
mod server {
use super::*;
use crate::digest::{DigestPart, DigestVerify};
use base64::prelude::*;
use tracing::{debug, warn};
fn verify<D: sha2::Digest + sha2::digest::FixedOutputReset>(
@ -71,7 +73,7 @@ mod server {
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
{
debug!("Verifying digest type, {}", name);
let encoded = base64::encode(&digest.finalize_reset());
let encoded = BASE64_STANDARD.encode(&digest.finalize_reset());
return part.digest == encoded;
}

View file

@ -40,17 +40,18 @@ impl DigestName for Sha3_512 {
const NAME: &'static str = "SHA3-512";
}
#[cfg(features = "client")]
#[cfg(feature = "client")]
mod client {
use super::*;
use crate::digest::DigestCreate;
use base64::prelude::*;
fn create<D: sha3::Digest + sha3::digest::FixedOutputReset>(
digest: &mut D,
input: &[u8],
) -> String {
digest.update(input);
base64::encode(&digest.finalize_reset())
sha3::Digest::update(digest, input);
BASE64_STANDARD.encode(&digest.finalize_reset())
}
impl DigestCreate for Sha3_224 {
@ -112,6 +113,7 @@ mod client {
mod server {
use super::*;
use crate::digest::{DigestPart, DigestVerify};
use base64::prelude::*;
use tracing::{debug, warn};
fn verify<D: sha3::Digest + sha3::digest::FixedOutputReset>(
@ -124,7 +126,7 @@ mod server {
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
{
debug!("Verifying digest type, {}", name);
let encoded = base64::encode(&digest.finalize_reset());
let encoded = BASE64_STANDARD.encode(&digest.finalize_reset());
return part.digest == encoded;
}

View file

@ -257,7 +257,7 @@ pub mod verify {
}
#[cfg(feature = "client")]
pub use self::client::{Canceled, PrepareSignError, Sign, Spawn};
pub use self::client::{PrepareSignError, Sign};
#[cfg(feature = "server")]
pub use self::server::{PrepareVerifyError, SignatureVerify};
@ -285,9 +285,68 @@ pub struct Config<Spawner = DefaultSpawner> {
#[derive(Clone, Copy, Debug, Default)]
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")]
mod client {
use super::{Config, DefaultSpawner, RequiredError};
use super::{Config, RequiredError, Spawn};
use actix_http::header::{InvalidHeaderValue, ToStrError};
use actix_rt::task::JoinError;
use std::{fmt::Display, future::Future, pin::Pin};
@ -354,65 +413,6 @@ mod client {
/// Invalid Date header
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")]
@ -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 {
@ -507,7 +517,7 @@ impl<Spawner> Config<Spawner> {
}
}
#[cfg(client)]
#[cfg(feature = "client")]
/// Set the spawner for spawning blocking tasks
///
/// http-signature-normalization-actix offloads signing messages and generating hashes to a

View file

@ -1,13 +1,13 @@
//! Types for verifying requests with Actix Web
use crate::{Config, PrepareVerifyError, SignatureVerify};
use crate::{Config, PrepareVerifyError, SignatureVerify, Spawn};
use actix_web::{
body::MessageBody,
dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform},
http::StatusCode,
Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, ResponseError,
};
use futures_util::future::LocalBoxFuture;
use futures_core::future::LocalBoxFuture;
use std::{
collections::HashSet,
future::{ready, Ready},
@ -45,11 +45,11 @@ impl SignatureVerified {
/// .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)]
#[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)]
enum HeaderKind {
@ -126,7 +126,7 @@ impl VerifyError {
}
}
impl<T> VerifySignature<T>
impl<T, Spawner> VerifySignature<T, Spawner>
where
T: SignatureVerify,
{
@ -135,7 +135,10 @@ where
///
/// By default, this middleware expects to verify Signature headers, and requires the presence
/// 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)
}
@ -145,7 +148,7 @@ where
}
}
impl<T, S, B> VerifyMiddleware<T, S>
impl<T, Spawner, S, B> VerifyMiddleware<T, Spawner, S>
where
T: SignatureVerify + Clone + '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
T: SignatureVerify + Clone + 'static,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
S::Error: 'static,
B: MessageBody + 'static,
Spawner: Clone,
{
type Response = ServiceResponse<B>;
type Error = actix_web::Error;
type Transform = VerifyMiddleware<T, S>;
type Transform = VerifyMiddleware<T, Spawner, S>;
type 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
T: SignatureVerify + Clone + 'static,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,

View file

@ -5,11 +5,11 @@
"systems": "systems"
},
"locked": {
"lastModified": 1689068808,
"narHash": "sha256-6ixXo3wt24N/melDWjq70UuHQLxGV8jZvooRanIHXw0=",
"lastModified": 1694529238,
"narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "919d646de7be200f3bf08cb76ae1f09402b6f9b4",
"rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
"type": "github"
},
"original": {
@ -20,11 +20,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1690272529,
"narHash": "sha256-MakzcKXEdv/I4qJUtq/k/eG+rVmyOZLnYNC2w1mB59Y=",
"lastModified": 1700794826,
"narHash": "sha256-RyJTnTNKhO0yqRpDISk03I/4A67/dp96YRxc86YOPgU=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "ef99fa5c5ed624460217c31ac4271cfb5cb2502c",
"rev": "5a09cb4b393d58f9ed0d9ca1555016a8543c2ac8",
"type": "github"
},
"original": {

View file

@ -1,7 +1,7 @@
[package]
name = "http-signature-normalization-reqwest"
description = "An HTTP Signatures library that leaves the signing to you"
version = "0.9.0"
version = "0.12.0"
authors = ["asonix <asonix@asonix.dog>"]
license = "AGPL-3.0"
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
[features]
default = ["sha-2", "sha-3"]
middleware = ["reqwest-middleware"]
digest = ["base64", "tokio"]
sha-2 = ["digest", "sha2"]
sha-3 = ["digest", "sha3"]
default = ["sha-2", "default-spawner"]
middleware = ["dep:reqwest-middleware"]
default-spawner = ["dep:tokio"]
digest = ["dep:base64"]
ring = ["digest", "dep:ring"]
sha-2 = ["digest", "dep:sha2"]
sha-3 = ["digest", "dep:sha3"]
[[example]]
name = "client"
required-features = ["sha-2"]
required-features = ["default-spawner", "ring"]
[dependencies]
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 = ".." }
httpdate = "1.0.2"
reqwest = { version = "0.11", default-features = false, features = ["json"] }
reqwest-middleware = { version = "0.2.0", optional = true }
reqwest = { version = "0.12", default-features = false, features = ["json"] }
reqwest-middleware = { version = "0.3.0", optional = true }
ring = { version = "0.17.5", optional = true }
sha2 = { version = "0.10", optional = true }
sha3 = { version = "0.10", optional = true }
thiserror = "1.0"
@ -36,7 +39,7 @@ tokio = { version = "1", default-features = false, features = [
], optional = true }
[dev-dependencies]
pretty_env_logger = "0.4"
pretty_env_logger = "0.5"
tokio = { version = "1", default-features = false, features = [
"rt-multi-thread",
"macros",

View file

@ -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::{
header::{ACCEPT, USER_AGENT},
Client,
};
use sha2::{Digest, Sha256};
async fn request(config: Config) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let digest = Sha256::new();
@ -16,7 +16,7 @@ async fn request(config: Config) -> Result<(), Box<dyn std::error::Error + Send
.header(ACCEPT, "text/plain")
.signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
println!("Signing String\n{}", s);
Ok(base64::encode(s)) as Result<_, MyError>
Ok(STANDARD.encode(s)) as Result<_, MyError>
})
.await?;

View file

@ -1,7 +1,9 @@
use crate::{Config, Sign, SignError};
use crate::{Config, Sign, SignError, Spawn};
use reqwest::{Body, Request, RequestBuilder};
use std::fmt::Display;
#[cfg(feature = "ring")]
pub mod ring;
#[cfg(feature = "sha-2")]
mod sha2;
#[cfg(feature = "sha-3")]
@ -23,9 +25,9 @@ pub trait DigestCreate {
/// a malicious entity
#[async_trait::async_trait]
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,
config: Config,
config: Config<S>,
key_id: K,
digest: D,
v: V,
@ -37,11 +39,12 @@ pub trait SignExt: Sign {
K: Display + Send + 'static,
D: DigestCreate + Send + 'static,
V: AsRef<[u8]> + Into<Body> + Send + 'static,
S: Spawn + Send + Sync,
Self: Sized;
async fn signature_with_digest<F, E, K, D, V>(
async fn signature_with_digest<F, E, K, S, D, V>(
self,
config: Config,
config: Config<S>,
key_id: K,
digest: D,
v: V,
@ -53,14 +56,15 @@ pub trait SignExt: Sign {
K: Display + Send + 'static,
D: DigestCreate + Send + 'static,
V: AsRef<[u8]> + Into<Body> + Send + 'static,
S: Spawn + Send + Sync,
Self: Sized;
}
#[async_trait::async_trait]
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,
config: Config,
config: Config<S>,
key_id: K,
mut digest: D,
v: V,
@ -72,13 +76,16 @@ impl SignExt for RequestBuilder {
K: Display + Send + 'static,
D: DigestCreate + Send + 'static,
V: AsRef<[u8]> + Into<Body> + Send + 'static,
S: Spawn + Send + Sync,
{
let (v, digest) = tokio::task::spawn_blocking(move || {
let digest = digest.compute(v.as_ref());
(v, digest)
})
.await
.map_err(|_| SignError::Canceled)?;
let (v, digest) = config
.spawner
.spawn_blocking(move || {
let digest = digest.compute(v.as_ref());
(v, digest)
})
.await
.map_err(|_| SignError::Canceled)?;
let mut req = self
.header("Digest", format!("{}={}", D::NAME, digest))
@ -90,9 +97,9 @@ impl SignExt for RequestBuilder {
Ok(req)
}
async fn signature_with_digest<F, E, K, D, V>(
async fn signature_with_digest<F, E, K, S, D, V>(
self,
config: Config,
config: Config<S>,
key_id: K,
mut digest: D,
v: V,
@ -104,13 +111,16 @@ impl SignExt for RequestBuilder {
K: Display + Send + 'static,
D: DigestCreate + Send + 'static,
V: AsRef<[u8]> + Into<Body> + Send + 'static,
S: Spawn + Send + Sync,
{
let (v, digest) = tokio::task::spawn_blocking(move || {
let digest = digest.compute(v.as_ref());
(v, digest)
})
.await
.map_err(|_| SignError::Canceled)?;
let (v, digest) = config
.spawner
.spawn_blocking(move || {
let digest = digest.compute(v.as_ref());
(v, digest)
})
.await
.map_err(|_| SignError::Canceled)?;
let mut req = self
.header("Digest", format!("{}={}", D::NAME, digest))
@ -125,16 +135,16 @@ impl SignExt for RequestBuilder {
#[cfg(feature = "middleware")]
mod middleware {
use super::{Config, DigestCreate, Sign, SignError, SignExt};
use super::{Config, DigestCreate, Sign, SignError, SignExt, Spawn};
use reqwest::{Body, Request};
use reqwest_middleware::RequestBuilder;
use std::fmt::Display;
#[async_trait::async_trait]
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,
config: Config,
config: Config<S>,
key_id: K,
mut digest: D,
v: V,
@ -146,14 +156,17 @@ mod middleware {
K: Display + Send + 'static,
D: DigestCreate + Send + 'static,
V: AsRef<[u8]> + Into<Body> + Send + 'static,
S: Spawn + Send + Sync,
Self: Sized,
{
let (v, digest) = tokio::task::spawn_blocking(move || {
let digest = digest.compute(v.as_ref());
(v, digest)
})
.await
.map_err(|_| SignError::Canceled)?;
let (v, digest) = config
.spawner
.spawn_blocking(move || {
let digest = digest.compute(v.as_ref());
(v, digest)
})
.await
.map_err(|_| SignError::Canceled)?;
let mut req = self
.header("Digest", format!("{}={}", D::NAME, digest))
@ -165,9 +178,9 @@ mod middleware {
Ok(req)
}
async fn signature_with_digest<F, E, K, D, V>(
async fn signature_with_digest<F, E, K, S, D, V>(
self,
config: Config,
config: Config<S>,
key_id: K,
mut digest: D,
v: V,
@ -179,14 +192,17 @@ mod middleware {
K: Display + Send + 'static,
D: DigestCreate + Send + 'static,
V: AsRef<[u8]> + Into<Body> + Send + 'static,
S: Spawn + Send + Sync,
Self: Sized,
{
let (v, digest) = tokio::task::spawn_blocking(move || {
let digest = digest.compute(v.as_ref());
(v, digest)
})
.await
.map_err(|_| SignError::Canceled)?;
let (v, digest) = config
.spawner
.spawn_blocking(move || {
let digest = digest.compute(v.as_ref());
(v, digest)
})
.await
.map_err(|_| SignError::Canceled)?;
let mut req = self
.header("Digest", format!("{}={}", D::NAME, digest))

113
reqwest/src/digest/ring.rs Normal file
View 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)
}
}

View file

@ -1,3 +1,4 @@
use base64::prelude::*;
use sha2::{Sha224, Sha256, Sha384, Sha512};
use super::DigestCreate;
@ -7,7 +8,7 @@ fn create<D: sha2::Digest + sha2::digest::FixedOutputReset>(
input: &[u8],
) -> String {
sha2::Digest::update(digest, input);
base64::encode(&digest.finalize_reset())
BASE64_STANDARD.encode(&digest.finalize_reset())
}
impl DigestCreate for Sha224 {

View file

@ -1,3 +1,4 @@
use base64::prelude::*;
use sha3::{
Keccak224, Keccak256, Keccak256Full, Keccak384, Keccak512, Sha3_224, Sha3_256, Sha3_384,
Sha3_512,
@ -10,7 +11,7 @@ fn create<D: sha3::Digest + sha3::digest::FixedOutputReset>(
input: &[u8],
) -> String {
sha3::Digest::update(digest, input);
base64::encode(&digest.finalize_reset())
BASE64_STANDARD.encode(&digest.finalize_reset())
}
impl DigestCreate for Sha3_224 {

View file

@ -18,16 +18,23 @@ pub mod digest;
pub mod prelude {
pub use crate::{Config, Sign, SignError};
#[cfg(feature = "default-spawner")]
pub use crate::default_spawner::DefaultSpawner;
#[cfg(feature = "digest")]
pub use crate::digest::{DigestCreate, SignExt};
}
#[cfg(feature = "default-spawner")]
pub use default_spawner::DefaultSpawner;
#[cfg(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 {
pub struct Config<Spawner = DefaultSpawner> {
/// The inner config type
config: http_signature_normalization::Config,
@ -36,15 +43,115 @@ pub struct Config {
/// Whether to set the Date header
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
#[async_trait::async_trait]
pub trait Sign {
/// Add an Authorization Signature to the request
async fn authorization_signature<F, E, K>(
async fn authorization_signature<F, E, K, S>(
self,
config: &Config,
config: &Config<S>,
key_id: K,
f: F,
) -> Result<Request, E>
@ -52,15 +159,17 @@ pub trait Sign {
Self: Sized,
F: FnOnce(&str) -> Result<String, E> + 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
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
Self: Sized,
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<SignError> + From<reqwest::Error> + Send + 'static,
K: Display + Send;
K: Display + Send,
S: Spawn + Send + Sync;
}
#[derive(Debug, thiserror::Error)]
@ -88,9 +197,15 @@ pub enum SignError {
Canceled,
}
impl Config {
pub fn new() -> Self {
Default::default()
impl<Spawner> Config<Spawner> {
/// Create a new config with the provided spawner
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
@ -100,6 +215,7 @@ impl Config {
config: self.config,
set_host: true,
set_date: self.set_date,
spawner: self.spawner,
}
}
@ -112,6 +228,7 @@ impl Config {
config: self.config.mastodon_compat(),
set_host: true,
set_date: true,
spawner: self.spawner,
}
}
@ -123,6 +240,7 @@ impl Config {
config: self.config.require_digest(),
set_host: self.set_host,
set_date: self.set_date,
spawner: self.spawner,
}
}
@ -135,6 +253,7 @@ impl Config {
config: self.config.dont_use_created_field(),
set_host: self.set_host,
set_date: self.set_date,
spawner: self.spawner,
}
}
@ -144,6 +263,7 @@ impl Config {
config: self.config.set_expiration(expiries_after),
set_host: self.set_host,
set_date: self.set_date,
spawner: self.spawner,
}
}
@ -153,15 +273,25 @@ impl Config {
config: self.config.require_header(header),
set_host: self.set_host,
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]
impl Sign for RequestBuilder {
async fn authorization_signature<F, E, K>(
async fn authorization_signature<F, E, K, S>(
self,
config: &Config,
config: &Config<S>,
key_id: K,
f: F,
) -> Result<Request, E>
@ -169,6 +299,7 @@ impl Sign for RequestBuilder {
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<SignError> + From<reqwest::Error> + Send + 'static,
K: Display + Send,
S: Spawn + Send + Sync,
{
let mut request = self.build()?;
let signed = prepare(&mut request, config, key_id, f).await?;
@ -182,11 +313,12 @@ impl Sign for RequestBuilder {
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
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<SignError> + From<reqwest::Error> + Send + 'static,
K: Display + Send,
S: Spawn + Send + Sync,
{
let mut request = self.build()?;
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
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<SignError> + Send + 'static,
K: Display + Send,
S: Spawn,
{
if config.set_date && !req.headers().contains_key("date") {
req.headers_mut().insert(
@ -249,7 +387,9 @@ where
.map_err(SignError::from)?;
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
.map_err(|_| SignError::Canceled)??;
Ok(signed)
@ -257,16 +397,16 @@ where
#[cfg(feature = "middleware")]
mod middleware {
use super::{prepare, Config, Sign, SignError};
use super::{prepare, Config, Sign, SignError, Spawn};
use reqwest::Request;
use reqwest_middleware::RequestBuilder;
use std::fmt::Display;
#[async_trait::async_trait]
impl Sign for RequestBuilder {
async fn authorization_signature<F, E, K>(
async fn authorization_signature<F, E, K, S>(
self,
config: &Config,
config: &Config<S>,
key_id: K,
f: F,
) -> Result<Request, E>
@ -274,6 +414,7 @@ mod middleware {
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<SignError> + From<reqwest::Error> + Send + 'static,
K: Display + Send,
S: Spawn + Send + Sync,
{
let mut request = self.build()?;
let signed = prepare(&mut request, config, key_id, f).await?;
@ -287,11 +428,17 @@ mod middleware {
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
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<SignError> + From<reqwest::Error> + Send + 'static,
K: Display + Send,
S: Spawn + Send + Sync,
{
let mut request = self.build()?;
let signed = prepare(&mut request, config, key_id, f).await?;