http_signature_normalization_http/
create.rs

1//! Types used for signing a request
2use http::header::{HeaderMap, HeaderName, HeaderValue, InvalidHeaderValue, AUTHORIZATION};
3
4/// A thin wrapper around the base library's Signed type
5pub struct Signed {
6    /// The inner Signed type which can produce string versions of HTTP headers
7    pub signed: http_signature_normalization::create::Signed,
8}
9
10/// A thin wrapper around the base library's Unsigned type
11///
12/// This is used to produce a Signed type that can interact with http's types
13pub struct Unsigned {
14    /// The inner Unsigned type, which can produce the base library's Signed type
15    pub unsigned: http_signature_normalization::create::Unsigned,
16}
17
18impl Signed {
19    /// Set the Signature Header in a given HeaderMap
20    pub fn signature_header(self, hm: &mut HeaderMap) -> Result<(), InvalidHeaderValue> {
21        hm.insert(
22            HeaderName::from_static("Signature"),
23            HeaderValue::from_str(&self.signed.signature_header())?,
24        );
25
26        Ok(())
27    }
28
29    /// Set the Authorization Header in a given HeaderMap
30    pub fn authorization_header(self, hm: &mut HeaderMap) -> Result<(), InvalidHeaderValue> {
31        hm.insert(
32            AUTHORIZATION,
33            HeaderValue::from_str(&self.signed.authorization_header())?,
34        );
35        Ok(())
36    }
37}
38
39impl Unsigned {
40    /// Sign the request
41    ///
42    /// ```rust,ignore
43    /// let signed = unsigned.sign("my-key-id".to_owned(), |signing_string| {
44    ///     let signature = private_key.sign(signing_string)?;
45    ///     Ok(base64::encode(signature))
46    /// })?;
47    /// ```
48    pub fn sign<F, E>(self, key_id: String, f: F) -> Result<Signed, E>
49    where
50        F: FnOnce(&str) -> Result<String, E>,
51    {
52        let signed = self.unsigned.sign(key_id, f)?;
53        Ok(Signed { signed })
54    }
55}