~vpzom/hancock

ref: 92161de0bb7e17d2e388d38060692973fc8c1502 hancock/src/lib.rs -rw-r--r-- 4.2 KiB
92161de0Colin Reeder Remove unused error case 1 year, 7 months ago
                                                                                
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
#[derive(Debug, thiserror::Error)]
pub enum SignError<T: std::fmt::Debug> {
    #[error("IO error occurred")]
    IO(#[from] std::io::Error),
    #[error("Failed in signer call")]
    User(T),
}

enum SignatureHeaderName {
    RequestTarget,
    Created,
    Expires,
    NormalHeader(http::header::HeaderName),
}

impl SignatureHeaderName {
    pub fn as_str(&self) -> &str {
        match self {
            SignatureHeaderName::RequestTarget => "(request-target)",
            SignatureHeaderName::Created => "(created)",
            SignatureHeaderName::Expires => "(expires)",
            SignatureHeaderName::NormalHeader(header) => header.as_str(),
        }
    }
}

impl From<http::header::HeaderName> for SignatureHeaderName {
    fn from(src: http::header::HeaderName) -> Self {
        SignatureHeaderName::NormalHeader(src)
    }
}

pub struct Signature<'a> {
    algorithm: Option<http::header::HeaderName>,
    created: Option<u64>,
    expires: Option<u64>,
    headers: Option<Vec<SignatureHeaderName>>,
    key_id: Option<&'a str>,
    signature: Vec<u8>,
}

impl<'a> Signature<'a> {
    pub fn create<E: std::fmt::Debug>(
        key_id: &'a str,
        request_method: &http::method::Method,
        request_path_and_query: &str,
        lifetime_secs: u64,
        headers: &mut http::header::HeaderMap,
        sign: impl FnOnce(Vec<u8>) -> Result<Vec<u8>, E>,
    ) -> Result<Self, SignError<E>> {
        use std::io::Write;

        let created = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("Timestamp is wildly unrealistic (before epoch)")
            .as_secs();
        let expires = created + lifetime_secs;

        let mut body = Vec::new();

        write!(
            body,
            "(request-target): {} {}\n(created): {}\n(expires): {}",
            request_method.as_str().to_lowercase(),
            request_path_and_query,
            created,
            expires,
        )?;

        for name in headers.keys() {
            write!(body, "\n{}: ", name)?;

            let mut first = true;
            for value in headers.get_all(name) {
                if first {
                    first = false;
                } else {
                    write!(body, ", ")?;
                }

                body.extend(value.as_bytes());
            }
        }

        let header_names: Vec<_> = vec![
            SignatureHeaderName::RequestTarget,
            SignatureHeaderName::Created,
            SignatureHeaderName::Expires,
        ]
        .into_iter()
        .chain(headers.keys().cloned().map(Into::into))
        .collect();

        let signature = sign(body).map_err(SignError::User)?;

        Ok(Self {
            algorithm: Some(http::header::HeaderName::from_static("hs2019")),
            created: Some(created),
            expires: Some(expires),
            headers: Some(header_names),
            key_id: Some(key_id),
            signature,
        })
    }

    pub fn to_header(&self) -> http::header::HeaderValue {
        use std::fmt::Write;
        let mut params = String::new();

        write!(params, "headers=\"").unwrap();
        if let Some(ref headers) = self.headers {
            for (idx, name) in headers.iter().enumerate() {
                if idx != 0 {
                    write!(params, " ").unwrap();
                }
                write!(params, "{}", name.as_str()).unwrap();
            }
        } else {
            write!(params, "(created)").unwrap();
        }
        write!(params, "\"").unwrap();

        if let Some(ref algorithm) = self.algorithm {
            write!(params, ",algorithm={}", algorithm).unwrap();
        }
        if let Some(created) = self.created {
            write!(params, ",created={}", created).unwrap();
        }
        if let Some(expires) = self.expires {
            write!(params, ",expires={}", expires).unwrap();
        }
        if let Some(key_id) = self.key_id {
            write!(params, ",keyId={}", key_id).unwrap();
        }

        write!(params, ",signature=\"").unwrap();
        base64::encode_config_buf(&self.signature, base64::STANDARD, &mut params);
        write!(params, "\"").unwrap();

        http::header::HeaderValue::from_bytes(params.as_bytes()).unwrap()
    }
}