use base64::{engine::general_purpose::URL_SAFE, Engine as _};
use hmac::{Hmac, Mac as _};
use serde::Serialize;
use sha1::Sha1;
use crate::error::Result;
type HmacSha1 = Hmac<Sha1>;
pub(crate) const FORM_CONTENT_TYPE: &str = "application/x-www-form-urlencoded";
pub(crate) const JSON_CONTENT_TYPE: &str = "application/json";
pub(crate) fn urlsafe_b64(data: &[u8]) -> String {
URL_SAFE.encode(data)
}
#[derive(Clone)]
pub struct Mac {
access_key: String,
secret_key: String,
}
impl std::fmt::Debug for Mac {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Mac")
.field("access_key", &self.access_key)
.field("secret_key", &"[redacted]")
.finish()
}
}
impl Mac {
pub fn new(access_key: impl Into<String>, secret_key: impl Into<String>) -> Self {
Mac {
access_key: access_key.into(),
secret_key: secret_key.into(),
}
}
fn hmac_raw(&self, data: &[u8]) -> Vec<u8> {
let mut mac = HmacSha1::new_from_slice(self.secret_key.as_bytes())
.expect("HMAC accepts any key length");
mac.update(data);
mac.finalize().into_bytes().to_vec()
}
fn sign(&self, data: &str) -> String {
format!(
"{}:{}",
self.access_key,
urlsafe_b64(&self.hmac_raw(data.as_bytes()))
)
}
pub fn access_key(&self) -> &str {
&self.access_key
}
pub fn upload_token(&self, policy: &PutPolicy) -> Result<String> {
let json = serde_json::to_vec(policy)?;
let encoded_policy = urlsafe_b64(&json);
let encoded_sign = urlsafe_b64(&self.hmac_raw(encoded_policy.as_bytes()));
Ok(format!(
"{}:{}:{}",
self.access_key, encoded_sign, encoded_policy
))
}
pub fn qbox_authorization(&self, signing_str: &str) -> String {
format!("QBox {}", self.sign(signing_str))
}
pub fn up_authorization(upload_token: &str) -> String {
format!("UpToken {upload_token}")
}
pub fn qiniu_authorization(
&self,
method: &str,
path_and_query: &str,
host: &str,
content_type: &str,
body: &str,
) -> String {
let content_type = if content_type.is_empty() {
FORM_CONTENT_TYPE
} else {
content_type
};
let mut signing_str =
format!("{method} {path_and_query}\nHost: {host}\nContent-Type: {content_type}\n\n");
if content_type == FORM_CONTENT_TYPE || content_type == JSON_CONTENT_TYPE {
signing_str.push_str(body);
}
format!("Qiniu {}", self.sign(&signing_str))
}
pub fn private_download_url(&self, base_url: &str, deadline: i64) -> String {
let sep = if base_url.contains('?') { '&' } else { '?' };
let signed_url = format!("{base_url}{sep}e={deadline}");
let token = self.sign(&signed_url);
format!("{signed_url}&token={token}")
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PutPolicy {
pub scope: String,
pub deadline: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub insert_only: Option<u8>,
#[serde(skip_serializing_if = "Option::is_none")]
pub save_key: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mime_types: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fsize_limit: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_body: Option<String>,
}
impl PutPolicy {
pub fn for_bucket(bucket: &str, deadline: i64) -> Self {
PutPolicy {
scope: bucket.to_string(),
deadline,
insert_only: None,
save_key: None,
mime_types: None,
fsize_limit: None,
return_body: None,
}
}
pub fn for_key(bucket: &str, key: &str, deadline: i64) -> Self {
PutPolicy {
scope: format!("{bucket}:{key}"),
..Self::for_bucket(bucket, deadline)
}
}
pub fn insert_only(mut self, on: bool) -> Self {
self.insert_only = if on { Some(1) } else { None };
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn qiniu_authorization_signs_request_line_and_headers() {
let mac = Mac::new("AK", "SK");
let host = "rs-z0.qiniuapi.com";
let path = "/private";
let body = "bucket=demo&private=1";
let ct = FORM_CONTENT_TYPE;
let signing_str = format!("POST {path}\nHost: {host}\nContent-Type: {ct}\n\n{body}");
let mut mac2 = HmacSha1::new_from_slice(b"SK").expect("HMAC accepts any key length");
mac2.update(signing_str.as_bytes());
let expected = format!("Qiniu AK:{}", urlsafe_b64(&mac2.finalize().into_bytes()));
assert_eq!(
mac.qiniu_authorization("POST", path, host, "", body),
expected
);
}
#[test]
fn only_form_and_json_bodies_take_part_in_the_signature() {
let mac = Mac::new("AK", "SK");
assert_ne!(
mac.qiniu_authorization("POST", "/x", "h", JSON_CONTENT_TYPE, "{}"),
mac.qiniu_authorization("POST", "/x", "h", JSON_CONTENT_TYPE, "")
);
assert_eq!(
mac.qiniu_authorization("POST", "/x", "h", "text/plain", "a"),
mac.qiniu_authorization("POST", "/x", "h", "text/plain", "b")
);
}
#[test]
fn qbox_and_qiniu_are_distinct_schemes() {
let mac = Mac::new("AK", "SK");
let qbox = mac.qbox_authorization("/stat/abc\n");
let qiniu = mac.qiniu_authorization("POST", "/stat/abc", "rs-z0.qiniuapi.com", "", "");
assert!(qbox.starts_with("QBox AK:"));
assert!(qiniu.starts_with("Qiniu AK:"));
}
#[test]
fn private_download_url_signs_the_full_url() {
let mac = Mac::new("AK", "SK");
let got = mac.private_download_url("https://iovip-z2.qiniuio.com/a.png", 1_700_000_000);
let signed = "https://iovip-z2.qiniuio.com/a.png?e=1700000000";
let mut mac2 = HmacSha1::new_from_slice(b"SK").expect("HMAC accepts any key length");
mac2.update(signed.as_bytes());
let expected = format!(
"{signed}&token=AK:{}",
urlsafe_b64(&mac2.finalize().into_bytes())
);
assert_eq!(got, expected);
}
#[test]
fn private_download_url_keeps_an_existing_query() {
let mac = Mac::new("AK", "SK");
let got = mac.private_download_url("https://h.example.com/a.png?x=1", 2);
assert!(got.starts_with("https://h.example.com/a.png?x=1&e=2&token=AK:"));
}
}