//! An S3 server inside the test process: path-style, one bucket, objects in //! memory. It checks every request's SigV4 signature as Garage does, from //! the request as it arrived (method, path, query, the signed headers and //! the payload's hash, which must match the body), so a client that signs //! one thing and sends another fails here. A listing comes in pages of two //! keys with tokens that need encoding, so the client's paging is //! exercised. `fail_next` makes it answer 503 to the next requests. use std::collections::BTreeMap; use std::sync::{Arc, Mutex}; use axum::Router; use axum::body::Body; use axum::extract::{Request, State}; use axum::http::{HeaderMap, Method, StatusCode, header}; use axum::response::Response; use visa::s3::{S3Config, sha256_hex, sigv4, uri_encode}; pub const KEY_ID: &str = "GK0123456789abcdef01234567"; pub const SECRET: &str = "test-s3-secret-not-secret"; pub const BUCKET: &str = "visa-documents"; struct Shared { objects: Mutex>>, requests: Mutex>, fail_next: Mutex, } pub struct FakeS3 { pub endpoint: String, shared: Arc, task: tokio::task::JoinHandle<()>, } impl Drop for FakeS3 { fn drop(&mut self) { self.task.abort(); } } impl FakeS3 { pub async fn start() -> FakeS3 { let shared = Arc::new(Shared { objects: Mutex::new(BTreeMap::new()), requests: Mutex::new(Vec::new()), fail_next: Mutex::new(0), }); let app = Router::new().fallback(handle).with_state(shared.clone()); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); let task = tokio::spawn(async move { axum::serve(listener, app).await.ok(); }); FakeS3 { endpoint: format!("http://{addr}"), shared, task, } } pub fn config(&self) -> S3Config { S3Config { endpoint: self.endpoint.clone(), bucket: BUCKET.into(), region: "garage".into(), access_key_id: KEY_ID.into(), secret_access_key: SECRET.into(), } } pub fn object(&self, key: &str) -> Option> { self.shared.objects.lock().unwrap().get(key).cloned() } pub fn put(&self, key: &str, bytes: &[u8]) { self.shared .objects .lock() .unwrap() .insert(key.to_string(), bytes.to_vec()); } pub fn remove(&self, key: &str) { self.shared.objects.lock().unwrap().remove(key); } pub fn keys(&self) -> Vec { self.shared .objects .lock() .unwrap() .keys() .cloned() .collect() } /// Answer 503 to the next `n` requests. pub fn fail_next(&self, n: usize) { *self.shared.fail_next.lock().unwrap() = n; } /// The requests so far: `METHOD path?query`, with ` if-none-match` when /// a PUT carried it. pub fn requests(&self) -> Vec { self.shared.requests.lock().unwrap().clone() } } fn answer(status: StatusCode, body: Vec) -> Response { Response::builder() .status(status) .body(Body::from(body)) .unwrap() } fn error(status: StatusCode, code: &str) -> Response { let xml = format!( "{code}\ {code}" ); Response::builder() .status(status) .header(header::CONTENT_TYPE, "application/xml") .body(Body::from(xml)) .unwrap() } fn decode(s: &str) -> String { let b = s.as_bytes(); let mut out = Vec::with_capacity(b.len()); let mut i = 0; while i < b.len() { if b[i] == b'%' && i + 3 <= b.len() && let Some(v) = std::str::from_utf8(&b[i + 1..i + 3]) .ok() .and_then(|h| u8::from_str_radix(h, 16).ok()) { out.push(v); i += 3; continue; } out.push(b[i]); i += 1; } String::from_utf8_lossy(&out).into_owned() } fn xml_escape(s: &str) -> String { s.replace('&', "&") .replace('<', "<") .replace('>', ">") } fn hex(s: &str) -> String { s.bytes().map(|b| format!("{b:02x}")).collect() } fn unhex(s: &str) -> Option { let bytes: Option> = (0..s.len()) .step_by(2) .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok()) .collect(); String::from_utf8(bytes?).ok() } /// The signature check: what Garage refuses, this refuses. The error is /// the answer to send. #[allow(clippy::result_large_err)] fn verify( method: &Method, path: &str, query: &str, headers: &HeaderMap, body: &[u8], ) -> Result<(), Response> { let deny = |code: &str| error(StatusCode::FORBIDDEN, code); let h = |name: &str| { headers .get(name) .and_then(|v| v.to_str().ok()) .map(str::to_string) }; let auth = h("authorization").ok_or_else(|| deny("AccessDenied"))?; let rest = auth .strip_prefix("AWS4-HMAC-SHA256 ") .ok_or_else(|| deny("AccessDenied"))?; let mut credential = ""; let mut signed = ""; let mut signature = ""; for part in rest.split(", ") { if let Some(v) = part.strip_prefix("Credential=") { credential = v; } else if let Some(v) = part.strip_prefix("SignedHeaders=") { signed = v; } else if let Some(v) = part.strip_prefix("Signature=") { signature = v; } } let scope: Vec<&str> = credential.split('/').collect(); let [key_id, date, region, "s3", "aws4_request"] = scope.as_slice() else { return Err(deny("AuthorizationHeaderMalformed")); }; if *key_id != KEY_ID { return Err(deny("InvalidAccessKeyId")); } let amz_date = h("x-amz-date").unwrap_or_default(); if !amz_date.starts_with(date) || *region != "garage" { return Err(deny("SignatureDoesNotMatch")); } let payload = h("x-amz-content-sha256").unwrap_or_default(); if payload != sha256_hex(body) { return Err(error(StatusCode::BAD_REQUEST, "XAmzContentSHA256Mismatch")); } let names: Vec<&str> = signed.split(';').collect(); for must in ["host", "x-amz-content-sha256", "x-amz-date"] { if !names.contains(&must) { return Err(deny("SignatureDoesNotMatch")); } } for (name, _) in headers { if name.as_str().starts_with("x-amz-") && !names.contains(&name.as_str()) { return Err(deny("SignatureDoesNotMatch")); } } let signed_headers: Vec<(String, String)> = names .iter() .map(|n| (n.to_string(), h(n).unwrap_or_default())) .collect(); let mut q: Vec<(String, String)> = query .split('&') .filter(|p| !p.is_empty()) .map(|p| { let (k, v) = p.split_once('=').unwrap_or((p, "")); (uri_encode(&decode(k), false), uri_encode(&decode(v), false)) }) .collect(); q.sort(); let canonical_query = q .iter() .map(|(k, v)| format!("{k}={v}")) .collect::>() .join("&"); let want = sigv4( method.as_str(), &uri_encode(&decode(path), true), &canonical_query, &signed_headers, &payload, &amz_date, region, key_id, SECRET, ); if want.rsplit("Signature=").next() != Some(signature) { return Err(deny("SignatureDoesNotMatch")); } Ok(()) } async fn handle(State(s): State>, req: Request) -> Response { let (parts, body) = req.into_parts(); let body = axum::body::to_bytes(body, usize::MAX) .await .unwrap() .to_vec(); let path = parts.uri.path().to_string(); let query = parts.uri.query().unwrap_or_default().to_string(); let method = parts.method.clone(); let conditional = parts.headers.contains_key(header::IF_NONE_MATCH); s.requests.lock().unwrap().push(format!( "{method} {path}{}{}", if query.is_empty() { String::new() } else { format!("?{query}") }, if conditional { " if-none-match" } else { "" } )); let busy = { let mut n = s.fail_next.lock().unwrap(); let busy = *n > 0; *n = n.saturating_sub(1); busy }; if busy { return error(StatusCode::SERVICE_UNAVAILABLE, "SlowDown"); } if let Err(r) = verify(&method, &path, &query, &parts.headers, &body) { return r; } let rest = match path.strip_prefix(&format!("/{BUCKET}")) { Some("") => String::new(), Some(r) if r.starts_with('/') => decode(&r[1..]), _ => return error(StatusCode::NOT_FOUND, "NoSuchBucket"), }; let params: BTreeMap = query .split('&') .filter(|p| !p.is_empty()) .map(|p| { let (k, v) = p.split_once('=').unwrap_or((p, "")); (decode(k), decode(v)) }) .collect(); let mut objects = s.objects.lock().unwrap(); if rest.is_empty() { if method != Method::GET || params.get("list-type").map(String::as_str) != Some("2") { return error(StatusCode::NOT_IMPLEMENTED, "NotImplemented"); } let prefix = params.get("prefix").cloned().unwrap_or_default(); let max: usize = params .get("max-keys") .and_then(|m| m.parse().ok()) .unwrap_or(1000) .min(2); let start = match params.get("continuation-token") { Some(t) => match t.strip_prefix("tok+/=").and_then(unhex) { Some(k) => k, None => return error(StatusCode::BAD_REQUEST, "InvalidArgument"), }, None => String::new(), }; let keys: Vec<(&String, &Vec)> = objects .iter() .filter(|(k, _)| k.starts_with(&prefix) && **k >= start) .collect(); let page = &keys[..keys.len().min(max)]; let mut xml = format!( "\ \ {BUCKET}{}{}\ {max}{}", xml_escape(&prefix), page.len(), keys.len() > page.len() ); for (k, v) in page { xml.push_str(&format!( "{}{}STANDARD", xml_escape(k), v.len() )); } if keys.len() > page.len() { xml.push_str(&format!( "tok+/={}", hex(keys[page.len()].0) )); } xml.push_str(""); return answer(StatusCode::OK, xml.into_bytes()); } match method { Method::PUT => { if conditional && objects.contains_key(&rest) { return error(StatusCode::PRECONDITION_FAILED, "PreconditionFailed"); } objects.insert(rest, body); answer(StatusCode::OK, Vec::new()) } Method::GET => match objects.get(&rest) { Some(b) => answer(StatusCode::OK, b.clone()), None => error(StatusCode::NOT_FOUND, "NoSuchKey"), }, Method::HEAD => match objects.get(&rest) { Some(b) => Response::builder() .status(StatusCode::OK) .header(header::CONTENT_LENGTH, b.len()) .body(Body::empty()) .unwrap(), None => answer(StatusCode::NOT_FOUND, Vec::new()), }, Method::DELETE => { objects.remove(&rest); answer(StatusCode::NO_CONTENT, Vec::new()) } _ => error(StatusCode::NOT_IMPLEMENTED, "NotImplemented"), } }