use hmac::{Hmac, Mac as _};
use sha2::{Digest, Sha256};
pub const ALGORITHM: &str = "AWS4-HMAC-SHA256";
const REQUEST_LABEL: &str = "aws4_request";
type HmacSha256 = Hmac<Sha256>;
pub struct Credentials<'a> {
pub access_key: &'a str,
pub secret_key: &'a str,
pub session_token: Option<&'a str>,
pub region: &'a str,
pub service: &'a str,
}
impl Credentials<'_> {
pub fn scope(&self, amz_date: &str) -> String {
format!(
"{}/{}/{}/{}",
&amz_date[..8],
self.region,
self.service,
REQUEST_LABEL
)
}
}
pub struct RequestToSign<'a> {
pub method: &'a str,
pub canonical_uri: &'a str,
pub query: &'a [(String, String)],
pub headers: Vec<(String, String)>,
pub payload_sha256: &'a str,
pub amz_date: &'a str,
}
impl RequestToSign<'_> {
pub fn canonical_request(&self) -> String {
format!(
"{}\n{}\n{}\n{}\n{}\n{}",
self.method.to_ascii_uppercase(),
self.canonical_uri,
canonical_query(self.query),
canonical_headers(&self.headers),
signed_headers(&self.headers),
self.payload_sha256,
)
}
pub fn string_to_sign(&self, creds: &Credentials<'_>) -> String {
format!(
"{ALGORITHM}\n{}\n{}\n{}",
self.amz_date,
creds.scope(self.amz_date),
sha256_hex(self.canonical_request().as_bytes())
)
}
pub fn authorization(&self, creds: &Credentials<'_>) -> String {
let sig = signature(creds, &self.string_to_sign(creds));
format!(
"{ALGORITHM} Credential={}/{}, SignedHeaders={}, Signature={}",
creds.access_key,
creds.scope(self.amz_date),
signed_headers(&self.headers),
sig
)
}
pub fn presign(&self, creds: &Credentials<'_>, expires: u64) -> (String, String) {
let mut q: Vec<(String, String)> = self.query.to_vec();
q.push(("X-Amz-Algorithm".to_string(), ALGORITHM.to_string()));
q.push((
"X-Amz-Credential".to_string(),
format!("{}/{}", creds.access_key, creds.scope(self.amz_date)),
));
q.push(("X-Amz-Date".to_string(), self.amz_date.to_string()));
q.push(("X-Amz-Expires".to_string(), expires.to_string()));
q.push((
"X-Amz-SignedHeaders".to_string(),
signed_headers(&self.headers),
));
if let Some(token) = creds.session_token {
q.push(("X-Amz-Security-Token".to_string(), token.to_string()));
}
let canonical_q = canonical_query(&q);
let canonical_request = format!(
"{}\n{}\n{}\n{}\n{}\n{}",
self.method.to_ascii_uppercase(),
self.canonical_uri,
canonical_q,
canonical_headers(&self.headers),
signed_headers(&self.headers),
"UNSIGNED-PAYLOAD",
);
let sts = format!(
"{ALGORITHM}\n{}\n{}\n{}",
self.amz_date,
creds.scope(self.amz_date),
sha256_hex(canonical_request.as_bytes())
);
let sig = signature(creds, &sts);
let mut appended = canonical_q;
appended.push_str("&X-Amz-Signature=");
appended.push_str(&uri_encode(&sig, true));
(appended, sig)
}
}
fn hmac(key: &[u8], data: &[u8]) -> Vec<u8> {
let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts any key length");
mac.update(data);
mac.finalize().into_bytes().to_vec()
}
pub fn sha256_hex(data: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(data);
to_hex(&hasher.finalize())
}
fn to_hex(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut s = String::with_capacity(bytes.len() * 2);
for &b in bytes {
s.push(HEX[(b >> 4) as usize] as char);
s.push(HEX[(b & 0x0f) as usize] as char);
}
s
}
fn signing_key(creds: &Credentials<'_>, amz_date: &str) -> Vec<u8> {
let k_date = hmac(
format!("AWS4{}", creds.secret_key).as_bytes(),
amz_date.as_bytes(),
);
let k_region = hmac(&k_date, creds.region.as_bytes());
let k_service = hmac(&k_region, creds.service.as_bytes());
hmac(&k_service, REQUEST_LABEL.as_bytes())
}
fn signature(creds: &Credentials<'_>, string_to_sign: &str) -> String {
let date = string_to_sign
.lines()
.nth(1)
.map(|d| &d[..8.min(d.len())])
.unwrap_or("");
to_hex(&hmac(&signing_key(creds, date), string_to_sign.as_bytes()))
}
pub fn uri_encode(s: &str, encode_slash: bool) -> String {
let mut out = String::new();
for &b in s.as_bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(b as char)
}
b'/' if !encode_slash => out.push('/'),
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
pub fn canonical_query(query: &[(String, String)]) -> String {
let mut pairs: Vec<(String, String)> = query
.iter()
.map(|(k, v)| (uri_encode(k, true), uri_encode(v, true)))
.collect();
pairs.sort();
pairs
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect::<Vec<_>>()
.join("&")
}
fn canonical_headers(headers: &[(String, String)]) -> String {
let mut hs: Vec<(String, String)> = headers
.iter()
.map(|(n, v)| (n.to_ascii_lowercase(), v.trim().to_string()))
.collect();
hs.sort();
let mut out = String::new();
for (n, v) in &hs {
out.push_str(n);
out.push(':');
out.push_str(v);
out.push('\n');
}
out
}
fn signed_headers(headers: &[(String, String)]) -> String {
let mut names: Vec<String> = headers
.iter()
.map(|(n, _)| n.to_ascii_lowercase())
.collect();
names.sort();
names.dedup();
names.join(";")
}
pub const EMPTY_PAYLOAD_SHA256: &str =
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
pub fn amz_date_now(now: std::time::SystemTime) -> String {
let dt = chrono_like_utc(now);
format!(
"{:04}{:02}{:02}T{:02}{:02}{:02}Z",
dt.0, dt.1, dt.2, dt.3, dt.4, dt.5
)
}
fn chrono_like_utc(now: std::time::SystemTime) -> (u32, u32, u32, u32, u32, u32) {
let secs = now
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let days = secs / 86_400;
let mut rem = secs % 86_400;
let hour = (rem / 3_600) as u32;
rem %= 3_600;
let min = (rem / 60) as u32;
let sec = (rem % 60) as u32;
let (y, m, d) = civil_from_days(days as i64);
(y as u32, m as u32, d as u32, hour, min, sec)
}
fn civil_from_days(z: i64) -> (i64, i64, i64) {
let z = z + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
(y, m, d)
}
#[cfg(test)]
mod tests {
use super::*;
const AK: &str = "AKIAIOSFODNN7EXAMPLE";
const SK: &str = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
fn creds() -> Credentials<'static> {
Credentials {
access_key: AK,
secret_key: SK,
session_token: None,
region: "us-east-1",
service: "s3",
}
}
#[test]
fn get_object_header_signature_matches_aws() {
let req = RequestToSign {
method: "GET",
canonical_uri: "/test.txt",
query: &[],
headers: vec![
("host".into(), "examplebucket.s3.amazonaws.com".into()),
("range".into(), "bytes=0-9".into()),
("x-amz-content-sha256".into(), EMPTY_PAYLOAD_SHA256.into()),
("x-amz-date".into(), "20130524T000000Z".into()),
],
payload_sha256: EMPTY_PAYLOAD_SHA256,
amz_date: "20130524T000000Z",
};
let sig = signature(&creds(), &req.string_to_sign(&creds()));
assert_eq!(
sig,
"f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
);
assert!(req.authorization(&creds()).contains(
"Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
));
}
#[test]
fn get_object_presigned_signature_matches_aws() {
let req = RequestToSign {
method: "GET",
canonical_uri: "/test.txt",
query: &[],
headers: vec![("host".into(), "examplebucket.s3.amazonaws.com".into())],
payload_sha256: "UNSIGNED-PAYLOAD",
amz_date: "20130524T000000Z",
};
let (appended, sig) = req.presign(&creds(), 86_400);
assert_eq!(
sig,
"aeeed9bbccd4d02ee5c0109b86d86835f995330da4c265957d157751f604d404"
);
assert!(appended.contains("X-Amz-Algorithm=AWS4-HMAC-SHA256"));
assert!(appended.contains(
"X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20130524%2Fus-east-1%2Fs3%2Faws4_request"
));
assert!(appended.contains("X-Amz-Date=20130524T000000Z"));
assert!(appended.contains("X-Amz-Expires=86400"));
assert!(appended.contains("X-Amz-SignedHeaders=host"));
assert!(appended.contains(&format!("X-Amz-Signature={sig}")));
assert!(!appended.contains("X-Amz-Credential=AKIAIOSFODNN7EXAMPLE/"));
}
#[test]
fn canonical_query_sorts_and_encodes() {
let q = vec![
("marker".into(), "some value".into()),
("prefix".into(), "a/b".into()),
];
assert_eq!(canonical_query(&q), "marker=some%20value&prefix=a%2Fb");
}
}