Phase 4: documents, encrypted on the server
CI / secret scan (push) Successful in 5s
CI / fmt, clippy, tests (push) Successful in 53s

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:
grabowski committed 2026-11-18 10:23:41 +07:00
1 parent d543c929e9
commit 2061e3a024
35 files changed
+4256 -58

No files matched your search

+96
View File
@@ -12,12 +12,19 @@
//! | `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_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.
use std::net::SocketAddr;
use std::path::PathBuf;
use anyhow::{Context, Result, bail, ensure};
use crate::files::FileKey;
#[derive(Clone, Debug)]
pub struct Config {
pub listen: SocketAddr,
@@ -26,6 +33,14 @@ pub struct Config {
pub database_url: String,
pub database_password: Option<String>,
pub auth: Auth,
/// Documents: off in local development without a files directory.
pub files: Option<FilesConfig>,
}
#[derive(Clone, Debug)]
pub struct FilesConfig {
pub dir: PathBuf,
pub key: FileKey,
}
#[derive(Clone, Debug)]
@@ -108,12 +123,35 @@ impl Config {
VISA_INSECURE_NO_LOGIN=1 for local development on a loopback address"
),
};
let key = match var("VISA_FILES_KEY_FILE") {
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),
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"
),
(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)"
);
}
Ok(Config {
listen,
public_url,
database_url,
database_password,
auth,
files,
})
}
@@ -189,6 +227,9 @@ mod tests {
std::fs::create_dir_all(&dir).unwrap();
let f = dir.join("secret");
std::fs::write(&f, "s3cret\n").unwrap();
let key = dir.join("files.key");
std::fs::write(&key, format!("{}\n", "ab".repeat(32))).unwrap();
let files_dir = dir.join("files");
let c = cfg(&[
("VISA_DATABASE_URL", "postgres://x/y"),
("VISA_PUBLIC_URL", "https://visa.example/"),
@@ -197,6 +238,8 @@ mod tests {
"https://id.example/oauth2/openid/visa-web/",
),
("VISA_OIDC_CLIENT_SECRET_FILE", f.to_str().unwrap()),
("VISA_FILES_DIR", files_dir.to_str().unwrap()),
("VISA_FILES_KEY_FILE", key.to_str().unwrap()),
])
.unwrap();
let Auth::Oidc(o) = &c.auth else {
@@ -220,6 +263,59 @@ mod tests {
])
.unwrap_err();
assert!(e.to_string().contains("https"), "{e}");
// with the login on, documents must be set up
let e = cfg(&[
("VISA_DATABASE_URL", "postgres://x/y"),
("VISA_PUBLIC_URL", "https://visa.example"),
(
"VISA_OIDC_ISSUER",
"https://id.example/oauth2/openid/visa-web",
),
("VISA_OIDC_CLIENT_SECRET_FILE", f.to_str().unwrap()),
])
.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!(!format!("{files:?}").contains("abab"));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn documents_need_both_the_directory_and_the_key() {
let dir = std::env::temp_dir().join(format!("visa-cfg-files-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let key = dir.join("files.key");
let base = [
("VISA_DATABASE_URL", "postgres://x/y"),
("VISA_INSECURE_NO_LOGIN", "1"),
];
// local development may go without documents
assert!(cfg(&base).unwrap().files.is_none());
let with = |extra: &[(&str, &str)]| {
let mut all = base.to_vec();
all.extend_from_slice(extra);
cfg(&all)
};
let e = with(&[("VISA_FILES_DIR", "/srv/files")]).unwrap_err();
assert!(e.to_string().contains("no file key"), "{e}");
std::fs::write(&key, "not hex").unwrap();
let e = with(&[
("VISA_FILES_DIR", "/srv/files"),
("VISA_FILES_KEY_FILE", key.to_str().unwrap()),
])
.unwrap_err();
assert!(format!("{e:#}").contains("64 hex digits"), "{e:#}");
// the systemd credential
std::fs::write(dir.join("files-key"), "cd".repeat(32)).unwrap();
let c = with(&[
("VISA_FILES_DIR", "/srv/files"),
("CREDENTIALS_DIRECTORY", dir.to_str().unwrap()),
])
.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}");
std::fs::remove_dir_all(&dir).ok();
}
}