multibucket 0.3.0

A unified async object-storage trait with from-scratch Qiniu Kodo and Amazon S3 (S3-compatible) backends (upload / download / delete / stat / list / signed URLs).
Documentation
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! AWS Signature Version 4 (SigV4) for the S3 backend.
//!
//! Implemented from the raw spec (no `aws-sdk` / `rust-s3` dependency) so the
//! crate keeps its "almost no heavyweight dependencies" profile. Two signing
//! modes are provided:
//!
//! * [`RequestToSign::authorization`] — header-based auth for normal API calls
//!   (the `Authorization: AWS4-HMAC-SHA256 ...` header).
//! * [`RequestToSign::presign`] — query-string auth for pre-signed URLs.
//!
//! The whole module is covered by the canonical AWS S3 worked examples
//! (see the `#[cfg(test)]` block at the bottom), so the bytes are known-good.

use hmac::{Hmac, Mac as _};
use sha2::{Digest, Sha256};

/// SigV4 algorithm name.
pub const ALGORITHM: &str = "AWS4-HMAC-SHA256";
/// The trailing component of every SigV4 scope.
const REQUEST_LABEL: &str = "aws4_request";

type HmacSha256 = Hmac<Sha256>;

/// Access credentials used to derive the SigV4 signing key.
pub struct Credentials<'a> {
    /// AWS / S3 access key id.
    pub access_key: &'a str,
    /// AWS / S3 secret access key.
    pub secret_key: &'a str,
    /// Session token for temporary credentials (STS / IAM role). `None` for
    /// long-lived keys.
    pub session_token: Option<&'a str>,
    /// Region id, e.g. `us-east-1`.
    pub region: &'a str,
    /// Service name, almost always `s3`.
    pub service: &'a str,
}

impl Credentials<'_> {
    /// The SigV4 scope string: `<YYYYMMDD>/<region>/<service>/aws4_request`.
    pub fn scope(&self, amz_date: &str) -> String {
        format!(
            "{}/{}/{}/{}",
            &amz_date[..8],
            self.region,
            self.service,
            REQUEST_LABEL
        )
    }
}

/// A request that needs a SigV4 signature.
///
/// `headers` is the set of headers that take part in the signature (their
/// lowercased names joined by `;` make up the `SignedHeaders` list). For
/// pre-signed URLs this is usually just `host`; for header auth it also
/// includes `x-amz-content-sha256`, `x-amz-date` and any `content-type` /
/// `x-amz-security-token`. The caller is responsible for sending every header
/// listed here (plus the `Authorization` header produced by
/// [`authorization`](Self::authorization)).
pub struct RequestToSign<'a> {
    /// HTTP method (`GET`, `PUT`, `POST`, `DELETE`, `HEAD`).
    pub method: &'a str,
    /// Canonical URI: the request path, already percent-encoded per RFC 3986
    /// but with `/` separators intact (e.g. `/photos/me%20.png`).
    pub canonical_uri: &'a str,
    /// Query parameters as decoded `(name, value)` pairs. These are encoded and
    /// sorted canonically by this module. Pass an empty slice for no query.
    pub query: &'a [(String, String)],
    /// Headers that participate in the signature, lowercased names, values
    /// already trimmed. Must include `host`; for header auth also
    /// `x-amz-content-sha256` and `x-amz-date`.
    pub headers: Vec<(String, String)>,
    /// Hex SHA-256 of the payload, or `UNSIGNED-PAYLOAD` for pre-signed URLs.
    pub payload_sha256: &'a str,
    /// `x-amz-date` value, `YYYYMMDDTHHMMSSZ` (UTC).
    pub amz_date: &'a str,
}

impl RequestToSign<'_> {
    /// Build the canonical request string (the first hash input of SigV4).
    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,
        )
    }

    /// The string-to-sign (the second hash input of SigV4).
    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())
        )
    }

    /// The final `Authorization` header value for header-based auth.
    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
        )
    }

    /// Produce a pre-signed URL query string (without the leading `?`) plus the
    /// signature. The caller appends `?{returned_string}` to the request URL.
    ///
    /// `expires` is the link lifetime in seconds (max 604800 for AWS S3). The
    /// body is always treated as `UNSIGNED-PAYLOAD` for query auth.
    pub fn presign(&self, creds: &Credentials<'_>, expires: u64) -> (String, String) {
        // Assemble the full query, including the X-Amz-* parameters.
        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);
        // The fourth line of the string-to-sign is the SHA-256 of the *entire*
        // canonical request (method / URI / query / headers / signed-headers /
        // payload), exactly as in [`string_to_sign`]. Using only the query here
        // would produce a wrong signature.
        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)
    }
}

// --------------------------------------------------------------------------
// Low-level primitives
// --------------------------------------------------------------------------

/// `HMAC-SHA256(key, data)` as raw bytes.
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()
}

/// Hex SHA-256 of `data`.
pub fn sha256_hex(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    to_hex(&hasher.finalize())
}

/// Lowercase hex encoding (SigV4 requires lowercase).
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
}

/// Derive the SigV4 signing key:
///
/// ```text
/// HMAC(HMAC(HMAC(HMAC("AWS4"+secret, date), region), service), "aws4_request")
/// ```
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())
}

/// The SigV4 signature: hex HMAC of the string-to-sign keyed by the signing key.
fn signature(creds: &Credentials<'_>, string_to_sign: &str) -> String {
    // The date is the second line of the string-to-sign (the `x-amz-date`
    // value, `YYYYMMDDTHHMMSSZ`); only its first 8 chars seed the key.
    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()))
}

/// Encode a string per RFC 3986 (AWS's `encodeURIComponent`).
///
/// Unreserved characters `A-Za-z0-9-_.~` are left untouched; everything else —
/// including `/` when `encode_slash` is `true` — becomes `%XX` (uppercase).
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
}

/// Canonical query string: every `(name, value)` URI-encoded, sorted by
/// `(encoded_name, encoded_value)`, joined with `&`.
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("&")
}

/// Canonical headers: each `name:value\n` (value trimmed, lowercased name),
/// sorted by name. The trailing newline is included so the canonical request
/// formatting stays correct.
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
}

/// `SignedHeaders`: the sorted, lowercased header names joined by `;`.
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(";")
}

/// SHA-256 hex of an empty body, required as `x-amz-content-sha256` for
/// `GET` / `HEAD` / `DELETE` requests.
pub const EMPTY_PAYLOAD_SHA256: &str =
    "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

/// Format a UTC timestamp as `YYYYMMDDTHHMMSSZ`.
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
    )
}

/// `(year, month, day, hour, min, sec)` in UTC without external crates.
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);
    // days since epoch
    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)
}

/// Inverse of `days_from_civil` (Howard Hinnant), days since 1970-01-01.
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",
        }
    }

    /// The canonical AWS S3 "Example: GET Object" (header auth).
    ///
    /// <https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html>
    #[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"
        );
        // The Authorization header's Signature= field must match too.
        assert!(req.authorization(&creds()).contains(
            "Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
        ));
    }

    /// The canonical AWS S3 "Example: GET Object — presigned URL" (query auth).
    #[test]
    fn get_object_presigned_signature_matches_aws() {
        let req = RequestToSign {
            method: "GET",
            canonical_uri: "/test.txt",
            query: &[],
            // Presigned requests sign only the `host` header.
            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"
        );
        // The X-Amz-* params must be present and sorted canonically.
        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}")));
        // The credential slash must be percent-encoded in the wire query.
        assert!(!appended.contains("X-Amz-Credential=AKIAIOSFODNN7EXAMPLE/"));
    }

    /// The canonical query must sort by name and encode values, including the
    /// slash in the credential.
    #[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");
    }
}