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
+145
-15
@@ -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();
|
||||
}
|
||||
}
|
||||
+121
-15
@@ -1,16 +1,19 @@
|
||||
//! Documents: scans and photos of a person's papers, and the company
|
||||
//! documents the extension packs need. A row holds what is known about a
|
||||
//! file; the file itself lies encrypted in the store (`files.rs`). A
|
||||
//! file; the file itself lies encrypted in the store (`files.rs`), on the
|
||||
//! server a bucket of the fleet's Garage. A
|
||||
//! person's document may belong to one of their records (a passport, an
|
||||
//! arrival, a 90-day report ...), and then shows next to that record too.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use chrono::{DateTime, NaiveDate, Utc};
|
||||
use sqlx::{PgPool, Postgres, Transaction};
|
||||
|
||||
use crate::files::{self, Store};
|
||||
use crate::s3::Put;
|
||||
|
||||
/// Whose document it is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -498,18 +501,14 @@ pub struct Check {
|
||||
/// size and checksum recorded at the upload; lists files that belong to no
|
||||
/// document.
|
||||
pub async fn check(db: &PgPool, store: &Store) -> Result<Check> {
|
||||
let rows: Vec<(i64, i32, String)> =
|
||||
sqlx::query_as("SELECT id, size_bytes, sha256 FROM documents ORDER BY id")
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let (ids, other) = store.entries()?;
|
||||
let rows = uploads(db).await?;
|
||||
let entries = store.entries().await?;
|
||||
let mut out = Check {
|
||||
documents: rows.len(),
|
||||
..Check::default()
|
||||
};
|
||||
let known: BTreeSet<i64> = rows.iter().map(|r| r.0).collect();
|
||||
for (id, size, sha) in &rows {
|
||||
match store.get(*id) {
|
||||
for (id, (size, sha)) in &rows {
|
||||
match store.get(*id).await {
|
||||
Ok(bytes) if bytes.len() == *size as usize && files::sha256_hex(&bytes) == *sha => {}
|
||||
Ok(_) => out.problems.push(format!(
|
||||
"document {id}: the file does not match the size and checksum of its upload"
|
||||
@@ -517,17 +516,124 @@ pub async fn check(db: &PgPool, store: &Store) -> Result<Check> {
|
||||
Err(e) => out.problems.push(format!("document {id}: {e:#}")),
|
||||
}
|
||||
}
|
||||
for id in ids.iter().filter(|id| !known.contains(id)) {
|
||||
out.problems
|
||||
.push(format!("{id}.vdoc: a file without its document"));
|
||||
for (id, _) in entries
|
||||
.files
|
||||
.iter()
|
||||
.filter(|(id, _)| !rows.contains_key(id))
|
||||
{
|
||||
out.problems.push(format!(
|
||||
"{}: a file without its document",
|
||||
files::file_name(*id)
|
||||
));
|
||||
}
|
||||
for name in other {
|
||||
for name in entries.other {
|
||||
out.problems
|
||||
.push(format!("{name}: not a file of the store"));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Every document's size and SHA-256 as recorded at its upload.
|
||||
async fn uploads(db: &PgPool) -> Result<BTreeMap<i64, (i32, String)>> {
|
||||
let rows: Vec<(i64, i32, String)> =
|
||||
sqlx::query_as("SELECT id, size_bytes, sha256 FROM documents ORDER BY id")
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(id, size, sha)| (id, (size, sha)))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// What `visa files-migrate` did.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Moved {
|
||||
/// Files copied into the store.
|
||||
pub copied: usize,
|
||||
/// Files the store had already, with the same bytes.
|
||||
pub there: usize,
|
||||
/// Files in the directory that belong to no document, left there.
|
||||
pub strays: Vec<String>,
|
||||
/// Documents whose file is neither in the directory nor in the store.
|
||||
pub missing: Vec<i64>,
|
||||
}
|
||||
|
||||
/// Copies the documents' files from a files directory (where they lay
|
||||
/// before the bucket, or a mirror the backups hold) into the store, as they
|
||||
/// are: still encrypted. Each file is opened with the key and compared with
|
||||
/// the size and checksum of its upload before it is copied, and read back
|
||||
/// from the store and compared again after. A file the store has already
|
||||
/// with the same bytes is counted and skipped, so the copy can run again; a
|
||||
/// file the store has with other bytes, or one that does not open, stops it
|
||||
/// with an error. Files of no document stay in the directory, listed.
|
||||
pub async fn migrate(db: &PgPool, from: &Path, to: &Store) -> Result<Moved> {
|
||||
if let Some(d) = to.dir() {
|
||||
ensure!(
|
||||
!files::same_dir(d, from),
|
||||
"{} is the store itself: files-migrate copies from another directory",
|
||||
from.display()
|
||||
);
|
||||
}
|
||||
ensure!(from.is_dir(), "{} is not a directory", from.display());
|
||||
let src = Store::in_dir(from.to_path_buf(), to.file_key().clone())?;
|
||||
let rows = uploads(db).await?;
|
||||
let present = src.entries().await?;
|
||||
let in_dir: BTreeSet<i64> = present.files.iter().map(|(id, _)| *id).collect();
|
||||
let mut out = Moved::default();
|
||||
for (id, (size, sha)) in &rows {
|
||||
let matches =
|
||||
|bytes: &[u8]| bytes.len() == *size as usize && files::sha256_hex(bytes) == *sha;
|
||||
if !in_dir.contains(id) {
|
||||
if to.get_sealed(*id).await?.is_some() {
|
||||
out.there += 1;
|
||||
} else {
|
||||
out.missing.push(*id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let plain = src
|
||||
.get(*id)
|
||||
.await
|
||||
.with_context(|| format!("document {id}: its file in the directory"))?;
|
||||
if !matches(&plain) {
|
||||
bail!(
|
||||
"document {id}: the file in {} does not match the size and checksum of its upload",
|
||||
from.display()
|
||||
);
|
||||
}
|
||||
let sealed = src
|
||||
.get_sealed(*id)
|
||||
.await?
|
||||
.with_context(|| format!("document {id}: its file went missing"))?;
|
||||
match to
|
||||
.put_sealed(*id, sealed)
|
||||
.await
|
||||
.with_context(|| format!("document {id}: copying its file"))?
|
||||
{
|
||||
Put::Written => out.copied += 1,
|
||||
Put::Same => out.there += 1,
|
||||
}
|
||||
let back = to
|
||||
.get(*id)
|
||||
.await
|
||||
.with_context(|| format!("document {id}: reading the copy back"))?;
|
||||
if !matches(&back) {
|
||||
bail!(
|
||||
"document {id}: the copy in {} does not match its upload",
|
||||
to.describe()
|
||||
);
|
||||
}
|
||||
}
|
||||
out.strays = present
|
||||
.files
|
||||
.iter()
|
||||
.filter(|(id, _)| !rows.contains_key(id))
|
||||
.map(|(id, _)| files::file_name(*id))
|
||||
.chain(present.other)
|
||||
.collect();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+440
-89
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ pub mod oidc;
|
||||
pub mod papers;
|
||||
pub mod people;
|
||||
pub mod records;
|
||||
pub mod s3;
|
||||
pub mod seed;
|
||||
pub mod session;
|
||||
pub mod web;
|
||||
|
||||
+91
-19
@@ -1,13 +1,14 @@
|
||||
//! `visa [serve|migrate|seed-demo|files-check|help]`: the server and its admin
|
||||
//! commands.
|
||||
//! `visa [serve|migrate|seed-demo|files-check|files-migrate|files-mirror|help]`:
|
||||
//! the server and its admin commands.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use tracing::info;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use visa::config::Config;
|
||||
use visa::files::Store;
|
||||
use visa::files::{self, Store};
|
||||
use visa::{dates, db, documents, seed, web};
|
||||
|
||||
const USAGE: &str = "\
|
||||
@@ -21,6 +22,13 @@ Commands:
|
||||
seed-demo add invented demo people and documents (local development only)
|
||||
files-check read every document's file back and compare it with its upload;
|
||||
list files without a document (exit status 1 on any problem)
|
||||
files-migrate --from DIR
|
||||
copy the documents' files from a files directory (the store
|
||||
before the bucket, or a backup's mirror) into the store, each
|
||||
checked against its upload; again is harmless
|
||||
files-mirror --to DIR
|
||||
make DIR hold exactly the store's files, still encrypted, for
|
||||
the backups
|
||||
help show this text
|
||||
|
||||
Settings come from the environment; see src/config.rs or README.md.";
|
||||
@@ -41,6 +49,24 @@ async fn main() -> ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// The directory after `flag` on the command line.
|
||||
fn dir_arg(flag: &str) -> Result<PathBuf> {
|
||||
let args: Vec<String> = std::env::args().skip(2).collect();
|
||||
match args.as_slice() {
|
||||
[f, dir] if f == flag && !dir.is_empty() => Ok(PathBuf::from(dir)),
|
||||
_ => bail!("give the directory as {flag} DIR; `visa help` lists the commands"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The store the settings name; an error when documents are off.
|
||||
fn store(cfg: &Config) -> Result<Store> {
|
||||
let f = cfg
|
||||
.files
|
||||
.as_ref()
|
||||
.context("documents are off here: no VISA_S3_BUCKET (or VISA_FILES_DIR) and file key")?;
|
||||
Store::open(f)
|
||||
}
|
||||
|
||||
async fn run(cmd: &str) -> Result<()> {
|
||||
match cmd {
|
||||
"serve" => serve().await,
|
||||
@@ -66,22 +92,18 @@ async fn run(cmd: &str) -> Result<()> {
|
||||
println!("demo people are there already");
|
||||
}
|
||||
match &cfg.files {
|
||||
Some(f) => {
|
||||
let store = Store::open(f.dir.clone(), f.key.clone())?;
|
||||
Some(_) => {
|
||||
let store = store(&cfg)?;
|
||||
let n = seed::demo_documents(&pool, &store, dates::today()).await?;
|
||||
println!("demo documents added: {n}");
|
||||
}
|
||||
None => println!("no demo documents: documents are off (no VISA_FILES_DIR)"),
|
||||
None => println!("no demo documents: documents are off (no place for them)"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
"files-check" => {
|
||||
let cfg = Config::from_env()?;
|
||||
let f = cfg
|
||||
.files
|
||||
.as_ref()
|
||||
.context("documents are off here: no VISA_FILES_DIR and file key")?;
|
||||
let store = Store::open(f.dir.clone(), f.key.clone())?;
|
||||
let store = store(&cfg)?;
|
||||
let pool = db::connect(&cfg).await?;
|
||||
let check = documents::check(&pool, &store).await?;
|
||||
for p in &check.problems {
|
||||
@@ -90,13 +112,55 @@ async fn run(cmd: &str) -> Result<()> {
|
||||
println!(
|
||||
"{} documents checked in {} (file key {}): {} problems",
|
||||
check.documents,
|
||||
store.dir().display(),
|
||||
store.describe(),
|
||||
store.key_id(),
|
||||
check.problems.len()
|
||||
);
|
||||
ensure!(check.problems.is_empty(), "the files need attention");
|
||||
Ok(())
|
||||
}
|
||||
"files-migrate" => {
|
||||
let from = dir_arg("--from")?;
|
||||
let cfg = Config::from_env()?;
|
||||
let store = store(&cfg)?;
|
||||
let pool = db::connect(&cfg).await?;
|
||||
let moved = documents::migrate(&pool, &from, &store).await?;
|
||||
for name in &moved.strays {
|
||||
println!(
|
||||
"left in {}: {name}, which is no document's file",
|
||||
from.display()
|
||||
);
|
||||
}
|
||||
for id in &moved.missing {
|
||||
println!(
|
||||
"problem: document {id} has no file in {} and none in the store",
|
||||
from.display()
|
||||
);
|
||||
}
|
||||
println!(
|
||||
"{} files copied into {}, {} there already (file key {})",
|
||||
moved.copied,
|
||||
store.describe(),
|
||||
moved.there,
|
||||
store.key_id()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
"files-mirror" => {
|
||||
let to = dir_arg("--to")?;
|
||||
let cfg = Config::from_env()?;
|
||||
let store = store(&cfg)?;
|
||||
let m = files::mirror(&store, &to).await?;
|
||||
println!(
|
||||
"{} mirrored into {}: {} copied, {} kept, {} removed",
|
||||
store.describe(),
|
||||
to.display(),
|
||||
m.copied,
|
||||
m.kept,
|
||||
m.removed
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
"help" | "--help" | "-h" => {
|
||||
println!("{USAGE}");
|
||||
Ok(())
|
||||
@@ -113,12 +177,20 @@ async fn serve() -> Result<()> {
|
||||
let login = cfg.login_enabled();
|
||||
let st = web::AppState::new(cfg, pool)?;
|
||||
match &st.files {
|
||||
Some(s) => info!(
|
||||
"documents in {} (file key {})",
|
||||
s.dir().display(),
|
||||
s.key_id()
|
||||
),
|
||||
None => info!("documents are off: no VISA_FILES_DIR (local development)"),
|
||||
Some(s) => {
|
||||
info!("documents in {} (file key {})", s.describe(), s.key_id());
|
||||
// A store that is not there yet (Garage starting) costs the
|
||||
// documents, not the records: the check only warns, and the
|
||||
// server listens meanwhile.
|
||||
let s = s.clone();
|
||||
tokio::spawn(async move {
|
||||
match s.check().await {
|
||||
Ok(()) => info!("documents: {} answers", s.describe()),
|
||||
Err(e) => warn!("documents: {} does not answer yet: {e:#}", s.describe()),
|
||||
}
|
||||
});
|
||||
}
|
||||
None => info!("documents are off: no place for them (local development)"),
|
||||
}
|
||||
web::spawn_background(st.clone());
|
||||
let app = web::router(st);
|
||||
|
||||
@@ -0,0 +1,712 @@
|
||||
//! A small S3 client for the document store: path-style requests (the
|
||||
//! bucket is the first part of the path) signed with AWS Signature Version 4,
|
||||
//! on reqwest and ring, as in proplan. It makes the five calls the store
|
||||
//! needs: PUT, GET, HEAD, DELETE and ListObjectsV2. Garage, the fleet's
|
||||
//! object store, answers them as AWS does.
|
||||
//!
|
||||
//! The objects are the store's encrypted files: this client never sees a
|
||||
//! document's contents in the clear, and its errors name the object and the
|
||||
//! answer, never the secret key.
|
||||
|
||||
use std::fmt;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use reqwest::{Method, StatusCode, Url};
|
||||
use ring::{digest, hmac};
|
||||
|
||||
/// Where the bucket is, and the key to it.
|
||||
#[derive(Clone)]
|
||||
pub struct S3Config {
|
||||
/// The server, without a path: `http://127.0.0.1:3900`.
|
||||
pub endpoint: String,
|
||||
pub bucket: String,
|
||||
/// Garage's is `garage`.
|
||||
pub region: String,
|
||||
pub access_key_id: String,
|
||||
pub secret_access_key: String,
|
||||
}
|
||||
|
||||
// The secret stays out of logs and panics.
|
||||
impl fmt::Debug for S3Config {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("S3Config")
|
||||
.field("endpoint", &self.endpoint)
|
||||
.field("bucket", &self.bucket)
|
||||
.field("region", &self.region)
|
||||
.field("access_key_id", &self.access_key_id)
|
||||
.field(
|
||||
"secret_access_key",
|
||||
&format_args!("<{} bytes>", self.secret_access_key.len()),
|
||||
)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// An object as a listing names it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Object {
|
||||
pub key: String,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
/// What [`Bucket::put_new`] did.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Put {
|
||||
Written,
|
||||
/// The object was there already with exactly these bytes (a retry, or a
|
||||
/// copy that ran before).
|
||||
Same,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Bucket {
|
||||
endpoint: String,
|
||||
bucket: String,
|
||||
region: String,
|
||||
key_id: String,
|
||||
secret: String,
|
||||
/// `host[:port]` as the request's Host header carries it.
|
||||
host: String,
|
||||
http: reqwest::Client,
|
||||
/// Between attempts at a request the server could not answer.
|
||||
pause: Duration,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Bucket {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Bucket({} at {})", self.bucket, self.endpoint)
|
||||
}
|
||||
}
|
||||
|
||||
/// An answer, read in full.
|
||||
struct Answer {
|
||||
status: StatusCode,
|
||||
headers: reqwest::header::HeaderMap,
|
||||
body: Vec<u8>,
|
||||
}
|
||||
|
||||
/// How often a request is tried when the server is away or busy.
|
||||
const ATTEMPTS: u32 = 3;
|
||||
|
||||
impl Bucket {
|
||||
pub fn new(cfg: &S3Config) -> Result<Bucket> {
|
||||
let endpoint = cfg.endpoint.trim().trim_end_matches('/').to_string();
|
||||
let url = Url::parse(&endpoint)
|
||||
.with_context(|| format!("the S3 endpoint {endpoint:?} is not a URL"))?;
|
||||
ensure!(
|
||||
matches!(url.scheme(), "http" | "https"),
|
||||
"the S3 endpoint {endpoint:?} must start with http:// or https://"
|
||||
);
|
||||
ensure!(
|
||||
url.path() == "/" && url.query().is_none(),
|
||||
"the S3 endpoint {endpoint:?} is a server's address, without a path"
|
||||
);
|
||||
let name = url
|
||||
.host_str()
|
||||
.with_context(|| format!("the S3 endpoint {endpoint:?} has no host"))?;
|
||||
let host = match url.port() {
|
||||
Some(p) => format!("{name}:{p}"),
|
||||
None => name.to_string(),
|
||||
};
|
||||
ensure!(
|
||||
valid_bucket_name(&cfg.bucket),
|
||||
"{:?} is not a bucket name (3 to 63 lowercase letters, digits, dots and hyphens)",
|
||||
cfg.bucket
|
||||
);
|
||||
ensure!(
|
||||
!cfg.access_key_id.trim().is_empty(),
|
||||
"the S3 key id is empty"
|
||||
);
|
||||
ensure!(
|
||||
!cfg.secret_access_key.is_empty(),
|
||||
"the S3 secret key is empty"
|
||||
);
|
||||
let http = reqwest::Client::builder()
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.timeout(Duration::from_secs(120))
|
||||
.user_agent(concat!("visa/", env!("CARGO_PKG_VERSION")))
|
||||
.build()?;
|
||||
Ok(Bucket {
|
||||
endpoint,
|
||||
bucket: cfg.bucket.clone(),
|
||||
region: if cfg.region.trim().is_empty() {
|
||||
"garage".into()
|
||||
} else {
|
||||
cfg.region.trim().to_string()
|
||||
},
|
||||
key_id: cfg.access_key_id.trim().to_string(),
|
||||
secret: cfg.secret_access_key.clone(),
|
||||
host,
|
||||
http,
|
||||
pause: Duration::from_millis(500),
|
||||
})
|
||||
}
|
||||
|
||||
/// A shorter pause between attempts, for the tests.
|
||||
pub fn with_pause(mut self, pause: Duration) -> Bucket {
|
||||
self.pause = pause;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &str {
|
||||
&self.bucket
|
||||
}
|
||||
|
||||
pub fn endpoint(&self) -> &str {
|
||||
&self.endpoint
|
||||
}
|
||||
|
||||
/// The canonical path of an object, or of the bucket for an empty key.
|
||||
fn path(&self, key: &str) -> String {
|
||||
format!("/{}/{}", self.bucket, uri_encode(key, true))
|
||||
}
|
||||
|
||||
/// One request, signed, sent and read in full. A connection that fails
|
||||
/// and the answers 500, 502, 503 and 504 are tried again, signed anew.
|
||||
async fn send(
|
||||
&self,
|
||||
method: Method,
|
||||
key: &str,
|
||||
query: &[(&str, &str)],
|
||||
body: &[u8],
|
||||
extra: &[(&str, &str)],
|
||||
) -> Result<Answer> {
|
||||
let path = self.path(key);
|
||||
let mut q: Vec<(String, String)> = query
|
||||
.iter()
|
||||
.map(|(k, v)| (uri_encode(k, false), uri_encode(v, false)))
|
||||
.collect();
|
||||
q.sort();
|
||||
let qs = q
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{k}={v}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("&");
|
||||
let url = if qs.is_empty() {
|
||||
format!("{}{path}", self.endpoint)
|
||||
} else {
|
||||
format!("{}{path}?{qs}", self.endpoint)
|
||||
};
|
||||
let payload = sha256_hex(body);
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
attempt += 1;
|
||||
let amz_date = amz_date(Utc::now());
|
||||
let mut headers: Vec<(String, String)> = vec![
|
||||
("host".into(), self.host.clone()),
|
||||
("x-amz-content-sha256".into(), payload.clone()),
|
||||
("x-amz-date".into(), amz_date.clone()),
|
||||
];
|
||||
for (k, v) in extra {
|
||||
headers.push((k.to_ascii_lowercase(), (*v).to_string()));
|
||||
}
|
||||
let auth = sigv4(
|
||||
method.as_str(),
|
||||
&path,
|
||||
&qs,
|
||||
&headers,
|
||||
&payload,
|
||||
&amz_date,
|
||||
&self.region,
|
||||
&self.key_id,
|
||||
&self.secret,
|
||||
);
|
||||
let mut rb = self
|
||||
.http
|
||||
.request(method.clone(), &url)
|
||||
.header("authorization", auth);
|
||||
for (k, v) in headers.iter().filter(|(k, _)| k != "host") {
|
||||
rb = rb.header(k, v);
|
||||
}
|
||||
if !body.is_empty() || method == Method::PUT {
|
||||
rb = rb.body(body.to_vec());
|
||||
}
|
||||
let what = || format!("S3 {method} {}", self.object_name(key));
|
||||
match rb.send().await {
|
||||
Ok(res) => {
|
||||
let status = res.status();
|
||||
let headers = res.headers().clone();
|
||||
let busy = matches!(status.as_u16(), 500 | 502 | 503 | 504);
|
||||
match res.bytes().await {
|
||||
Ok(b) if !busy || attempt >= ATTEMPTS => {
|
||||
return Ok(Answer {
|
||||
status,
|
||||
headers,
|
||||
body: b.to_vec(),
|
||||
});
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) if attempt >= ATTEMPTS => {
|
||||
return Err(e)
|
||||
.with_context(|| format!("{}: reading the answer", what()));
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
Err(e) if attempt >= ATTEMPTS => {
|
||||
return Err(e)
|
||||
.with_context(|| format!("{}: no answer from {}", what(), self.endpoint));
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
tokio::time::sleep(self.pause * attempt).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn object_name(&self, key: &str) -> String {
|
||||
if key.is_empty() {
|
||||
format!("bucket {}", self.bucket)
|
||||
} else {
|
||||
format!("{key} in bucket {}", self.bucket)
|
||||
}
|
||||
}
|
||||
|
||||
/// The error for an answer that is not what was asked for: the status
|
||||
/// and the S3 error code (`AccessDenied`, `NoSuchBucket` ...).
|
||||
fn failed(&self, what: &str, key: &str, a: &Answer) -> anyhow::Error {
|
||||
let text = String::from_utf8_lossy(&a.body);
|
||||
let code = tag(&text, "Code").unwrap_or_default();
|
||||
anyhow::anyhow!(
|
||||
"S3 {what} {}: HTTP {} {code}",
|
||||
self.object_name(key),
|
||||
a.status.as_u16()
|
||||
)
|
||||
}
|
||||
|
||||
/// Writes an object that must not exist yet. One that exists with the
|
||||
/// same bytes counts as written before ([`Put::Same`]), one with other
|
||||
/// bytes is an error and stays as it is. The server is asked first: that
|
||||
/// question is the guard on Garage, which ignores the write's condition
|
||||
/// ([`Bucket::put_if_absent`]). The store's ids are unique, so only a
|
||||
/// restore that brought an old id back could meet an object here.
|
||||
pub async fn put_new(&self, key: &str, bytes: &[u8]) -> Result<Put> {
|
||||
if self.head(key).await?.is_none() && self.put_if_absent(key, bytes).await? {
|
||||
return Ok(Put::Written);
|
||||
}
|
||||
self.same_or_refuse(key, bytes).await
|
||||
}
|
||||
|
||||
/// A PUT with `If-None-Match: *`: true when the object was written,
|
||||
/// false when the server refused because it exists (HTTP 412). AWS and
|
||||
/// MinIO honor the header; Garage 2.5 ignores it and writes (seen in
|
||||
/// tests/garage.rs on Nov 19, 2026), so on Garage this is a plain PUT.
|
||||
pub async fn put_if_absent(&self, key: &str, bytes: &[u8]) -> Result<bool> {
|
||||
let a = self
|
||||
.send(
|
||||
Method::PUT,
|
||||
key,
|
||||
&[],
|
||||
bytes,
|
||||
&[
|
||||
("content-type", "application/octet-stream"),
|
||||
("if-none-match", "*"),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
if a.status.is_success() {
|
||||
Ok(true)
|
||||
} else if a.status == StatusCode::PRECONDITION_FAILED {
|
||||
Ok(false)
|
||||
} else {
|
||||
Err(self.failed("PUT", key, &a))
|
||||
}
|
||||
}
|
||||
|
||||
async fn same_or_refuse(&self, key: &str, bytes: &[u8]) -> Result<Put> {
|
||||
match self.get(key).await? {
|
||||
Some(there) if there == bytes => Ok(Put::Same),
|
||||
Some(_) => bail!(
|
||||
"{} is there already with other bytes; it stays as it is",
|
||||
self.object_name(key)
|
||||
),
|
||||
None => bail!(
|
||||
"{} was there a moment ago and is gone now; try again",
|
||||
self.object_name(key)
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The object's bytes, or None when there is no such object.
|
||||
pub async fn get(&self, key: &str) -> Result<Option<Vec<u8>>> {
|
||||
let a = self.send(Method::GET, key, &[], &[], &[]).await?;
|
||||
match a.status {
|
||||
s if s.is_success() => Ok(Some(a.body)),
|
||||
StatusCode::NOT_FOUND
|
||||
if tag(&String::from_utf8_lossy(&a.body), "Code").as_deref()
|
||||
!= Some("NoSuchBucket") =>
|
||||
{
|
||||
Ok(None)
|
||||
}
|
||||
_ => Err(self.failed("GET", key, &a)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The object's size, or None when there is no such object.
|
||||
pub async fn head(&self, key: &str) -> Result<Option<u64>> {
|
||||
let a = self.send(Method::HEAD, key, &[], &[], &[]).await?;
|
||||
match a.status {
|
||||
s if s.is_success() => Ok(Some(
|
||||
a.headers
|
||||
.get(reqwest::header::CONTENT_LENGTH)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or_default(),
|
||||
)),
|
||||
StatusCode::NOT_FOUND => Ok(None),
|
||||
_ => Err(self.failed("HEAD", key, &a)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes an object; one that is gone already is fine.
|
||||
pub async fn delete(&self, key: &str) -> Result<()> {
|
||||
let a = self.send(Method::DELETE, key, &[], &[], &[]).await?;
|
||||
if a.status.is_success() || a.status == StatusCode::NOT_FOUND {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(self.failed("DELETE", key, &a))
|
||||
}
|
||||
}
|
||||
|
||||
/// Every object whose key starts with `prefix`, sorted by key; read
|
||||
/// page by page.
|
||||
pub async fn list(&self, prefix: &str) -> Result<Vec<Object>> {
|
||||
let mut out = Vec::new();
|
||||
let mut token: Option<String> = None;
|
||||
loop {
|
||||
let mut q = vec![("list-type", "2"), ("prefix", prefix)];
|
||||
if let Some(t) = &token {
|
||||
q.push(("continuation-token", t.as_str()));
|
||||
}
|
||||
let a = self.send(Method::GET, "", &q, &[], &[]).await?;
|
||||
if !a.status.is_success() {
|
||||
return Err(self.failed("LIST", "", &a));
|
||||
}
|
||||
let page = parse_list(&String::from_utf8_lossy(&a.body))?;
|
||||
out.extend(page.objects);
|
||||
match (page.truncated, page.next) {
|
||||
(true, Some(next)) if Some(&next) != token.as_ref() => token = Some(next),
|
||||
(true, _) => bail!(
|
||||
"S3 LIST {}: a page says more follow but gives no new token",
|
||||
self.object_name("")
|
||||
),
|
||||
(false, _) => break,
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.key.cmp(&b.key));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The bucket answers to this key (at the start and in `files-check`).
|
||||
pub async fn check(&self) -> Result<()> {
|
||||
let a = self
|
||||
.send(
|
||||
Method::GET,
|
||||
"",
|
||||
&[("list-type", "2"), ("max-keys", "1")],
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
if a.status.is_success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(self.failed("LIST", "", &a))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// S3's rule for bucket names, as Garage applies it.
|
||||
fn valid_bucket_name(name: &str) -> bool {
|
||||
(3..=63).contains(&name.len())
|
||||
&& name
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-')
|
||||
&& name.as_bytes()[0].is_ascii_alphanumeric()
|
||||
&& name.as_bytes()[name.len() - 1].is_ascii_alphanumeric()
|
||||
}
|
||||
|
||||
/// One page of a listing.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Page {
|
||||
pub objects: Vec<Object>,
|
||||
pub truncated: bool,
|
||||
pub next: Option<String>,
|
||||
}
|
||||
|
||||
/// Reads a ListObjectsV2 answer.
|
||||
pub fn parse_list(xml: &str) -> Result<Page> {
|
||||
ensure!(
|
||||
xml.contains("<ListBucketResult"),
|
||||
"S3 LIST: the answer is not a listing"
|
||||
);
|
||||
let mut page = Page {
|
||||
truncated: tag(xml, "IsTruncated").as_deref() == Some("true"),
|
||||
next: tag(xml, "NextContinuationToken").filter(|t| !t.is_empty()),
|
||||
..Page::default()
|
||||
};
|
||||
for part in xml.split("<Contents>").skip(1) {
|
||||
let part = part.split("</Contents>").next().unwrap_or_default();
|
||||
let key = tag(part, "Key").context("S3 LIST: an object without a key")?;
|
||||
let size = tag(part, "Size")
|
||||
.and_then(|s| s.parse().ok())
|
||||
.with_context(|| format!("S3 LIST: {key} without a size"))?;
|
||||
page.objects.push(Object { key, size });
|
||||
}
|
||||
Ok(page)
|
||||
}
|
||||
|
||||
/// The text of the first `<name>` element, unescaped.
|
||||
fn tag(xml: &str, name: &str) -> Option<String> {
|
||||
let open = format!("<{name}>");
|
||||
let close = format!("</{name}>");
|
||||
let start = xml.find(&open)? + open.len();
|
||||
let len = xml[start..].find(&close)?;
|
||||
Some(xml_unescape(&xml[start..start + len]))
|
||||
}
|
||||
|
||||
fn xml_unescape(s: &str) -> String {
|
||||
s.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace(""", "\"")
|
||||
.replace("'", "'")
|
||||
.replace("'", "'")
|
||||
.replace("&", "&")
|
||||
}
|
||||
|
||||
pub fn amz_date(t: DateTime<Utc>) -> String {
|
||||
t.format("%Y%m%dT%H%M%SZ").to_string()
|
||||
}
|
||||
|
||||
fn hex(b: &[u8]) -> String {
|
||||
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||
}
|
||||
|
||||
pub fn sha256_hex(b: &[u8]) -> String {
|
||||
hex(digest::digest(&digest::SHA256, b).as_ref())
|
||||
}
|
||||
|
||||
fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
|
||||
hmac::sign(&hmac::Key::new(hmac::HMAC_SHA256, key), data)
|
||||
.as_ref()
|
||||
.to_vec()
|
||||
}
|
||||
|
||||
/// URI-encodes as SigV4 wants: unreserved characters stay, every other byte
|
||||
/// becomes `%XX` in upper case; `/` stays in paths.
|
||||
pub fn uri_encode(s: &str, keep_slash: bool) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for b in s.bytes() {
|
||||
if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) || (keep_slash && b == b'/') {
|
||||
out.push(b as char);
|
||||
} else {
|
||||
out.push_str(&format!("%{b:02X}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The `Authorization` header of one request (SigV4): pure, so the tests
|
||||
/// check it against AWS's published example and the test server checks
|
||||
/// every request with it. `headers` are the signed ones; names may come in
|
||||
/// any case and order.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn sigv4(
|
||||
method: &str,
|
||||
canonical_path: &str,
|
||||
canonical_query: &str,
|
||||
headers: &[(String, String)],
|
||||
payload_hash: &str,
|
||||
amz_date: &str,
|
||||
region: &str,
|
||||
key_id: &str,
|
||||
secret: &str,
|
||||
) -> String {
|
||||
let date = &amz_date[..8.min(amz_date.len())];
|
||||
let mut hs: Vec<(String, String)> = headers
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
(
|
||||
k.to_ascii_lowercase(),
|
||||
v.split_whitespace().collect::<Vec<_>>().join(" "),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
hs.sort();
|
||||
let canonical_headers: String = hs.iter().map(|(k, v)| format!("{k}:{v}\n")).collect();
|
||||
let signed = hs
|
||||
.iter()
|
||||
.map(|(k, _)| k.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(";");
|
||||
let canonical = format!(
|
||||
"{method}\n{canonical_path}\n{canonical_query}\n{canonical_headers}\n{signed}\n{payload_hash}"
|
||||
);
|
||||
let scope = format!("{date}/{region}/s3/aws4_request");
|
||||
let to_sign = format!(
|
||||
"AWS4-HMAC-SHA256\n{amz_date}\n{scope}\n{}",
|
||||
sha256_hex(canonical.as_bytes())
|
||||
);
|
||||
let k = hmac_sha256(format!("AWS4{secret}").as_bytes(), date.as_bytes());
|
||||
let k = hmac_sha256(&k, region.as_bytes());
|
||||
let k = hmac_sha256(&k, b"s3");
|
||||
let k = hmac_sha256(&k, b"aws4_request");
|
||||
let signature = hex(&hmac_sha256(&k, to_sign.as_bytes()));
|
||||
format!(
|
||||
"AWS4-HMAC-SHA256 Credential={key_id}/{scope}, SignedHeaders={signed}, Signature={signature}"
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EMPTY: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
|
||||
/// The secret key of AWS's documented examples.
|
||||
const AWS_EXAMPLE_SECRET: &str = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
|
||||
|
||||
fn signature(auth: &str) -> &str {
|
||||
auth.rsplit("Signature=").next().unwrap()
|
||||
}
|
||||
|
||||
/// AWS's example "GET Object" (Signature Calculations for the
|
||||
/// Authorization Header: Transferring Payload in a Single Chunk). The
|
||||
/// signature depends on the secret alone, not on the key id.
|
||||
#[test]
|
||||
fn sigv4_matches_the_aws_get_example() {
|
||||
let auth = sigv4(
|
||||
"GET",
|
||||
"/test.txt",
|
||||
"",
|
||||
&[
|
||||
("Host".into(), "examplebucket.s3.amazonaws.com".into()),
|
||||
("Range".into(), "bytes=0-9".into()),
|
||||
("x-amz-content-sha256".into(), EMPTY.into()),
|
||||
("x-amz-date".into(), "20130524T000000Z".into()),
|
||||
],
|
||||
EMPTY,
|
||||
"20130524T000000Z",
|
||||
"us-east-1",
|
||||
"EXAMPLE-KEY-ID",
|
||||
AWS_EXAMPLE_SECRET,
|
||||
);
|
||||
assert!(
|
||||
auth.starts_with(
|
||||
"AWS4-HMAC-SHA256 Credential=EXAMPLE-KEY-ID/20130524/us-east-1/s3/aws4_request, \
|
||||
SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, "
|
||||
),
|
||||
"{auth}"
|
||||
);
|
||||
assert_eq!(
|
||||
signature(&auth),
|
||||
"f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
|
||||
);
|
||||
}
|
||||
|
||||
/// AWS's example "GET Bucket (List Objects)": a query string.
|
||||
#[test]
|
||||
fn sigv4_matches_the_aws_list_example() {
|
||||
let auth = sigv4(
|
||||
"GET",
|
||||
"/",
|
||||
"max-keys=2&prefix=J",
|
||||
&[
|
||||
("host".into(), "examplebucket.s3.amazonaws.com".into()),
|
||||
("x-amz-content-sha256".into(), EMPTY.into()),
|
||||
("x-amz-date".into(), "20130524T000000Z".into()),
|
||||
],
|
||||
EMPTY,
|
||||
"20130524T000000Z",
|
||||
"us-east-1",
|
||||
"EXAMPLE-KEY-ID",
|
||||
AWS_EXAMPLE_SECRET,
|
||||
);
|
||||
assert_eq!(
|
||||
signature(&auth),
|
||||
"34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_and_values_are_encoded_as_sigv4_wants() {
|
||||
assert_eq!(uri_encode("documents/7.vdoc", true), "documents/7.vdoc");
|
||||
assert_eq!(uri_encode("a b/c~d", true), "a%20b/c~d");
|
||||
assert_eq!(uri_encode("a b/c", false), "a%20b%2Fc");
|
||||
assert_eq!(uri_encode("tok+/=", false), "tok%2B%2F%3D");
|
||||
assert_eq!(uri_encode("ไ", false), "%E0%B9%84");
|
||||
for good in ["visa-documents", "proplan.lol", "abc"] {
|
||||
assert!(valid_bucket_name(good), "{good}");
|
||||
}
|
||||
for bad in ["", "ab", "Visa", "visa_documents", "-visa", "visa-", "a/b"] {
|
||||
assert!(!valid_bucket_name(bad), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_listing_reads_keys_sizes_and_the_next_page() {
|
||||
let xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
|
||||
<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\
|
||||
<Name>visa-documents</Name><Prefix>documents/</Prefix><KeyCount>2</KeyCount>\
|
||||
<MaxKeys>2</MaxKeys><IsTruncated>true</IsTruncated>\
|
||||
<Contents><Key>documents/1.vdoc</Key><LastModified>2026-11-19T10:00:00.000Z</LastModified>\
|
||||
<ETag>"9b2cf535f27731c974343645a3985328"</ETag><Size>1234</Size>\
|
||||
<StorageClass>STANDARD</StorageClass></Contents>\
|
||||
<Contents><Key>documents/a&b.vdoc</Key><Size>0</Size></Contents>\
|
||||
<NextContinuationToken>tok+/=</NextContinuationToken></ListBucketResult>";
|
||||
let page = parse_list(xml).unwrap();
|
||||
assert_eq!(
|
||||
page.objects,
|
||||
[
|
||||
Object {
|
||||
key: "documents/1.vdoc".into(),
|
||||
size: 1234
|
||||
},
|
||||
Object {
|
||||
key: "documents/a&b.vdoc".into(),
|
||||
size: 0
|
||||
}
|
||||
]
|
||||
);
|
||||
assert!(page.truncated);
|
||||
assert_eq!(page.next.as_deref(), Some("tok+/="));
|
||||
let last = parse_list(
|
||||
"<ListBucketResult><IsTruncated>false</IsTruncated><KeyCount>0</KeyCount></ListBucketResult>",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(last, Page::default());
|
||||
assert!(parse_list("<Error><Code>AccessDenied</Code></Error>").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_endpoint_is_a_server_and_the_secret_is_never_shown() {
|
||||
let cfg = |endpoint: &str| S3Config {
|
||||
endpoint: endpoint.into(),
|
||||
bucket: "visa-documents".into(),
|
||||
region: String::new(),
|
||||
access_key_id: "GK0011".into(),
|
||||
secret_access_key: "very-secret-value".into(),
|
||||
};
|
||||
let b = Bucket::new(&cfg("http://127.0.0.1:3900/")).unwrap();
|
||||
assert_eq!(b.host, "127.0.0.1:3900");
|
||||
assert_eq!(b.region, "garage");
|
||||
assert_eq!(b.endpoint(), "http://127.0.0.1:3900");
|
||||
assert_eq!(
|
||||
b.path("documents/7.vdoc"),
|
||||
"/visa-documents/documents/7.vdoc"
|
||||
);
|
||||
assert_eq!(b.path(""), "/visa-documents/");
|
||||
let b = Bucket::new(&cfg("http://[::1]:3900")).unwrap();
|
||||
assert_eq!(b.host, "[::1]:3900");
|
||||
for bad in [
|
||||
"127.0.0.1:3900",
|
||||
"ftp://x",
|
||||
"http://x/visa-documents",
|
||||
"nonsense",
|
||||
] {
|
||||
assert!(Bucket::new(&cfg(bad)).is_err(), "{bad}");
|
||||
}
|
||||
let shown = format!("{:?} {:?}", cfg("http://x"), b);
|
||||
assert!(!shown.contains("very-secret"), "{shown}");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -818,7 +818,7 @@ pub async fn demo_documents(db: &PgPool, store: &Store, today: NaiveDate) -> Res
|
||||
sha256: &sha256,
|
||||
};
|
||||
let id = documents::insert(&mut tx, *owner, &meta, &file, "seed").await?;
|
||||
store.put(id, bytes)?;
|
||||
store.put(id, bytes.clone()).await?;
|
||||
written.push(id);
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
|
||||
@@ -663,9 +663,7 @@ async fn save(
|
||||
sha256: &f.sha256,
|
||||
};
|
||||
let id = documents::insert(&mut tx, owner, meta, &file, &user.login).await?;
|
||||
let s = store.clone();
|
||||
let bytes = f.bytes;
|
||||
tokio::task::spawn_blocking(move || s.put(id, &bytes)).await??;
|
||||
store.put(id, f.bytes).await?;
|
||||
written.push(id);
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
@@ -690,7 +688,7 @@ async fn save(
|
||||
};
|
||||
if let Err(e) = result {
|
||||
for id in &written {
|
||||
if let Err(r) = store.remove(*id) {
|
||||
if let Err(r) = store.remove(*id).await {
|
||||
error!("removing the file of the failed upload {id}: {r:#}");
|
||||
}
|
||||
}
|
||||
@@ -822,7 +820,7 @@ pub async fn file(st: Arc<AppState>, user: User, owner: Owner, id: i64, q: FileQ
|
||||
let Some(store) = st.files.clone() else {
|
||||
return Ok(files_off(&st));
|
||||
};
|
||||
let bytes = match tokio::task::spawn_blocking(move || store.get(id)).await? {
|
||||
let bytes = match store.get(id).await {
|
||||
Ok(b) if files::sha256_hex(&b) == d.sha256 => b,
|
||||
Ok(_) => {
|
||||
error!("document {id}: the file does not match the checksum of its upload");
|
||||
@@ -1029,7 +1027,7 @@ pub async fn delete(st: Arc<AppState>, user: User, owner: Owner, id: i64) -> Res
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
if let Err(e) = tokio::task::spawn_blocking(move || store.remove(id)).await? {
|
||||
if let Err(e) = store.remove(id).await {
|
||||
error!("document {id} is deleted, but not its file: {e:#}");
|
||||
}
|
||||
Ok(Redirect::to(&list_page(owner)).into_response())
|
||||
|
||||
+3
-6
@@ -39,7 +39,8 @@ pub struct AppState {
|
||||
provider: RwLock<Option<Arc<oidc::Provider>>>,
|
||||
/// The form token of local development, which has no sessions.
|
||||
local_csrf: String,
|
||||
/// The documents' files; none in local development without a key.
|
||||
/// The documents' files; none in local development without a place
|
||||
/// and a key for them.
|
||||
pub files: Option<Store>,
|
||||
}
|
||||
|
||||
@@ -50,11 +51,7 @@ impl AppState {
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.user_agent(concat!("visa/", env!("CARGO_PKG_VERSION")))
|
||||
.build()?;
|
||||
let files = cfg
|
||||
.files
|
||||
.as_ref()
|
||||
.map(|f| Store::open(f.dir.clone(), f.key.clone()))
|
||||
.transpose()?;
|
||||
let files = cfg.files.as_ref().map(Store::open).transpose()?;
|
||||
Ok(Arc::new(AppState {
|
||||
templates: templates()?,
|
||||
files,
|
||||
|
||||
Reference in new issue
Block a user