Phase 4: documents, encrypted on the server
Scans and photos of a person's papers, and a company's documents for the extension packs, uploaded on a dashed strip that takes dropped files: up to 10 files of 20 MB each, 64 MB in all; PDF, JPEG, PNG and WebP, told by their first bytes. - src/files.rs: one file per document as <id>.vdoc, AES-256-GCM under a key per file (HKDF-SHA256 from the file key and a random salt in the header); the document's id is authenticated with it. The key comes from VISA_FILES_KEY_FILE or the credential files-key; with the login on, the app does not start without it and VISA_FILES_DIR. - migrations/0003: documents (a person's or a company's, the record it belongs to, kind, date on it, note, file name, type, size, SHA-256); audit_log gets company_id and the action download. - A Documents tab per person, the documents on the company's page, and each record's documents next to its Edit link with "+ Document". - An upload's form token is its first field and is checked before any file is read; the guard lets multipart through only to the two upload addresses. - Files open under their own CSP and are never cached; a download is named after the person or company, the kind and the date. Every upload, view, download, change and deletion is in the audit log. - visa files-check; demo documents in seed-demo; scripts/dev.sh keeps the local documents and their key in .dev/; /favicon.ico for image and PDF pages. Tests: 57 unit and 33 integration (8 new for documents). Edge check of the strip (choose, drop, too large), an upload, the PDF and image viewers under the file policy: no problems, no console errors.
This commit is contained in:
1 parent
d543c929e9
commit
2061e3a024
35 files changed
+4256
-58
No files matched your search
+410
@@ -0,0 +1,410 @@
|
||||
//! 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.
|
||||
//!
|
||||
//! 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::fmt;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use ring::aead::{self, Aad, LessSafeKey, Nonce, UnboundKey};
|
||||
use ring::rand::{SecureRandom, SystemRandom};
|
||||
use ring::{digest, hkdf};
|
||||
|
||||
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 files directory with the key; cheap to clone into a blocking task.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Store {
|
||||
dir: PathBuf,
|
||||
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()))?;
|
||||
}
|
||||
Ok(Store { dir, key })
|
||||
}
|
||||
|
||||
pub fn dir(&self) -> &Path {
|
||||
&self.dir
|
||||
}
|
||||
|
||||
pub fn key_id(&self) -> String {
|
||||
self.key.id_hex()
|
||||
}
|
||||
|
||||
pub fn path(&self, id: i64) -> PathBuf {
|
||||
self.dir.join(format!("{id}.vdoc"))
|
||||
}
|
||||
|
||||
/// 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()))
|
||||
}
|
||||
|
||||
/// 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()))
|
||||
}
|
||||
|
||||
/// 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())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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),
|
||||
}
|
||||
}
|
||||
ids.sort_unstable();
|
||||
other.sort();
|
||||
Ok((ids, other))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 the_store_writes_reads_and_removes() {
|
||||
let dir = std::env::temp_dir().join(format!("visa-store-{}", 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();
|
||||
assert!(!on_disk.windows(5).any(|w| w == b"three"));
|
||||
let e = store.put(3, b"%PDF-1.4 again").unwrap_err();
|
||||
assert!(e.to_string().contains("there already"), "{e}");
|
||||
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.remove(3).unwrap();
|
||||
store.remove(3).unwrap();
|
||||
assert!(store.get(3).is_err());
|
||||
fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user