//! 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/.vdoc`, or in a directory as `.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 { 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 { 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, 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 { 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 `.vdoc` files: local development and the tests. Dir(PathBuf), /// A bucket of an S3 store, objects `documents/.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, } /// File work off the async threads. async fn blocking(f: impl FnOnce() -> Result + Send + 'static) -> Result { 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 `.vdoc` files of a directory with their sizes, and the names of /// everything else in it. fn list_dir(dir: &Path) -> Result { 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 { 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 { 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 { 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) -> 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) -> Result { 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>> { 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> { 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/.vdoc` counts as something else. pub async fn entries(&self) -> Result { 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 `. pub async fn mirror(from: &Store, dir: &Path) -> Result { 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 = 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 = want.into_iter().collect(); let stale: Vec = 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 = 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"