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 -17
View File
@@ -4,6 +4,7 @@ pub mod activity;
pub mod auth;
pub mod companies;
pub mod dashboard;
pub mod documents;
pub mod people;
pub mod records;
@@ -11,7 +12,7 @@ use std::sync::{Arc, RwLock};
use std::time::Duration;
use axum::body::Body;
use axum::extract::{Path, Request, State};
use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, Request, State};
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header};
use axum::middleware::{self, Next};
use axum::response::{Html, IntoResponse, Redirect, Response};
@@ -22,6 +23,8 @@ use sqlx::PgPool;
use tracing::{error, info, warn};
use crate::config::{Auth, Config};
use crate::documents::Owner;
use crate::files::Store;
use crate::forms::Fields;
use crate::session::{self, Flows, SESSION_COOKIE, User};
use crate::{VERSION, countries, dates, embedded, oidc};
@@ -35,6 +38,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.
pub files: Option<Store>,
}
impl AppState {
@@ -44,8 +49,14 @@ 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()?;
Ok(Arc::new(AppState {
templates: templates()?,
files,
cfg,
db,
http,
@@ -225,6 +236,70 @@ pub fn router(st: Arc<AppState>) -> Router {
),
);
}
// Documents of people and of companies: the upload, a file, the page
// about one document, its change and its deletion. A person's documents
// have their own tab; a company's are on its page.
r = r.route("/people/{id}/documents", get(documents::person_tab));
type OwnerOf = fn(i64) -> Owner;
let owners: [(&str, OwnerOf); 2] = [("people", Owner::Person), ("companies", Owner::Company)];
for (prefix, owner) in owners {
let base = format!("/{prefix}/{{id}}/documents");
r = r
.route(
&base,
post(
move |State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
mp: Multipart| {
documents::upload(st, user, owner(id), mp)
},
)
.layer(DefaultBodyLimit::max(documents::UPLOAD_LIMIT)),
)
.route(
&format!("{base}/{{did}}/file"),
get(
move |State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, did)): Path<(i64, i64)>,
Query(q): Query<documents::FileQuery>| {
documents::file(st, user, owner(id), did, q)
},
),
)
.route(
&format!("{base}/{{did}}/edit"),
get(
move |State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, did)): Path<(i64, i64)>| {
documents::edit_form(st, user, owner(id), did)
},
),
)
.route(
&format!("{base}/{{did}}"),
post(
move |State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, did)): Path<(i64, i64)>,
Form(f): Form<Fields>| {
documents::update(st, user, owner(id), did, f)
},
),
)
.route(
&format!("{base}/{{did}}/delete"),
post(
move |State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path((id, did)): Path<(i64, i64)>| {
documents::delete(st, user, owner(id), did)
},
),
);
}
r.route("/activity", get(activity::page))
.route("/login", get(auth::login))
.route("/auth/callback", get(auth::callback))
@@ -232,6 +307,11 @@ pub fn router(st: Arc<AppState>) -> Router {
.route("/signed-out", get(auth::signed_out))
.route("/healthz", get(healthz))
.route("/static/{*path}", get(static_file))
// asked for by pages without their own icon: an image or a PDF
.route(
"/favicon.ico",
get(|| static_file(Path("favicon.svg".to_string()))),
)
.fallback(not_found)
.layer(middleware::from_fn_with_state(st.clone(), forms_guard))
.layer(middleware::from_fn_with_state(st.clone(), gate))
@@ -243,7 +323,7 @@ pub fn router(st: Arc<AppState>) -> Router {
fn is_public(path: &str) -> bool {
matches!(
path,
"/healthz" | "/login" | "/auth/callback" | "/signed-out"
"/healthz" | "/login" | "/auth/callback" | "/signed-out" | "/favicon.ico"
) || path.starts_with("/static/")
}
@@ -309,6 +389,23 @@ async fn forms_guard(State(st): State<Arc<AppState>>, req: Request, next: Next)
// public paths take no forms
return next.run(req).await;
};
let multipart = req
.headers()
.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|ct| ct.to_ascii_lowercase().starts_with("multipart/form-data"));
if multipart {
// An upload checks its token itself, as the form's first field, so
// that its files are not held here.
if is_upload(req.uri().path()) {
return next.run(req).await;
}
return (
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"This address takes no uploads.",
)
.into_response();
}
let (parts, body) = req.into_parts();
let bytes = match axum::body::to_bytes(body, FORM_LIMIT).await {
Ok(b) => b,
@@ -334,19 +431,35 @@ async fn forms_guard(State(st): State<Arc<AppState>>, req: Request, next: Next)
};
if !token.is_some_and(|t| session::same_token(&t, &user.csrf)) {
warn!("refused a form without a valid token from {}", user.login);
return message(
&st,
StatusCode::FORBIDDEN,
"The form has expired",
"The page was older than your current session. Go back, reload the page and send \
the form again.",
("/", "Open the app"),
);
return expired(&st);
}
next.run(Request::from_parts(parts, Body::from(bytes)))
.await
}
/// The addresses that take uploads: `/people/{id}/documents` and
/// `/companies/{id}/documents`.
fn is_upload(path: &str) -> bool {
let parts: Vec<&str> = path.split('/').collect();
matches!(
parts.as_slice(),
["", "people" | "companies", id, "documents"]
if !id.is_empty() && id.bytes().all(|b| b.is_ascii_digit())
)
}
/// A form without the session's token.
pub fn expired(st: &AppState) -> Response {
message(
st,
StatusCode::FORBIDDEN,
"The form has expired",
"The page was older than your current session. Go back, reload the page and send the \
form again.",
("/", "Open the app"),
)
}
pub fn same_site(st: &AppState, headers: &HeaderMap) -> bool {
match headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) {
Some(v) => v == "same-origin",
@@ -360,13 +473,16 @@ pub fn same_site(st: &AppState, headers: &HeaderMap) -> bool {
async fn security_headers(req: Request, next: Next) -> Response {
let mut resp = next.run(req).await;
let h = resp.headers_mut();
h.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(
"default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \
connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
),
);
// a document's file brings its own, stricter policy
if !h.contains_key(header::CONTENT_SECURITY_POLICY) {
h.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(
"default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \
connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
),
);
}
h.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),