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.
This commit is contained in:
1 parent
17426dba12
commit
0370e0154f
20 files changed
+2558
-218
No files matched your search
+333
@@ -0,0 +1,333 @@
|
||||
//! Documents in a bucket, where the server keeps them: an upload lands there
|
||||
//! encrypted and opens, downloads and goes again; the check finds what is
|
||||
//! wrong; the files of a directory move into the bucket, again and again
|
||||
//! without harm; the mirror for the backups follows the bucket and fills a
|
||||
//! new one; a busy server is asked again and a wrong key is an error.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use sqlx::PgPool;
|
||||
use visa::config::{Auth, Config, FilesConfig, FilesPlace};
|
||||
use visa::documents;
|
||||
use visa::files::{self, FileKey, Mirrored, Store};
|
||||
use visa::s3::Bucket;
|
||||
|
||||
use crate::common::fake_s3::FakeS3;
|
||||
use crate::common::{App, bucket_config, config, files_dir, local, pdf, with_config};
|
||||
use crate::documents::person;
|
||||
|
||||
fn on_bucket(pool: &PgPool, s3: &FakeS3) -> App {
|
||||
with_config(pool.clone(), bucket_config(Auth::Disabled, s3))
|
||||
}
|
||||
|
||||
fn object(id: i64) -> String {
|
||||
format!("documents/{id}.vdoc")
|
||||
}
|
||||
|
||||
async fn ids(pool: &PgPool) -> Vec<i64> {
|
||||
sqlx::query_scalar("SELECT id FROM documents ORDER BY id")
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Uploads one PDF per text to the person's documents.
|
||||
async fn upload(app: &App, person: i64, texts: &[&str]) {
|
||||
for t in texts {
|
||||
let r = app
|
||||
.upload(
|
||||
&format!("/people/{person}/documents"),
|
||||
&[("kind", "other")],
|
||||
&[(&format!("{t}.pdf"), &pdf(t))],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
}
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn an_upload_lies_encrypted_in_the_bucket_and_goes_with_its_document(pool: PgPool) {
|
||||
let s3 = FakeS3::start().await;
|
||||
let app = on_bucket(&pool, &s3);
|
||||
let id = person(&app, "Doe").await;
|
||||
let base = format!("/people/{id}/documents");
|
||||
let scan = pdf("the photo page of a passport");
|
||||
let r = app
|
||||
.upload(
|
||||
&base,
|
||||
&[("kind", "passport-photo-page")],
|
||||
&[("scan.pdf", &scan)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
let did = ids(&pool).await[0];
|
||||
|
||||
// in the bucket under its id, encrypted, and nothing else there
|
||||
assert_eq!(s3.keys(), [object(did)]);
|
||||
let stored = s3.object(&object(did)).unwrap();
|
||||
assert!(stored.starts_with(b"VISADOC1"));
|
||||
assert!(!stored.windows(10).any(|w| w == b"photo page"));
|
||||
// the write asked the server not to replace anything
|
||||
let put = format!("PUT /visa-documents/{} if-none-match", object(did));
|
||||
assert!(s3.requests().contains(&put), "{:?}", s3.requests());
|
||||
|
||||
// it opens and downloads as it was uploaded
|
||||
let file = format!("{base}/{did}/file");
|
||||
let r = app.get(&file).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(r.bytes, scan);
|
||||
let r = app.get(&format!("{file}?download=1")).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(r.bytes, scan);
|
||||
|
||||
// the check reads it back from the bucket
|
||||
let store = app.st.files.as_ref().unwrap();
|
||||
assert!(
|
||||
store
|
||||
.describe()
|
||||
.starts_with("bucket visa-documents at http://127.0.0.1:")
|
||||
);
|
||||
store.check().await.unwrap();
|
||||
let check = documents::check(&pool, store).await.unwrap();
|
||||
assert_eq!(check.documents, 1);
|
||||
assert!(check.problems.is_empty(), "{:?}", check.problems);
|
||||
|
||||
// deleted: the object goes with the row
|
||||
let r = app.post(&format!("{base}/{did}/delete"), &[]).await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||
assert!(s3.keys().is_empty(), "{:?}", s3.keys());
|
||||
assert_eq!(app.get(&file).await.status, StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn the_check_finds_swapped_missing_and_stray_objects(pool: PgPool) {
|
||||
let s3 = FakeS3::start().await;
|
||||
let app = on_bucket(&pool, &s3);
|
||||
let id = person(&app, "Doe").await;
|
||||
upload(&app, id, &["first", "second", "third", "fourth"]).await;
|
||||
let ids = ids(&pool).await;
|
||||
let store = app.st.files.as_ref().unwrap();
|
||||
assert!(
|
||||
documents::check(&pool, store)
|
||||
.await
|
||||
.unwrap()
|
||||
.problems
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
// the first two swapped, the third gone, two objects of no document
|
||||
let (a, b) = (
|
||||
s3.object(&object(ids[0])).unwrap(),
|
||||
s3.object(&object(ids[1])).unwrap(),
|
||||
);
|
||||
s3.put(&object(ids[0]), &b);
|
||||
s3.put(&object(ids[1]), &a);
|
||||
s3.remove(&object(ids[2]));
|
||||
s3.put(&object(77), b"left over");
|
||||
s3.put("notes.txt", b"not ours");
|
||||
|
||||
let r = app
|
||||
.get(&format!("/people/{id}/documents/{}/file", ids[0]))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::INTERNAL_SERVER_ERROR);
|
||||
assert!(r.text().contains("cannot be opened"), "{}", r.body);
|
||||
assert!(!r.bytes.windows(6).any(|w| w == b"second"));
|
||||
|
||||
// five objects, read in pages of two
|
||||
let check = documents::check(&pool, store).await.unwrap();
|
||||
let p = &check.problems;
|
||||
assert_eq!(p.len(), 5, "{p:?}");
|
||||
assert!(
|
||||
p[0].contains("damaged, or the file of another document"),
|
||||
"{p:?}"
|
||||
);
|
||||
assert!(
|
||||
p[1].contains("damaged, or the file of another document"),
|
||||
"{p:?}"
|
||||
);
|
||||
assert!(p[2].contains("is missing"), "{p:?}");
|
||||
assert!(
|
||||
p[3].contains("77.vdoc: a file without its document"),
|
||||
"{p:?}"
|
||||
);
|
||||
assert!(p[4].contains("notes.txt: not a file of the store"), "{p:?}");
|
||||
let lists = s3
|
||||
.requests()
|
||||
.iter()
|
||||
.filter(|r| r.contains("list-type=2"))
|
||||
.count();
|
||||
assert!(lists >= 3, "{:?}", s3.requests());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn the_files_move_from_their_directory_into_the_bucket(pool: PgPool) {
|
||||
// before: the files in a directory, as on the server until now
|
||||
let before = local(pool.clone());
|
||||
let id = person(&before, "Doe").await;
|
||||
upload(&before, id, &["passport", "receipt"]).await;
|
||||
let ids = ids(&pool).await;
|
||||
let old = before.st.files.as_ref().unwrap();
|
||||
let dir = old.dir().unwrap().to_path_buf();
|
||||
let key = old.file_key().clone();
|
||||
std::fs::write(dir.join("99.vdoc"), b"no document's").unwrap();
|
||||
std::fs::write(dir.join(".98.vdoc.part"), b"cut short").unwrap();
|
||||
let e = documents::migrate(&pool, &dir, old).await.unwrap_err();
|
||||
assert!(e.to_string().contains("the store itself"), "{e}");
|
||||
|
||||
// after: the same key, the files in the bucket, byte for byte
|
||||
let s3 = FakeS3::start().await;
|
||||
let store = Store::in_bucket(&s3.config(), key.clone()).unwrap();
|
||||
let moved = documents::migrate(&pool, &dir, &store).await.unwrap();
|
||||
assert_eq!((moved.copied, moved.there), (2, 0));
|
||||
assert_eq!(moved.strays, ["99.vdoc", ".98.vdoc.part"]);
|
||||
assert!(moved.missing.is_empty());
|
||||
for id in &ids {
|
||||
let on_disk = std::fs::read(dir.join(files::file_name(*id))).unwrap();
|
||||
assert_eq!(s3.object(&object(*id)).unwrap(), on_disk);
|
||||
}
|
||||
assert!(s3.object(&object(99)).is_none(), "strays stay behind");
|
||||
|
||||
// the app on the bucket opens them
|
||||
let after = with_config(
|
||||
pool.clone(),
|
||||
Config {
|
||||
files: Some(FilesConfig {
|
||||
place: FilesPlace::Bucket(s3.config()),
|
||||
key: key.clone(),
|
||||
}),
|
||||
..config(Auth::Disabled)
|
||||
},
|
||||
);
|
||||
for (id_, text) in ids.iter().zip(["passport", "receipt"]) {
|
||||
let r = after
|
||||
.get(&format!("/people/{id}/documents/{id_}/file"))
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(r.bytes, pdf(text));
|
||||
}
|
||||
|
||||
// again: nothing to copy, so a stopped run can simply start over
|
||||
let moved = documents::migrate(&pool, &dir, &store).await.unwrap();
|
||||
assert_eq!((moved.copied, moved.there), (0, 2));
|
||||
|
||||
// a file in neither place is reported, not invented
|
||||
std::fs::remove_file(dir.join(files::file_name(ids[1]))).unwrap();
|
||||
s3.remove(&object(ids[1]));
|
||||
let moved = documents::migrate(&pool, &dir, &store).await.unwrap();
|
||||
assert_eq!(moved.missing, [ids[1]]);
|
||||
|
||||
// the bucket holding other bytes for a document stops the copy, and
|
||||
// the object stays as it is
|
||||
s3.put(&object(ids[0]), b"other bytes");
|
||||
let e = documents::migrate(&pool, &dir, &store).await.unwrap_err();
|
||||
assert!(format!("{e:#}").contains("other bytes"), "{e:#}");
|
||||
assert_eq!(s3.object(&object(ids[0])).unwrap(), b"other bytes");
|
||||
|
||||
// a damaged file in the directory is never copied
|
||||
s3.remove(&object(ids[0]));
|
||||
let path = dir.join(files::file_name(ids[0]));
|
||||
let mut damaged = std::fs::read(&path).unwrap();
|
||||
let last = damaged.len() - 20;
|
||||
damaged[last] ^= 1;
|
||||
std::fs::write(&path, damaged).unwrap();
|
||||
let e = documents::migrate(&pool, &dir, &store).await.unwrap_err();
|
||||
assert!(format!("{e:#}").contains("damaged"), "{e:#}");
|
||||
assert!(s3.object(&object(ids[0])).is_none());
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn the_mirror_follows_the_bucket_and_fills_a_new_one(pool: PgPool) {
|
||||
let s3 = FakeS3::start().await;
|
||||
let app = on_bucket(&pool, &s3);
|
||||
let id = person(&app, "Doe").await;
|
||||
upload(&app, id, &["one", "two", "three"]).await;
|
||||
let ids = ids(&pool).await;
|
||||
let store = app.st.files.as_ref().unwrap();
|
||||
let mirror = files_dir();
|
||||
|
||||
let m = files::mirror(store, &mirror).await.unwrap();
|
||||
assert_eq!(
|
||||
m,
|
||||
Mirrored {
|
||||
copied: 3,
|
||||
kept: 0,
|
||||
removed: 0
|
||||
}
|
||||
);
|
||||
for id in &ids {
|
||||
assert_eq!(
|
||||
std::fs::read(mirror.join(files::file_name(*id))).unwrap(),
|
||||
s3.object(&object(*id)).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
// a deletion reaches the mirror at its next run
|
||||
let r = app
|
||||
.post(&format!("/people/{id}/documents/{}/delete", ids[2]), &[])
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||
let m = files::mirror(store, &mirror).await.unwrap();
|
||||
assert_eq!(
|
||||
m,
|
||||
Mirrored {
|
||||
copied: 0,
|
||||
kept: 2,
|
||||
removed: 1
|
||||
}
|
||||
);
|
||||
|
||||
// the bucket is lost: a new one is filled from the mirror and checks
|
||||
// out against the database
|
||||
let fresh = FakeS3::start().await;
|
||||
let restored = Store::in_bucket(&fresh.config(), store.file_key().clone()).unwrap();
|
||||
let moved = documents::migrate(&pool, &mirror, &restored).await.unwrap();
|
||||
assert_eq!((moved.copied, moved.there), (2, 0));
|
||||
let check = documents::check(&pool, &restored).await.unwrap();
|
||||
assert_eq!(check.documents, 2);
|
||||
assert!(check.problems.is_empty(), "{:?}", check.problems);
|
||||
std::fs::remove_dir_all(&mirror).ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_busy_server_is_asked_again_and_a_wrong_key_is_an_error() {
|
||||
let s3 = FakeS3::start().await;
|
||||
let key = FileKey::random();
|
||||
let bucket = Bucket::new(&s3.config())
|
||||
.unwrap()
|
||||
.with_pause(Duration::from_millis(10));
|
||||
let store = Store::with_bucket(bucket, key.clone());
|
||||
|
||||
// two refusals, then an answer: the third attempt goes through
|
||||
s3.fail_next(2);
|
||||
store.put(5, pdf("five")).await.unwrap();
|
||||
assert_eq!(store.get(5).await.unwrap(), pdf("five"));
|
||||
// three refusals are an error that says what happened
|
||||
s3.fail_next(3);
|
||||
let e = store.get(5).await.unwrap_err();
|
||||
assert!(format!("{e:#}").contains("HTTP 503 SlowDown"), "{e:#}");
|
||||
|
||||
// the same id again: refused, and the object stays
|
||||
let e = store.put(5, pdf("other")).await.unwrap_err();
|
||||
assert!(format!("{e:#}").contains("other bytes"), "{e:#}");
|
||||
assert_eq!(store.get(5).await.unwrap(), pdf("five"));
|
||||
|
||||
// a wrong secret is refused, never taken for a missing file
|
||||
let mut cfg = s3.config();
|
||||
cfg.secret_access_key = "wrong".into();
|
||||
let wrong = Store::in_bucket(&cfg, key.clone()).unwrap();
|
||||
let e = wrong.get(5).await.unwrap_err();
|
||||
assert!(format!("{e:#}").contains("SignatureDoesNotMatch"), "{e:#}");
|
||||
assert!(wrong.check().await.is_err());
|
||||
assert!(store.check().await.is_ok());
|
||||
|
||||
// a bucket that does not exist is not a missing file either
|
||||
let mut cfg = s3.config();
|
||||
cfg.bucket = "other-bucket".into();
|
||||
let other = Store::in_bucket(&cfg, key).unwrap();
|
||||
let e = other.get_sealed(5).await.unwrap_err();
|
||||
assert!(format!("{e:#}").contains("NoSuchBucket"), "{e:#}");
|
||||
|
||||
// no secret in any of these messages
|
||||
assert!(!format!("{e:#}").contains(crate::common::fake_s3::SECRET));
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
//! 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('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
}
|
||||
|
||||
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"),
|
||||
}
|
||||
}
|
||||
+21
-4
@@ -1,5 +1,7 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
pub mod fake_s3;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
@@ -11,12 +13,12 @@ use chrono::NaiveDate;
|
||||
use http_body_util::BodyExt;
|
||||
use sqlx::PgPool;
|
||||
use tower::ServiceExt;
|
||||
use visa::config::{Auth, Config, FilesConfig, OidcConfig};
|
||||
use visa::config::{Auth, Config, FilesConfig, FilesPlace, OidcConfig};
|
||||
use visa::files::FileKey;
|
||||
use visa::web::{self, AppState};
|
||||
|
||||
/// A files directory of its own for each app, under the target directory.
|
||||
fn files_dir() -> PathBuf {
|
||||
pub fn files_dir() -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!(
|
||||
"files-{}-{}",
|
||||
@@ -34,12 +36,23 @@ pub fn config(auth: Auth) -> Config {
|
||||
database_password: None,
|
||||
auth,
|
||||
files: Some(FilesConfig {
|
||||
dir: files_dir(),
|
||||
place: FilesPlace::Dir(files_dir()),
|
||||
key: FileKey::random(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Documents on, in the test server's bucket, with a fresh key.
|
||||
pub fn bucket_config(auth: Auth, s3: &fake_s3::FakeS3) -> Config {
|
||||
Config {
|
||||
files: Some(FilesConfig {
|
||||
place: FilesPlace::Bucket(s3.config()),
|
||||
key: FileKey::random(),
|
||||
}),
|
||||
..config(auth)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn oidc_config(issuer: &str) -> OidcConfig {
|
||||
OidcConfig {
|
||||
issuer: issuer.into(),
|
||||
@@ -58,7 +71,11 @@ pub struct App {
|
||||
// The test's files go with it.
|
||||
impl Drop for App {
|
||||
fn drop(&mut self) {
|
||||
if let Some(dir) = self.st.cfg.files.as_ref().map(|f| f.dir.clone()) {
|
||||
if let Some(FilesConfig {
|
||||
place: FilesPlace::Dir(dir),
|
||||
..
|
||||
}) = &self.st.cfg.files
|
||||
{
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
}
|
||||
|
||||
+14
-10
@@ -10,7 +10,7 @@ use visa::web::documents::FILE_LIMIT;
|
||||
|
||||
use crate::common::{App, Part, config, id_from, local, pdf, with_config};
|
||||
|
||||
async fn person(app: &App, surname: &str) -> i64 {
|
||||
pub async fn person(app: &App, surname: &str) -> i64 {
|
||||
let r = app
|
||||
.post(
|
||||
"/people",
|
||||
@@ -70,10 +70,10 @@ type Refusal<'a> = (Vec<(&'a str, &'a str)>, Vec<(&'a str, &'a [u8])>, &'a str);
|
||||
/// A forged upload: its parts, its headers, the answer and what it says.
|
||||
type Forged<'a> = (Vec<Part<'a>>, &'a [(&'a str, &'a str)], StatusCode, &'a str);
|
||||
|
||||
fn stored(app: &App) -> usize {
|
||||
async fn stored(app: &App) -> usize {
|
||||
let store = app.st.files.as_ref().unwrap();
|
||||
let (ids, other) = store.entries().unwrap();
|
||||
ids.len() + other.len()
|
||||
let e = store.entries().await.unwrap();
|
||||
e.files.len() + e.other.len()
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
@@ -105,7 +105,7 @@ async fn a_scan_is_stored_encrypted_and_every_step_is_audited(pool: PgPool) {
|
||||
|
||||
// on the disk only encrypted, under the document's id
|
||||
let store = app.st.files.as_ref().unwrap();
|
||||
let on_disk = std::fs::read(store.path(did)).unwrap();
|
||||
let on_disk = std::fs::read(store.dir().unwrap().join(format!("{did}.vdoc"))).unwrap();
|
||||
assert!(on_disk.starts_with(b"VISADOC1"));
|
||||
assert!(!on_disk.windows(10).any(|w| w == b"photo page"));
|
||||
|
||||
@@ -167,7 +167,7 @@ async fn a_scan_is_stored_encrypted_and_every_step_is_audited(pool: PgPool) {
|
||||
.post(&format!("/people/{id}/documents/{did}/delete"), &[])
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||
assert!(!store.path(did).exists());
|
||||
assert!(store.get_sealed(did).await.unwrap().is_none());
|
||||
assert_eq!(count(&pool).await, 0);
|
||||
assert_eq!(app.get(&file).await.status, StatusCode::NOT_FOUND);
|
||||
|
||||
@@ -262,7 +262,7 @@ async fn uploads_are_checked_before_anything_is_stored(pool: PgPool) {
|
||||
assert!(t.contains("Nothing was uploaded"), "{want}");
|
||||
}
|
||||
assert_eq!(count(&pool).await, 0);
|
||||
assert_eq!(stored(&app), 0);
|
||||
assert_eq!(stored(&app).await, 0);
|
||||
|
||||
// the same file again for the same person
|
||||
let r = app
|
||||
@@ -363,7 +363,7 @@ async fn an_upload_needs_the_form_token_first_and_this_site(pool: PgPool) {
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(count(&pool).await, 0);
|
||||
assert_eq!(stored(&app), 0);
|
||||
assert_eq!(stored(&app).await, 0);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
@@ -527,7 +527,11 @@ async fn a_file_cannot_pass_for_another_and_the_check_finds_it(pool: PgPool) {
|
||||
);
|
||||
|
||||
// the two files swapped on the disk
|
||||
let (pa, pb) = (store.path(ids[0]), store.path(ids[1]));
|
||||
let dir = store.dir().unwrap();
|
||||
let (pa, pb) = (
|
||||
dir.join(format!("{}.vdoc", ids[0])),
|
||||
dir.join(format!("{}.vdoc", ids[1])),
|
||||
);
|
||||
let tmp = pa.with_extension("swap");
|
||||
std::fs::rename(&pa, &tmp).unwrap();
|
||||
std::fs::rename(&pb, &pa).unwrap();
|
||||
@@ -536,7 +540,7 @@ async fn a_file_cannot_pass_for_another_and_the_check_finds_it(pool: PgPool) {
|
||||
assert_eq!(r.status, StatusCode::INTERNAL_SERVER_ERROR);
|
||||
assert!(r.text().contains("cannot be opened"), "{}", r.body);
|
||||
assert!(!r.bytes.windows(6).any(|w| w == b"second"));
|
||||
std::fs::write(store.dir().join("77.vdoc"), b"left over").unwrap();
|
||||
std::fs::write(dir.join("77.vdoc"), b"left over").unwrap();
|
||||
let check = documents::check(&pool, store).await.unwrap();
|
||||
assert_eq!(check.documents, 2);
|
||||
assert_eq!(check.problems.len(), 3, "{:?}", check.problems);
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! The store against a real Garage, the version cnx01 runs:
|
||||
//! `bash scripts/dev-garage.sh` starts one in Docker and writes
|
||||
//! `.dev/garage.env`; `. .dev/garage.env` before `cargo test` runs this.
|
||||
//! Without VISA_TEST_S3_* set it is skipped (CI has no Garage; the test
|
||||
//! server in tests/common/fake_s3.rs covers the same calls there).
|
||||
|
||||
use visa::files::{FileKey, Store};
|
||||
use visa::s3::{Bucket, Put, S3Config};
|
||||
|
||||
use crate::common::pdf;
|
||||
|
||||
fn garage() -> Option<S3Config> {
|
||||
let v = |n: &str| std::env::var(n).ok().filter(|s| !s.is_empty());
|
||||
let secret = std::fs::read_to_string(v("VISA_TEST_S3_SECRET_FILE")?).ok()?;
|
||||
Some(S3Config {
|
||||
endpoint: v("VISA_TEST_S3_ENDPOINT")?,
|
||||
bucket: v("VISA_TEST_S3_BUCKET")?,
|
||||
region: v("VISA_TEST_S3_REGION").unwrap_or_else(|| "garage".into()),
|
||||
access_key_id: v("VISA_TEST_S3_ACCESS_KEY_ID")?,
|
||||
secret_access_key: secret.trim().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Ids no other run uses at the same time: the bucket is shared.
|
||||
fn fresh_ids(n: i64) -> Vec<i64> {
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.subsec_nanos() as i64;
|
||||
let base = 1_000_000_000 + (std::process::id() as i64 % 1000) * 1_000_000 + nanos % 1_000_000;
|
||||
(0..n).map(|i| base + i * 7).collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_store_works_against_a_real_garage() {
|
||||
let Some(cfg) = garage() else {
|
||||
eprintln!("VISA_TEST_S3_* not set: skipped (scripts/dev-garage.sh)");
|
||||
return;
|
||||
};
|
||||
let key = FileKey::random();
|
||||
let store = Store::in_bucket(&cfg, key.clone()).unwrap();
|
||||
store.check().await.unwrap();
|
||||
let ids = fresh_ids(3);
|
||||
for id in &ids {
|
||||
store
|
||||
.put(*id, pdf(&format!("document {id}")))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
for id in &ids {
|
||||
assert_eq!(
|
||||
store.get(*id).await.unwrap(),
|
||||
pdf(&format!("document {id}"))
|
||||
);
|
||||
}
|
||||
// the listing names them with their sizes, page after page
|
||||
let entries = store.entries().await.unwrap();
|
||||
for id in &ids {
|
||||
let size = store.get_sealed(*id).await.unwrap().unwrap().len() as u64;
|
||||
assert!(entries.files.contains(&(*id, size)), "{id}: {entries:?}");
|
||||
}
|
||||
// never replaced: the same bytes count as stored, others are refused
|
||||
let sealed = store.get_sealed(ids[0]).await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
store.put_sealed(ids[0], sealed.clone()).await.unwrap(),
|
||||
Put::Same
|
||||
);
|
||||
let e = store.put(ids[0], pdf("other")).await.unwrap_err();
|
||||
assert!(format!("{e:#}").contains("other bytes"), "{e:#}");
|
||||
assert_eq!(store.get_sealed(ids[0]).await.unwrap().unwrap(), sealed);
|
||||
// Garage 2.5 ignores If-None-Match on a PUT and writes (seen on Nov 19,
|
||||
// 2026): on a scratch object of this run, never on a document's
|
||||
let bucket = Bucket::new(&cfg).unwrap();
|
||||
let scratch = format!("scratch/{}.probe", ids[0]);
|
||||
assert!(bucket.put_if_absent(&scratch, b"first").await.unwrap());
|
||||
let honored = !bucket.put_if_absent(&scratch, b"second").await.unwrap();
|
||||
let kept = bucket.get(&scratch).await.unwrap().unwrap();
|
||||
assert_eq!(
|
||||
(honored, kept.as_slice()),
|
||||
(false, b"second".as_slice()),
|
||||
"Garage now honors If-None-Match: update the comment on Bucket::put_if_absent"
|
||||
);
|
||||
bucket.delete(&scratch).await.unwrap();
|
||||
// a wrong secret is refused, not taken for a missing file
|
||||
let mut wrong = cfg.clone();
|
||||
wrong.secret_access_key = "wrong".into();
|
||||
let e = Store::in_bucket(&wrong, key)
|
||||
.unwrap()
|
||||
.get(ids[0])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(format!("{e:#}").contains("HTTP 403"), "{e:#}");
|
||||
for id in &ids {
|
||||
store.remove(*id).await.unwrap();
|
||||
store.remove(*id).await.unwrap();
|
||||
assert!(store.get_sealed(*id).await.unwrap().is_none());
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,12 @@
|
||||
//! databases); each `#[sqlx::test]` gets its own database.
|
||||
|
||||
mod auth;
|
||||
mod bucket;
|
||||
mod common;
|
||||
mod companies;
|
||||
mod deadlines;
|
||||
mod documents;
|
||||
mod garage;
|
||||
mod pages;
|
||||
mod papers;
|
||||
mod people;
|
||||
|
||||
Reference in new issue
Block a user