mirror of
https://git.asonix.dog/asonix/http-signature-normalization.git
synced 2024-06-12 10:19:30 +00:00
Compare commits
28 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 | |||
e526699c87 | |||
cb198f6922 | |||
40ace55619 | |||
5de17a130b | |||
ac25b1d951 | |||
c7cb3ce602 |
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -2,3 +2,5 @@
|
|||
/target
|
||||
**/*.rs.bk
|
||||
Cargo.lock
|
||||
/.direnv
|
||||
/.envrc
|
||||
|
|
|
@ -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"
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
[package]
|
||||
name = "http-signature-normalization-actix"
|
||||
description = "An HTTP Signatures library that leaves the signing to you"
|
||||
version = "0.8.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]
|
||||
|
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -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,
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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")]
|
||||
|
@ -26,7 +28,7 @@ pub trait DigestName {
|
|||
|
||||
#[cfg(feature = "client")]
|
||||
mod client {
|
||||
use crate::{Config, PrepareSignError, Sign};
|
||||
use crate::{Config, PrepareSignError, Sign, Spawn};
|
||||
use actix_http::header::InvalidHeaderValue;
|
||||
use actix_rt::task::JoinError;
|
||||
use awc::{ClientRequest, SendClientRequest};
|
||||
|
@ -47,9 +49,9 @@ mod client {
|
|||
/// a malicious entity
|
||||
pub trait SignExt: Sign {
|
||||
/// Set the Digest and Authorization headers on the request
|
||||
fn authorization_signature_with_digest<F, E, K, D, V>(
|
||||
fn authorization_signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
digest: D,
|
||||
v: V,
|
||||
|
@ -59,19 +61,21 @@ mod client {
|
|||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Send + 'static,
|
||||
Self: Sized;
|
||||
|
||||
/// Set the Digest and Signature headers on the request
|
||||
fn signature_with_digest<F, E, K, D, V>(
|
||||
fn signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
digest: D,
|
||||
v: V,
|
||||
|
@ -81,11 +85,13 @@ mod client {
|
|||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Send + 'static,
|
||||
Self: Sized;
|
||||
|
|
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 {
|
||||
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;
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -5,13 +5,13 @@ use std::{fmt::Display, future::Future, pin::Pin};
|
|||
|
||||
use crate::{
|
||||
digest::{DigestClient, DigestCreate, SignExt},
|
||||
Config, PrepareSignError, Sign,
|
||||
Config, PrepareSignError, Sign, Spawn,
|
||||
};
|
||||
|
||||
impl SignExt for ClientRequest {
|
||||
fn authorization_signature_with_digest<F, E, K, D, V>(
|
||||
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,
|
||||
|
@ -21,21 +21,25 @@ impl SignExt for ClientRequest {
|
|||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Send + 'static,
|
||||
Self: Sized,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let (d, v) = actix_rt::task::spawn_blocking(move || {
|
||||
let d = digest.compute(v.as_ref());
|
||||
Ok((d, v)) as Result<(String, V), E>
|
||||
})
|
||||
.await??;
|
||||
let (d, v) = config
|
||||
.spawner
|
||||
.spawn_blocking(move || {
|
||||
let d = digest.compute(v.as_ref());
|
||||
Ok((d, v)) as Result<(String, V), E>
|
||||
})
|
||||
.await??;
|
||||
|
||||
let c = self
|
||||
.insert_header(("Digest", format!("{}={}", D::NAME, d)))
|
||||
|
@ -46,9 +50,9 @@ impl SignExt for ClientRequest {
|
|||
})
|
||||
}
|
||||
|
||||
fn signature_with_digest<F, E, K, D, V>(
|
||||
fn signature_with_digest<F, E, K, S, D, V>(
|
||||
self,
|
||||
config: Config,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
mut digest: D,
|
||||
v: V,
|
||||
|
@ -58,21 +62,25 @@ impl SignExt for ClientRequest {
|
|||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Send + 'static,
|
||||
Self: Sized,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let (d, v) = actix_rt::task::spawn_blocking(move || {
|
||||
let d = digest.compute(v.as_ref());
|
||||
Ok((d, v)) as Result<(String, V), E>
|
||||
})
|
||||
.await??;
|
||||
let (d, v) = config
|
||||
.spawner
|
||||
.spawn_blocking(move || {
|
||||
let d = digest.compute(v.as_ref());
|
||||
Ok((d, v)) as Result<(String, V), E>
|
||||
})
|
||||
.await??;
|
||||
|
||||
let c = self
|
||||
.insert_header(("Digest", format!("{}={}", D::NAME, d)))
|
||||
|
|
117
actix/src/lib.rs
117
actix/src/lib.rs
|
@ -267,7 +267,7 @@ pub use self::server::{PrepareVerifyError, SignatureVerify};
|
|||
///
|
||||
/// 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,
|
||||
|
||||
|
@ -276,11 +276,77 @@ pub struct Config {
|
|||
|
||||
/// Whether to set the Date header
|
||||
set_date: bool,
|
||||
|
||||
/// The spawner used to create blocking operations
|
||||
spawner: Spawner,
|
||||
}
|
||||
|
||||
/// A default implementation of Spawner for spawning blocking operations
|
||||
#[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, 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};
|
||||
|
@ -288,9 +354,9 @@ mod client {
|
|||
/// A trait implemented by the awc ClientRequest type to add an HTTP signature to the request
|
||||
pub trait Sign {
|
||||
/// Add an Authorization Signature to the request
|
||||
fn authorization_signature<F, E, K>(
|
||||
fn authorization_signature<F, E, K, S>(
|
||||
self,
|
||||
config: Config,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
|
||||
|
@ -298,17 +364,19 @@ mod client {
|
|||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
Self: Sized;
|
||||
|
||||
/// Add a Signature to the request
|
||||
fn signature<F, E, K>(
|
||||
fn signature<F, E, K, S>(
|
||||
self,
|
||||
config: Config,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
|
||||
|
@ -316,11 +384,13 @@ mod client {
|
|||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
Self: Sized;
|
||||
}
|
||||
|
||||
|
@ -415,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 {
|
||||
|
@ -422,7 +502,9 @@ impl Config {
|
|||
pub fn new() -> Self {
|
||||
Config::default()
|
||||
}
|
||||
}
|
||||
|
||||
impl<Spawner> Config<Spawner> {
|
||||
/// Since manually setting the Host header doesn't work so well in AWC, you can use this method
|
||||
/// to enable setting the Host header for signing requests without breaking client
|
||||
/// functionality
|
||||
|
@ -431,6 +513,24 @@ impl Config {
|
|||
config: self.config,
|
||||
set_host: true,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "client")]
|
||||
/// Set the spawner for spawning blocking tasks
|
||||
///
|
||||
/// http-signature-normalization-actix offloads signing messages and generating hashes to a
|
||||
/// blocking threadpool, which can be configured by providing a custom spawner.
|
||||
pub fn spawner<S>(self, spawner: S) -> Config<S>
|
||||
where
|
||||
S: Spawn,
|
||||
{
|
||||
Config {
|
||||
config: self.config,
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -443,6 +543,7 @@ impl Config {
|
|||
config: self.config.mastodon_compat(),
|
||||
set_host: true,
|
||||
set_date: true,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -454,6 +555,7 @@ impl Config {
|
|||
config: self.config.require_digest(),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -466,6 +568,7 @@ impl Config {
|
|||
config: self.config.dont_use_created_field(),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -475,6 +578,7 @@ impl Config {
|
|||
config: self.config.set_expiration(expires_after),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -484,6 +588,7 @@ impl Config {
|
|||
config: self.config.require_header(header),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
use crate::{create::Signed, Config, PrepareSignError, Sign};
|
||||
use crate::{create::Signed, Config, PrepareSignError, Sign, Spawn};
|
||||
use actix_rt::task::JoinError;
|
||||
use awc::{
|
||||
http::header::{HttpDate, InvalidHeaderValue, TryIntoHeaderValue},
|
||||
|
@ -7,9 +7,9 @@ use awc::{
|
|||
use std::{fmt::Display, future::Future, pin::Pin, time::SystemTime};
|
||||
|
||||
impl Sign for ClientRequest {
|
||||
fn authorization_signature<F, E, K>(
|
||||
fn authorization_signature<F, E, K, S>(
|
||||
mut self,
|
||||
config: Config,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
|
||||
|
@ -17,11 +17,13 @@ impl Sign for ClientRequest {
|
|||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
Self: Sized,
|
||||
{
|
||||
Box::pin(async move {
|
||||
|
@ -31,9 +33,9 @@ impl Sign for ClientRequest {
|
|||
})
|
||||
}
|
||||
|
||||
fn signature<F, E, K>(
|
||||
fn signature<F, E, K, S>(
|
||||
mut self,
|
||||
config: Config,
|
||||
config: Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
|
||||
|
@ -42,10 +44,12 @@ impl Sign for ClientRequest {
|
|||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<InvalidHeaderValue>
|
||||
+ From<crate::Canceled>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display + 'static,
|
||||
S: Spawn + 'static,
|
||||
Self: Sized,
|
||||
{
|
||||
Box::pin(async move {
|
||||
|
@ -56,16 +60,22 @@ impl Sign for ClientRequest {
|
|||
}
|
||||
}
|
||||
|
||||
async fn prepare<F, E, K>(
|
||||
async fn prepare<F, E, K, S>(
|
||||
request: &mut ClientRequest,
|
||||
config: &Config,
|
||||
config: &Config<S>,
|
||||
key_id: K,
|
||||
f: F,
|
||||
) -> Result<Signed, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<JoinError> + From<PrepareSignError> + std::fmt::Debug + Send + 'static,
|
||||
E: From<JoinError>
|
||||
+ From<PrepareSignError>
|
||||
+ From<crate::Canceled>
|
||||
+ std::fmt::Debug
|
||||
+ Send
|
||||
+ 'static,
|
||||
K: Display,
|
||||
S: Spawn + 'static,
|
||||
{
|
||||
if config.set_date && !request.headers().contains_key("date") {
|
||||
request.headers_mut().insert(
|
||||
|
@ -103,7 +113,10 @@ where
|
|||
|
||||
let key_id = key_id.to_string();
|
||||
|
||||
let signed = actix_rt::task::spawn_blocking(move || unsigned.sign(key_id, f)).await??;
|
||||
let signed = config
|
||||
.spawner
|
||||
.spawn_blocking(move || unsigned.sign(key_id, f))
|
||||
.await??;
|
||||
|
||||
Ok(signed)
|
||||
}
|
||||
|
|
61
flake.lock
Normal file
61
flake.lock
Normal file
|
@ -0,0 +1,61 @@
|
|||
{
|
||||
"nodes": {
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1694529238,
|
||||
"narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1700794826,
|
||||
"narHash": "sha256-RyJTnTNKhO0yqRpDISk03I/4A67/dp96YRxc86YOPgU=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "5a09cb4b393d58f9ed0d9ca1555016a8543c2ac8",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"flake-utils": "flake-utils",
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
},
|
||||
"systems": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
25
flake.nix
Normal file
25
flake.nix
Normal file
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
description = "http-signature-normalization";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
flake-utils.url = "github:numtide/flake-utils";
|
||||
};
|
||||
|
||||
outputs = { self, nixpkgs, flake-utils }:
|
||||
flake-utils.lib.eachDefaultSystem (system:
|
||||
let
|
||||
pkgs = import nixpkgs {
|
||||
inherit system;
|
||||
};
|
||||
in
|
||||
{
|
||||
packages.default = pkgs.hello;
|
||||
|
||||
devShell = with pkgs; mkShell {
|
||||
nativeBuildInputs = [ cargo cargo-expand cargo-outdated cargo-zigbuild clippy gcc protobuf rust-analyzer rustc rustfmt ];
|
||||
|
||||
RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}";
|
||||
};
|
||||
});
|
||||
}
|
|
@ -1,7 +1,7 @@
|
|||
[package]
|
||||
name = "http-signature-normalization-reqwest"
|
||||
description = "An HTTP Signatures library that leaves the signing to you"
|
||||
version = "0.8.0"
|
||||
version = "0.12.0"
|
||||
authors = ["asonix <asonix@asonix.dog>"]
|
||||
license = "AGPL-3.0"
|
||||
readme = "README.md"
|
||||
|
@ -11,22 +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]
|
||||
base64 = { version = "0.13", optional = true }
|
||||
async-trait = "0.1.71"
|
||||
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"
|
||||
|
@ -35,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",
|
||||
|
|
|
@ -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?;
|
||||
|
||||
|
|
|
@ -1,7 +1,9 @@
|
|||
use crate::{Config, Sign, SignError};
|
||||
use crate::{Config, Sign, SignError, Spawn};
|
||||
use reqwest::{Body, Request, RequestBuilder};
|
||||
use std::{fmt::Display, future::Future, pin::Pin};
|
||||
use std::fmt::Display;
|
||||
|
||||
#[cfg(feature = "ring")]
|
||||
pub mod ring;
|
||||
#[cfg(feature = "sha-2")]
|
||||
mod sha2;
|
||||
#[cfg(feature = "sha-3")]
|
||||
|
@ -21,184 +23,195 @@ pub trait DigestCreate {
|
|||
/// It generates HTTP Signatures after the Digest header has been added, in order to have
|
||||
/// verification that the body has not been tampered with, or that the request can't be replayed by
|
||||
/// a malicious entity
|
||||
#[async_trait::async_trait]
|
||||
pub trait SignExt: Sign {
|
||||
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,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Request, E>> + Send>>
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
S: Spawn + Send + Sync,
|
||||
Self: Sized;
|
||||
|
||||
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,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Request, E>> + Send>>
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
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 {
|
||||
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,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Request, E>> + Send>>
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
Self: Sized,
|
||||
S: Spawn + Send + Sync,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let (v, digest) = tokio::task::spawn_blocking(move || {
|
||||
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))
|
||||
.authorization_signature(&config, key_id, f)?;
|
||||
let mut req = self
|
||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||
.authorization_signature(&config, key_id, f)
|
||||
.await?;
|
||||
|
||||
*req.body_mut() = Some(Body::from(v.as_ref().to_vec()));
|
||||
*req.body_mut() = Some(Body::from(v.as_ref().to_vec()));
|
||||
|
||||
Ok(req)
|
||||
})
|
||||
Ok(req)
|
||||
}
|
||||
|
||||
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,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Request, E>> + Send>>
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
Self: Sized,
|
||||
S: Spawn + Send + Sync,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let (v, digest) = tokio::task::spawn_blocking(move || {
|
||||
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))
|
||||
.signature(&config, key_id, f)?;
|
||||
let mut req = self
|
||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||
.signature(&config, key_id, f)
|
||||
.await?;
|
||||
|
||||
*req.body_mut() = Some(Body::from(v.as_ref().to_vec()));
|
||||
*req.body_mut() = Some(Body::from(v.as_ref().to_vec()));
|
||||
|
||||
Ok(req)
|
||||
})
|
||||
Ok(req)
|
||||
}
|
||||
}
|
||||
|
||||
#[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, future::Future, pin::Pin};
|
||||
use std::fmt::Display;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl SignExt for RequestBuilder {
|
||||
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,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Request, E>> + Send>>
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
S: Spawn + Send + Sync,
|
||||
Self: Sized,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let (v, digest) = tokio::task::spawn_blocking(move || {
|
||||
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))
|
||||
.authorization_signature(&config, key_id, f)?;
|
||||
let mut req = self
|
||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||
.authorization_signature(&config, key_id, f)
|
||||
.await?;
|
||||
|
||||
*req.body_mut() = Some(Body::from(v.as_ref().to_vec()));
|
||||
*req.body_mut() = Some(Body::from(v.as_ref().to_vec()));
|
||||
|
||||
Ok(req)
|
||||
})
|
||||
Ok(req)
|
||||
}
|
||||
|
||||
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,
|
||||
f: F,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Request, E>> + Send>>
|
||||
) -> Result<Request, E>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send + 'static,
|
||||
D: DigestCreate + Send + 'static,
|
||||
V: AsRef<[u8]> + Into<Body> + Send + 'static,
|
||||
S: Spawn + Send + Sync,
|
||||
Self: Sized,
|
||||
{
|
||||
Box::pin(async move {
|
||||
let (v, digest) = tokio::task::spawn_blocking(move || {
|
||||
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))
|
||||
.signature(&config, key_id, f)?;
|
||||
let mut req = self
|
||||
.header("Digest", format!("{}={}", D::NAME, digest))
|
||||
.signature(&config, key_id, f)
|
||||
.await?;
|
||||
|
||||
*req.body_mut() = Some(Body::from(v.as_ref().to_vec()));
|
||||
*req.body_mut() = Some(Body::from(v.as_ref().to_vec()));
|
||||
|
||||
Ok(req)
|
||||
})
|
||||
Ok(req)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
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 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 {
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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,30 +43,133 @@ 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
|
||||
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>
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnOnce(&str) -> Result<String, E>,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display;
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send,
|
||||
S: Spawn + Send + Sync;
|
||||
|
||||
/// Add a Signature to the request
|
||||
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>,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display;
|
||||
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
|
||||
E: From<SignError> + From<reqwest::Error> + Send + 'static,
|
||||
K: Display + Send,
|
||||
S: Spawn + Send + Sync;
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
|
@ -87,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
|
||||
|
@ -99,6 +215,7 @@ impl Config {
|
|||
config: self.config,
|
||||
set_host: true,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -111,6 +228,7 @@ impl Config {
|
|||
config: self.config.mastodon_compat(),
|
||||
set_host: true,
|
||||
set_date: true,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -122,6 +240,7 @@ impl Config {
|
|||
config: self.config.require_digest(),
|
||||
set_host: self.set_host,
|
||||
set_date: self.set_date,
|
||||
spawner: self.spawner,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -134,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,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -143,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,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -152,24 +273,36 @@ 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 {
|
||||
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>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E>,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display,
|
||||
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)?;
|
||||
let signed = prepare(&mut request, config, key_id, f).await?;
|
||||
|
||||
let auth_header = signed.authorization_header();
|
||||
request.headers_mut().insert(
|
||||
|
@ -180,14 +313,15 @@ impl Sign for RequestBuilder {
|
|||
Ok(request)
|
||||
}
|
||||
|
||||
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>,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display,
|
||||
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)?;
|
||||
let signed = prepare(&mut request, config, key_id, f).await?;
|
||||
|
||||
let sig_header = signed.signature_header();
|
||||
|
||||
|
@ -200,11 +334,17 @@ impl Sign for RequestBuilder {
|
|||
}
|
||||
}
|
||||
|
||||
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>,
|
||||
E: From<SignError>,
|
||||
K: Display,
|
||||
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(
|
||||
|
@ -246,31 +386,38 @@ where
|
|||
.begin_sign(req.method().as_str(), &path_and_query, bt)
|
||||
.map_err(SignError::from)?;
|
||||
|
||||
let signed = unsigned.sign(key_id.to_string(), f)?;
|
||||
let key_string = key_id.to_string();
|
||||
let signed = config
|
||||
.spawner
|
||||
.spawn_blocking(move || unsigned.sign(key_string, f))
|
||||
.await
|
||||
.map_err(|_| SignError::Canceled)??;
|
||||
Ok(signed)
|
||||
}
|
||||
|
||||
#[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 {
|
||||
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>
|
||||
where
|
||||
F: FnOnce(&str) -> Result<String, E>,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display,
|
||||
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)?;
|
||||
let signed = prepare(&mut request, config, key_id, f).await?;
|
||||
|
||||
let auth_header = signed.authorization_header();
|
||||
request.headers_mut().insert(
|
||||
|
@ -281,14 +428,20 @@ mod middleware {
|
|||
Ok(request)
|
||||
}
|
||||
|
||||
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>,
|
||||
E: From<SignError> + From<reqwest::Error>,
|
||||
K: Display,
|
||||
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)?;
|
||||
let signed = prepare(&mut request, config, key_id, f).await?;
|
||||
|
||||
let sig_header = signed.signature_header();
|
||||
|
||||
|
|
Loading…
Reference in a new issue