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

+440 -89
View File
@@ -1,25 +1,34 @@
//! The document store. Each uploaded file lies in the files directory as
//! `<id>.vdoc`, encrypted with AES-256-GCM under a key of its own: HKDF-SHA256
//! derives it from the app's file key and a random salt kept in the file's
//! header. The document's id is authenticated with the file, so a file
//! renamed to another id does not open. The file key is a systemd
//! credential and is never in the database or its dumps: without it the
//! files and their backups cannot be read.
//! The document store. Each uploaded file is encrypted with AES-256-GCM
//! before it is stored, under a key of its own: HKDF-SHA256 derives it from
//! the app's file key and a random salt kept in the file's header. The
//! document's id is authenticated with the file, so a file renamed to
//! another id does not open. The file key is a systemd credential and is
//! never in the database or its dumps: without it the files and their
//! backups cannot be read.
//!
//! The encrypted files lie in a bucket of an S3 store (on the server, the
//! fleet's Garage) as `documents/<id>.vdoc`, or in a directory as `<id>.vdoc`
//! (local development and the tests). Only encrypted bytes ever leave the
//! app, so the store holds no document in the clear.
//!
//! A file is `VISADOC1`, the key id (8 bytes), the salt (32 bytes), the
//! ciphertext and the tag (16 bytes). The key id names the key that sealed a
//! file, so a wrong key is reported as such and not as damage.
use std::collections::BTreeMap;
use std::fmt;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, ensure};
use anyhow::{Context, Result, bail, ensure};
use ring::aead::{self, Aad, LessSafeKey, Nonce, UnboundKey};
use ring::rand::{SecureRandom, SystemRandom};
use ring::{digest, hkdf};
use crate::config::{FilesConfig, FilesPlace};
use crate::s3::{Bucket, Put, S3Config};
const MAGIC: &[u8; 8] = b"VISADOC1";
const KEY_ID: usize = 8;
const SALT: usize = 32;
@@ -211,103 +220,364 @@ pub fn is_image(content_type: &str) -> bool {
content_type.starts_with("image/")
}
/// The files directory with the key; cheap to clone into a blocking task.
/// The objects' key prefix in a bucket.
pub const PREFIX: &str = "documents/";
/// The name of document `id`'s file.
pub fn file_name(id: i64) -> String {
format!("{id}.vdoc")
}
/// The document whose file has this name (`7.vdoc`, not `07.vdoc`).
pub fn id_of(name: &str) -> Option<i64> {
let id: i64 = name.strip_suffix(".vdoc")?.parse().ok()?;
(id > 0 && file_name(id) == name).then_some(id)
}
/// Where the encrypted files lie.
#[derive(Clone, Debug)]
enum Place {
/// A directory of `<id>.vdoc` files: local development and the tests.
Dir(PathBuf),
/// A bucket of an S3 store, objects `documents/<id>.vdoc`: the server.
Bucket(Bucket),
}
/// The document store with its key; cheap to clone.
#[derive(Clone, Debug)]
pub struct Store {
dir: PathBuf,
place: Place,
key: FileKey,
}
impl Store {
/// The files directory, created (only its owner may enter) when missing.
pub fn open(dir: PathBuf, key: FileKey) -> Result<Store> {
fs::create_dir_all(&dir)
.with_context(|| format!("creating the files directory {}", dir.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&dir, fs::Permissions::from_mode(0o700))
.with_context(|| format!("closing the files directory {}", dir.display()))?;
/// What a store holds: the documents' files with their sizes in bytes, and
/// the names of anything else (a part file left by a crash, say).
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Entries {
pub files: Vec<(i64, u64)>,
pub other: Vec<String>,
}
/// File work off the async threads.
async fn blocking<T: Send + 'static>(f: impl FnOnce() -> Result<T> + Send + 'static) -> Result<T> {
tokio::task::spawn_blocking(f)
.await
.context("a file task stopped")?
}
/// A directory only its owner may enter, created when missing.
fn private_dir(dir: &Path) -> Result<()> {
fs::create_dir_all(dir).with_context(|| format!("creating the directory {}", dir.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(dir, fs::Permissions::from_mode(0o700))
.with_context(|| format!("closing the directory {}", dir.display()))?;
}
Ok(())
}
/// Writes `bytes` as `dir/name`: to a part file first, on disk before it
/// takes its name (replacing a file of that name).
fn write_file(dir: &Path, name: &str, bytes: &[u8]) -> Result<()> {
let path = dir.join(name);
let part = dir.join(format!(".{name}.part"));
let write = || -> io::Result<()> {
let mut f = File::create(&part)?;
f.write_all(bytes)?;
f.sync_all()?;
fs::rename(&part, &path)?;
sync_dir(dir)
};
write()
.inspect_err(|_| {
fs::remove_file(&part).ok();
})
.with_context(|| format!("writing {}", path.display()))
}
/// The `<id>.vdoc` files of a directory with their sizes, and the names of
/// everything else in it.
fn list_dir(dir: &Path) -> Result<Entries> {
let mut out = Entries::default();
for entry in fs::read_dir(dir).with_context(|| format!("listing {}", dir.display()))? {
let entry = entry?;
let name = entry.file_name().to_string_lossy().into_owned();
match id_of(&name) {
Some(id) if entry.file_type()?.is_file() => {
out.files.push((id, entry.metadata()?.len()))
}
_ => out.other.push(name),
}
Ok(Store { dir, key })
}
out.files.sort_unstable();
out.other.sort();
Ok(out)
}
/// Whether two paths name the same directory.
pub fn same_dir(a: &Path, b: &Path) -> bool {
match (fs::canonicalize(a), fs::canonicalize(b)) {
(Ok(a), Ok(b)) => a == b,
_ => a == b,
}
}
impl Store {
/// A files directory, created (only its owner may enter) when missing.
pub fn in_dir(dir: PathBuf, key: FileKey) -> Result<Store> {
private_dir(&dir)?;
Ok(Store {
place: Place::Dir(dir),
key,
})
}
pub fn dir(&self) -> &Path {
&self.dir
/// A bucket; nothing is asked of the server until the first file.
pub fn in_bucket(cfg: &S3Config, key: FileKey) -> Result<Store> {
Ok(Store::with_bucket(Bucket::new(cfg)?, key))
}
pub fn with_bucket(bucket: Bucket, key: FileKey) -> Store {
Store {
place: Place::Bucket(bucket),
key,
}
}
pub fn open(cfg: &FilesConfig) -> Result<Store> {
match &cfg.place {
FilesPlace::Dir(dir) => Store::in_dir(dir.clone(), cfg.key.clone()),
FilesPlace::Bucket(b) => Store::in_bucket(b, cfg.key.clone()),
}
}
/// Where the files are, for the log and the admin commands.
pub fn describe(&self) -> String {
match &self.place {
Place::Dir(dir) => format!("the directory {}", dir.display()),
Place::Bucket(b) => format!("bucket {} at {}", b.name(), b.endpoint()),
}
}
/// The files directory, when the files lie in one.
pub fn dir(&self) -> Option<&Path> {
match &self.place {
Place::Dir(dir) => Some(dir),
Place::Bucket(_) => None,
}
}
pub fn key_id(&self) -> String {
self.key.id_hex()
}
pub fn path(&self, id: i64) -> PathBuf {
self.dir.join(format!("{id}.vdoc"))
pub fn file_key(&self) -> &FileKey {
&self.key
}
/// Encrypts and writes the file of document `id`: to a part file first,
/// on disk before it takes its name. An existing file is never replaced.
pub fn put(&self, id: i64, plain: &[u8]) -> Result<()> {
let path = self.path(id);
ensure!(
!path.exists(),
"{} is there already without its document (after a restore?); `visa files-check` \
lists such files",
path.display()
);
let sealed = seal(&self.key, id, plain);
let part = self.dir.join(format!(".{id}.vdoc.part"));
let write = || -> io::Result<()> {
let mut f = File::create(&part)?;
f.write_all(&sealed)?;
f.sync_all()?;
fs::rename(&part, &path)?;
sync_dir(&self.dir)
};
write()
.inspect_err(|_| {
fs::remove_file(&part).ok();
})
.with_context(|| format!("writing {}", path.display()))
fn object(id: i64) -> String {
format!("{PREFIX}{}", file_name(id))
}
/// Where document `id`'s file is, for messages.
pub fn location(&self, id: i64) -> String {
match &self.place {
Place::Dir(dir) => dir.join(file_name(id)).display().to_string(),
Place::Bucket(b) => format!("{} in bucket {}", Store::object(id), b.name()),
}
}
/// Encrypts and stores the file of document `id`. An existing file is
/// never replaced.
pub async fn put(&self, id: i64, plain: Vec<u8>) -> Result<()> {
let key = self.key.clone();
let sealed = blocking(move || Ok(seal(&key, id, &plain))).await?;
self.put_sealed(id, sealed).await.map(|_| ())
}
/// Stores an encrypted file as it is (a copy from another place). An
/// existing file is never replaced: one with the same bytes counts as
/// stored ([`Put::Same`]), one with other bytes is an error.
pub async fn put_sealed(&self, id: i64, sealed: Vec<u8>) -> Result<Put> {
match &self.place {
Place::Dir(dir) => {
let dir = dir.clone();
blocking(move || {
let path = dir.join(file_name(id));
if path.exists() {
let there = fs::read(&path)
.with_context(|| format!("reading {}", path.display()))?;
if there == sealed {
return Ok(Put::Same);
}
bail!(
"{} is there already without its document (after a restore?); \
`visa files-check` lists such files",
path.display()
);
}
write_file(&dir, &file_name(id), &sealed)?;
Ok(Put::Written)
})
.await
}
Place::Bucket(b) => b.put_new(&Store::object(id), &sealed).await,
}
}
/// The encrypted file of document `id` as it is stored, or None.
pub async fn get_sealed(&self, id: i64) -> Result<Option<Vec<u8>>> {
match &self.place {
Place::Dir(dir) => {
let path = dir.join(file_name(id));
blocking(move || match fs::read(&path) {
Ok(b) => Ok(Some(b)),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
})
.await
}
Place::Bucket(b) => b.get(&Store::object(id)).await,
}
}
/// The decrypted file of document `id`.
pub fn get(&self, id: i64) -> Result<Vec<u8>> {
let path = self.path(id);
let sealed = fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
open(&self.key, id, &sealed).with_context(|| format!("opening {}", path.display()))
pub async fn get(&self, id: i64) -> Result<Vec<u8>> {
let at = self.location(id);
let sealed = self
.get_sealed(id)
.await?
.with_context(|| format!("{at} is missing"))?;
let key = self.key.clone();
blocking(move || open(&key, id, &sealed).with_context(|| format!("opening {at}"))).await
}
/// Removes the file of document `id`; a file that is gone already is fine.
pub fn remove(&self, id: i64) -> Result<()> {
let path = self.path(id);
match fs::remove_file(&path) {
Ok(()) => sync_dir(&self.dir).with_context(|| format!("removing {}", path.display())),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e).with_context(|| format!("removing {}", path.display())),
pub async fn remove(&self, id: i64) -> Result<()> {
match &self.place {
Place::Dir(dir) => {
let dir = dir.clone();
blocking(move || {
let path = dir.join(file_name(id));
match fs::remove_file(&path) {
Ok(()) => {
sync_dir(&dir).with_context(|| format!("removing {}", path.display()))
}
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e).with_context(|| format!("removing {}", path.display())),
}
})
.await
}
Place::Bucket(b) => b.delete(&Store::object(id)).await,
}
}
/// What lies in the directory: the documents' ids, and the names of
/// anything else (a part file left by a crash, say).
pub fn entries(&self) -> Result<(Vec<i64>, Vec<String>)> {
let mut ids = Vec::new();
let mut other = Vec::new();
for entry in
fs::read_dir(&self.dir).with_context(|| format!("listing {}", self.dir.display()))?
{
let name = entry?.file_name().to_string_lossy().into_owned();
match name
.strip_suffix(".vdoc")
.and_then(|n| n.parse::<i64>().ok())
{
Some(id) if id > 0 => ids.push(id),
_ => other.push(name),
/// What the store holds. In a bucket, every object outside
/// `documents/<id>.vdoc` counts as something else.
pub async fn entries(&self) -> Result<Entries> {
match &self.place {
Place::Dir(dir) => {
let dir = dir.clone();
blocking(move || list_dir(&dir)).await
}
Place::Bucket(b) => {
let mut out = Entries::default();
for o in b.list("").await? {
match o.key.strip_prefix(PREFIX).and_then(id_of) {
Some(id) => out.files.push((id, o.size)),
None => out.other.push(o.key),
}
}
out.files.sort_unstable();
Ok(out)
}
}
ids.sort_unstable();
other.sort();
Ok((ids, other))
}
/// The store answers: the directory is there, or the bucket answers to
/// the key.
pub async fn check(&self) -> Result<()> {
match &self.place {
Place::Dir(dir) => {
ensure!(dir.is_dir(), "{} is not a directory", dir.display());
Ok(())
}
Place::Bucket(b) => b.check().await,
}
}
}
/// What [`mirror`] did.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Mirrored {
pub copied: usize,
pub kept: usize,
pub removed: usize,
}
/// Makes `dir` hold exactly the store's files, still encrypted, for the
/// backups: a file the store has and `dir` lacks, or holds at another size,
/// is copied (to a part file, synced, then renamed), and a file the store no
/// longer has is removed. The store's files never change once written, so
/// the size tells a copy apart. `dir` then reads like a files directory, and
/// a restore is `visa files-migrate --from <dir>`.
pub async fn mirror(from: &Store, dir: &Path) -> Result<Mirrored> {
if let Some(d) = from.dir() {
ensure!(
!same_dir(d, dir),
"the mirror cannot be the store's own directory {}",
d.display()
);
}
let target = dir.to_path_buf();
let have = blocking(move || {
private_dir(&target)?;
list_dir(&target)
})
.await?;
let want = from.entries().await?.files;
let have_sizes: BTreeMap<i64, u64> = have.files.iter().copied().collect();
let mut out = Mirrored::default();
for (id, size) in &want {
if have_sizes.get(id) == Some(size) {
out.kept += 1;
continue;
}
let sealed = from
.get_sealed(*id)
.await?
.with_context(|| format!("{} went missing while it was copied", from.location(*id)))?;
let target = dir.to_path_buf();
let id = *id;
blocking(move || write_file(&target, &file_name(id), &sealed)).await?;
out.copied += 1;
}
let keep: BTreeMap<i64, u64> = want.into_iter().collect();
let stale: Vec<String> = have
.files
.iter()
.filter(|(id, _)| !keep.contains_key(id))
.map(|(id, _)| file_name(*id))
.collect();
out.removed = stale.len();
// and part files a stopped copy left behind
let parts = have
.other
.into_iter()
.filter(|n| n.starts_with('.') && n.ends_with(".vdoc.part"));
let gone: Vec<String> = stale.into_iter().chain(parts).collect();
let target = dir.to_path_buf();
blocking(move || {
for name in &gone {
let path = target.join(name);
fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
}
sync_dir(&target).with_context(|| format!("syncing {}", target.display()))
})
.await?;
Ok(out)
}
/// A rename is on disk only once its directory is.
@@ -387,24 +657,105 @@ mod tests {
}
#[test]
fn the_store_writes_reads_and_removes() {
let dir = std::env::temp_dir().join(format!("visa-store-{}", std::process::id()));
fn only_a_documents_own_name_is_its_file() {
assert_eq!(id_of("7.vdoc"), Some(7));
assert_eq!(id_of("1234.vdoc"), Some(1234));
for bad in [
"07.vdoc",
"0.vdoc",
"-3.vdoc",
"7.vdoc.part",
".7.vdoc.part",
"x.vdoc",
"7",
] {
assert_eq!(id_of(bad), None, "{bad}");
}
}
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("visa-{name}-{}", std::process::id()));
fs::remove_dir_all(&dir).ok();
let store = Store::open(dir.clone(), FileKey::random()).unwrap();
store.put(3, b"%PDF-1.4 three").unwrap();
assert_eq!(store.get(3).unwrap(), b"%PDF-1.4 three");
let on_disk = fs::read(store.path(3)).unwrap();
dir
}
#[tokio::test]
async fn the_store_writes_reads_and_removes() {
let dir = temp_dir("store");
let store = Store::in_dir(dir.clone(), FileKey::random()).unwrap();
store.put(3, b"%PDF-1.4 three".to_vec()).await.unwrap();
assert_eq!(store.get(3).await.unwrap(), b"%PDF-1.4 three");
let on_disk = fs::read(dir.join("3.vdoc")).unwrap();
assert!(!on_disk.windows(5).any(|w| w == b"three"));
let e = store.put(3, b"%PDF-1.4 again").unwrap_err();
let e = store.put(3, b"%PDF-1.4 again".to_vec()).await.unwrap_err();
assert!(e.to_string().contains("there already"), "{e}");
// the same bytes again: a copy that ran before
assert_eq!(
store.put_sealed(3, on_disk.clone()).await.unwrap(),
Put::Same
);
fs::write(dir.join(".9.vdoc.part"), b"left over").unwrap();
assert_eq!(
store.entries().unwrap(),
(vec![3], vec![".9.vdoc.part".to_string()])
store.entries().await.unwrap(),
Entries {
files: vec![(3, on_disk.len() as u64)],
other: vec![".9.vdoc.part".to_string()]
}
);
store.remove(3).unwrap();
store.remove(3).unwrap();
assert!(store.get(3).is_err());
store.remove(3).await.unwrap();
store.remove(3).await.unwrap();
assert!(store.get(3).await.is_err());
assert!(store.get_sealed(3).await.unwrap().is_none());
fs::remove_dir_all(&dir).ok();
}
#[tokio::test]
async fn the_mirror_follows_the_store() {
let (src, dst) = (temp_dir("mirror-src"), temp_dir("mirror-dst"));
let store = Store::in_dir(src.clone(), FileKey::random()).unwrap();
for id in [1, 2, 3] {
store
.put(id, format!("%PDF-1.4 file {id}").into_bytes())
.await
.unwrap();
}
assert_eq!(
mirror(&store, &dst).await.unwrap(),
Mirrored {
copied: 3,
kept: 0,
removed: 0
}
);
for id in [1, 2, 3] {
assert_eq!(
fs::read(dst.join(file_name(id))).unwrap(),
store.get_sealed(id).await.unwrap().unwrap()
);
}
store.remove(2).await.unwrap();
store.put(4, b"%PDF-1.4 file 4".to_vec()).await.unwrap();
fs::write(dst.join("1.vdoc"), b"cut short").unwrap();
fs::write(dst.join(".5.vdoc.part"), b"left over").unwrap();
assert_eq!(
mirror(&store, &dst).await.unwrap(),
Mirrored {
copied: 2,
kept: 1,
removed: 1
}
);
let mut names: Vec<String> = fs::read_dir(&dst)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
names.sort();
assert_eq!(names, ["1.vdoc", "3.vdoc", "4.vdoc"]);
assert!(
mirror(&store, &src).await.is_err(),
"not into the store itself"
);
fs::remove_dir_all(&src).ok();
fs::remove_dir_all(&dst).ok();
}
}