multibucket 0.1.1

A unified async object-storage trait with a from-scratch Qiniu Kodo backend (upload / download / delete / stat / list / signed URLs).
Documentation
//! Qiniu request signing (the `Mac`).
//!
//! Implements the three credentials Qiniu verifies, each cross-checked against
//! the official algorithm docs:
//!
//! * **Upload token** — `AccessKey:EncodedSign:EncodedPutPolicy`, where the
//!   signature is HMAC-SHA1 over the URL-safe-Base64 put policy.
//! * **Download (private URL) token** — HMAC-SHA1 over `<path>?e=<deadline>`.
//! * **Management (`QBox`) token** — HMAC-SHA1 over `<path>?<query>\n[<body>]`.

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>;

/// URL-safe Base64 **with** padding, matching Qiniu's `urlsafe_base64_encode`.
pub(crate) fn urlsafe_b64(data: &[u8]) -> String {
    URL_SAFE.encode(data)
}

/// Qiniu credentials (AccessKey / SecretKey pair).
#[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 {
        // Never leak the secret key in logs / `{:?}` output.
        f.debug_struct("Mac")
            .field("access_key", &self.access_key)
            .field("secret_key", &"[redacted]")
            .finish()
    }
}

impl Mac {
    /// Create a signer from an AccessKey / SecretKey pair.
    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(),
        }
    }

    /// Raw HMAC-SHA1 of `data` keyed by the SecretKey.
    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()
    }

    /// `AccessKey:EncodedSign` over `data`.
    fn sign(&self, data: &str) -> String {
        format!(
            "{}:{}",
            self.access_key,
            urlsafe_b64(&self.hmac_raw(data.as_bytes()))
        )
    }

    /// The raw `AccessKey` (needed when assembling the final URL).
    pub fn access_key(&self) -> &str {
        &self.access_key
    }

    /// Build an upload token for the given policy.
    ///
    /// `uploadToken = AccessKey + ":" + encodedSign + ":" + encodedPutPolicy`.
    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
        ))
    }

    /// `Authorization` header value for the `QBox` management scheme.
    ///
    /// `signing_str` must already be `<path>?<query>\n<body>` exactly as the
    /// request is sent (empty body => trailing `\n` only).
    pub fn qbox_authorization(&self, signing_str: &str) -> String {
        format!("QBox {}", self.sign(signing_str))
    }

    /// `Authorization` header value for the **`UpToken`** scheme used by the
    /// resumable-upload (分片上传 v2) API.
    ///
    /// Unlike `QBox`, this scheme does not sign the request — it simply carries
    /// the upload token: `Authorization: UpToken <uploadToken>`.
    pub fn up_authorization(upload_token: &str) -> String {
        format!("UpToken {upload_token}")
    }

    /// Signed, time-limited download URL for a private bucket.
    ///
    /// Signs `<encoded_path>?e=<deadline>` and appends `&token=AccessKey:sign`.
    pub fn private_download_url(
        &self,
        base_url: &str,
        encoded_path: &str,
        deadline: i64,
    ) -> String {
        // `base_url` already ends with the (encoded) path; only its path+query
        // part is signed, so we rebuild from the known encoded path.
        let sign_data = format!("{encoded_path}?e={deadline}");
        let token = self.sign(&sign_data);
        // Preserve any query the caller already put on `base_url`.
        let sep = if base_url.contains('?') { '&' } else { '?' };
        format!("{base_url}{sep}e={deadline}&token={token}")
    }
}

/// The upload policy (`putPolicy`) embedded in an upload token.
///
/// Only `scope` and `deadline` are required; the rest are optional overrides.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PutPolicy {
    /// `"bucket"` (any key) or `"bucket:key"` (a single key).
    pub scope: String,
    /// Unix timestamp after which the token is rejected.
    pub deadline: i64,
    /// `1` to forbid overwriting an existing key (`insertOnly`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub insert_only: Option<u8>,
    /// Server-side save key template (Qiniu macros such as `$(fname)`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub save_key: Option<String>,
    /// Allowed MIME types for the upload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mime_types: Option<Vec<String>>,
    /// Maximum file size in bytes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fsize_limit: Option<u64>,
    /// Custom response body template returned after a successful upload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_body: Option<String>,
}

impl PutPolicy {
    /// Allow uploading any key into `bucket`, valid until `deadline`.
    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,
        }
    }

    /// Restrict the token to a single `key` inside `bucket`.
    pub fn for_key(bucket: &str, key: &str, deadline: i64) -> Self {
        PutPolicy {
            scope: format!("{bucket}:{key}"),
            ..Self::for_bucket(bucket, deadline)
        }
    }

    /// Restrict to a single object AND forbid overwriting (Qiniu `insertOnly=1`).
    pub fn insert_only(mut self, on: bool) -> Self {
        self.insert_only = if on { Some(1) } else { None };
        self
    }
}