Files
grabowski 0370e0154f
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 52s
Documents in a bucket of Garage, still encrypted by the app
Asked for on November 19, 2026: the uploaded files land in an S3 bucket of
the fleet's Garage instead of a directory on cnx01, as the fleet's other
apps keep theirs. The app encrypts each file exactly as before (AES-256-GCM
under a key from HKDF, the document's id authenticated), so the bucket holds
the same VISADOC1 files and Garage never sees a key or a document in the
clear. Garage's SSE-C stays off: its key would come from the same secret.

src/s3.rs is a small S3 client on reqwest and ring, as in proplan: SigV4
(checked against AWS's two published examples), path-style PUT, GET, HEAD,
DELETE and ListObjectsV2 page by page, three attempts when the server is
away or busy. It asks before it writes, so no object is replaced; it sends
If-None-Match: * as well, which Garage 2.5 ignores (seen in tests/garage.rs).

The store (src/files.rs) keeps the files as documents/<id>.vdoc in the
bucket, or as <id>.vdoc in a directory for development and the tests. Its
calls are async now. VISA_S3_BUCKET, _ENDPOINT, _REGION and _ACCESS_KEY_ID
name the bucket, the secret comes from VISA_S3_SECRET_ACCESS_KEY_FILE or the
credential s3-secret; the bucket and a directory together are refused. At
the start the app checks the bucket in the background and only warns.

New commands: `visa files-migrate --from DIR` copies the files of a
directory into the store, each opened and compared with its upload before
and after, and may run again; `visa files-mirror --to DIR` makes a
directory hold exactly the bucket's files, still encrypted, for the
backups, and a restore is files-migrate from it.

Tests: an S3 server inside the test process that checks every request's
signature and pages its listings (tests/common/fake_s3.rs); uploads, views,
downloads and deletions through it, the check finding swapped, missing and
stray objects, the move from a directory (again, missing, other bytes,
damaged), the mirror and a restore from it, a busy server and a wrong key.
tests/garage.rs runs the store against Garage 2.5.0, the version cnx01 runs,
which scripts/dev-garage.sh starts in Docker; VISA_DEV_S3=1 scripts/dev.sh
runs the dev server on it. The 14 demo documents moved into it with
files-migrate and a browser upload landed there.
2026-11-19 20:35:32 +07:00

380 lines
12 KiB
Rust

//! 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<BTreeMap<String, Vec<u8>>>,
requests: Mutex<Vec<String>>,
fail_next: Mutex<usize>,
}
pub struct FakeS3 {
pub endpoint: String,
shared: Arc<Shared>,
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<Vec<u8>> {
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<String> {
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<String> {
self.shared.requests.lock().unwrap().clone()
}
}
fn answer(status: StatusCode, body: Vec<u8>) -> Response {
Response::builder()
.status(status)
.body(Body::from(body))
.unwrap()
}
fn error(status: StatusCode, code: &str) -> Response {
let xml = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><Error><Code>{code}</Code>\
<Message>{code}</Message></Error>"
);
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('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
}
fn hex(s: &str) -> String {
s.bytes().map(|b| format!("{b:02x}")).collect()
}
fn unhex(s: &str) -> Option<String> {
let bytes: Option<Vec<u8>> = (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::<Vec<_>>()
.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<Arc<Shared>>, 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<String, String> = 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<u8>)> = objects
.iter()
.filter(|(k, _)| k.starts_with(&prefix) && **k >= start)
.collect();
let page = &keys[..keys.len().min(max)];
let mut xml = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\
<Name>{BUCKET}</Name><Prefix>{}</Prefix><KeyCount>{}</KeyCount>\
<MaxKeys>{max}</MaxKeys><IsTruncated>{}</IsTruncated>",
xml_escape(&prefix),
page.len(),
keys.len() > page.len()
);
for (k, v) in page {
xml.push_str(&format!(
"<Contents><Key>{}</Key><Size>{}</Size><StorageClass>STANDARD</StorageClass></Contents>",
xml_escape(k),
v.len()
));
}
if keys.len() > page.len() {
xml.push_str(&format!(
"<NextContinuationToken>tok+/={}</NextContinuationToken>",
hex(keys[page.len()].0)
));
}
xml.push_str("</ListBucketResult>");
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"),
}
}