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
//! [Ref](https://github.com/apolloconfig/agollo/blob/master/protocol/auth/sign/sign.go)

use std::time::{SystemTime, SystemTimeError, UNIX_EPOCH};

use hmac::{digest::crypto_common::InvalidLength as HmacInvalidLength, Hmac, Mac as _};
use http::{
    header::InvalidHeaderValue, uri::InvalidUri as HttpInvalidUri, HeaderMap, HeaderValue, Uri,
};
use sha1::Sha1;

//
type HmacSha1 = Hmac<Sha1>;
const DELIMITER: char = '\n';

//
pub const HTTP_HEADER_AUTHORIZATION: &str = "Authorization";
pub const HTTP_HEADER_TIMESTAMP: &str = "Timestamp";

//
#[derive(Debug, Clone)]
pub struct AuthSignature;

impl AuthSignature {
    pub fn http_headers(
        &self,
        url: impl AsRef<str>,
        app_id: impl AsRef<str>,
        secret: impl AsRef<str>,
    ) -> Result<HeaderMap, AuthSignatureError> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_err(AuthSignatureError::GetTimestampFailed)?
            .as_millis();

        let path_with_query =
            url_to_path_with_query(url).map_err(AuthSignatureError::UrlInvalid)?;

        let string_to_sign = format!("{}{}{}", timestamp, DELIMITER, path_with_query);
        let signature = sign_string(string_to_sign, secret.as_ref())
            .map_err(|err| AuthSignatureError::AccessKeySecretInvalidLength(err.0))?;

        //
        let mut headers = HeaderMap::new();

        headers.insert(
            HTTP_HEADER_AUTHORIZATION,
            format!("Apollo {}:{}", app_id.as_ref(), signature)
                .parse::<HeaderValue>()
                .map_err(AuthSignatureError::ToHeaderValueFailed)?,
        );

        headers.insert(
            HTTP_HEADER_TIMESTAMP,
            timestamp
                .to_string()
                .parse::<HeaderValue>()
                .map_err(AuthSignatureError::ToHeaderValueFailed)?,
        );

        Ok(headers)
    }
}

error_macro::r#enum! {
    pub enum AuthSignatureError {
        GetTimestampFailed(SystemTimeError),
        UrlInvalid(UrlInvalid),
        AccessKeySecretInvalidLength(HmacInvalidLength),
        ToHeaderValueFailed(InvalidHeaderValue),
    }
}

//
fn sign_string(
    string_to_sign: impl AsRef<[u8]>,
    access_key_secret: impl AsRef<[u8]>,
) -> Result<String, AccessKeySecretInvalidLength> {
    let mut hmac = HmacSha1::new_from_slice(access_key_secret.as_ref())
        .map_err(AccessKeySecretInvalidLength)?;
    hmac.update(string_to_sign.as_ref());
    Ok(base64::encode(hmac.finalize().into_bytes()))
}

error_macro::r#struct! {
    pub struct AccessKeySecretInvalidLength(HmacInvalidLength);
}

//
fn url_to_path_with_query(raw_url: impl AsRef<str>) -> Result<String, UrlInvalid> {
    let uri = raw_url
        .as_ref()
        .parse::<Uri>()
        .map_err(UrlInvalid::InvalidUri)?;

    uri.path_and_query()
        .map(|x| x.to_string())
        .ok_or(UrlInvalid::PathAndQueryEmpty(()))
}

error_macro::r#enum! {
    pub enum UrlInvalid {
        InvalidUri(HttpInvalidUri),
        PathAndQueryEmpty(()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // https://github.com/apolloconfig/agollo/blob/master/protocol/auth/sign/sign_test.go

    const RAW_URL: &str = "http://baidu.com/a/b?key=1";
    const SECRET: &str = "6ce3ff7e96a24335a9634fe9abca6d51";
    const APP_ID: &str = "testApplication_yang";

    #[test]
    fn test_sign_string() {
        assert_eq!(
            sign_string(RAW_URL, SECRET).unwrap(),
            "mcS95GXa7CpCjIfrbxgjKr0lRu8="
        );
    }

    #[test]
    fn test_url_to_path_with_query() {
        assert_eq!(url_to_path_with_query(RAW_URL).unwrap(), "/a/b?key=1");
        assert_eq!(
            url_to_path_with_query("http://baidu.com/a/b").unwrap(),
            "/a/b"
        );
    }

    #[test]
    fn test_http_headers() {
        let headers = AuthSignature.http_headers(RAW_URL, APP_ID, SECRET).unwrap();
        println!("{:?}", headers);
        assert!(headers
            .get("Authorization")
            .unwrap()
            .as_bytes()
            .starts_with(b"Apollo testApplication_yang:"));
        assert_eq!(headers.get("Timestamp").unwrap().len(), 13);
    }
}