This commit is contained in:
asonix 2022-11-28 19:36:50 -06:00
parent 69e607bf7a
commit 953b75a22d
3 changed files with 314 additions and 62 deletions

View file

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

View file

@ -27,7 +27,7 @@ pub struct Cfg;
pub struct Key; pub struct Key;
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum MyError { pub enum VerifyError {
#[error("Unsupported algorithm")] #[error("Unsupported algorithm")]
Algorithm, Algorithm,
@ -46,7 +46,7 @@ impl ConfigGenerator for Cfg {
#[async_trait::async_trait(?Send)] #[async_trait::async_trait(?Send)]
impl VerifyKey for Key { impl VerifyKey for Key {
type Error = MyError; type Error = VerifyError;
async fn init( async fn init(
_: &HttpRequest, _: &HttpRequest,
@ -55,11 +55,11 @@ impl VerifyKey for Key {
) -> Result<Self, Self::Error> { ) -> Result<Self, Self::Error> {
match algorithm { match algorithm {
Some(Algorithm::Hs2019 | Algorithm::Deprecated(DeprecatedAlgorithm::RsaSha256)) => (), Some(Algorithm::Hs2019 | Algorithm::Deprecated(DeprecatedAlgorithm::RsaSha256)) => (),
_ => return Err(MyError::Algorithm), _ => return Err(VerifyError::Algorithm),
}; };
if key_id != "my-key-id" { if key_id != "my-key-id" {
return Err(MyError::Key); return Err(VerifyError::Key);
} }
Ok(Key) Ok(Key)
@ -68,16 +68,13 @@ impl VerifyKey for Key {
fn verify(&mut self, signature: &str, signing_string: &str) -> Result<bool, Self::Error> { fn verify(&mut self, signature: &str, signing_string: &str) -> Result<bool, Self::Error> {
use subtle::ConstantTimeEq; use subtle::ConstantTimeEq;
let decoded = match base64::decode(&signature) { let decoded = base64::decode(&signature).map_err(|_| VerifyError::Decode)?;
Ok(decoded) => decoded,
Err(_) => return Err(MyError::Decode),
};
Ok(decoded.ct_eq(signing_string.as_bytes()).into()) Ok(decoded.ct_eq(signing_string.as_bytes()).into())
} }
} }
impl ResponseError for MyError { impl ResponseError for VerifyError {
fn status_code(&self) -> StatusCode { fn status_code(&self) -> StatusCode {
StatusCode::BAD_REQUEST StatusCode::BAD_REQUEST
} }

View file

@ -1,6 +1,101 @@
// #![deny(missing_docs)] // #![deny(missing_docs)]
//! Experimental Extractor for request signatures //! # Http Signature Normalization Actix Extractor
//! _Experimental Extractor for request signatures_
//!
//! This library takes a different approach from the other implementation, which prefers
//! Middlewares.
//!
//! ```rust
//! use actix_web::{http::StatusCode, web, App, HttpRequest, HttpResponse, HttpServer, ResponseError};
//! use http_signature_normalization_actix_extractor::{
//! Algorithm, Config, ConfigGenerator, DeprecatedAlgorithm, Signed, VerifyKey,
//! };
//! use sha2::Sha256;
//!
//! #[actix_web::main]
//! async fn main() -> std::io::Result<()> {
//! /*
//! HttpServer::new(|| App::new().route("/", web::post().to(protected)))
//! .bind("127.0.0.1:8010")?
//! .run()
//! .await
//! */
//! Ok(())
//! }
//!
//! async fn protected(signed_request: Signed<String, Cfg, Sha256, Key>) -> &'static str {
//! let (value, signature) = signed_request.into_parts();
//!
//! println!("{}", value);
//! println!("{:#?}", signature);
//!
//! "hewwo, mr obama"
//! }
//!
//! pub struct Cfg;
//!
//! #[derive(Debug)]
//! pub struct Key;
//!
//! #[derive(Debug, thiserror::Error)]
//! pub enum VerifyError {
//! #[error("Unsupported algorithm")]
//! Algorithm,
//!
//! #[error("Couldn't decode signature")]
//! Decode,
//!
//! #[error("Invalid key")]
//! Key,
//! }
//!
//! impl ConfigGenerator for Cfg {
//! fn config() -> Config {
//! Config::new().require_header("accept")
//! }
//! }
//!
//! #[async_trait::async_trait(?Send)]
//! impl VerifyKey for Key {
//! type Error = VerifyError;
//!
//! async fn init(
//! _: &HttpRequest,
//! key_id: &str,
//! algorithm: Option<&Algorithm>,
//! ) -> Result<Self, Self::Error> {
//! match algorithm {
//! Some(Algorithm::Hs2019 | Algorithm::Deprecated(DeprecatedAlgorithm::RsaSha256)) => (),
//! _ => return Err(VerifyError::Algorithm),
//! };
//!
//! if key_id != "my-key-id" {
//! return Err(VerifyError::Key);
//! }
//!
//! Ok(Key)
//! }
//!
//! fn verify(&mut self, signature: &str, signing_string: &str) -> Result<bool, Self::Error> {
//! use subtle::ConstantTimeEq;
//!
//! let decoded = base64::decode(&signature).map_err(|_| VerifyError::Decode)?;
//!
//! Ok(decoded.ct_eq(signing_string.as_bytes()).into())
//! }
//! }
//!
//! impl ResponseError for VerifyError {
//! fn status_code(&self) -> StatusCode {
//! StatusCode::BAD_REQUEST
//! }
//!
//! fn error_response(&self) -> HttpResponse {
//! HttpResponse::BadRequest().finish()
//! }
//! }
//! ```
pub use actix_web_lab::extract::RequestSignature; pub use actix_web_lab::extract::RequestSignature;
pub use http_signature_normalization::{ pub use http_signature_normalization::{
@ -8,65 +103,38 @@ pub use http_signature_normalization::{
Config, PrepareVerifyError, Config, PrepareVerifyError,
}; };
/// An alias to simplify extracting a signed request
/// ```rust,ignore
/// async fn protected(_: Signed<String, (), (), Key>) -> &'static str {
/// "hewwo, mr obama"
/// }
/// ```
pub type Signed<Extractor, Config, Digest, VerifyKey> = pub type Signed<Extractor, Config, Digest, VerifyKey> =
RequestSignature<Extractor, SignatureScheme<Config, Digest, VerifyKey>>; RequestSignature<Extractor, SignedRequest<Config, Digest, VerifyKey>>;
#[cfg(feature = "sha-2")] #[cfg(feature = "sha-2")]
mod sha2_digest; mod sha2_digest;
#[derive(Debug)] #[derive(Debug)]
/// Errors produced by the Extractor
pub enum Error { pub enum Error {
/// The provided Digest header was invalid
Digest, Digest,
/// The provided Signature or Authorization header was invalid
Signature, Signature,
/// Another header required for verifying the signature is invalid
InvalidHeaderValue, InvalidHeaderValue,
/// There was an error preparing for verification
PrepareVerify(PrepareVerifyError), PrepareVerify(PrepareVerifyError),
} }
impl std::fmt::Display for Error { /// The SignedRequest Signature scheme
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { ///
match self { /// This implements SignatureScheme to allow extracing a signed request
Self::Digest => write!(f, "Digest is inavlid"), pub struct SignedRequest<C, D, K> {
Self::Signature => write!(f, "Signature is invalid"),
Self::InvalidHeaderValue => write!(f, "Invalid header value"),
Self::PrepareVerify(_) => write!(f, "Error preparint verification"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::PrepareVerify(ref e) => Some(e),
Self::Digest => None,
Self::Signature => None,
Self::InvalidHeaderValue => None,
}
}
}
impl actix_web::ResponseError for Error {
fn status_code(&self) -> actix_web::http::StatusCode {
actix_web::http::StatusCode::BAD_REQUEST
}
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
actix_web::HttpResponse::build(self.status_code()).finish()
}
}
impl From<PrepareVerifyError> for Error {
fn from(e: PrepareVerifyError) -> Self {
Error::PrepareVerify(e)
}
}
impl From<actix_web::http::header::ToStrError> for Error {
fn from(_: actix_web::http::header::ToStrError) -> Self {
Error::InvalidHeaderValue
}
}
pub struct SignatureScheme<C, D, K> {
config_generator: std::marker::PhantomData<C>, config_generator: std::marker::PhantomData<C>,
key: std::marker::PhantomData<K>, key: std::marker::PhantomData<K>,
digest_verifier: Option<D>, digest_verifier: Option<D>,
@ -74,12 +142,17 @@ pub struct SignatureScheme<C, D, K> {
} }
#[derive(Debug)] #[derive(Debug)]
/// A parsed part of a Digest header
pub struct DigestPart { pub struct DigestPart {
/// The Algorithm this digest was computed with
pub algorithm: String, pub algorithm: String,
/// The base64-encoded digest
pub digest: String, pub digest: String,
} }
#[derive(Debug)] #[derive(Debug)]
/// All the required pieces for validating a request signature
pub struct Signature<D, K> { pub struct Signature<D, K> {
key: K, key: K,
unverified: http_signature_normalization::verify::Unverified, unverified: http_signature_normalization::verify::Unverified,
@ -87,37 +160,174 @@ pub struct Signature<D, K> {
digest_parts: Option<Vec<DigestPart>>, digest_parts: Option<Vec<DigestPart>>,
} }
pub trait DigestName { /// Injects a customized [`Config`] type for signature verification
const NAME: &'static str; ///
} /// If you don't need to customize the `Config`, you can use `()`
///
/// ```rust
/// use http_signature_normalization_actix_extractor::{Config, ConfigGenerator};
///
/// struct Gen;
///
/// impl ConfigGenerator for Gen {
/// fn config() -> Config {
/// Config::new()
/// }
/// }
/// ```
pub trait ConfigGenerator { pub trait ConfigGenerator {
/// Produce a new `Config`
fn config() -> Config; fn config() -> Config;
} }
#[async_trait::async_trait(?Send)] #[async_trait::async_trait(?Send)]
/// Extracts a key from the request
///
/// ```rust
/// use actix_web::{http::StatusCode, web::Data, HttpRequest, HttpResponse, ResponseError};
/// use http_signature_normalization_actix_extractor::{Algorithm, DeprecatedAlgorithm, VerifyKey};
/// use openssl::{hash::MessageDigest, pkey::{PKey, Public}, sign::Verifier};
///
/// pub struct OpenSSLPublicKey(PKey<Public>);
///
/// #[async_trait::async_trait(?Send)]
/// impl VerifyKey for OpenSSLPublicKey {
/// type Error = VerifyError;
///
/// async fn init(
/// req: &HttpRequest,
/// key_id: &str,
/// algorithm: Option<&Algorithm>,
/// ) -> Result<Self, Self::Error> {
/// match algorithm {
/// Some(Algorithm::Hs2019 | Algorithm::Deprecated(DeprecatedAlgorithm::RsaSha256)) => (),
/// _ => return Err(VerifyError::Algorithm),
/// };
///
/// if key_id != "my-key-id" {
/// return Err(VerifyError::Key);
/// }
///
/// let key = req.app_data::<Data<PKey<Public>>>().expect("Key loaded").as_ref().clone();
///
/// Ok(OpenSSLPublicKey(key))
/// }
///
/// fn verify(&mut self, signature: &str, signing_string: &str) -> Result<bool, Self::Error> {
/// let decoded = openssl::base64::decode_block(&signature).map_err(|_| VerifyError::Decode)?;
///
/// let verifier = Verifier::new(MessageDigest::sha256(), &self.0).map_err(|_| VerifyError::Verifier)?;
///
/// verifier.verify(&decoded).map_err(|_| VerifyError::Verify)
/// }
/// }
///
/// #[derive(Debug, thiserror::Error)]
/// pub enum VerifyError {
/// #[error("Unsupported algorithm")]
/// Algorithm,
///
/// #[error("Couldn't decode signature")]
/// Decode,
///
/// #[error("Invalid key")]
/// Key,
///
/// #[error("Failed to create Verifier from key")]
/// Verifier,
///
/// #[error("Failed to verify signature")]
/// Verify,
/// }
///
/// impl ResponseError for VerifyError {
/// fn status_code(&self) -> StatusCode {
/// StatusCode::BAD_REQUEST
/// }
///
/// fn error_response(&self) -> HttpResponse {
/// HttpResponse::BadRequest().finish()
/// }
/// }
/// ```
pub trait VerifyKey: Sized + Send { pub trait VerifyKey: Sized + Send {
/// Errors that can happen when extracting keys or verifying the signature
type Error: Into<actix_web::Error>; type Error: Into<actix_web::Error>;
/// Extract the key from the request, given the key_id and algorithm
async fn init( async fn init(
req: &actix_web::HttpRequest, req: &actix_web::HttpRequest,
key_id: &str, key_id: &str,
algorithm: Option<&Algorithm>, algorithm: Option<&Algorithm>,
) -> Result<Self, Self::Error>; ) -> Result<Self, Self::Error>;
/// Verify the signature with the given signing string
fn verify(&mut self, signature: &str, signing_string: &str) -> Result<bool, Self::Error>; fn verify(&mut self, signature: &str, signing_string: &str) -> Result<bool, Self::Error>;
} }
/// Verifies the Digest header from the request
///
/// For endpoints that do not accept request bodies, `()` can be used as the verifier
///
/// ### Example:
/// ```rust
/// use http_signature_normalization_actix_extractor::{DigestPart, VerifyDigest};
/// use openssl::sha::Sha256;
///
/// struct OpenSSLSha256(Option<Sha256>);
///
/// impl Default for OpenSSLSha256 {
/// fn default() -> Self {
/// Self::new()
/// }
/// }
///
/// impl OpenSSLSha256 {
/// fn new() -> Self {
/// Self(Some(Sha256::new()))
/// }
/// }
///
/// impl VerifyDigest for OpenSSLSha256 {
/// fn update(&mut self, bytes: &[u8]) {
/// self.0.as_mut().expect("Update called after verify").update(bytes);
/// }
///
/// fn verify(&mut self, parts: &[DigestPart]) -> bool {
/// if let Some(decoded) = parts.iter().find_map(|p| {
/// if p.algorithm.to_lowercase() == "sha-256" {
/// openssl::base64::decode_block(&p.digest).ok()
/// } else {
/// None
/// }
/// }) {
/// return openssl::memcmp::eq(
/// &self.0.take().expect("verify called more than once").finish(),
/// &decoded,
/// );
/// }
///
/// false
/// }
/// }
/// ```
pub trait VerifyDigest: Default + Send + 'static { pub trait VerifyDigest: Default + Send + 'static {
/// Whether to run this verifier
const REQUIRED: bool = true; const REQUIRED: bool = true;
/// Update the verifier with th eprovided bytes
fn update(&mut self, bytes: &[u8]); fn update(&mut self, bytes: &[u8]);
/// Given a slice of parts, verify that the one matching the current verifier is valid
fn verify(&mut self, parts: &[DigestPart]) -> bool; fn verify(&mut self, parts: &[DigestPart]) -> bool;
} }
trait DigestName {
const NAME: &'static str;
}
#[async_trait::async_trait(?Send)] #[async_trait::async_trait(?Send)]
impl<C, D, K> actix_web_lab::extract::RequestSignatureScheme for SignatureScheme<C, D, K> impl<C, D, K> actix_web_lab::extract::RequestSignatureScheme for SignedRequest<C, D, K>
where where
C: ConfigGenerator, C: ConfigGenerator,
D: VerifyDigest, D: VerifyDigest,
@ -137,7 +347,7 @@ where
req.headers(), req.headers(),
)?; )?;
Ok(SignatureScheme { Ok(SignedRequest {
config_generator: std::marker::PhantomData, config_generator: std::marker::PhantomData,
key: std::marker::PhantomData, key: std::marker::PhantomData,
digest_verifier: Some(D::default()), digest_verifier: Some(D::default()),
@ -283,3 +493,47 @@ impl VerifyDigest for () {
true true
} }
} }
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Digest => write!(f, "Digest is inavlid"),
Self::Signature => write!(f, "Signature is invalid"),
Self::InvalidHeaderValue => write!(f, "Invalid header value"),
Self::PrepareVerify(_) => write!(f, "Error preparint verification"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::PrepareVerify(ref e) => Some(e),
Self::Digest => None,
Self::Signature => None,
Self::InvalidHeaderValue => None,
}
}
}
impl actix_web::ResponseError for Error {
fn status_code(&self) -> actix_web::http::StatusCode {
actix_web::http::StatusCode::BAD_REQUEST
}
fn error_response(&self) -> actix_web::HttpResponse<actix_web::body::BoxBody> {
actix_web::HttpResponse::build(self.status_code()).finish()
}
}
impl From<PrepareVerifyError> for Error {
fn from(e: PrepareVerifyError) -> Self {
Error::PrepareVerify(e)
}
}
impl From<actix_web::http::header::ToStrError> for Error {
fn from(_: actix_web::http::header::ToStrError) -> Self {
Error::InvalidHeaderValue
}
}