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

+133 -3
View File
@@ -1,6 +1,8 @@
#![allow(dead_code)]
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use axum::Router;
use axum::body::Body;
@@ -9,9 +11,21 @@ use chrono::NaiveDate;
use http_body_util::BodyExt;
use sqlx::PgPool;
use tower::ServiceExt;
use visa::config::{Auth, Config, OidcConfig};
use visa::config::{Auth, Config, FilesConfig, OidcConfig};
use visa::files::FileKey;
use visa::web::{self, AppState};
/// A files directory of its own for each app, under the target directory.
fn files_dir() -> PathBuf {
static N: AtomicUsize = AtomicUsize::new(0);
PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!(
"files-{}-{}",
std::process::id(),
N.fetch_add(1, Ordering::Relaxed)
))
}
/// Documents on, in a fresh directory with a fresh key.
pub fn config(auth: Auth) -> Config {
Config {
listen: "127.0.0.1:0".parse().unwrap(),
@@ -19,6 +33,10 @@ pub fn config(auth: Auth) -> Config {
database_url: "postgres://unused".into(),
database_password: None,
auth,
files: Some(FilesConfig {
dir: files_dir(),
key: FileKey::random(),
}),
}
}
@@ -37,13 +55,26 @@ pub struct App {
pub pool: PgPool,
}
// The test's files go with it.
impl Drop for App {
fn drop(&mut self) {
if let Some(dir) = self.st.cfg.files.as_ref().map(|f| f.dir.clone()) {
std::fs::remove_dir_all(dir).ok();
}
}
}
/// Local development mode: no login, everyone is "local".
pub fn local(pool: PgPool) -> App {
with_auth(pool, Auth::Disabled)
}
pub fn with_auth(pool: PgPool, auth: Auth) -> App {
let st = AppState::new(config(auth), pool.clone()).unwrap();
with_config(pool, config(auth))
}
pub fn with_config(pool: PgPool, cfg: Config) -> App {
let st = AppState::new(cfg, pool.clone()).unwrap();
App {
router: web::router(st.clone()),
st,
@@ -55,12 +86,18 @@ pub struct Resp {
pub status: StatusCode,
pub headers: HeaderMap,
pub body: String,
/// The body as it came, for files.
pub bytes: Vec<u8>,
}
impl Resp {
pub fn location(&self) -> &str {
self.header("location")
}
pub fn header(&self, name: &str) -> &str {
self.headers
.get("location")
.get(name)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
}
@@ -92,6 +129,7 @@ impl App {
status,
headers,
body: String::from_utf8_lossy(&bytes).into_owned(),
bytes: bytes.to_vec(),
}
}
@@ -130,6 +168,98 @@ impl App {
self.call(req.body(Body::from(form_body(form))).unwrap())
.await
}
/// An upload as the page sends it: the form token first, then the
/// fields, then the files.
pub async fn upload(
&self,
uri: &str,
fields: &[(&str, &str)],
files: &[(&str, &[u8])],
) -> Resp {
let csrf = self.st.local_csrf().to_string();
let mut parts = vec![Part::field("csrf", csrf.as_bytes())];
for (k, v) in fields {
parts.push(Part::field(k, v.as_bytes()));
}
for (name, data) in files {
parts.push(Part::file(name, data));
}
self.upload_raw(uri, &parts, &[("sec-fetch-site", "same-origin")])
.await
}
pub async fn upload_raw(
&self,
uri: &str,
parts: &[Part<'_>],
headers: &[(&str, &str)],
) -> Resp {
let mut req = Request::post(uri).header(
"content-type",
format!("multipart/form-data; boundary={BOUNDARY}"),
);
for (k, v) in headers {
req = req.header(*k, *v);
}
self.call(req.body(Body::from(multipart_body(parts))).unwrap())
.await
}
}
const BOUNDARY: &str = "----visa-test-7d1f0c";
/// One part of a multipart form.
pub struct Part<'a> {
pub name: &'a str,
pub file_name: Option<&'a str>,
pub data: &'a [u8],
}
impl<'a> Part<'a> {
pub fn field(name: &'a str, data: &'a [u8]) -> Part<'a> {
Part {
name,
file_name: None,
data,
}
}
pub fn file(file_name: &'a str, data: &'a [u8]) -> Part<'a> {
Part {
name: "file",
file_name: Some(file_name),
data,
}
}
}
pub fn multipart_body(parts: &[Part<'_>]) -> Vec<u8> {
let mut body = Vec::new();
for p in parts {
body.extend_from_slice(format!("--{BOUNDARY}\r\n").as_bytes());
let head = match p.file_name {
Some(f) => format!(
"Content-Disposition: form-data; name=\"{}\"; filename=\"{f}\"\r\n\
Content-Type: application/octet-stream\r\n\r\n",
p.name
),
None => format!(
"Content-Disposition: form-data; name=\"{}\"\r\n\r\n",
p.name
),
};
body.extend_from_slice(head.as_bytes());
body.extend_from_slice(p.data);
body.extend_from_slice(b"\r\n");
}
body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
body
}
/// A small PDF that says what it is.
pub fn pdf(text: &str) -> Vec<u8> {
format!("%PDF-1.4\n% {text}\n%%EOF\n").into_bytes()
}
pub fn d(s: &str) -> NaiveDate {