actix: Split Server and Client into features

This commit is contained in:
Aode (Lion) 2021-09-23 17:05:11 -05:00
parent 9be4a14206
commit bb42dd3f9a
8 changed files with 640 additions and 533 deletions

View file

@ -1,7 +1,7 @@
[package] [package]
name = "http-signature-normalization-actix" name = "http-signature-normalization-actix"
description = "An HTTP Signatures library that leaves the signing to you" description = "An HTTP Signatures library that leaves the signing to you"
version = "0.5.0-beta.9" version = "0.5.0-beta.10"
authors = ["asonix <asonix@asonix.dog>"] authors = ["asonix <asonix@asonix.dog>"]
license-file = "LICENSE" license-file = "LICENSE"
readme = "README.md" readme = "README.md"
@ -11,22 +11,26 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features] [features]
default = ["sha-2", "sha-3"] default = ["server", "sha-2", "sha-3"]
client = ["awc"]
digest = ["base64"] digest = ["base64"]
server = ["actix-web"]
sha-2 = ["digest", "sha2"] sha-2 = ["digest", "sha2"]
sha-3 = ["digest", "sha3"] sha-3 = ["digest", "sha3"]
[[example]] [[example]]
name = "server" name = "server"
required-features = ["sha-2"] required-features = ["server", "sha-2"]
[[example]] [[example]]
name = "client" name = "client"
required-features = ["sha-2"] required-features = ["client", "sha-2"]
[dependencies] [dependencies]
actix-web = { version = "4.0.0-beta.8", default-features = false } actix-http = { version = "3.0.0-beta.10", default-features = false }
awc = { version = "3.0.0-beta.7", default-features = false } actix-rt = "2.2.0"
actix-web = { version = "4.0.0-beta.8", default-features = false, optional = true }
awc = { version = "3.0.0-beta.7", default-features = false, optional = true }
base64 = { version = "0.13", optional = true } base64 = { version = "0.13", optional = true }
chrono = "0.4.6" chrono = "0.4.6"
futures-util = { version = "0.3", default-features = false } futures-util = { version = "0.3", default-features = false }
@ -40,6 +44,5 @@ tracing-error = "0.1"
tracing-futures = "0.2" tracing-futures = "0.2"
[dev-dependencies] [dev-dependencies]
actix-rt = "2.1.0"
tracing-actix-web = { version = "0.4.0-beta.13" } tracing-actix-web = { version = "0.4.0-beta.13" }
tracing-subscriber = { version = "0.2", features = ["fmt"] } tracing-subscriber = { version = "0.2", features = ["fmt"] }

View file

@ -1,6 +1,6 @@
//! Types for signing requests with Actix Web //! Types for signing requests with Actix Web
use actix_web::http::header::{ use actix_http::http::header::{
HeaderMap, HeaderName, HeaderValue, InvalidHeaderValue, AUTHORIZATION, HeaderMap, HeaderName, HeaderValue, InvalidHeaderValue, AUTHORIZATION,
}; };

View file

@ -3,128 +3,147 @@
//! Digest headers are commonly used in conjunction with HTTP Signatures to verify the whole //! Digest headers are commonly used in conjunction with HTTP Signatures to verify the whole
//! request when request bodies are present //! request when request bodies are present
use actix_web::{error::BlockingError, http::header::InvalidHeaderValue}; #[cfg(feature = "server")]
use awc::{ClientRequest, SendClientRequest};
use std::{fmt::Display, future::Future, pin::Pin};
use crate::{Config, PrepareSignError, Sign};
pub mod middleware; pub mod middleware;
#[cfg(feature = "sha-2")] #[cfg(feature = "sha-2")]
mod sha2; mod sha2;
#[cfg(feature = "sha-3")] #[cfg(feature = "sha-3")]
mod sha3; mod sha3;
#[cfg(feature = "client")]
mod sign; mod sign;
/// A trait for creating digests of an array of bytes #[cfg(feature = "client")]
pub trait DigestCreate { pub use self::client::{DigestClient, DigestCreate, SignExt};
#[cfg(feature = "server")]
pub use self::server::{DigestPart, DigestVerify};
/// Giving names to Digest implementations
pub trait DigestName {
/// The name of the digest algorithm /// The name of the digest algorithm
const NAME: &'static str; const NAME: &'static str;
/// Compute the digest of the input bytes
fn compute(&mut self, input: &[u8]) -> String;
} }
/// A trait for verifying digests #[cfg(feature = "client")]
pub trait DigestVerify { mod client {
/// Update the verifier with bytes from the request body use crate::{Config, PrepareSignError, Sign};
fn update(&mut self, part: &[u8]); use actix_http::{error::BlockingError, http::header::InvalidHeaderValue};
use awc::{ClientRequest, SendClientRequest};
use std::{fmt::Display, future::Future, pin::Pin};
/// Verify the request body against the digests from the request headers use super::DigestName;
fn verify(&mut self, digests: &[DigestPart]) -> bool;
}
/// Extend the Sign trait with support for adding Digest Headers to the request /// A trait for creating digests of an array of bytes
/// pub trait DigestCreate: DigestName {
/// It generates HTTP Signatures after the Digest header has been added, in order to have /// Compute the digest of the input bytes
/// verification that the body has not been tampered with, or that the request can't be replayed by fn compute(&mut self, input: &[u8]) -> String;
/// 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>(
self,
config: Config,
key_id: K,
digest: D,
v: V,
f: F,
) -> Pin<Box<dyn Future<Output = Result<DigestClient<V>, E>>>>
where
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<BlockingError>
+ From<PrepareSignError>
+ From<InvalidHeaderValue>
+ std::fmt::Debug
+ Send
+ 'static,
K: Display + '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>(
self,
config: Config,
key_id: K,
digest: D,
v: V,
f: F,
) -> Pin<Box<dyn Future<Output = Result<DigestClient<V>, E>>>>
where
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<BlockingError>
+ From<PrepareSignError>
+ From<InvalidHeaderValue>
+ std::fmt::Debug
+ Send
+ 'static,
K: Display + 'static,
D: DigestCreate + Send + 'static,
V: AsRef<[u8]> + Send + 'static,
Self: Sized;
}
/// A parsed digest from the request
#[derive(Debug)]
pub struct DigestPart {
/// The alrogithm used to produce the digest
pub algorithm: String,
/// The digest itself
pub digest: String,
}
/// An intermediate type between setting the Digest and Signature or Authorization headers, and
/// actually sending the request
///
/// This exists so that the return type for the [`SignExt`] trait can be named
pub struct DigestClient<V> {
req: ClientRequest,
body: V,
}
impl<V> DigestClient<V>
where
V: AsRef<[u8]>,
{
fn new(req: ClientRequest, body: V) -> Self {
DigestClient { req, body }
} }
/// Send the request /// Extend the Sign trait with support for adding Digest Headers to the request
/// ///
/// This is analogous to `ClientRequest::send_body` and uses the body provided when producing /// It generates HTTP Signatures after the Digest header has been added, in order to have
/// the digest /// verification that the body has not been tampered with, or that the request can't be replayed by
pub fn send(self) -> SendClientRequest { /// a malicious entity
self.req.send_body(self.body.as_ref().to_vec()) pub trait SignExt: Sign {
/// Set the Digest and Authorization headers on the request
fn authorization_signature_with_digest<F, E, K, D, V>(
self,
config: Config,
key_id: K,
digest: D,
v: V,
f: F,
) -> Pin<Box<dyn Future<Output = Result<DigestClient<V>, E>>>>
where
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<BlockingError>
+ From<PrepareSignError>
+ From<InvalidHeaderValue>
+ std::fmt::Debug
+ Send
+ 'static,
K: Display + '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>(
self,
config: Config,
key_id: K,
digest: D,
v: V,
f: F,
) -> Pin<Box<dyn Future<Output = Result<DigestClient<V>, E>>>>
where
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<BlockingError>
+ From<PrepareSignError>
+ From<InvalidHeaderValue>
+ std::fmt::Debug
+ Send
+ 'static,
K: Display + 'static,
D: DigestCreate + Send + 'static,
V: AsRef<[u8]> + Send + 'static,
Self: Sized;
} }
/// Split the parts of the request /// An intermediate type between setting the Digest and Signature or Authorization headers, and
/// actually sending the request
/// ///
/// In case the caller needs to interrogate the ClientRequest before sending /// This exists so that the return type for the [`SignExt`] trait can be named
pub fn split(self) -> (ClientRequest, V) { pub struct DigestClient<V> {
(self.req, self.body) req: ClientRequest,
body: V,
}
impl<V> DigestClient<V>
where
V: AsRef<[u8]>,
{
pub(super) fn new(req: ClientRequest, body: V) -> Self {
DigestClient { req, body }
}
/// Send the request
///
/// This is analogous to `ClientRequest::send_body` and uses the body provided when producing
/// the digest
pub fn send(self) -> SendClientRequest {
self.req.send_body(self.body.as_ref().to_vec())
}
/// Split the parts of the request
///
/// In case the caller needs to interrogate the ClientRequest before sending
pub fn split(self) -> (ClientRequest, V) {
(self.req, self.body)
}
}
}
#[cfg(feature = "server")]
mod server {
use super::DigestName;
/// A trait for verifying digests
pub trait DigestVerify: DigestName {
/// Update the verifier with bytes from the request body
fn update(&mut self, part: &[u8]);
/// Verify the request body against the digests from the request headers
fn verify(&mut self, digests: &[DigestPart]) -> bool;
}
/// A parsed digest from the request
#[derive(Debug)]
pub struct DigestPart {
/// The alrogithm used to produce the digest
pub algorithm: String,
/// The digest itself
pub digest: String,
} }
} }

View file

@ -1,143 +1,166 @@
use crate::digest::DigestName;
use sha2::{Sha224, Sha256, Sha384, Sha512, Sha512Trunc224, Sha512Trunc256}; use sha2::{Sha224, Sha256, Sha384, Sha512, Sha512Trunc224, Sha512Trunc256};
use tracing::{debug, warn};
use super::{DigestCreate, DigestPart, DigestVerify}; impl DigestName for Sha224 {
const NAME: &'static str = "SHA-244";
fn create(digest: &mut impl sha2::Digest, input: &[u8]) -> String {
digest.update(input);
base64::encode(&digest.finalize_reset())
} }
fn verify(digest: &mut impl sha2::Digest, name: &str, parts: &[DigestPart]) -> bool { impl DigestName for Sha256 {
if let Some(part) = parts
.iter()
.find(|p| p.algorithm.to_lowercase() == name.to_lowercase())
{
debug!("Verifying digest type, {}", name);
let encoded = base64::encode(&digest.finalize_reset());
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 DigestCreate for Sha224 {
const NAME: &'static str = "SHA-224";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestVerify for Sha224 {
fn update(&mut self, part: &[u8]) {
sha2::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Sha256 {
const NAME: &'static str = "SHA-256"; const NAME: &'static str = "SHA-256";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
} }
impl DigestVerify for Sha256 { impl DigestName for Sha384 {
fn update(&mut self, part: &[u8]) {
sha2::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Sha384 {
const NAME: &'static str = "SHA-384"; const NAME: &'static str = "SHA-384";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
} }
impl DigestVerify for Sha384 { impl DigestName for Sha512 {
fn update(&mut self, part: &[u8]) {
sha2::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Sha512 {
const NAME: &'static str = "SHA-512"; const NAME: &'static str = "SHA-512";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
} }
impl DigestVerify for Sha512 { impl DigestName for Sha512Trunc224 {
fn update(&mut self, part: &[u8]) {
sha2::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Sha512Trunc224 {
const NAME: &'static str = "SHA-512-224"; const NAME: &'static str = "SHA-512-224";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
} }
impl DigestVerify for Sha512Trunc224 { impl DigestName for Sha512Trunc256 {
fn update(&mut self, part: &[u8]) {
sha2::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Sha512Trunc256 {
const NAME: &'static str = "SHA-512-256"; const NAME: &'static str = "SHA-512-256";
}
fn compute(&mut self, input: &[u8]) -> String { #[cfg(feature = "client")]
create(self, input) mod client {
use super::*;
use crate::digest::DigestCreate;
fn create(digest: &mut impl sha2::Digest, input: &[u8]) -> String {
digest.update(input);
base64::encode(&digest.finalize_reset())
}
impl DigestCreate for Sha224 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Sha256 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Sha384 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Sha512 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Sha512Trunc224 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Sha512Trunc256 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
} }
} }
impl DigestVerify for Sha512Trunc256 { #[cfg(feature = "server")]
fn update(&mut self, part: &[u8]) { mod server {
sha2::Digest::update(self, part); use super::*;
use crate::digest::{DigestPart, DigestVerify};
use tracing::{debug, warn};
fn verify(digest: &mut impl sha2::Digest, 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 encoded = base64::encode(&digest.finalize_reset());
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
} }
fn verify(&mut self, parts: &[DigestPart]) -> bool { impl DigestVerify for Sha224 {
verify(self, <Self as DigestCreate>::NAME, parts) fn update(&mut self, part: &[u8]) {
sha2::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Sha256 {
fn update(&mut self, part: &[u8]) {
sha2::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Sha384 {
fn update(&mut self, part: &[u8]) {
sha2::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Sha512 {
fn update(&mut self, part: &[u8]) {
sha2::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Sha512Trunc224 {
fn update(&mut self, part: &[u8]) {
sha2::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Sha512Trunc256 {
fn update(&mut self, part: &[u8]) {
sha2::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
} }
} }

View file

@ -1,200 +1,229 @@
use crate::digest::DigestName;
use sha3::{ use sha3::{
Keccak224, Keccak256, Keccak256Full, Keccak384, Keccak512, Sha3_224, Sha3_256, Sha3_384, Keccak224, Keccak256, Keccak256Full, Keccak384, Keccak512, Sha3_224, Sha3_256, Sha3_384,
Sha3_512, Sha3_512,
}; };
use tracing::{debug, warn};
use super::{DigestCreate, DigestPart, DigestVerify}; impl DigestName for Keccak224 {
fn create(digest: &mut impl sha3::Digest, input: &[u8]) -> String {
digest.update(input);
base64::encode(&digest.finalize_reset())
}
fn verify(digest: &mut impl sha3::Digest, 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 encoded = base64::encode(&digest.finalize_reset());
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 DigestCreate for Sha3_224 {
const NAME: &'static str = "SHA3-224";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestVerify for Sha3_224 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Sha3_256 {
const NAME: &'static str = "SHA3-256";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestVerify for Sha3_256 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Sha3_384 {
const NAME: &'static str = "SHA3-384";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestVerify for Sha3_384 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Sha3_512 {
const NAME: &'static str = "SHA3-512";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestVerify for Sha3_512 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Keccak224 {
const NAME: &'static str = "keccak-224"; const NAME: &'static str = "keccak-224";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
} }
impl DigestVerify for Keccak224 { impl DigestName for Keccak256 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Keccak256 {
const NAME: &'static str = "keccak-256"; const NAME: &'static str = "keccak-256";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
} }
impl DigestVerify for Keccak256 { impl DigestName for Keccak256Full {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Keccak256Full {
const NAME: &'static str = "keccak-256-full"; const NAME: &'static str = "keccak-256-full";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
} }
impl DigestVerify for Keccak256Full { impl DigestName for Keccak384 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Keccak384 {
const NAME: &'static str = "keccak-384"; const NAME: &'static str = "keccak-384";
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
} }
impl DigestVerify for Keccak384 { impl DigestName for Keccak512 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, <Self as DigestCreate>::NAME, parts)
}
}
impl DigestCreate for Keccak512 {
const NAME: &'static str = "keccak-512"; const NAME: &'static str = "keccak-512";
}
fn compute(&mut self, input: &[u8]) -> String { impl DigestName for Sha3_224 {
create(self, input) const NAME: &'static str = "SHA3-224";
}
impl DigestName for Sha3_256 {
const NAME: &'static str = "SHA3-256";
}
impl DigestName for Sha3_384 {
const NAME: &'static str = "SHA3-384";
}
impl DigestName for Sha3_512 {
const NAME: &'static str = "SHA3-512";
}
#[cfg(features = "client")]
mod client {
use super::*;
use crate::digest::DigestCreate;
fn create(digest: &mut impl sha3::Digest, input: &[u8]) -> String {
digest.update(input);
base64::encode(&digest.finalize_reset())
}
impl DigestCreate for Sha3_224 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Sha3_256 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Sha3_384 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Sha3_512 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Keccak224 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Keccak256 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Keccak256Full {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Keccak384 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
}
impl DigestCreate for Keccak512 {
fn compute(&mut self, input: &[u8]) -> String {
create(self, input)
}
} }
} }
impl DigestVerify for Keccak512 { #[cfg(feature = "server")]
fn update(&mut self, part: &[u8]) { mod server {
sha3::Digest::update(self, part); use super::*;
use crate::digest::{DigestPart, DigestVerify};
use tracing::{debug, warn};
fn verify(digest: &mut impl sha3::Digest, 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 encoded = base64::encode(&digest.finalize_reset());
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
} }
fn verify(&mut self, parts: &[DigestPart]) -> bool { impl DigestVerify for Sha3_224 {
verify(self, <Self as DigestCreate>::NAME, parts) fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Sha3_256 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Sha3_384 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Sha3_512 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Keccak224 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Keccak256 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Keccak256Full {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Keccak384 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
}
impl DigestVerify for Keccak512 {
fn update(&mut self, part: &[u8]) {
sha3::Digest::update(self, part);
}
fn verify(&mut self, parts: &[DigestPart]) -> bool {
verify(self, Self::NAME, parts)
}
} }
} }

View file

@ -1,4 +1,4 @@
use actix_web::{error::BlockingError, http::header::InvalidHeaderValue, web}; use actix_http::{error::BlockingError, http::header::InvalidHeaderValue};
use awc::ClientRequest; use awc::ClientRequest;
use std::{fmt::Display, future::Future, pin::Pin}; use std::{fmt::Display, future::Future, pin::Pin};
@ -30,11 +30,11 @@ impl SignExt for ClientRequest {
Self: Sized, Self: Sized,
{ {
Box::pin(async move { Box::pin(async move {
let (d, v) = web::block(move || { let (d, v) = actix_rt::task::spawn_blocking(move || {
let d = digest.compute(v.as_ref()); let d = digest.compute(v.as_ref());
Ok((d, v)) as Result<(String, V), E> Ok((d, v)) as Result<(String, V), E>
}) })
.await??; .await.map_err(|_| BlockingError)??;
let c = self let c = self
.insert_header(("Digest", format!("{}={}", D::NAME, d))) .insert_header(("Digest", format!("{}={}", D::NAME, d)))
@ -67,11 +67,11 @@ impl SignExt for ClientRequest {
Self: Sized, Self: Sized,
{ {
Box::pin(async move { Box::pin(async move {
let (d, v) = web::block(move || { let (d, v) = actix_rt::task::spawn_blocking(move || {
let d = digest.compute(v.as_ref()); let d = digest.compute(v.as_ref());
Ok((d, v)) as Result<(String, V), E> Ok((d, v)) as Result<(String, V), E>
}) })
.await??; .await.map_err(|_| BlockingError)??;
let c = self let c = self
.insert_header(("Digest", format!("{}={}", D::NAME, d))) .insert_header(("Digest", format!("{}={}", D::NAME, d)))

View file

@ -159,44 +159,57 @@
//! } //! }
//! ``` //! ```
use actix_web::{
error::BlockingError,
http::{
header::{HeaderMap, InvalidHeaderValue, ToStrError},
uri::PathAndQuery,
Method,
},
};
use chrono::Duration; use chrono::Duration;
use std::{collections::BTreeMap, fmt::Display, future::Future, pin::Pin};
#[cfg(any(feature = "client", feature = "server"))]
use actix_http::http::{
header::{HeaderMap, ToStrError},
uri::PathAndQuery,
Method,
};
#[cfg(any(feature = "client", feature = "server"))]
use std::collections::BTreeMap;
#[cfg(feature = "client")]
mod sign; mod sign;
#[cfg(feature = "digest")] #[cfg(feature = "digest")]
pub mod digest; pub mod digest;
#[cfg(feature = "client")]
pub mod create; pub mod create;
#[cfg(feature = "server")]
pub mod middleware; pub mod middleware;
pub use http_signature_normalization::RequiredError; pub use http_signature_normalization::RequiredError;
/// Useful types and traits for using this library in Actix Web /// Useful types and traits for using this library in Actix Web
pub mod prelude { pub mod prelude {
pub use crate::{Config, RequiredError};
#[cfg(feature = "client")]
pub use crate::{PrepareSignError, Sign};
#[cfg(feature = "server")]
pub use crate::{ pub use crate::{
middleware::{SignatureVerified, VerifySignature}, middleware::{SignatureVerified, VerifySignature},
verify::{Algorithm, DeprecatedAlgorithm, Unverified}, verify::{Algorithm, DeprecatedAlgorithm, Unverified},
Config, PrepareSignError, PrepareVerifyError, RequiredError, Sign, SignatureVerify, PrepareVerifyError, SignatureVerify,
}; };
#[cfg(feature = "digest")] #[cfg(all(feature = "digest", feature = "client"))]
pub use crate::digest::{DigestClient, DigestCreate, SignExt};
#[cfg(all(feature = "digest", feature = "server"))]
pub use crate::digest::{ pub use crate::digest::{
middleware::{DigestVerified, VerifyDigest}, middleware::{DigestVerified, VerifyDigest},
DigestClient, DigestCreate, DigestPart, DigestVerify, SignExt, DigestPart, DigestVerify,
}; };
pub use actix_web::http::header::{InvalidHeaderValue, ToStrError}; pub use actix_http::http::header::{InvalidHeaderValue, ToStrError};
} }
#[cfg(feature = "server")]
/// Types for Verifying an HTTP Signature /// Types for Verifying an HTTP Signature
pub mod verify { pub mod verify {
pub use http_signature_normalization::verify::{ pub use http_signature_normalization::verify::{
@ -205,69 +218,11 @@ pub mod verify {
}; };
} }
use self::{ #[cfg(feature = "client")]
create::Unsigned, pub use self::client::{PrepareSignError, Sign};
verify::{Algorithm, Unverified},
};
/// A trait for verifying signatures #[cfg(feature = "server")]
pub trait SignatureVerify { pub use self::server::{PrepareVerifyError, SignatureVerify};
/// An error produced while attempting to verify the signature. This can be anything
/// implementing ResponseError
type Error: actix_web::ResponseError;
/// The future that resolves to the verification state of the signature
type Future: Future<Output = Result<bool, Self::Error>>;
/// Given the algorithm, key_id, signature, and signing_string, produce a future that resulves
/// to a the verification status
fn signature_verify(
&mut self,
algorithm: Option<Algorithm>,
key_id: String,
signature: String,
signing_string: String,
) -> Self::Future;
}
/// 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>(
self,
config: Config,
key_id: K,
f: F,
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
where
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<BlockingError>
+ From<PrepareSignError>
+ From<InvalidHeaderValue>
+ std::fmt::Debug
+ Send
+ 'static,
K: Display + 'static,
Self: Sized;
/// Add a Signature to the request
fn signature<F, E, K>(
self,
config: Config,
key_id: K,
f: F,
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
where
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<BlockingError>
+ From<PrepareSignError>
+ From<InvalidHeaderValue>
+ std::fmt::Debug
+ Send
+ 'static,
K: Display + 'static,
Self: Sized;
}
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
/// Configuration for signing and verifying signatures /// Configuration for signing and verifying signatures
@ -282,60 +237,136 @@ pub struct Config {
set_host: bool, set_host: bool,
} }
#[derive(Debug, thiserror::Error)] #[cfg(feature = "client")]
/// An error when preparing to verify a request mod client {
pub enum PrepareVerifyError { use super::{Config, RequiredError};
#[error("Header is missing")] use actix_http::{
/// Header is missing error::BlockingError,
Missing, http::header::{InvalidHeaderValue, ToStrError},
};
use std::{fmt::Display, future::Future, pin::Pin};
#[error("Header is expired")] /// A trait implemented by the awc ClientRequest type to add an HTTP signature to the request
/// Header is expired pub trait Sign {
Expired, /// Add an Authorization Signature to the request
fn authorization_signature<F, E, K>(
self,
config: Config,
key_id: K,
f: F,
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
where
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<BlockingError>
+ From<PrepareSignError>
+ From<InvalidHeaderValue>
+ std::fmt::Debug
+ Send
+ 'static,
K: Display + 'static,
Self: Sized;
#[error("Couldn't parse required field, {0}")] /// Add a Signature to the request
/// Couldn't parse required field fn signature<F, E, K>(
ParseField(&'static str), self,
config: Config,
key_id: K,
f: F,
) -> Pin<Box<dyn Future<Output = Result<Self, E>>>>
where
F: FnOnce(&str) -> Result<String, E> + Send + 'static,
E: From<BlockingError>
+ From<PrepareSignError>
+ From<InvalidHeaderValue>
+ std::fmt::Debug
+ Send
+ 'static,
K: Display + 'static,
Self: Sized;
}
#[error("Failed to read header, {0}")] #[derive(Debug, thiserror::Error)]
/// An error converting the header to a string for validation /// An error when preparing to sign a request
Header(#[from] ToStrError), pub enum PrepareSignError {
#[error("Failed to read header, {0}")]
/// An error occurred when reading the request's headers
Header(#[from] ToStrError),
#[error("{0}")] #[error("{0}")]
/// Required headers were missing from request /// Some headers were marked as required, but are missing
Required(#[from] RequiredError), RequiredError(#[from] RequiredError),
#[error("No host provided for URL, {0}")]
/// Missing host
Host(String),
}
} }
#[derive(Debug, thiserror::Error)] #[cfg(feature = "server")]
/// An error when preparing to sign a request mod server {
pub enum PrepareSignError { use super::RequiredError;
#[error("Failed to read header, {0}")] use actix_http::http::header::ToStrError;
/// An error occurred when reading the request's headers use std::future::Future;
Header(#[from] ToStrError),
#[error("{0}")] /// A trait for verifying signatures
/// Some headers were marked as required, but are missing pub trait SignatureVerify {
RequiredError(#[from] RequiredError), /// An error produced while attempting to verify the signature. This can be anything
/// implementing ResponseError
type Error: actix_web::ResponseError;
#[error("No host provided for URL, {0}")] /// The future that resolves to the verification state of the signature
/// Missing host type Future: Future<Output = Result<bool, Self::Error>>;
Host(String),
}
impl From<http_signature_normalization::PrepareVerifyError> for PrepareVerifyError { /// Given the algorithm, key_id, signature, and signing_string, produce a future that resulves
fn from(e: http_signature_normalization::PrepareVerifyError) -> Self { /// to a the verification status
use http_signature_normalization as hsn; fn signature_verify(
&mut self,
algorithm: Option<super::verify::Algorithm>,
key_id: String,
signature: String,
signing_string: String,
) -> Self::Future;
}
match e { #[derive(Debug, thiserror::Error)]
hsn::PrepareVerifyError::Parse(parse_error) => { /// An error when preparing to verify a request
PrepareVerifyError::ParseField(parse_error.missing_field()) pub enum PrepareVerifyError {
} #[error("Header is missing")]
hsn::PrepareVerifyError::Validate(validate_error) => match validate_error { /// Header is missing
hsn::verify::ValidateError::Missing => PrepareVerifyError::Missing, Missing,
hsn::verify::ValidateError::Expired => PrepareVerifyError::Expired,
}, #[error("Header is expired")]
hsn::PrepareVerifyError::Required(required_error) => { /// Header is expired
PrepareVerifyError::Required(required_error) Expired,
#[error("Couldn't parse required field, {0}")]
/// Couldn't parse required field
ParseField(&'static str),
#[error("Failed to read header, {0}")]
/// An error converting the header to a string for validation
Header(#[from] ToStrError),
#[error("{0}")]
/// Required headers were missing from request
Required(#[from] RequiredError),
}
impl From<http_signature_normalization::PrepareVerifyError> for PrepareVerifyError {
fn from(e: http_signature_normalization::PrepareVerifyError) -> Self {
use http_signature_normalization as hsn;
match e {
hsn::PrepareVerifyError::Parse(parse_error) => {
PrepareVerifyError::ParseField(parse_error.missing_field())
}
hsn::PrepareVerifyError::Validate(validate_error) => match validate_error {
hsn::verify::ValidateError::Missing => PrepareVerifyError::Missing,
hsn::verify::ValidateError::Expired => PrepareVerifyError::Expired,
},
hsn::PrepareVerifyError::Required(required_error) => {
PrepareVerifyError::Required(required_error)
}
} }
} }
} }
@ -405,13 +436,14 @@ impl Config {
} }
} }
#[cfg(feature = "client")]
/// Begin the process of singing a request /// Begin the process of singing a request
pub fn begin_sign( pub fn begin_sign(
&self, &self,
method: &Method, method: &Method,
path_and_query: Option<&PathAndQuery>, path_and_query: Option<&PathAndQuery>,
headers: HeaderMap, headers: HeaderMap,
) -> Result<Unsigned, PrepareSignError> { ) -> Result<self::create::Unsigned, PrepareSignError> {
let headers = headers let headers = headers
.iter() .iter()
.map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string()))) .map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string())))
@ -425,16 +457,17 @@ impl Config {
.config .config
.begin_sign(&method.to_string(), &path_and_query, headers)?; .begin_sign(&method.to_string(), &path_and_query, headers)?;
Ok(Unsigned { unsigned }) Ok(self::create::Unsigned { unsigned })
} }
#[cfg(feature = "server")]
/// Begin the proess of verifying a request /// Begin the proess of verifying a request
pub fn begin_verify( pub fn begin_verify(
&self, &self,
method: &Method, method: &Method,
path_and_query: Option<&PathAndQuery>, path_and_query: Option<&PathAndQuery>,
headers: HeaderMap, headers: HeaderMap,
) -> Result<Unverified, PrepareVerifyError> { ) -> Result<self::verify::Unverified, PrepareVerifyError> {
let headers = headers let headers = headers
.iter() .iter()
.map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string()))) .map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string())))

View file

@ -1,4 +1,4 @@
use actix_web::{error::BlockingError, http::header::InvalidHeaderValue, web}; use actix_http::{error::BlockingError, http::header::InvalidHeaderValue};
use awc::ClientRequest; use awc::ClientRequest;
use std::{fmt::Display, future::Future, pin::Pin}; use std::{fmt::Display, future::Future, pin::Pin};
@ -92,7 +92,7 @@ where
let key_id = key_id.to_string(); let key_id = key_id.to_string();
let signed = web::block(move || unsigned.sign(key_id, f)).await??; let signed = actix_rt::task::spawn_blocking(move || unsigned.sign(key_id, f)).await.map_err(|_| BlockingError)??;
Ok(signed) Ok(signed)
} }