#![deny(missing_docs)]
use actix_web::http::{
header::{HeaderMap, InvalidHeaderValue, ToStrError},
uri::PathAndQuery,
Method,
};
use std::{collections::BTreeMap, fmt::Display, future::Future};
mod sign;
#[cfg(feature = "digest")]
pub mod digest;
pub mod create;
pub mod middleware;
pub mod prelude {
pub use crate::{
middleware::{SignatureVerified, VerifySignature},
verify::{Algorithm, Unverified},
Config, PrepareVerifyError, Sign, SignatureVerify,
};
#[cfg(feature = "digest")]
pub use crate::digest::{
middleware::{DigestVerified, VerifyDigest},
DigestClient, DigestCreate, DigestPart, DigestVerify, SignExt,
};
pub use actix_web::http::header::{InvalidHeaderValue, ToStrError};
}
pub mod verify {
pub use http_signature_normalization::verify::{
Algorithm, DeprecatedAlgorithm, ParseSignatureError, ParsedHeader, Unvalidated, Unverified,
ValidateError,
};
}
use self::{
create::Unsigned,
verify::{Algorithm, Unverified},
};
pub trait SignatureVerify {
type Error: actix_web::ResponseError;
type Future: Future<Output = Result<bool, Self::Error>>;
fn signature_verify(
&mut self,
algorithm: Option<Algorithm>,
key_id: &str,
signature: &str,
signing_string: &str,
) -> Self::Future;
}
pub trait Sign {
fn authorization_signature<F, E, K>(self, config: &Config, key_id: K, f: F) -> Result<Self, E>
where
F: FnOnce(&str) -> Result<String, E>,
E: From<ToStrError> + From<InvalidHeaderValue>,
K: Display,
Self: Sized;
fn signature<F, E, K>(self, config: &Config, key_id: K, f: F) -> Result<Self, E>
where
F: FnOnce(&str) -> Result<String, E>,
E: From<ToStrError> + From<InvalidHeaderValue>,
K: Display,
Self: Sized;
}
#[derive(Clone, Debug, Default)]
pub struct Config {
pub config: http_signature_normalization::Config,
}
#[derive(Debug, thiserror::Error)]
pub enum PrepareVerifyError {
#[error("Signature error, {0}")]
Sig(#[from] http_signature_normalization::PrepareVerifyError),
#[error("Failed to read header, {0}")]
Header(#[from] ToStrError),
}
impl Config {
pub fn begin_sign(
&self,
method: &Method,
path_and_query: Option<&PathAndQuery>,
headers: HeaderMap,
) -> Result<Unsigned, ToStrError> {
let headers = headers
.iter()
.map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string())))
.collect::<Result<BTreeMap<_, _>, ToStrError>>()?;
let path_and_query = path_and_query
.map(|p| p.to_string())
.unwrap_or(String::from("/"));
let unsigned = self
.config
.begin_sign(&method.to_string(), &path_and_query, headers);
Ok(Unsigned { unsigned })
}
pub fn begin_verify(
&self,
method: &Method,
path_and_query: Option<&PathAndQuery>,
headers: HeaderMap,
) -> Result<Unverified, PrepareVerifyError> {
let headers = headers
.iter()
.map(|(k, v)| v.to_str().map(|v| (k.to_string(), v.to_string())))
.collect::<Result<BTreeMap<_, _>, ToStrError>>()?;
let path_and_query = path_and_query
.map(|p| p.to_string())
.unwrap_or(String::from("/"));
let unverified = self
.config
.begin_verify(&method.to_string(), &path_and_query, headers)?;
Ok(unverified)
}
}