1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#![deny(missing_docs)]
//! Integration of Http Signature Normalization with the HTTP crate
//!
//! This provides a thin wrapper around transforming HTTP's `HeaderMap`, `PathAndQuery`, and
//! `Method` types into BTreeMaps and Strings for signing and verifying requests

use http::{
    header::{HeaderMap, ToStrError},
    method::Method,
    uri::PathAndQuery,
};
use std::{collections::BTreeMap, error::Error, fmt};

use self::{create::Unsigned, verify::Unverified};

/// Export useful types signing and verifying requests
pub mod prelude {
    pub use http::{
        header::{HeaderMap, InvalidHeaderValue, ToStrError},
        method::Method,
        uri::PathAndQuery,
    };

    pub use crate::create::{Signed, Unsigned};

    pub use crate::verify::{
        Algorithm, DeprecatedAlgorithm, ParseSignatureError, ParsedHeader, Unvalidated, Unverified,
        ValidateError,
    };

    pub use crate::{Config, PrepareVerifyError};
}

pub mod create;

/// Export types used for signature verification
pub mod verify {
    pub use http_signature_normalization::verify::{
        Algorithm, DeprecatedAlgorithm, ParseSignatureError, ParsedHeader, Unvalidated, Unverified,
        ValidateError,
    };
}

#[derive(Clone, Default)]
/// Thinly wrap Http Signature Normalization's config type
pub struct Config {
    /// Expose the inner Config
    pub config: http_signature_normalization::Config,
}

#[derive(Debug)]
/// Errors produced when preparing to verify an Http Signature
pub enum PrepareVerifyError {
    /// There was an error in the underlying library
    Sig(http_signature_normalization::PrepareVerifyError),
    /// There was an error producing a String from the HeaderValue
    Header(ToStrError),
}

impl Config {
    /// Begin the process of signing a request
    ///
    /// The types required from this function can be produced from http's Request and URI types.
    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 })
    }

    /// Begin the process of verifying a request
    ///
    /// The types required from this function can be produced from http's Request and URI types.
    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)
    }
}

impl fmt::Display for PrepareVerifyError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            PrepareVerifyError::Sig(ref e) => write!(f, "Sig error, {}", e),
            PrepareVerifyError::Header(ref e) => write!(f, "Header error, {}", e),
        }
    }
}

impl Error for PrepareVerifyError {
    fn description(&self) -> &str {
        match *self {
            PrepareVerifyError::Sig(ref e) => e.description(),
            PrepareVerifyError::Header(ref e) => e.description(),
        }
    }

    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match *self {
            PrepareVerifyError::Sig(ref e) => Some(e),
            PrepareVerifyError::Header(ref e) => Some(e),
        }
    }
}

impl From<http_signature_normalization::PrepareVerifyError> for PrepareVerifyError {
    fn from(e: http_signature_normalization::PrepareVerifyError) -> Self {
        PrepareVerifyError::Sig(e)
    }
}

impl From<ToStrError> for PrepareVerifyError {
    fn from(e: ToStrError) -> Self {
        PrepareVerifyError::Header(e)
    }
}