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.
762 lines
26 KiB
Rust
762 lines
26 KiB
Rust
//! 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, 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;
|
|
const HEADER: usize = MAGIC.len() + KEY_ID + SALT;
|
|
const TAG: usize = 16;
|
|
const INFO: &[u8] = b"visa document v1";
|
|
/// Each file's key is used once, so the nonce can be fixed.
|
|
const NONCE: [u8; 12] = [0; 12];
|
|
|
|
/// The app's file key: 32 random bytes, written as 64 hex digits in its file
|
|
/// (`openssl rand -hex 32`).
|
|
#[derive(Clone)]
|
|
pub struct FileKey([u8; 32]);
|
|
|
|
// The key stays out of logs and panics; its id is enough to tell keys apart.
|
|
impl fmt::Debug for FileKey {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
write!(f, "FileKey(id {})", self.id_hex())
|
|
}
|
|
}
|
|
|
|
impl FileKey {
|
|
pub fn from_hex(text: &str) -> Result<FileKey> {
|
|
let t = text.trim();
|
|
ensure!(
|
|
t.len() == 64 && t.bytes().all(|b| b.is_ascii_hexdigit()),
|
|
"the file key must be 64 hex digits (32 bytes), as `openssl rand -hex 32` writes it"
|
|
);
|
|
let mut key = [0u8; 32];
|
|
for (i, pair) in t.as_bytes().chunks(2).enumerate() {
|
|
key[i] = u8::from_str_radix(std::str::from_utf8(pair)?, 16)?;
|
|
}
|
|
Ok(FileKey(key))
|
|
}
|
|
|
|
/// A fresh key, for the tests.
|
|
pub fn random() -> FileKey {
|
|
let mut key = [0u8; 32];
|
|
SystemRandom::new()
|
|
.fill(&mut key)
|
|
.expect("the system's random source");
|
|
FileKey(key)
|
|
}
|
|
|
|
/// Names the key without giving it away: the start of a hash of it.
|
|
pub fn id(&self) -> [u8; KEY_ID] {
|
|
let mut ctx = digest::Context::new(&digest::SHA256);
|
|
ctx.update(b"visa file key id:");
|
|
ctx.update(&self.0);
|
|
let d = ctx.finish();
|
|
let mut id = [0u8; KEY_ID];
|
|
id.copy_from_slice(&d.as_ref()[..KEY_ID]);
|
|
id
|
|
}
|
|
|
|
pub fn id_hex(&self) -> String {
|
|
hex(&self.id())
|
|
}
|
|
|
|
fn cipher(&self, salt: &[u8]) -> LessSafeKey {
|
|
let prk = hkdf::Salt::new(hkdf::HKDF_SHA256, salt).extract(&self.0);
|
|
let okm = prk
|
|
.expand(&[INFO], &aead::AES_256_GCM)
|
|
.expect("32 bytes are a valid HKDF output length");
|
|
LessSafeKey::new(UnboundKey::from(okm))
|
|
}
|
|
}
|
|
|
|
pub fn hex(bytes: &[u8]) -> String {
|
|
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
|
}
|
|
|
|
pub fn sha256_hex(bytes: &[u8]) -> String {
|
|
hex(digest::digest(&digest::SHA256, bytes).as_ref())
|
|
}
|
|
|
|
fn aad(id: i64) -> String {
|
|
format!("visa document {id}")
|
|
}
|
|
|
|
/// Encrypts the file of document `id`.
|
|
pub fn seal(key: &FileKey, id: i64, plain: &[u8]) -> Vec<u8> {
|
|
let mut salt = [0u8; SALT];
|
|
SystemRandom::new()
|
|
.fill(&mut salt)
|
|
.expect("the system's random source");
|
|
let mut out = Vec::with_capacity(HEADER + plain.len() + TAG);
|
|
out.extend_from_slice(MAGIC);
|
|
out.extend_from_slice(&key.id());
|
|
out.extend_from_slice(&salt);
|
|
out.extend_from_slice(plain);
|
|
let tag = key
|
|
.cipher(&salt)
|
|
.seal_in_place_separate_tag(
|
|
Nonce::assume_unique_for_key(NONCE),
|
|
Aad::from(aad(id).as_bytes()),
|
|
&mut out[HEADER..],
|
|
)
|
|
.expect("AES-GCM seals any size the app accepts");
|
|
out.extend_from_slice(tag.as_ref());
|
|
out
|
|
}
|
|
|
|
#[derive(Debug, PartialEq, Eq)]
|
|
pub enum OpenError {
|
|
/// Not a file of this store.
|
|
NotADocument,
|
|
/// Sealed with another file key.
|
|
OtherKey,
|
|
/// Changed, cut short, or the file of another document.
|
|
Damaged,
|
|
}
|
|
|
|
impl fmt::Display for OpenError {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.write_str(match self {
|
|
OpenError::NotADocument => "not a document file",
|
|
OpenError::OtherKey => "encrypted with another file key",
|
|
OpenError::Damaged => "damaged, or the file of another document",
|
|
})
|
|
}
|
|
}
|
|
|
|
impl std::error::Error for OpenError {}
|
|
|
|
/// Decrypts the file of document `id`.
|
|
pub fn open(key: &FileKey, id: i64, sealed: &[u8]) -> Result<Vec<u8>, OpenError> {
|
|
if sealed.len() < HEADER + TAG || &sealed[..MAGIC.len()] != MAGIC {
|
|
return Err(OpenError::NotADocument);
|
|
}
|
|
if sealed[MAGIC.len()..MAGIC.len() + KEY_ID] != key.id() {
|
|
return Err(OpenError::OtherKey);
|
|
}
|
|
let salt = &sealed[MAGIC.len() + KEY_ID..HEADER];
|
|
let mut buf = sealed[HEADER..].to_vec();
|
|
let len = key
|
|
.cipher(salt)
|
|
.open_in_place(
|
|
Nonce::assume_unique_for_key(NONCE),
|
|
Aad::from(aad(id).as_bytes()),
|
|
&mut buf,
|
|
)
|
|
.map_err(|_| OpenError::Damaged)?
|
|
.len();
|
|
buf.truncate(len);
|
|
Ok(buf)
|
|
}
|
|
|
|
/// The types the app takes, told by the file's first bytes: the name and the
|
|
/// browser's word for the type are not trusted.
|
|
pub fn sniff(bytes: &[u8]) -> Option<&'static str> {
|
|
// PDF allows a little before its header
|
|
let head = &bytes[..bytes.len().min(1024)];
|
|
if head.windows(5).any(|w| w == b"%PDF-") {
|
|
Some("application/pdf")
|
|
} else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
|
|
Some("image/jpeg")
|
|
} else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
|
|
Some("image/png")
|
|
} else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
|
|
Some("image/webp")
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
|
|
/// What the page calls a type.
|
|
pub fn type_label(content_type: &str) -> &'static str {
|
|
match content_type {
|
|
"application/pdf" => "PDF",
|
|
"image/jpeg" => "JPEG",
|
|
"image/png" => "PNG",
|
|
"image/webp" => "WebP",
|
|
_ => "file",
|
|
}
|
|
}
|
|
|
|
pub fn extension(content_type: &str) -> &'static str {
|
|
match content_type {
|
|
"application/pdf" => "pdf",
|
|
"image/jpeg" => "jpg",
|
|
"image/png" => "png",
|
|
"image/webp" => "webp",
|
|
_ => "bin",
|
|
}
|
|
}
|
|
|
|
pub fn is_image(content_type: &str) -> bool {
|
|
content_type.starts_with("image/")
|
|
}
|
|
|
|
/// 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 {
|
|
place: Place,
|
|
key: FileKey,
|
|
}
|
|
|
|
/// 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),
|
|
}
|
|
}
|
|
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,
|
|
})
|
|
}
|
|
|
|
/// 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 file_key(&self) -> &FileKey {
|
|
&self.key
|
|
}
|
|
|
|
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 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 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 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)
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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.
|
|
fn sync_dir(dir: &Path) -> io::Result<()> {
|
|
#[cfg(unix)]
|
|
File::open(dir)?.sync_all()?;
|
|
#[cfg(not(unix))]
|
|
let _ = dir;
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn sealed_files_open_with_their_key_and_id_only() {
|
|
let key = FileKey::random();
|
|
let plain = b"%PDF-1.4 a scan of a passport page".to_vec();
|
|
let sealed = seal(&key, 7, &plain);
|
|
assert_eq!(sealed.len(), HEADER + plain.len() + TAG);
|
|
assert!(!sealed.windows(9).any(|w| w == b"a scan of"));
|
|
assert_eq!(open(&key, 7, &sealed).unwrap(), plain);
|
|
// the file of document 7 does not pass for document 8
|
|
assert_eq!(open(&key, 8, &sealed), Err(OpenError::Damaged));
|
|
assert_eq!(
|
|
open(&FileKey::random(), 7, &sealed),
|
|
Err(OpenError::OtherKey)
|
|
);
|
|
let mut changed = sealed.clone();
|
|
let last = changed.len() - 20;
|
|
changed[last] ^= 1;
|
|
assert_eq!(open(&key, 7, &changed), Err(OpenError::Damaged));
|
|
assert_eq!(
|
|
open(&key, 7, &sealed[..sealed.len() - 1]),
|
|
Err(OpenError::Damaged)
|
|
);
|
|
assert_eq!(open(&key, 7, b"%PDF-1.4"), Err(OpenError::NotADocument));
|
|
// two seals of the same file differ (a fresh salt each time)
|
|
assert_ne!(seal(&key, 7, &plain), sealed);
|
|
assert_eq!(open(&key, 7, &seal(&key, 7, b"")).unwrap(), b"");
|
|
}
|
|
|
|
#[test]
|
|
fn the_key_is_64_hex_digits_and_never_printed() {
|
|
let text = "00112233445566778899aabbccddeeff00112233445566778899AABBCCDDEEFF\n";
|
|
let key = FileKey::from_hex(text).unwrap();
|
|
assert_eq!(key.0[1], 0x11);
|
|
assert_eq!(key.0[31], 0xff);
|
|
let shown = format!("{key:?}");
|
|
assert!(!shown.contains("00112233"), "{shown}");
|
|
assert!(shown.contains(&key.id_hex()));
|
|
for bad in ["", "0011", &"zz".repeat(32), &"00".repeat(33)] {
|
|
assert!(FileKey::from_hex(bad).is_err(), "{bad:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn types_come_from_the_first_bytes() {
|
|
assert_eq!(sniff(b"%PDF-1.7\n"), Some("application/pdf"));
|
|
assert_eq!(sniff(b"\n\n%PDF-1.4"), Some("application/pdf"));
|
|
assert_eq!(
|
|
sniff(&[0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10]),
|
|
Some("image/jpeg")
|
|
);
|
|
assert_eq!(sniff(b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR"), Some("image/png"));
|
|
assert_eq!(sniff(b"RIFF\x24\0\0\0WEBPVP8 "), Some("image/webp"));
|
|
for bad in [
|
|
b"<html><script>".as_slice(),
|
|
b"<svg xmlns=".as_slice(),
|
|
b"GIF89a".as_slice(),
|
|
b"PK\x03\x04".as_slice(),
|
|
b"".as_slice(),
|
|
] {
|
|
assert_eq!(sniff(bad), None, "{bad:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
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();
|
|
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".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().await.unwrap(),
|
|
Entries {
|
|
files: vec![(3, on_disk.len() as u64)],
|
|
other: vec![".9.vdoc.part".to_string()]
|
|
}
|
|
);
|
|
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();
|
|
}
|
|
}
|