Documents in a bucket of Garage, still encrypted by the app
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 52s

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:
grabowski committed 2026-11-19 20:35:32 +07:00
1 parent 17426dba12
commit 0370e0154f
20 files changed
+2558 -218

No files matched your search

+145 -15
View File
@@ -12,11 +12,17 @@
//! | `VISA_OIDC_CLIENT_SECRET_FILE` | else credential `oidc-client-secret` |
//! | `VISA_OIDC_GROUP` | default `visa` |
//! | `VISA_INSECURE_NO_LOGIN` | `1`: no login, loopback addresses only |
//! | `VISA_FILES_DIR` | where the encrypted documents lie |
//! | `VISA_S3_BUCKET` | the bucket the encrypted documents lie in |
//! | `VISA_S3_ENDPOINT` | the S3 server, `http://127.0.0.1:3900` (Garage) |
//! | `VISA_S3_REGION` | default `garage` |
//! | `VISA_S3_ACCESS_KEY_ID` | the bucket key's id |
//! | `VISA_S3_SECRET_ACCESS_KEY_FILE` | its secret (else credential `s3-secret`) |
//! | `VISA_FILES_DIR` | a directory for them instead (development) |
//! | `VISA_FILES_KEY_FILE` | the file key (else credential `files-key`) |
//!
//! With the login on, documents are required: the files directory and the
//! file key. Local development may go without them; uploads are then off.
//! With the login on, documents are required: a place for them (the bucket,
//! or a directory) and the file key. Local development may go without them;
//! uploads are then off.
use std::net::SocketAddr;
use std::path::PathBuf;
@@ -24,6 +30,7 @@ use std::path::PathBuf;
use anyhow::{Context, Result, bail, ensure};
use crate::files::FileKey;
use crate::s3::S3Config;
#[derive(Clone, Debug)]
pub struct Config {
@@ -33,16 +40,33 @@ pub struct Config {
pub database_url: String,
pub database_password: Option<String>,
pub auth: Auth,
/// Documents: off in local development without a files directory.
/// Documents: off in local development without a place for them.
pub files: Option<FilesConfig>,
}
#[derive(Clone, Debug)]
pub struct FilesConfig {
pub dir: PathBuf,
pub place: FilesPlace,
pub key: FileKey,
}
/// Where the encrypted files lie.
#[derive(Clone, Debug)]
pub enum FilesPlace {
/// A bucket of an S3 store: the fleet's Garage.
Bucket(S3Config),
/// A directory: local development and the tests.
Dir(PathBuf),
}
/// The S3 settings that only mean something with `VISA_S3_BUCKET`.
const S3_VARS: [&str; 4] = [
"VISA_S3_ENDPOINT",
"VISA_S3_REGION",
"VISA_S3_ACCESS_KEY_ID",
"VISA_S3_SECRET_ACCESS_KEY_FILE",
];
#[derive(Clone, Debug)]
pub enum Auth {
Oidc(OidcConfig),
@@ -127,22 +151,39 @@ impl Config {
Some(path) => Some(read_file(&PathBuf::from(path), "the file key")?),
None => credential(var, "files-key")?,
};
let files = match (var("VISA_FILES_DIR"), key) {
(Some(dir), Some(key)) => Some(FilesConfig {
dir: PathBuf::from(dir),
let place = match (var("VISA_S3_BUCKET"), var("VISA_FILES_DIR")) {
(Some(_), Some(_)) => bail!(
"VISA_S3_BUCKET and VISA_FILES_DIR are both set: the documents lie in one place, \
the bucket or the directory"
),
(Some(bucket), None) => Some(FilesPlace::Bucket(s3_config(var, bucket)?)),
(None, dir) => {
if let Some(v) = S3_VARS.iter().find(|v| var(v).is_some()) {
bail!("{v} is set but VISA_S3_BUCKET is not");
}
dir.map(|d| FilesPlace::Dir(PathBuf::from(d)))
}
};
let files = match (place, key) {
(Some(place), Some(key)) => Some(FilesConfig {
place,
key: FileKey::from_hex(&key).context("reading the file key")?,
}),
(None, None) => None,
(Some(_), None) => bail!(
"VISA_FILES_DIR is set but there is no file key: set VISA_FILES_KEY_FILE or pass \
the credential files-key"
"the documents have a place but there is no file key: set VISA_FILES_KEY_FILE or \
pass the credential files-key"
),
(None, Some(_)) => bail!(
"there is a file key but no place for the documents: set VISA_S3_BUCKET with the \
S3 settings, or VISA_FILES_DIR"
),
(None, Some(_)) => bail!("there is a file key but no VISA_FILES_DIR"),
};
if matches!(auth, Auth::Oidc(_)) && files.is_none() {
bail!(
"documents are not set up: with the login on, set VISA_FILES_DIR and the file \
key (VISA_FILES_KEY_FILE or the credential files-key)"
"documents are not set up: with the login on, set VISA_S3_BUCKET with the S3 \
settings (or VISA_FILES_DIR) and the file key (VISA_FILES_KEY_FILE or the \
credential files-key)"
);
}
Ok(Config {
@@ -164,6 +205,30 @@ impl Config {
}
}
/// The bucket's settings; the secret from its file or the credential
/// `s3-secret`.
fn s3_config(var: &dyn Fn(&str) -> Option<String>, bucket: String) -> Result<S3Config> {
let need =
|name: &str| var(name).with_context(|| format!("VISA_S3_BUCKET is set but {name} is not"));
let secret_access_key = match var("VISA_S3_SECRET_ACCESS_KEY_FILE") {
Some(path) => read_file(&PathBuf::from(path), "the S3 secret key")?,
None => credential(var, "s3-secret")?.context(
"VISA_S3_BUCKET is set but there is no S3 secret key: set \
VISA_S3_SECRET_ACCESS_KEY_FILE or pass the credential s3-secret",
)?,
};
let cfg = S3Config {
endpoint: need("VISA_S3_ENDPOINT")?,
bucket,
region: var("VISA_S3_REGION").unwrap_or_else(|| "garage".into()),
access_key_id: need("VISA_S3_ACCESS_KEY_ID")?,
secret_access_key,
};
// the endpoint and the name are checked now, not at the first upload
crate::s3::Bucket::new(&cfg)?;
Ok(cfg)
}
/// A systemd credential (`LoadCredential=`), when the unit passes one.
fn credential(var: &dyn Fn(&str) -> Option<String>, name: &str) -> Result<Option<String>> {
let Some(dir) = var("CREDENTIALS_DIRECTORY") else {
@@ -276,7 +341,7 @@ mod tests {
.unwrap_err();
assert!(e.to_string().contains("documents are not set up"), "{e}");
let files = c.files.unwrap();
assert_eq!(files.dir, files_dir);
assert!(matches!(&files.place, FilesPlace::Dir(d) if *d == files_dir));
assert!(!format!("{files:?}").contains("abab"));
std::fs::remove_dir_all(&dir).ok();
}
@@ -315,7 +380,72 @@ mod tests {
.unwrap();
assert!(c.files.is_some());
let e = with(&[("CREDENTIALS_DIRECTORY", dir.to_str().unwrap())]).unwrap_err();
assert!(e.to_string().contains("no VISA_FILES_DIR"), "{e}");
assert!(e.to_string().contains("no place for the documents"), "{e}");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn documents_in_a_bucket_take_its_settings_and_the_secret_from_a_credential() {
let dir = std::env::temp_dir().join(format!("visa-cfg-s3-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("files-key"), "cd".repeat(32)).unwrap();
std::fs::write(dir.join("s3-secret"), "s3-secret-value\n").unwrap();
let creds = dir.to_str().unwrap();
let base = [
("VISA_DATABASE_URL", "postgres://x/y"),
("VISA_INSECURE_NO_LOGIN", "1"),
("CREDENTIALS_DIRECTORY", creds),
];
let with = |extra: &[(&str, &str)]| {
let mut all = base.to_vec();
all.extend_from_slice(extra);
cfg(&all)
};
let bucket = [
("VISA_S3_BUCKET", "visa-documents"),
("VISA_S3_ENDPOINT", "http://127.0.0.1:3900"),
("VISA_S3_ACCESS_KEY_ID", "GK00112233"),
];
let c = with(&bucket).unwrap();
let Some(FilesConfig {
place: FilesPlace::Bucket(b),
..
}) = &c.files
else {
panic!("a bucket expected: {:?}", c.files)
};
assert_eq!(b.bucket, "visa-documents");
assert_eq!(b.region, "garage");
assert_eq!(b.secret_access_key, "s3-secret-value");
assert!(!format!("{c:?}").contains("s3-secret-value"));
// every part is needed, and one place only
for missing in ["VISA_S3_ENDPOINT", "VISA_S3_ACCESS_KEY_ID"] {
let some: Vec<_> = bucket
.iter()
.copied()
.filter(|(k, _)| *k != missing)
.collect();
let e = with(&some).unwrap_err();
assert!(e.to_string().contains(missing), "{e}");
}
let mut both = bucket.to_vec();
both.push(("VISA_FILES_DIR", "/srv/files"));
let e = with(&both).unwrap_err();
assert!(e.to_string().contains("both set"), "{e}");
let e = with(&[("VISA_S3_ENDPOINT", "http://127.0.0.1:3900")]).unwrap_err();
assert!(e.to_string().contains("VISA_S3_BUCKET is not"), "{e}");
let mut bad = bucket.to_vec();
bad[1] = ("VISA_S3_ENDPOINT", "127.0.0.1:3900");
assert!(with(&bad).is_err());
// without the credential, the secret's file must be named
std::fs::remove_file(dir.join("s3-secret")).unwrap();
let e = with(&bucket).unwrap_err();
assert!(e.to_string().contains("no S3 secret key"), "{e}");
let f = dir.join("secret-file");
std::fs::write(&f, "from-a-file").unwrap();
let mut named = bucket.to_vec();
named.push(("VISA_S3_SECRET_ACCESS_KEY_FILE", f.to_str().unwrap()));
assert!(with(&named).is_ok());
std::fs::remove_dir_all(&dir).ok();
}
}