1use crate::{
7 date_time::{format_date, format_date_time},
8 http_request::SigningError,
9 SigningOutput,
10};
11use aws_credential_types::Credentials;
12use aws_smithy_runtime_api::{client::identity::Identity, http::Headers};
13use bytes::Bytes;
14use hmac::{digest::FixedOutput, Hmac, KeyInit, Mac};
15use sha2::{Digest, Sha256};
16use std::time::SystemTime;
17
18#[allow(dead_code)] pub(crate) fn sha256_hex_string(bytes: impl AsRef<[u8]>) -> String {
21 let mut hasher = Sha256::new();
22 hasher.update(bytes);
23 hex::encode(hasher.finalize_fixed())
24}
25
26pub(crate) const EMPTY_PAYLOAD_SHA256: &str =
28 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
29
30pub fn calculate_signature(signing_key: impl AsRef<[u8]>, string_to_sign: &[u8]) -> String {
32 let mut mac = Hmac::<Sha256>::new_from_slice(signing_key.as_ref())
33 .expect("HMAC can take key of any size");
34 mac.update(string_to_sign);
35 hex::encode(mac.finalize_fixed())
36}
37
38pub fn generate_signing_key(
40 secret: &str,
41 time: SystemTime,
42 region: &str,
43 service: &str,
44) -> impl AsRef<[u8]> {
45 let secret = format!("AWS4{secret}");
52 let mut mac =
53 Hmac::<Sha256>::new_from_slice(secret.as_ref()).expect("HMAC can take key of any size");
54 mac.update(format_date(time).as_bytes());
55 let tag = mac.finalize_fixed();
56
57 let mut mac = Hmac::<Sha256>::new_from_slice(&tag).expect("HMAC can take key of any size");
59 mac.update(region.as_bytes());
60 let tag = mac.finalize_fixed();
61
62 let mut mac = Hmac::<Sha256>::new_from_slice(&tag).expect("HMAC can take key of any size");
64 mac.update(service.as_bytes());
65 let tag = mac.finalize_fixed();
66
67 let mut mac = Hmac::<Sha256>::new_from_slice(&tag).expect("HMAC can take key of any size");
69 mac.update("aws4_request".as_bytes());
70 mac.finalize_fixed()
71}
72
73#[derive(Debug)]
75#[non_exhaustive]
76pub struct SigningParams<'a, S> {
77 pub(crate) identity: &'a Identity,
79
80 pub(crate) region: &'a str,
82 pub(crate) name: &'a str,
86 pub(crate) time: SystemTime,
88
89 pub(crate) settings: S,
91}
92
93pub(crate) const HMAC_SHA256: &str = "AWS4-HMAC-SHA256";
94const HMAC_SHA256_PAYLOAD: &str = "AWS4-HMAC-SHA256-PAYLOAD";
95const HMAC_SHA256_TRAILER: &str = "AWS4-HMAC-SHA256-TRAILER";
96
97impl<S> SigningParams<'_, S> {
98 pub fn region(&self) -> &str {
100 self.region
101 }
102
103 pub fn name(&self) -> &str {
105 self.name
106 }
107
108 pub fn algorithm(&self) -> &'static str {
110 HMAC_SHA256
111 }
112}
113
114impl<'a, S: Default> SigningParams<'a, S> {
115 pub fn builder() -> signing_params::Builder<'a, S> {
117 Default::default()
118 }
119}
120
121pub mod signing_params {
123 use super::SigningParams;
124 use aws_smithy_runtime_api::client::identity::Identity;
125 use std::error::Error;
126 use std::fmt;
127 use std::time::SystemTime;
128
129 #[derive(Debug)]
131 pub struct BuildError {
132 reason: &'static str,
133 }
134 impl BuildError {
135 fn new(reason: &'static str) -> Self {
136 Self { reason }
137 }
138 }
139
140 impl fmt::Display for BuildError {
141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 write!(f, "{}", self.reason)
143 }
144 }
145
146 impl Error for BuildError {}
147
148 #[derive(Debug, Default)]
150 pub struct Builder<'a, S> {
151 identity: Option<&'a Identity>,
152 region: Option<&'a str>,
153 name: Option<&'a str>,
154 time: Option<SystemTime>,
155 settings: Option<S>,
156 }
157
158 impl<'a, S> Builder<'a, S> {
159 builder_methods!(
160 set_identity,
161 identity,
162 &'a Identity,
163 "Sets the identity (required)",
164 set_region,
165 region,
166 &'a str,
167 "Sets the region (required)",
168 set_name,
169 name,
170 &'a str,
171 "Sets the name (required)",
172 set_time,
173 time,
174 SystemTime,
175 "Sets the time to be used in the signature (required)",
176 set_settings,
177 settings,
178 S,
179 "Sets additional signing settings (required)"
180 );
181
182 pub fn build(self) -> Result<SigningParams<'a, S>, BuildError> {
185 Ok(SigningParams {
186 identity: self
187 .identity
188 .ok_or_else(|| BuildError::new("identity is required"))?,
189 region: self
190 .region
191 .ok_or_else(|| BuildError::new("region is required"))?,
192 name: self
193 .name
194 .ok_or_else(|| BuildError::new("name is required"))?,
195 time: self
196 .time
197 .ok_or_else(|| BuildError::new("time is required"))?,
198 settings: self
199 .settings
200 .ok_or_else(|| BuildError::new("settings are required"))?,
201 })
202 }
203 }
204}
205
206pub fn sign_chunk<'a, S>(
210 chunk: &Bytes,
211 running_signature: &'a str,
212 params: &'a SigningParams<'a, S>,
213) -> Result<SigningOutput<()>, SigningError> {
214 let payload_hash = format!("{EMPTY_PAYLOAD_SHA256}\n{}", sha256_hex_string(chunk));
215 sign_streaming_payload(
216 HMAC_SHA256_PAYLOAD,
217 running_signature,
218 params,
219 &payload_hash,
220 )
221}
222
223pub fn sign_trailer<'a, S>(
227 headers: &'a Headers,
228 running_signature: &'a str,
229 params: &'a SigningParams<'a, S>,
230) -> Result<SigningOutput<()>, SigningError> {
231 fn canonical_headers(headers: &Headers) -> Vec<u8> {
232 let mut sorted_headers: Vec<_> = headers.iter().collect();
233 sorted_headers.sort_by_key(|(name, _)| name.to_lowercase());
234 let mut buf = Vec::with_capacity(sorted_headers.len());
235 for (name, value) in sorted_headers.iter() {
236 buf.extend_from_slice(name.to_lowercase().as_bytes());
237 buf.extend_from_slice(b":");
238 buf.extend_from_slice(value.trim().as_bytes());
239 buf.extend_from_slice(b"\n");
240 }
241 buf
242 }
243
244 let payload_hash = sha256_hex_string(canonical_headers(headers));
245 sign_streaming_payload(
246 HMAC_SHA256_TRAILER,
247 running_signature,
248 params,
249 &payload_hash,
250 )
251}
252
253fn sign_streaming_payload<'a, S>(
254 algorithm: &str,
255 running_signature: &'a str,
256 params: &'a SigningParams<'a, S>,
257 payload_hash: &str,
258) -> Result<SigningOutput<()>, SigningError> {
259 let creds = params
260 .identity
261 .data::<Credentials>()
262 .expect("identity must contain credentials");
263
264 let signing_key = generate_signing_key(
265 creds.secret_access_key(),
266 params.time,
267 params.region,
268 params.name,
269 );
270
271 let scope = format!(
272 "{}/{}/{}/aws4_request",
273 format_date(params.time),
274 params.region,
275 params.name
276 );
277
278 let string_to_sign = format!(
279 "{}\n{}\n{}\n{}\n{}",
280 algorithm,
281 format_date_time(params.time),
282 scope,
283 running_signature,
284 payload_hash,
285 );
286
287 let signature = calculate_signature(signing_key, string_to_sign.as_bytes());
288 Ok(SigningOutput::new((), signature))
289}
290
291#[cfg(test)]
292mod tests {
293 use super::{
294 calculate_signature, generate_signing_key, sha256_hex_string, EMPTY_PAYLOAD_SHA256,
295 };
296 use crate::date_time::test_parsers::parse_date_time;
297
298 #[test]
299 fn test_signature_calculation() {
300 let secret = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
301 let creq = r#"AWS4-HMAC-SHA256
30220150830T123600Z
30320150830/us-east-1/iam/aws4_request
304f536975d06c0309214f805bb90ccff089219ecd68b2577efef23edd43b7e1a59"#;
305 let time = parse_date_time("20150830T123600Z").unwrap();
306
307 let derived_key = generate_signing_key(secret, time, "us-east-1", "iam");
308 let signature = calculate_signature(derived_key, creq.as_bytes());
309
310 let expected = "5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7";
311 assert_eq!(expected, &signature);
312 }
313
314 #[test]
315 fn sign_payload_empty_string() {
316 let expected = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
317 let actual = sha256_hex_string([]);
318 assert_eq!(expected, actual);
319 assert_eq!(EMPTY_PAYLOAD_SHA256, actual);
320 }
321}