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

+2
View File
@@ -187,6 +187,7 @@ pub async fn callback(
entity: Entity::Session,
entity_id: None,
person_id: None,
company_id: None,
fields: &[],
},
)
@@ -228,6 +229,7 @@ pub async fn logout(
entity: Entity::Session,
entity_id: None,
person_id: None,
company_id: None,
fields: &[],
},
)
+34 -5
View File
@@ -1,6 +1,7 @@
//! Pages for companies: the list, a company with the people it employs, the
//! form, archiving, and adding or removing employees.
use std::collections::HashMap;
use std::sync::Arc;
use axum::extract::{Path, Query, State};
@@ -10,11 +11,13 @@ use axum::{Extension, Form};
use minijinja::context;
use serde::Deserialize;
use super::documents;
use super::records::datalists;
use super::{AppState, Res, not_found_page, page};
use crate::audit::{self, Action, Entity, Entry};
use crate::companies;
use crate::dates;
use crate::documents::Owner;
use crate::forms::{Errors, Fields, err, get};
use crate::records::{self, COMPANIES, Options, Values};
use crate::session::User;
@@ -55,6 +58,7 @@ fn company_entry<'a>(user: &'a User, action: Action, id: i64, fields: &'a [Strin
entity: Entity::Company,
entity_id: Some(id),
person_id: None,
company_id: Some(id),
fields,
}
}
@@ -160,23 +164,47 @@ pub async fn show(
State(st): State<Arc<AppState>>,
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Res {
company_page(
&st,
&user,
id,
&documents::Values::default(),
&Errors::new(),
StatusCode::OK,
)
.await
}
/// The company's page, with its documents and their upload form (and the
/// upload's errors, when one was refused).
pub async fn company_page(
st: &AppState,
user: &User,
id: i64,
values: &documents::Values,
errors: &Errors,
status: StatusCode,
) -> Res {
let Some(r) = records::get(&st.db, &COMPANIES, None, id).await? else {
return Ok(not_found_page(&st));
return Ok(not_found_page(st));
};
let archived_at = companies::archived_at(&st.db, id).await?.flatten();
let c = companies::view(&r, archived_at);
let employees = companies::employees(&st.db, id, dates::today()).await?;
let candidates = companies::candidates(&st.db, id).await?;
let owner = Owner::Company(id);
let docs = documents::views(st, owner, &HashMap::new()).await?;
let upload = documents::upload_context(st, owner, values, errors, &[]);
let title = c.name.clone();
Ok(page(
&st,
&user,
st,
user,
"company.html",
&title,
"companies",
StatusCode::OK,
context! { c, employees, candidates },
status,
context! { c, employees, candidates, docs, upload },
))
}
@@ -272,6 +300,7 @@ fn employer_changed<'a>(user: &'a User, person: i64, fields: &'a [String]) -> En
entity: Entity::Person,
entity_id: Some(person),
person_id: Some(person),
company_id: None,
fields,
}
}
+1051
View File
File diff suppressed because it is too large. Load diff
+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"),
+3
View File
@@ -193,6 +193,7 @@ fn log<'a>(
entity,
entity_id: Some(id),
person_id: Some(person),
company_id: None,
fields,
}
}
@@ -322,6 +323,7 @@ pub async fn show(
let assessment = deadlines::for_person(&st.db, id, today).await?;
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
let recent = audit::recent(&st.db, Some(id), 6).await?;
let docs = super::documents::chips(&st, id).await?;
let title = view.name.clone();
Ok(page(
&st,
@@ -335,6 +337,7 @@ pub async fn show(
tab => "overview",
passports,
addresses,
docs,
recent,
stay => assessment.stay,
deadlines => assessment.items,
+3
View File
@@ -86,6 +86,7 @@ pub async fn stay(st: Arc<AppState>, user: User, id: i64) -> Res {
});
}
let assessment = deadlines::for_person(&st.db, id, today).await?;
let docs = super::documents::chips(&st, id).await?;
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
let title = format!("Visa and stay: {}", view.name);
Ok(page(
@@ -99,6 +100,7 @@ pub async fn stay(st: Arc<AppState>, user: User, id: i64) -> Res {
p => view,
tab => "stay",
sections,
docs,
stay => assessment.stay,
deadlines => assessment.items,
},
@@ -235,6 +237,7 @@ fn entry<'a>(
entity: kind.entity,
entity_id: Some(record),
person_id: Some(person),
company_id: None,
fields,
}
}