Compare commits

...

6 commits

Author SHA1 Message Date
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
6 changed files with 342 additions and 66 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-reqwest"
description = "An HTTP Signatures library that leaves the signing to you"
version = "0.9.0"
version = "0.10.0"
authors = ["asonix <asonix@asonix.dog>"]
license = "AGPL-3.0"
readme = "README.md"
@ -11,15 +11,17 @@ 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"
@ -28,6 +30,7 @@ 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 }
ring = { version = "0.16.20", optional = true }
sha2 = { version = "0.10", optional = true }
sha3 = { version = "0.10", optional = true }
thiserror = "1.0"

View file

@ -1,9 +1,8 @@
use http_signature_normalization_reqwest::prelude::*;
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();

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))

111
reqwest/src/digest/ring.rs Normal file
View file

@ -0,0 +1,111 @@
//! 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 {
context.update(input);
let digest = context.finish();
base64::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

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