messagesign/
lib.rs

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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
//! This crate provides a [signature] function that can be used to sign an requests
//! using Mehal signing algorithm.
//! It's based on https://github.com/uv-rust/s3v4
//!
//! The function returns an [Error] generated by the [::error_chain] crate which can be
//! converted to a `String` or accessed through the `description` method or the
//! `display_chain` and `backtrace` methods in case a full backtrace is needed.
//!
//! # Examples
//!
//! ## Signing a request
//! ```ignore
//!    let signature: s3v4::Signature = s3v4::signature(
//!        url,
//!        method,
//!        &access,
//!        &secret,
//!        &region,
//!        &"brog",
//!        machineid
//!        "UNSIGNED-PAYLOAD", //payload hash, or "UNSIGNED-PAYLOAD"
//!    ).map_err(|err| format!("Signature error: {}", err.display_chain()))?;
//!```
//!
//! ### Using the signature data to make a request
//!
//! #### Hyper
//! ```ignore
//!    let req = Request::builder()
//!        .method(Method::GET)
//!        .header("x-mhl-content-sha256", "UNSIGNED-PAYLOAD")
//!        .header("x-mhl-date", &signature.date_time)
//!        .header("x-mhl-mid", &machineid)
//!        .header("authorization", &signature.auth_header)
//! ```
//! #### Ureq
//! ```ignore
//!    let agent = AgentBuilder::new().build();
//!    let response = agent
//!        .put(&uri)
//!        .set("x-mhl-content-sha256", "UNSIGNED-PAYLOAD")
//!        .set("x-mhl-date", &signature.date_time)
//!        .set("x-mhl-mid", &machineid)
//!        .set("authorization", &signature.auth_header)
//!

use chrono::{DateTime, Utc};
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use url::Url;
use urlencoding::encode as url_encode;

type HeadersMap = BTreeMap<String, String>;

type HmacSha256 = Hmac<Sha256>;

const LONG_DATETIME_FMT: &str = "%Y%m%dT%H%M%SZ";
const SHORT_DATE_FMT: &str = "%Y%m%d";

#[macro_use]
extern crate error_chain;

mod errors {
    error_chain! {}
}

pub use errors::*;

// -----------------------------------------------------------------------------
/// Generate a canonical query string from the query pairs in the given URL.
/// The current implementation does not support repeated keys, which should not
/// be a problem for the query string used in the request.
fn canonical_query_string(uri: &Url) -> String {
    let mut qs = BTreeMap::new();
    uri.query_pairs().for_each(|(k, v)| {
        qs.insert(
            url_encode(k.as_ref()).to_string(),
            url_encode(&v).to_string(),
        );
    });
    let kv: Vec<String> = qs.iter().map(|(k, v)| format!("{}={}", k, v)).collect();
    kv.join("&")
}

// -----------------------------------------------------------------------------
/// Generate a canonical header string using only x-mhl-, host and content-length headers.
fn canonical_header_string(headers: &HeadersMap) -> String {
    let key_values = headers
        .iter()
        .filter_map(|(key, value)| {
            let k = key.as_str().to_lowercase();
            if k.starts_with("x-mhl-") || k == "host" {
                Some(k + ":" + value.as_str().trim())
            } else {
                None
            }
        })
        .collect::<Vec<String>>();
    key_values.join("\n")
}

// -----------------------------------------------------------------------------
/// Generate a signed header string using only x-mhl-, host and content-length headers.
fn signed_header_string(headers: &HeadersMap) -> String {
    let keys = headers
        .keys()
        .filter_map(|key| {
            let k = key.as_str().to_lowercase();
            if k.starts_with("x-mhl-") || k == "host" {
                Some(k)
            } else {
                None
            }
        })
        .collect::<Vec<String>>();
    keys.join(";")
}

// -----------------------------------------------------------------------------
/// Generate a canonical request.
fn canonical_request(
    method: &str,
    url: &Url,
    headers: &HeadersMap,
    payload_sha256: &str,
) -> String {
    format!(
        "{method}\n{uri}\n{query_string}\n{headers}\n\n{signed}\n{sha256}",
        method = method,
        uri = url.path().to_ascii_lowercase(),
        query_string = canonical_query_string(url),
        headers = canonical_header_string(headers),
        signed = signed_header_string(headers),
        sha256 = payload_sha256
    )
}

// -----------------------------------------------------------------------------
/// Generate a scope string.
fn scope_string(date_time: &DateTime<Utc>, region: &str) -> String {
    format!(
        "{date}/{region}/brog/gitops_request",
        date = date_time.format(SHORT_DATE_FMT),
        region = region
    )
}

// -----------------------------------------------------------------------------
/// Generate the "string to sign" - the value to which the HMAC signing is
/// applied to sign requests.
fn string_to_sign(date_time: &DateTime<Utc>, region: &str, canonical_req: &str) -> String {
    let mut hasher = Sha256::default();
    hasher.update(canonical_req.as_bytes());
    let string_to = format!(
        "MHL4-HMAC-SHA256\n{timestamp}\n{scope}\n{hash}",
        timestamp = date_time.format(LONG_DATETIME_FMT),
        scope = scope_string(date_time, region),
        hash = hex::encode(hasher.finalize().as_slice())
    );
    string_to
}

// -----------------------------------------------------------------------------
/// Generate the Mehal signing key, derived from the secret key, date, region,
/// and service name.
fn signing_key(
    date_time: &DateTime<Utc>,
    secret_key: &str,
    region: &str,
    service: &str,
) -> Result<Vec<u8>> {
    let secret = format!("MHL{}", secret_key);
    let mut date_hmac =
        HmacSha256::new_from_slice(secret.as_bytes()).chain_err(|| "error hashing secret")?;
    date_hmac.update(date_time.format(SHORT_DATE_FMT).to_string().as_bytes());
    let mut region_hmac = HmacSha256::new_from_slice(&date_hmac.finalize().into_bytes())
        .chain_err(|| "error hashing date")?;
    region_hmac.update(region.to_string().as_bytes());
    let mut service_hmac = HmacSha256::new_from_slice(&region_hmac.finalize().into_bytes())
        .chain_err(|| "error hashing region")?;
    service_hmac.update(service.as_bytes());
    let mut signing_hmac = HmacSha256::new_from_slice(&service_hmac.finalize().into_bytes())
        .chain_err(|| "error hashing service")?;
    signing_hmac.update(b"mhl_request");
    Ok(signing_hmac.finalize().into_bytes().to_vec())
}

// -----------------------------------------------------------------------------
/// Generate the Mehal authorization header.
fn authorization_header(
    access_key: &str,
    date_time: &DateTime<Utc>,
    region: &str,
    signed_headers: &str,
    signature: &str,
) -> String {
    format!(
        "AWS4-HMAC-SHA256 Credential={access_key}/{scope},\
            SignedHeaders={signed_headers},Signature={signature}",
        access_key = access_key,
        scope = scope_string(date_time, region),
        signed_headers = signed_headers,
        signature = signature
    )
}

#[allow(clippy::too_many_arguments)]
// -----------------------------------------------------------------------------
pub fn create_sign(
    method: &str,
    payload_hash: &str,
    url_string: &str,
    headers: &HeadersMap,
    date_time: &DateTime<Utc>,
    secret: &str,
    region: &str,
    service: &str,
) -> Result<String> {
    let url = Url::parse(url_string).chain_err(|| "error parsing url")?;
    let canonical = canonical_request(&method.to_uppercase(), &url, headers, payload_hash);

    let string_to_sign = string_to_sign(date_time, region, &canonical);
    let signing_key = signing_key(date_time, secret, region, service)?;
    let mut hmac =
        Hmac::<Sha256>::new_from_slice(&signing_key).chain_err(|| "error hashing signing key")?;
    hmac.update(string_to_sign.as_bytes());
    Ok(hex::encode(hmac.finalize().into_bytes()))
}
// -----------------------------------------------------------------------------
/// Struct containing authorisation header and timestamp. Returned by `sign_request`.
pub struct Signature {
    pub auth_header: String,
    pub date_time: String,
}

#[allow(clippy::too_many_arguments)]
/// Return signed header and timestamp.
pub fn signature(
    url: &url::Url,
    method: &str,
    access: &str,
    secret: &str,
    region: &str,
    service: &str,
    machineid: &str,
    payload_hash: &str,
) -> Result<Signature> {
    const LONG_DATE_TIME: &str = "%Y%m%dT%H%M%SZ";
    let host_port = url
        .host()
        .chain_err(|| "Error parsing host from url")?
        .to_string()
        + &if let Some(port) = url.port() {
            format!(":{}", port)
        } else {
            "".to_string()
        };
    let uri = url.as_str().trim_end_matches('/');
    let mut headers = HeadersMap::new();

    headers.insert("host".to_string(), host_port);

    headers.insert("x-mhl-content-sha256".to_string(), payload_hash.to_string());
    let date_time = Utc::now();
    let date_time_string = date_time.format(LONG_DATE_TIME).to_string();
    headers.insert("x-mhl-date".to_string(), date_time_string.clone());

    headers.insert("x-mhl-mid".to_string(), machineid.to_string());

    let signature = create_sign(
        method,
        payload_hash,
        uri,
        &headers,
        &date_time,
        secret,
        region,
        service,
    )?;
    let auth = authorization_header(
        access,
        &date_time,
        region,
        &signed_header_string(&headers),
        &signature,
    );
    Ok(Signature {
        auth_header: auth,
        date_time: date_time_string,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{TimeZone, Utc};

    #[test]
    fn test_signature() -> Result<()> {
        const EXPECTED_SIGNATURE: &str =
            "c0cc110abe9ace556024b35da8abd9aa1d00dea5a468df7f438e7cf0d22b2f93";
        let url = "https://mehal.tech";
        let method = "GET";
        let payload_hash = "UNSIGNED-PAYLOAD";
        let date_time = Utc.with_ymd_and_hms(2022, 2, 2, 0, 0, 0).unwrap();
        let secret = "ivegotthesecret";
        let region = "global";
        let service = "brog";
        let mut headers = HeadersMap::new();
        headers.insert("host".to_string(), "aws.com".to_string());
        headers.insert("x-mhl-content-sha256".to_string(), payload_hash.to_string());
        let signature = create_sign(
            method,
            payload_hash,
            url,
            &headers,
            &date_time,
            secret,
            region,
            service,
        )?;
        assert_eq!(EXPECTED_SIGNATURE, signature);
        Ok(())
    }
}