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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#![deny(missing_docs)]

//! # HTTP Signature Normaliztion
//! _An HTTP Signatures library that leaves the signing to you_
//!
//! - [crates.io](https://crates.io/crates/http-signature-normalization)
//! - [docs.rs](https://docs.rs/http-signature-normalization)
//! - [Join the discussion on Matrix](https://matrix.to/#/!IRQaBCMWKbpBWKjQgx:asonix.dog?via=asonix.dog)
//!
//! Http Signature Normalization is a minimal-dependency crate for producing HTTP Signatures with user-provided signing and verification. The API is simple; there's a series of steps for creation and verification with types that ensure reasonable usage.
//!
//! ```rust
//! use chrono::Duration;
//! use http_signature_normalization::Config;
//! use std::collections::BTreeMap;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let config = Config {
//!         expires_after: Duration::seconds(5),
//!     };
//!
//!     let headers = BTreeMap::new();
//!
//!     let signature_header_value = config
//!         .begin_sign("GET", "/foo?bar=baz", headers)
//!         .sign("my-key-id".to_owned(), |signing_string| {
//!             // sign the string here
//!             Ok(signing_string.to_owned()) as Result<_, Box<dyn std::error::Error>>
//!         })?
//!         .signature_header();
//!
//!     let mut headers = BTreeMap::new();
//!     headers.insert("Signature".to_owned(), signature_header_value);
//!
//!     let verified = config
//!         .begin_verify("GET", "/foo?bar=baz", headers)?
//!         .verify(|sig, signing_string| {
//!             // Verify the signature here
//!             sig == signing_string
//!         });
//!
//!     assert!(verified);
//!     Ok(())
//! }
//! ```

use chrono::{DateTime, Duration, Utc};
use std::{collections::BTreeMap, error::Error, fmt};

pub mod create;
pub mod verify;

use self::{
    create::Unsigned,
    verify::{ParseSignatureError, ParsedHeader, Unverified, ValidateError},
};

const REQUEST_TARGET: &'static str = "(request-target)";
const CREATED: &'static str = "(created)";
const EXPIRES: &'static str = "(expires)";

const KEY_ID_FIELD: &'static str = "keyId";
const ALGORITHM_FIELD: &'static str = "algorithm";
const ALGORITHM_VALUE: &'static str = "hs2019";
const CREATED_FIELD: &'static str = "created";
const EXPIRES_FIELD: &'static str = "expires";
const HEADERS_FIELD: &'static str = "headers";
const SIGNATURE_FIELD: &'static str = "signature";

#[derive(Clone, Debug)]
/// Configuration for signing and verifying signatures
///
/// Currently, the only configuration provided is how long a signature should be considered valid
/// before it expires.
pub struct Config {
    /// How long a singature is valid
    pub expires_after: Duration,
}

#[derive(Debug)]
/// Error preparing a header for validation
///
/// This could be due to a missing header, and unparsable header, or an expired header
pub enum PrepareVerifyError {
    /// Error validating the header
    Validate(ValidateError),
    /// Error parsing the header
    Parse(ParseSignatureError),
}

impl Config {
    /// Perform the neccessary operations to produce an [`Unsigned`] type, which can be used to
    /// sign the header
    pub fn begin_sign(
        &self,
        method: &str,
        path_and_query: &str,
        headers: BTreeMap<String, String>,
    ) -> Unsigned {
        let mut headers = headers
            .into_iter()
            .map(|(k, v)| (k.to_lowercase(), v))
            .collect();
        let sig_headers = build_headers_list(&headers);

        let created = Utc::now();
        let expires = created + self.expires_after;

        let signing_string = build_signing_string(
            method,
            path_and_query,
            Some(created),
            Some(expires),
            &sig_headers,
            &mut headers,
        );

        Unsigned {
            signing_string,
            sig_headers,
            created,
            expires,
        }
    }

    /// Perform the neccessary operations to produce and [`Unerified`] type, which can be used to
    /// verify the header
    pub fn begin_verify(
        &self,
        method: &str,
        path_and_query: &str,
        headers: BTreeMap<String, String>,
    ) -> Result<Unverified, PrepareVerifyError> {
        let mut headers: BTreeMap<String, String> = headers
            .into_iter()
            .map(|(k, v)| (k.to_lowercase().to_owned(), v))
            .collect();

        let header = headers
            .remove("authorization")
            .or_else(|| headers.remove("signature"))
            .ok_or(ValidateError::Missing)?;

        let parsed_header: ParsedHeader = header.parse()?;
        let unvalidated = parsed_header.into_unvalidated(method, path_and_query, &mut headers);

        Ok(unvalidated.validate(self.expires_after)?)
    }
}

fn build_headers_list(btm: &BTreeMap<String, String>) -> Vec<String> {
    let http_header_keys: Vec<String> = btm.keys().cloned().collect();

    let mut sig_headers = vec![
        REQUEST_TARGET.to_owned(),
        CREATED.to_owned(),
        EXPIRES.to_owned(),
    ];

    sig_headers.extend(http_header_keys);

    sig_headers
}

fn build_signing_string(
    method: &str,
    path_and_query: &str,
    created: Option<DateTime<Utc>>,
    expires: Option<DateTime<Utc>>,
    sig_headers: &[String],
    btm: &mut BTreeMap<String, String>,
) -> String {
    let request_target = format!("{} {}", method.to_string().to_lowercase(), path_and_query);

    btm.insert(REQUEST_TARGET.to_owned(), request_target.clone());
    if let Some(created) = created {
        btm.insert(CREATED.to_owned(), created.timestamp().to_string());
    }
    if let Some(expires) = expires {
        btm.insert(EXPIRES.to_owned(), expires.timestamp().to_string());
    }

    let signing_string = sig_headers
        .iter()
        .filter_map(|h| btm.remove(h).map(|v| format!("{}: {}", h, v)))
        .collect::<Vec<_>>()
        .join("\n");

    signing_string
}

impl fmt::Display for PrepareVerifyError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            PrepareVerifyError::Validate(ref e) => fmt::Display::fmt(e, f),
            PrepareVerifyError::Parse(ref e) => fmt::Display::fmt(e, f),
        }
    }
}

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

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

impl From<ValidateError> for PrepareVerifyError {
    fn from(v: ValidateError) -> Self {
        PrepareVerifyError::Validate(v)
    }
}

impl From<ParseSignatureError> for PrepareVerifyError {
    fn from(p: ParseSignatureError) -> Self {
        PrepareVerifyError::Parse(p)
    }
}

impl Default for Config {
    fn default() -> Self {
        Config {
            expires_after: Duration::seconds(10),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Config;
    use std::collections::BTreeMap;

    fn prepare_headers() -> BTreeMap<String, String> {
        let mut headers = BTreeMap::new();
        headers.insert(
            "Content-Type".to_owned(),
            "application/activity+json".to_owned(),
        );
        headers
    }

    #[test]
    fn round_trip_authorization() {
        let headers = prepare_headers();
        let config = Config::default();

        let authorization_header = config
            .begin_sign("GET", "/foo?bar=baz", headers)
            .sign("hi".to_owned(), |s| {
                Ok(s.to_owned()) as Result<_, std::io::Error>
            })
            .unwrap()
            .authorization_header();

        let mut headers = prepare_headers();
        headers.insert("Authorization".to_owned(), authorization_header);

        let verified = config
            .begin_verify("GET", "/foo?bar=baz", headers)
            .unwrap()
            .verify(|sig, signing_string| sig == signing_string);

        assert!(verified);
    }

    #[test]
    fn round_trip_signature() {
        let headers = prepare_headers();
        let config = Config::default();

        let signature_header = config
            .begin_sign("GET", "/foo?bar=baz", headers)
            .sign("hi".to_owned(), |s| {
                Ok(s.to_owned()) as Result<_, std::io::Error>
            })
            .unwrap()
            .signature_header();

        let mut headers = prepare_headers();
        headers.insert("Signature".to_owned(), signature_header);

        let verified = config
            .begin_verify("GET", "/foo?bar=baz", headers)
            .unwrap()
            .verify(|sig, signing_string| sig == signing_string);

        assert!(verified);
    }
}