http-signature-normalization/actix/src/create.rs

60 lines
1.9 KiB
Rust
Raw Normal View History

2019-09-21 16:26:11 +00:00
//! Types for signing requests with Actix Web
2021-12-12 20:28:34 +00:00
use actix_http::header::{HeaderMap, HeaderName, HeaderValue, InvalidHeaderValue, AUTHORIZATION};
2019-09-11 22:05:58 +00:00
2019-09-21 16:26:11 +00:00
/// A thin wrapper around the underlying library's Signed type
///
/// This type can add signatures to Actix Web's HeaderMap
2019-09-11 22:05:58 +00:00
pub struct Signed {
2019-09-21 16:26:11 +00:00
/// The inner Signed type
///
/// This type can produce Strings representing the Authorization or Signature headers
2019-09-11 22:05:58 +00:00
pub signed: http_signature_normalization::create::Signed,
}
2019-09-21 16:26:11 +00:00
/// A thin wrapper around the underlying library's Unsigned type
///
/// This is used to prodice the proper Signed type
2019-09-11 22:05:58 +00:00
pub struct Unsigned {
2019-09-21 16:26:11 +00:00
/// The inner Unsigned type
2019-09-11 22:05:58 +00:00
pub unsigned: http_signature_normalization::create::Unsigned,
}
impl Signed {
2019-09-21 16:26:11 +00:00
/// Add the Signature Header to a given HeaderMap
2019-09-11 22:05:58 +00:00
pub fn signature_header(self, hm: &mut HeaderMap) -> Result<(), InvalidHeaderValue> {
let sig_header = self.signed.signature_header();
2019-09-11 22:05:58 +00:00
hm.insert(
HeaderName::from_static("signature"),
HeaderValue::from_str(&sig_header)?,
2019-09-11 22:05:58 +00:00
);
Ok(())
}
2019-09-21 16:26:11 +00:00
/// Add the Authorization Header to a give HeaderMap
2019-09-11 22:05:58 +00:00
pub fn authorization_header(self, hm: &mut HeaderMap) -> Result<(), InvalidHeaderValue> {
let auth_header = self.signed.authorization_header();
hm.insert(AUTHORIZATION, HeaderValue::from_str(&auth_header)?);
2019-09-11 22:05:58 +00:00
Ok(())
}
}
impl Unsigned {
2019-09-21 16:26:11 +00:00
/// Sign the signing_string for the request
///
/// ```rust,ignore
/// let signed = unsigned.sign("my-key-id".to_owned(), |signing_string| {
/// let signature = private_key.sign(signing_string)?;
/// Ok(base64::encode(signature))
/// })?;
/// ```
2019-09-11 22:05:58 +00:00
pub fn sign<F, E>(self, key_id: String, f: F) -> Result<Signed, E>
where
F: FnOnce(&str) -> Result<String, E>,
2019-09-11 22:05:58 +00:00
{
let signed = self.unsigned.sign(key_id, f)?;
Ok(Signed { signed })
}
}