//! A small S3 client for the document store: path-style requests (the //! bucket is the first part of the path) signed with AWS Signature Version 4, //! on reqwest and ring, as in proplan. It makes the five calls the store //! needs: PUT, GET, HEAD, DELETE and ListObjectsV2. Garage, the fleet's //! object store, answers them as AWS does. //! //! The objects are the store's encrypted files: this client never sees a //! document's contents in the clear, and its errors name the object and the //! answer, never the secret key. use std::fmt; use std::time::Duration; use anyhow::{Context, Result, bail, ensure}; use chrono::{DateTime, Utc}; use reqwest::{Method, StatusCode, Url}; use ring::{digest, hmac}; /// Where the bucket is, and the key to it. #[derive(Clone)] pub struct S3Config { /// The server, without a path: `http://127.0.0.1:3900`. pub endpoint: String, pub bucket: String, /// Garage's is `garage`. pub region: String, pub access_key_id: String, pub secret_access_key: String, } // The secret stays out of logs and panics. impl fmt::Debug for S3Config { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("S3Config") .field("endpoint", &self.endpoint) .field("bucket", &self.bucket) .field("region", &self.region) .field("access_key_id", &self.access_key_id) .field( "secret_access_key", &format_args!("<{} bytes>", self.secret_access_key.len()), ) .finish() } } /// An object as a listing names it. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Object { pub key: String, pub size: u64, } /// What [`Bucket::put_new`] did. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Put { Written, /// The object was there already with exactly these bytes (a retry, or a /// copy that ran before). Same, } #[derive(Clone)] pub struct Bucket { endpoint: String, bucket: String, region: String, key_id: String, secret: String, /// `host[:port]` as the request's Host header carries it. host: String, http: reqwest::Client, /// Between attempts at a request the server could not answer. pause: Duration, } impl fmt::Debug for Bucket { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Bucket({} at {})", self.bucket, self.endpoint) } } /// An answer, read in full. struct Answer { status: StatusCode, headers: reqwest::header::HeaderMap, body: Vec, } /// How often a request is tried when the server is away or busy. const ATTEMPTS: u32 = 3; impl Bucket { pub fn new(cfg: &S3Config) -> Result { let endpoint = cfg.endpoint.trim().trim_end_matches('/').to_string(); let url = Url::parse(&endpoint) .with_context(|| format!("the S3 endpoint {endpoint:?} is not a URL"))?; ensure!( matches!(url.scheme(), "http" | "https"), "the S3 endpoint {endpoint:?} must start with http:// or https://" ); ensure!( url.path() == "/" && url.query().is_none(), "the S3 endpoint {endpoint:?} is a server's address, without a path" ); let name = url .host_str() .with_context(|| format!("the S3 endpoint {endpoint:?} has no host"))?; let host = match url.port() { Some(p) => format!("{name}:{p}"), None => name.to_string(), }; ensure!( valid_bucket_name(&cfg.bucket), "{:?} is not a bucket name (3 to 63 lowercase letters, digits, dots and hyphens)", cfg.bucket ); ensure!( !cfg.access_key_id.trim().is_empty(), "the S3 key id is empty" ); ensure!( !cfg.secret_access_key.is_empty(), "the S3 secret key is empty" ); let http = reqwest::Client::builder() .connect_timeout(Duration::from_secs(5)) .timeout(Duration::from_secs(120)) .user_agent(concat!("visa/", env!("CARGO_PKG_VERSION"))) .build()?; Ok(Bucket { endpoint, bucket: cfg.bucket.clone(), region: if cfg.region.trim().is_empty() { "garage".into() } else { cfg.region.trim().to_string() }, key_id: cfg.access_key_id.trim().to_string(), secret: cfg.secret_access_key.clone(), host, http, pause: Duration::from_millis(500), }) } /// A shorter pause between attempts, for the tests. pub fn with_pause(mut self, pause: Duration) -> Bucket { self.pause = pause; self } pub fn name(&self) -> &str { &self.bucket } pub fn endpoint(&self) -> &str { &self.endpoint } /// The canonical path of an object, or of the bucket for an empty key. fn path(&self, key: &str) -> String { format!("/{}/{}", self.bucket, uri_encode(key, true)) } /// One request, signed, sent and read in full. A connection that fails /// and the answers 500, 502, 503 and 504 are tried again, signed anew. async fn send( &self, method: Method, key: &str, query: &[(&str, &str)], body: &[u8], extra: &[(&str, &str)], ) -> Result { let path = self.path(key); let mut q: Vec<(String, String)> = query .iter() .map(|(k, v)| (uri_encode(k, false), uri_encode(v, false))) .collect(); q.sort(); let qs = q .iter() .map(|(k, v)| format!("{k}={v}")) .collect::>() .join("&"); let url = if qs.is_empty() { format!("{}{path}", self.endpoint) } else { format!("{}{path}?{qs}", self.endpoint) }; let payload = sha256_hex(body); let mut attempt = 0; loop { attempt += 1; let amz_date = amz_date(Utc::now()); let mut headers: Vec<(String, String)> = vec![ ("host".into(), self.host.clone()), ("x-amz-content-sha256".into(), payload.clone()), ("x-amz-date".into(), amz_date.clone()), ]; for (k, v) in extra { headers.push((k.to_ascii_lowercase(), (*v).to_string())); } let auth = sigv4( method.as_str(), &path, &qs, &headers, &payload, &amz_date, &self.region, &self.key_id, &self.secret, ); let mut rb = self .http .request(method.clone(), &url) .header("authorization", auth); for (k, v) in headers.iter().filter(|(k, _)| k != "host") { rb = rb.header(k, v); } if !body.is_empty() || method == Method::PUT { rb = rb.body(body.to_vec()); } let what = || format!("S3 {method} {}", self.object_name(key)); match rb.send().await { Ok(res) => { let status = res.status(); let headers = res.headers().clone(); let busy = matches!(status.as_u16(), 500 | 502 | 503 | 504); match res.bytes().await { Ok(b) if !busy || attempt >= ATTEMPTS => { return Ok(Answer { status, headers, body: b.to_vec(), }); } Ok(_) => {} Err(e) if attempt >= ATTEMPTS => { return Err(e) .with_context(|| format!("{}: reading the answer", what())); } Err(_) => {} } } Err(e) if attempt >= ATTEMPTS => { return Err(e) .with_context(|| format!("{}: no answer from {}", what(), self.endpoint)); } Err(_) => {} } tokio::time::sleep(self.pause * attempt).await; } } fn object_name(&self, key: &str) -> String { if key.is_empty() { format!("bucket {}", self.bucket) } else { format!("{key} in bucket {}", self.bucket) } } /// The error for an answer that is not what was asked for: the status /// and the S3 error code (`AccessDenied`, `NoSuchBucket` ...). fn failed(&self, what: &str, key: &str, a: &Answer) -> anyhow::Error { let text = String::from_utf8_lossy(&a.body); let code = tag(&text, "Code").unwrap_or_default(); anyhow::anyhow!( "S3 {what} {}: HTTP {} {code}", self.object_name(key), a.status.as_u16() ) } /// Writes an object that must not exist yet. One that exists with the /// same bytes counts as written before ([`Put::Same`]), one with other /// bytes is an error and stays as it is. The server is asked first: that /// question is the guard on Garage, which ignores the write's condition /// ([`Bucket::put_if_absent`]). The store's ids are unique, so only a /// restore that brought an old id back could meet an object here. pub async fn put_new(&self, key: &str, bytes: &[u8]) -> Result { if self.head(key).await?.is_none() && self.put_if_absent(key, bytes).await? { return Ok(Put::Written); } self.same_or_refuse(key, bytes).await } /// A PUT with `If-None-Match: *`: true when the object was written, /// false when the server refused because it exists (HTTP 412). AWS and /// MinIO honor the header; Garage 2.5 ignores it and writes (seen in /// tests/garage.rs on Nov 19, 2026), so on Garage this is a plain PUT. pub async fn put_if_absent(&self, key: &str, bytes: &[u8]) -> Result { let a = self .send( Method::PUT, key, &[], bytes, &[ ("content-type", "application/octet-stream"), ("if-none-match", "*"), ], ) .await?; if a.status.is_success() { Ok(true) } else if a.status == StatusCode::PRECONDITION_FAILED { Ok(false) } else { Err(self.failed("PUT", key, &a)) } } async fn same_or_refuse(&self, key: &str, bytes: &[u8]) -> Result { match self.get(key).await? { Some(there) if there == bytes => Ok(Put::Same), Some(_) => bail!( "{} is there already with other bytes; it stays as it is", self.object_name(key) ), None => bail!( "{} was there a moment ago and is gone now; try again", self.object_name(key) ), } } /// The object's bytes, or None when there is no such object. pub async fn get(&self, key: &str) -> Result>> { let a = self.send(Method::GET, key, &[], &[], &[]).await?; match a.status { s if s.is_success() => Ok(Some(a.body)), StatusCode::NOT_FOUND if tag(&String::from_utf8_lossy(&a.body), "Code").as_deref() != Some("NoSuchBucket") => { Ok(None) } _ => Err(self.failed("GET", key, &a)), } } /// The object's size, or None when there is no such object. pub async fn head(&self, key: &str) -> Result> { let a = self.send(Method::HEAD, key, &[], &[], &[]).await?; match a.status { s if s.is_success() => Ok(Some( a.headers .get(reqwest::header::CONTENT_LENGTH) .and_then(|v| v.to_str().ok()) .and_then(|v| v.parse().ok()) .unwrap_or_default(), )), StatusCode::NOT_FOUND => Ok(None), _ => Err(self.failed("HEAD", key, &a)), } } /// Removes an object; one that is gone already is fine. pub async fn delete(&self, key: &str) -> Result<()> { let a = self.send(Method::DELETE, key, &[], &[], &[]).await?; if a.status.is_success() || a.status == StatusCode::NOT_FOUND { Ok(()) } else { Err(self.failed("DELETE", key, &a)) } } /// Every object whose key starts with `prefix`, sorted by key; read /// page by page. pub async fn list(&self, prefix: &str) -> Result> { let mut out = Vec::new(); let mut token: Option = None; loop { let mut q = vec![("list-type", "2"), ("prefix", prefix)]; if let Some(t) = &token { q.push(("continuation-token", t.as_str())); } let a = self.send(Method::GET, "", &q, &[], &[]).await?; if !a.status.is_success() { return Err(self.failed("LIST", "", &a)); } let page = parse_list(&String::from_utf8_lossy(&a.body))?; out.extend(page.objects); match (page.truncated, page.next) { (true, Some(next)) if Some(&next) != token.as_ref() => token = Some(next), (true, _) => bail!( "S3 LIST {}: a page says more follow but gives no new token", self.object_name("") ), (false, _) => break, } } out.sort_by(|a, b| a.key.cmp(&b.key)); Ok(out) } /// The bucket answers to this key (at the start and in `files-check`). pub async fn check(&self) -> Result<()> { let a = self .send( Method::GET, "", &[("list-type", "2"), ("max-keys", "1")], &[], &[], ) .await?; if a.status.is_success() { Ok(()) } else { Err(self.failed("LIST", "", &a)) } } } /// S3's rule for bucket names, as Garage applies it. fn valid_bucket_name(name: &str) -> bool { (3..=63).contains(&name.len()) && name .bytes() .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-') && name.as_bytes()[0].is_ascii_alphanumeric() && name.as_bytes()[name.len() - 1].is_ascii_alphanumeric() } /// One page of a listing. #[derive(Debug, Default, PartialEq, Eq)] pub struct Page { pub objects: Vec, pub truncated: bool, pub next: Option, } /// Reads a ListObjectsV2 answer. pub fn parse_list(xml: &str) -> Result { ensure!( xml.contains("").skip(1) { let part = part.split("").next().unwrap_or_default(); let key = tag(part, "Key").context("S3 LIST: an object without a key")?; let size = tag(part, "Size") .and_then(|s| s.parse().ok()) .with_context(|| format!("S3 LIST: {key} without a size"))?; page.objects.push(Object { key, size }); } Ok(page) } /// The text of the first `` element, unescaped. fn tag(xml: &str, name: &str) -> Option { let open = format!("<{name}>"); let close = format!(""); let start = xml.find(&open)? + open.len(); let len = xml[start..].find(&close)?; Some(xml_unescape(&xml[start..start + len])) } fn xml_unescape(s: &str) -> String { s.replace("<", "<") .replace(">", ">") .replace(""", "\"") .replace("'", "'") .replace("'", "'") .replace("&", "&") } pub fn amz_date(t: DateTime) -> String { t.format("%Y%m%dT%H%M%SZ").to_string() } fn hex(b: &[u8]) -> String { b.iter().map(|x| format!("{x:02x}")).collect() } pub fn sha256_hex(b: &[u8]) -> String { hex(digest::digest(&digest::SHA256, b).as_ref()) } fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec { hmac::sign(&hmac::Key::new(hmac::HMAC_SHA256, key), data) .as_ref() .to_vec() } /// URI-encodes as SigV4 wants: unreserved characters stay, every other byte /// becomes `%XX` in upper case; `/` stays in paths. pub fn uri_encode(s: &str, keep_slash: bool) -> String { let mut out = String::with_capacity(s.len()); for b in s.bytes() { if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) || (keep_slash && b == b'/') { out.push(b as char); } else { out.push_str(&format!("%{b:02X}")); } } out } /// The `Authorization` header of one request (SigV4): pure, so the tests /// check it against AWS's published example and the test server checks /// every request with it. `headers` are the signed ones; names may come in /// any case and order. #[allow(clippy::too_many_arguments)] pub fn sigv4( method: &str, canonical_path: &str, canonical_query: &str, headers: &[(String, String)], payload_hash: &str, amz_date: &str, region: &str, key_id: &str, secret: &str, ) -> String { let date = &amz_date[..8.min(amz_date.len())]; let mut hs: Vec<(String, String)> = headers .iter() .map(|(k, v)| { ( k.to_ascii_lowercase(), v.split_whitespace().collect::>().join(" "), ) }) .collect(); hs.sort(); let canonical_headers: String = hs.iter().map(|(k, v)| format!("{k}:{v}\n")).collect(); let signed = hs .iter() .map(|(k, _)| k.as_str()) .collect::>() .join(";"); let canonical = format!( "{method}\n{canonical_path}\n{canonical_query}\n{canonical_headers}\n{signed}\n{payload_hash}" ); let scope = format!("{date}/{region}/s3/aws4_request"); let to_sign = format!( "AWS4-HMAC-SHA256\n{amz_date}\n{scope}\n{}", sha256_hex(canonical.as_bytes()) ); let k = hmac_sha256(format!("AWS4{secret}").as_bytes(), date.as_bytes()); let k = hmac_sha256(&k, region.as_bytes()); let k = hmac_sha256(&k, b"s3"); let k = hmac_sha256(&k, b"aws4_request"); let signature = hex(&hmac_sha256(&k, to_sign.as_bytes())); format!( "AWS4-HMAC-SHA256 Credential={key_id}/{scope}, SignedHeaders={signed}, Signature={signature}" ) } #[cfg(test)] mod tests { use super::*; const EMPTY: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; /// The secret key of AWS's documented examples. const AWS_EXAMPLE_SECRET: &str = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"; fn signature(auth: &str) -> &str { auth.rsplit("Signature=").next().unwrap() } /// AWS's example "GET Object" (Signature Calculations for the /// Authorization Header: Transferring Payload in a Single Chunk). The /// signature depends on the secret alone, not on the key id. #[test] fn sigv4_matches_the_aws_get_example() { let auth = sigv4( "GET", "/test.txt", "", &[ ("Host".into(), "examplebucket.s3.amazonaws.com".into()), ("Range".into(), "bytes=0-9".into()), ("x-amz-content-sha256".into(), EMPTY.into()), ("x-amz-date".into(), "20130524T000000Z".into()), ], EMPTY, "20130524T000000Z", "us-east-1", "EXAMPLE-KEY-ID", AWS_EXAMPLE_SECRET, ); assert!( auth.starts_with( "AWS4-HMAC-SHA256 Credential=EXAMPLE-KEY-ID/20130524/us-east-1/s3/aws4_request, \ SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, " ), "{auth}" ); assert_eq!( signature(&auth), "f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41" ); } /// AWS's example "GET Bucket (List Objects)": a query string. #[test] fn sigv4_matches_the_aws_list_example() { let auth = sigv4( "GET", "/", "max-keys=2&prefix=J", &[ ("host".into(), "examplebucket.s3.amazonaws.com".into()), ("x-amz-content-sha256".into(), EMPTY.into()), ("x-amz-date".into(), "20130524T000000Z".into()), ], EMPTY, "20130524T000000Z", "us-east-1", "EXAMPLE-KEY-ID", AWS_EXAMPLE_SECRET, ); assert_eq!( signature(&auth), "34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7" ); } #[test] fn names_and_values_are_encoded_as_sigv4_wants() { assert_eq!(uri_encode("documents/7.vdoc", true), "documents/7.vdoc"); assert_eq!(uri_encode("a b/c~d", true), "a%20b/c~d"); assert_eq!(uri_encode("a b/c", false), "a%20b%2Fc"); assert_eq!(uri_encode("tok+/=", false), "tok%2B%2F%3D"); assert_eq!(uri_encode("ไ", false), "%E0%B9%84"); for good in ["visa-documents", "proplan.lol", "abc"] { assert!(valid_bucket_name(good), "{good}"); } for bad in ["", "ab", "Visa", "visa_documents", "-visa", "visa-", "a/b"] { assert!(!valid_bucket_name(bad), "{bad}"); } } #[test] fn a_listing_reads_keys_sizes_and_the_next_page() { let xml = "\ \ visa-documentsdocuments/2\ 2true\ documents/1.vdoc2026-11-19T10:00:00.000Z\ "9b2cf535f27731c974343645a3985328"1234\ STANDARD\ documents/a&b.vdoc0\ tok+/="; let page = parse_list(xml).unwrap(); assert_eq!( page.objects, [ Object { key: "documents/1.vdoc".into(), size: 1234 }, Object { key: "documents/a&b.vdoc".into(), size: 0 } ] ); assert!(page.truncated); assert_eq!(page.next.as_deref(), Some("tok+/=")); let last = parse_list( "false0", ) .unwrap(); assert_eq!(last, Page::default()); assert!(parse_list("AccessDenied").is_err()); } #[test] fn the_endpoint_is_a_server_and_the_secret_is_never_shown() { let cfg = |endpoint: &str| S3Config { endpoint: endpoint.into(), bucket: "visa-documents".into(), region: String::new(), access_key_id: "GK0011".into(), secret_access_key: "very-secret-value".into(), }; let b = Bucket::new(&cfg("http://127.0.0.1:3900/")).unwrap(); assert_eq!(b.host, "127.0.0.1:3900"); assert_eq!(b.region, "garage"); assert_eq!(b.endpoint(), "http://127.0.0.1:3900"); assert_eq!( b.path("documents/7.vdoc"), "/visa-documents/documents/7.vdoc" ); assert_eq!(b.path(""), "/visa-documents/"); let b = Bucket::new(&cfg("http://[::1]:3900")).unwrap(); assert_eq!(b.host, "[::1]:3900"); for bad in [ "127.0.0.1:3900", "ftp://x", "http://x/visa-documents", "nonsense", ] { assert!(Bucket::new(&cfg(bad)).is_err(), "{bad}"); } let shown = format!("{:?} {:?}", cfg("http://x"), b); assert!(!shown.contains("very-secret"), "{shown}"); } }