yah-local-driver 0.8.20

Local-tier infrastructure primitives shared by cloud (sim/pond reconciler) and yubaba (pond MinIO slot lifecycle): docker-CLI runtime detection + S3 SigV4 helpers.
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! AWS Signature Version 4 helpers for S3-compatible object storage.
//!
//! Shared by `provider::hetzner` (Hetzner Object Storage) and
//! `provider::local_docker` (MinIO). Both speak S3 + AWS SigV4 for bucket
//! create/head/delete; only the endpoint and region differ.

use anyhow::{Context, Result};
use hmac::{Hmac, Mac};
use reqwest::header::HeaderMap;
use sha2::{Digest, Sha256};

type HmacSha256 = Hmac<Sha256>;

/// AWS Sig V4 for any S3 verb that sends no body (PUT CreateBucket, HEAD,
/// DELETE bucket). Callers supply the full `url`, S3 `region` string, and
/// HMAC credentials.
pub fn sign_s3_empty_body(
    method: &str,
    url: &str,
    region: &str,
    access_key: &str,
    secret_key: &str,
) -> Result<HeaderMap> {
    let now = chrono::Utc::now();
    let date = now.format("%Y%m%d").to_string();
    let datetime = now.format("%Y%m%dT%H%M%SZ").to_string();

    let parsed = reqwest::Url::parse(url).context("parsing S3 URL")?;
    let host = parsed.host_str().context("no host in S3 URL")?.to_string();
    let uri = parsed.path().to_string();

    let empty_hash = {
        let mut h = Sha256::new();
        h.update(b"");
        hex::encode(h.finalize())
    };

    let canonical_headers = format!(
        "content-length:0\nhost:{host}\nx-amz-content-sha256:{empty_hash}\nx-amz-date:{datetime}\n"
    );
    let signed_headers = "content-length;host;x-amz-content-sha256;x-amz-date";

    let canonical_request =
        format!("{method}\n{uri}\n\n{canonical_headers}\n{signed_headers}\n{empty_hash}");

    let cr_hash = {
        let mut h = Sha256::new();
        h.update(canonical_request.as_bytes());
        hex::encode(h.finalize())
    };

    let credential_scope = format!("{date}/{region}/s3/aws4_request");
    let string_to_sign =
        format!("AWS4-HMAC-SHA256\n{datetime}\n{credential_scope}\n{cr_hash}");

    let hmac_sign = |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()
    };

    let date_key = hmac_sign(format!("AWS4{secret_key}").as_bytes(), date.as_bytes());
    let date_region_key = hmac_sign(&date_key, region.as_bytes());
    let date_region_service_key = hmac_sign(&date_region_key, b"s3");
    let signing_key = hmac_sign(&date_region_service_key, b"aws4_request");
    let signature = hex::encode(hmac_sign(&signing_key, string_to_sign.as_bytes()));

    let authorization = format!(
        "AWS4-HMAC-SHA256 Credential={access_key}/{credential_scope}, \
         SignedHeaders={signed_headers}, Signature={signature}"
    );

    let mut headers = HeaderMap::new();
    headers.insert("host", host.parse()?);
    headers.insert("x-amz-date", datetime.parse()?);
    headers.insert("x-amz-content-sha256", empty_hash.parse()?);
    headers.insert("content-length", "0".parse()?);
    headers.insert("authorization", authorization.parse()?);
    Ok(headers)
}

pub fn sign_s3_put_bucket(
    url: &str,
    region: &str,
    access_key: &str,
    secret_key: &str,
) -> Result<HeaderMap> {
    sign_s3_empty_body("PUT", url, region, access_key, secret_key)
}

pub fn sign_s3_head_bucket(
    url: &str,
    region: &str,
    access_key: &str,
    secret_key: &str,
) -> Result<HeaderMap> {
    sign_s3_empty_body("HEAD", url, region, access_key, secret_key)
}

pub fn sign_s3_delete_bucket(
    url: &str,
    region: &str,
    access_key: &str,
    secret_key: &str,
) -> Result<HeaderMap> {
    sign_s3_empty_body("DELETE", url, region, access_key, secret_key)
}

/// AWS Sig V4 for a `GET` with an empty body and a canonical query string.
///
/// `canonical_query` is the already-formed query (no leading `?`) sorted
/// lexicographically by parameter name with URL-encoded keys + values, e.g.
/// `"list-type=2&prefix=whisper%2F"`. The caller is responsible for ordering
/// and encoding; this helper signs the request as given.
///
/// Used by `ListObjectsV2`. The returned headers are suitable for `reqwest`'s
/// `GET <url>` where `<url>` already includes the `?<canonical_query>` suffix.
pub fn sign_s3_get_with_query(
    url: &str,
    canonical_query: &str,
    region: &str,
    access_key: &str,
    secret_key: &str,
) -> Result<HeaderMap> {
    sign_s3_no_body("GET", url, canonical_query, region, access_key, secret_key)
}

/// AWS Sig V4 for any body-less verb (`GET`, `HEAD`) **without** signing
/// `content-length`.
///
/// reqwest/hyper strip the `content-length: 0` header off the wire for
/// body-less requests, so signing it — as [`sign_s3_empty_body`] does — leaves
/// the server unable to reproduce the signature, yielding
/// `403 SignatureDoesNotMatch`. Object `GET`/`HEAD` must use this signer; only
/// methods that actually carry a (possibly empty) body and emit
/// `content-length` on the wire may use [`sign_s3_empty_body`].
///
/// `canonical_query` follows the [`sign_s3_get_with_query`] contract (empty
/// string for no query).
pub fn sign_s3_no_body(
    method: &str,
    url: &str,
    canonical_query: &str,
    region: &str,
    access_key: &str,
    secret_key: &str,
) -> Result<HeaderMap> {
    let now = chrono::Utc::now();
    let date = now.format("%Y%m%d").to_string();
    let datetime = now.format("%Y%m%dT%H%M%SZ").to_string();

    let parsed = reqwest::Url::parse(url).context("parsing S3 URL")?;
    let host = parsed.host_str().context("no host in S3 URL")?.to_string();
    let uri = parsed.path().to_string();

    let empty_hash = {
        let mut h = Sha256::new();
        h.update(b"");
        hex::encode(h.finalize())
    };

    let canonical_headers = format!(
        "host:{host}\nx-amz-content-sha256:{empty_hash}\nx-amz-date:{datetime}\n"
    );
    let signed_headers = "host;x-amz-content-sha256;x-amz-date";

    let canonical_request = format!(
        "{method}\n{uri}\n{canonical_query}\n{canonical_headers}\n{signed_headers}\n{empty_hash}"
    );

    let cr_hash = {
        let mut h = Sha256::new();
        h.update(canonical_request.as_bytes());
        hex::encode(h.finalize())
    };

    let credential_scope = format!("{date}/{region}/s3/aws4_request");
    let string_to_sign =
        format!("AWS4-HMAC-SHA256\n{datetime}\n{credential_scope}\n{cr_hash}");

    let hmac_sign = |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()
    };

    let date_key = hmac_sign(format!("AWS4{secret_key}").as_bytes(), date.as_bytes());
    let date_region_key = hmac_sign(&date_key, region.as_bytes());
    let date_region_service_key = hmac_sign(&date_region_key, b"s3");
    let signing_key = hmac_sign(&date_region_service_key, b"aws4_request");
    let signature = hex::encode(hmac_sign(&signing_key, string_to_sign.as_bytes()));

    let authorization = format!(
        "AWS4-HMAC-SHA256 Credential={access_key}/{credential_scope}, \
         SignedHeaders={signed_headers}, Signature={signature}"
    );

    let mut headers = HeaderMap::new();
    headers.insert("host", host.parse()?);
    headers.insert("x-amz-date", datetime.parse()?);
    headers.insert("x-amz-content-sha256", empty_hash.parse()?);
    headers.insert("authorization", authorization.parse()?);
    Ok(headers)
}

/// AWS Sig V4 for `PUT /<bucket>/<key>` with an object body.
///
/// The caller pre-computes `body_sha256 = hex(sha256(body))` and passes
/// `content_length = body.len()` separately so the headers can be computed
/// without holding the bytes in this function.
pub fn sign_s3_put_object(
    url: &str,
    body_sha256: &str,
    content_type: &str,
    content_length: usize,
    region: &str,
    access_key: &str,
    secret_key: &str,
) -> Result<HeaderMap> {
    let now = chrono::Utc::now();
    let date = now.format("%Y%m%d").to_string();
    let datetime = now.format("%Y%m%dT%H%M%SZ").to_string();

    let parsed = reqwest::Url::parse(url).context("parsing S3 object URL")?;
    let host = parsed.host_str().context("no host in S3 object URL")?.to_string();
    let uri = parsed.path().to_string();

    // Headers in lexicographic order (SigV4 requirement).
    let canonical_headers = format!(
        "content-length:{content_length}\ncontent-type:{content_type}\nhost:{host}\n\
         x-amz-content-sha256:{body_sha256}\nx-amz-date:{datetime}\n"
    );
    let signed_headers = "content-length;content-type;host;x-amz-content-sha256;x-amz-date";

    let canonical_request =
        format!("PUT\n{uri}\n\n{canonical_headers}\n{signed_headers}\n{body_sha256}");

    let cr_hash = {
        let mut h = Sha256::new();
        h.update(canonical_request.as_bytes());
        hex::encode(h.finalize())
    };

    let credential_scope = format!("{date}/{region}/s3/aws4_request");
    let string_to_sign =
        format!("AWS4-HMAC-SHA256\n{datetime}\n{credential_scope}\n{cr_hash}");

    let hmac_sign = |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()
    };

    let date_key = hmac_sign(format!("AWS4{secret_key}").as_bytes(), date.as_bytes());
    let date_region_key = hmac_sign(&date_key, region.as_bytes());
    let date_region_service_key = hmac_sign(&date_region_key, b"s3");
    let signing_key = hmac_sign(&date_region_service_key, b"aws4_request");
    let signature = hex::encode(hmac_sign(&signing_key, string_to_sign.as_bytes()));

    let authorization = format!(
        "AWS4-HMAC-SHA256 Credential={access_key}/{credential_scope}, \
         SignedHeaders={signed_headers}, Signature={signature}"
    );

    let mut headers = HeaderMap::new();
    headers.insert("host", host.parse()?);
    headers.insert("x-amz-date", datetime.parse()?);
    headers.insert("x-amz-content-sha256", body_sha256.parse()?);
    headers.insert("content-length", content_length.to_string().parse()?);
    headers.insert("content-type", content_type.parse()?);
    headers.insert("authorization", authorization.parse()?);
    Ok(headers)
}

/// AWS Sig V4 for `PUT /<bucket>?policy` with a JSON body.
///
/// Modern MinIO dropped the `?acl` endpoint; use this to apply an S3 bucket
/// policy document instead. The caller provides the raw JSON bytes; this
/// function hashes them for the signature and returns headers suitable for a
/// `reqwest` PUT with that body.
pub fn sign_s3_put_bucket_policy(
    url: &str,
    region: &str,
    access_key: &str,
    secret_key: &str,
    policy_json: &[u8],
) -> Result<HeaderMap> {
    let now = chrono::Utc::now();
    let date = now.format("%Y%m%d").to_string();
    let datetime = now.format("%Y%m%dT%H%M%SZ").to_string();

    let parsed = reqwest::Url::parse(url).context("parsing S3 URL")?;
    let host = parsed.host_str().context("no host in S3 URL")?.to_string();
    let uri = parsed.path().to_string();
    let canonical_query = "policy=";
    let content_length = policy_json.len();

    let body_hash = {
        let mut h = Sha256::new();
        h.update(policy_json);
        hex::encode(h.finalize())
    };

    let canonical_headers = format!(
        "content-length:{content_length}\ncontent-type:application/json\nhost:{host}\nx-amz-content-sha256:{body_hash}\nx-amz-date:{datetime}\n"
    );
    let signed_headers = "content-length;content-type;host;x-amz-content-sha256;x-amz-date";

    let canonical_request =
        format!("PUT\n{uri}\n{canonical_query}\n{canonical_headers}\n{signed_headers}\n{body_hash}");

    let cr_hash = {
        let mut h = Sha256::new();
        h.update(canonical_request.as_bytes());
        hex::encode(h.finalize())
    };

    let credential_scope = format!("{date}/{region}/s3/aws4_request");
    let string_to_sign =
        format!("AWS4-HMAC-SHA256\n{datetime}\n{credential_scope}\n{cr_hash}");

    let hmac_sign = |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()
    };

    let date_key = hmac_sign(format!("AWS4{secret_key}").as_bytes(), date.as_bytes());
    let date_region_key = hmac_sign(&date_key, region.as_bytes());
    let date_region_service_key = hmac_sign(&date_region_key, b"s3");
    let signing_key = hmac_sign(&date_region_service_key, b"aws4_request");
    let signature = hex::encode(hmac_sign(&signing_key, string_to_sign.as_bytes()));

    let authorization = format!(
        "AWS4-HMAC-SHA256 Credential={access_key}/{credential_scope}, \
         SignedHeaders={signed_headers}, Signature={signature}"
    );

    let mut headers = HeaderMap::new();
    headers.insert("host", host.parse()?);
    headers.insert("x-amz-date", datetime.parse()?);
    headers.insert("x-amz-content-sha256", body_hash.parse()?);
    headers.insert("content-length", content_length.to_string().parse()?);
    headers.insert("content-type", "application/json".parse()?);
    headers.insert("authorization", authorization.parse()?);
    Ok(headers)
}

/// AWS Sig V4 for `PUT /<bucket>?acl` with a canned-ACL header.
///
/// **Deprecated for MinIO**: modern MinIO does not implement the ACL endpoint.
/// Use [`sign_s3_put_bucket_policy`] for pond/local-docker targets and
/// keep this only for S3-compatible providers that still honour canned ACLs
/// (e.g. Hetzner Object Storage).
pub fn sign_s3_put_bucket_acl(
    url: &str,
    region: &str,
    access_key: &str,
    secret_key: &str,
    acl: &str,
) -> Result<HeaderMap> {
    let now = chrono::Utc::now();
    let date = now.format("%Y%m%d").to_string();
    let datetime = now.format("%Y%m%dT%H%M%SZ").to_string();

    let parsed = reqwest::Url::parse(url).context("parsing S3 URL")?;
    let host = parsed.host_str().context("no host in S3 URL")?.to_string();
    let uri = parsed.path().to_string();
    let canonical_query = "acl=";

    let empty_hash = {
        let mut h = Sha256::new();
        h.update(b"");
        hex::encode(h.finalize())
    };

    // Headers listed in lexicographic order (required by SigV4).
    let canonical_headers = format!(
        "content-length:0\nhost:{host}\nx-amz-acl:{acl}\nx-amz-content-sha256:{empty_hash}\nx-amz-date:{datetime}\n"
    );
    let signed_headers = "content-length;host;x-amz-acl;x-amz-content-sha256;x-amz-date";

    let canonical_request =
        format!("PUT\n{uri}\n{canonical_query}\n{canonical_headers}\n{signed_headers}\n{empty_hash}");

    let cr_hash = {
        let mut h = Sha256::new();
        h.update(canonical_request.as_bytes());
        hex::encode(h.finalize())
    };

    let credential_scope = format!("{date}/{region}/s3/aws4_request");
    let string_to_sign =
        format!("AWS4-HMAC-SHA256\n{datetime}\n{credential_scope}\n{cr_hash}");

    let hmac_sign = |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()
    };

    let date_key = hmac_sign(format!("AWS4{secret_key}").as_bytes(), date.as_bytes());
    let date_region_key = hmac_sign(&date_key, region.as_bytes());
    let date_region_service_key = hmac_sign(&date_region_key, b"s3");
    let signing_key = hmac_sign(&date_region_service_key, b"aws4_request");
    let signature = hex::encode(hmac_sign(&signing_key, string_to_sign.as_bytes()));

    let authorization = format!(
        "AWS4-HMAC-SHA256 Credential={access_key}/{credential_scope}, \
         SignedHeaders={signed_headers}, Signature={signature}"
    );

    let mut headers = HeaderMap::new();
    headers.insert("host", host.parse()?);
    headers.insert("x-amz-date", datetime.parse()?);
    headers.insert("x-amz-content-sha256", empty_hash.parse()?);
    headers.insert("content-length", "0".parse()?);
    headers.insert("x-amz-acl", acl.parse()?);
    headers.insert("authorization", authorization.parse()?);
    Ok(headers)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sign_produces_required_headers() {
        let headers = sign_s3_put_bucket(
            "https://fsn1.your-objectstorage.com/test-bucket",
            "fsn1",
            "AK",
            "SK",
        )
        .unwrap();
        assert!(headers.contains_key("authorization"));
        assert!(headers.contains_key("x-amz-date"));
        assert!(headers.contains_key("x-amz-content-sha256"));
        let auth = headers.get("authorization").unwrap().to_str().unwrap();
        assert!(auth.starts_with("AWS4-HMAC-SHA256 Credential=AK/"));
        assert!(
            auth.contains("SignedHeaders=content-length;host;x-amz-content-sha256;x-amz-date")
        );
    }

    #[test]
    fn sign_get_with_query_signed_headers_omit_content_length() {
        let headers = sign_s3_get_with_query(
            "https://acct.r2.cloudflarestorage.com/yah-dev",
            "list-type=2&prefix=whisper%2F",
            "auto",
            "AK",
            "SK",
        )
        .unwrap();
        let auth = headers.get("authorization").unwrap().to_str().unwrap();
        assert!(auth.starts_with("AWS4-HMAC-SHA256 Credential=AK/"));
        assert!(
            auth.contains("SignedHeaders=host;x-amz-content-sha256;x-amz-date"),
            "GET with query must NOT include content-length in SignedHeaders: {auth}"
        );
        assert!(!headers.contains_key("content-length"));
    }

    #[test]
    fn sign_no_body_get_object_omits_content_length() {
        // Plain object GET: empty query, no content-length signed (reqwest
        // strips content-length: 0 on the wire → would 403 otherwise).
        let headers = sign_s3_no_body(
            "GET",
            "https://acct.r2.cloudflarestorage.com/yah-dev/_yah-manifest.json",
            "",
            "auto",
            "AK",
            "SK",
        )
        .unwrap();
        let auth = headers.get("authorization").unwrap().to_str().unwrap();
        assert!(
            auth.contains("SignedHeaders=host;x-amz-content-sha256;x-amz-date"),
            "object GET must NOT sign content-length: {auth}"
        );
        assert!(!headers.contains_key("content-length"));
    }

    #[test]
    fn sign_no_body_head_uses_head_method() {
        // HEAD shares the body-less signing path; the canonical request must
        // use the HEAD verb, not GET, but still omit content-length.
        let head = sign_s3_no_body(
            "HEAD",
            "https://acct.r2.cloudflarestorage.com/yah-dev/k",
            "",
            "auto",
            "AK",
            "SK",
        )
        .unwrap();
        let get = sign_s3_no_body(
            "GET",
            "https://acct.r2.cloudflarestorage.com/yah-dev/k",
            "",
            "auto",
            "AK",
            "SK",
        )
        .unwrap();
        assert!(!head.contains_key("content-length"));
        // Different verb → different signature for the same URL/time-window.
        assert_ne!(
            head.get("authorization").unwrap().to_str().unwrap(),
            get.get("authorization").unwrap().to_str().unwrap(),
        );
    }

    #[test]
    fn sign_put_bucket_acl_includes_acl_header_and_query() {
        let headers = sign_s3_put_bucket_acl(
            "https://fsn1.your-objectstorage.com/test-bucket?acl",
            "fsn1",
            "AK",
            "SK",
            "public-read",
        )
        .unwrap();
        assert!(headers.contains_key("authorization"));
        assert!(headers.contains_key("x-amz-acl"));
        assert_eq!(headers.get("x-amz-acl").unwrap().to_str().unwrap(), "public-read");
        let auth = headers.get("authorization").unwrap().to_str().unwrap();
        assert!(auth.starts_with("AWS4-HMAC-SHA256 Credential=AK/"));
        assert!(auth.contains("x-amz-acl"));
        assert!(auth.contains("SignedHeaders=content-length;host;x-amz-acl;x-amz-content-sha256;x-amz-date"));
    }
}