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 {
+612
View File
@@ -0,0 +1,612 @@
//! Documents: uploads into the encrypted store, opening and downloading,
//! changes, deletion, company documents, the checks before anything is
//! stored, and the audit trail of every step.
use axum::http::StatusCode;
use sqlx::PgPool;
use visa::config::{Auth, Config};
use visa::documents::{self, Owner};
use visa::web::documents::FILE_LIMIT;
use crate::common::{App, Part, config, id_from, local, pdf, with_config};
async fn person(app: &App, surname: &str) -> i64 {
let r = app
.post(
"/people",
&[
("action", "save"),
("surname", surname),
("first_name", "Jane"),
("nationality", "USA"),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
id_from(r.location())
}
async fn passport(app: &App, person: i64, number: &str) -> i64 {
let r = app
.post(
&format!("/people/{person}/passports"),
&[
("number", number),
("issuing_country", "USA"),
("expires_on", "2034-05-01"),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
sqlx::query_scalar("SELECT id FROM passports WHERE person_id = $1 AND number = $2")
.bind(person)
.bind(number)
.fetch_one(&app.pool)
.await
.unwrap()
}
/// The audit entries about documents: action, id and field names.
async fn trail(pool: &PgPool) -> Vec<String> {
sqlx::query_scalar(
"SELECT action || ' ' || entity_id || ' ' || array_to_string(fields, ',') \
FROM audit_log WHERE entity = 'document' ORDER BY id",
)
.fetch_all(pool)
.await
.unwrap()
}
async fn count(pool: &PgPool) -> i64 {
sqlx::query_scalar("SELECT count(*) FROM documents")
.fetch_one(pool)
.await
.unwrap()
}
/// An upload that is refused: its fields, its files and what the page says.
type Refusal<'a> = (Vec<(&'a str, &'a str)>, Vec<(&'a str, &'a [u8])>, &'a str);
/// A forged upload: its parts, its headers, the answer and what it says.
type Forged<'a> = (Vec<Part<'a>>, &'a [(&'a str, &'a str)], StatusCode, &'a str);
fn stored(app: &App) -> usize {
let store = app.st.files.as_ref().unwrap();
let (ids, other) = store.entries().unwrap();
ids.len() + other.len()
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn a_scan_is_stored_encrypted_and_every_step_is_audited(pool: PgPool) {
let app = local(pool.clone());
let id = person(&app, "Doe").await;
let pp = passport(&app, id, "X1234567").await;
let scan = pdf("the photo page of a passport");
let link = format!("passports:{pp}");
let r = app
.upload(
&format!("/people/{id}/documents"),
&[
("kind", "passport-photo-page"),
("link", &link),
("dated_on", ""),
("note", "front cover too"),
],
&[("C:\\Scans\\pass port.pdf", &scan)],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
let did: i64 = sqlx::query_scalar("SELECT id FROM documents WHERE person_id = $1")
.bind(id)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(r.location(), format!("/people/{id}/documents#doc-{did}"));
// on the disk only encrypted, under the document's id
let store = app.st.files.as_ref().unwrap();
let on_disk = std::fs::read(store.path(did)).unwrap();
assert!(on_disk.starts_with(b"VISADOC1"));
assert!(!on_disk.windows(10).any(|w| w == b"photo page"));
// listed on the tab, and next to its passport on the overview
let t = app.get(&format!("/people/{id}/documents")).await.text();
for want in [
"Passport photo page",
"pass port.pdf",
"Passport: X1234567",
"front cover too",
] {
assert!(t.contains(want), "{want}: {t}");
}
let file = format!("/people/{id}/documents/{did}/file");
let t = app.get(&format!("/people/{id}")).await.text();
assert!(t.contains(&format!("href=\"{file}\"")), "{t}");
// opened: the same bytes, its own policy, not kept in caches
let r = app.get(&file).await;
assert_eq!(r.status, StatusCode::OK);
assert_eq!(r.bytes, scan);
assert_eq!(r.header("content-type"), "application/pdf");
assert!(
r.header("content-disposition")
.starts_with("inline; filename=\"DOE Jane - Passport photo page - "),
"{}",
r.header("content-disposition")
);
assert_eq!(r.header("cache-control"), "private, no-store");
assert!(
r.header("content-security-policy")
.starts_with("default-src 'none'")
);
assert_eq!(r.header("x-content-type-options"), "nosniff");
let r = app.get(&format!("{file}?download=1")).await;
assert_eq!(r.status, StatusCode::OK);
assert!(r.header("content-disposition").starts_with("attachment; "));
// the page about it, and a change
let r = app.get(&format!("/people/{id}/documents/{did}/edit")).await;
assert_eq!(r.status, StatusCode::OK);
assert!(r.text().contains("Delete this document"), "{}", r.body);
let r = app
.post(
&format!("/people/{id}/documents/{did}"),
&[
("kind", "other"),
("link", ""),
("dated_on", "2026-11-02"),
("note", "front cover too"),
],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
assert_eq!(r.location(), format!("/people/{id}/documents#doc-{did}"));
// deleted: the row and the file
let r = app
.post(&format!("/people/{id}/documents/{did}/delete"), &[])
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER);
assert!(!store.path(did).exists());
assert_eq!(count(&pool).await, 0);
assert_eq!(app.get(&file).await.status, StatusCode::NOT_FOUND);
assert_eq!(
trail(&pool).await,
[
format!("create {did} kind,file,passport_id,note"),
format!("view {did} file"),
format!("download {did} file"),
format!("view {did} "),
format!("update {did} dated_on,kind,passport_id"),
format!("delete {did} "),
]
);
// names of fields only, never what they hold
let logged: Vec<String> =
sqlx::query_scalar("SELECT array_to_string(fields, ',') FROM audit_log")
.fetch_all(&pool)
.await
.unwrap();
assert!(
!logged
.iter()
.any(|f| f.contains("front") || f.contains("port.pdf"))
);
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn uploads_are_checked_before_anything_is_stored(pool: PgPool) {
let app = local(pool.clone());
let id = person(&app, "Doe").await;
let other = person(&app, "Roe").await;
let theirs = format!("passports:{}", passport(&app, other, "Y7654321").await);
let base = format!("/people/{id}/documents");
let scan = pdf("a receipt");
let mut big = pdf("large");
big.resize(FILE_LIMIT + 1, b' ');
let html = b"<html><script>alert(1)</script></html>".to_vec();
let cases: Vec<Refusal> = vec![
(vec![("kind", "photo")], vec![], "Choose a file to upload."),
(
vec![("kind", "photo")],
vec![("scan.pdf", html.as_slice())],
"scan.pdf is not a PDF, JPEG, PNG or WebP file.",
),
(
vec![("kind", "photo")],
vec![("empty.pdf", &b""[..])],
"empty.pdf is empty.",
),
(
vec![("kind", "photo")],
vec![("big.pdf", big.as_slice())],
"big.pdf is larger than 20 MB.",
),
(
vec![("kind", "photo")],
vec![("a.pdf", scan.as_slice()), ("b.pdf", scan.as_slice())],
"b.pdf is in this upload twice.",
),
(
vec![("kind", "passport")],
vec![("a.pdf", scan.as_slice())],
"Choose what the document is.",
),
(
vec![("kind", "company-certificate")],
vec![("a.pdf", scan.as_slice())],
"Choose what the document is.",
),
(
vec![("kind", "passport-photo-page"), ("link", &theirs)],
vec![("a.pdf", scan.as_slice())],
"Choose one of this person's records, or none.",
),
(
vec![("kind", "photo"), ("link", "people:1")],
vec![("a.pdf", scan.as_slice())],
"Choose one of this person's records, or none.",
),
(
vec![("kind", "photo"), ("dated_on", "0026-11-12")],
vec![("a.pdf", scan.as_slice())],
"Enter a year from 1900 to 2100.",
),
];
for (fields, files, want) in &cases {
let r = app.upload(&base, fields, files).await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY, "{want}");
let t = r.text();
assert!(t.contains(want), "{want}: {t}");
assert!(t.contains("Nothing was uploaded"), "{want}");
}
assert_eq!(count(&pool).await, 0);
assert_eq!(stored(&app), 0);
// the same file again for the same person
let r = app
.upload(&base, &[("kind", "tm30-receipt")], &[("a.pdf", &scan)])
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
let r = app
.upload(&base, &[("kind", "other")], &[("copy.pdf", &scan)])
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(
r.text()
.contains("copy.pdf is here already: TM.30 receipt, added"),
"{}",
r.text()
);
// another person may have the same file
let r = app
.upload(
&format!("/people/{other}/documents"),
&[("kind", "other")],
&[("a.pdf", &scan)],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
assert_eq!(count(&pool).await, 2);
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn an_upload_needs_the_form_token_first_and_this_site(pool: PgPool) {
let app = local(pool.clone());
let id = person(&app, "Doe").await;
let base = format!("/people/{id}/documents");
let scan = pdf("a scan");
let token = app.st.local_csrf().to_string();
let same = [("sec-fetch-site", "same-origin")];
let refused: Vec<Forged> = vec![
// no token
(
vec![Part::field("kind", b"photo"), Part::file("a.pdf", &scan)],
&same,
StatusCode::FORBIDDEN,
"has expired",
),
// the token after a file: the file would be read first
(
vec![
Part::file("a.pdf", &scan),
Part::field("csrf", token.as_bytes()),
Part::field("kind", b"photo"),
],
&same,
StatusCode::FORBIDDEN,
"has expired",
),
// a wrong token
(
vec![
Part::field("csrf", b"not-the-token"),
Part::field("kind", b"photo"),
Part::file("a.pdf", &scan),
],
&same,
StatusCode::FORBIDDEN,
"has expired",
),
// from another site, with the right token
(
vec![
Part::field("csrf", token.as_bytes()),
Part::field("kind", b"photo"),
Part::file("a.pdf", &scan),
],
&[("sec-fetch-site", "cross-site")],
StatusCode::FORBIDDEN,
"from another site",
),
];
for (parts, headers, status, want) in &refused {
let r = app.upload_raw(&base, parts, headers).await;
assert_eq!(r.status, *status, "{want}: {}", r.body);
assert!(r.text().contains(want), "{want}: {}", r.body);
}
// an address that takes no uploads
let parts = [
Part::field("csrf", token.as_bytes()),
Part::field("surname", b"Roe"),
];
let r = app.upload_raw("/people", &parts, &same).await;
assert_eq!(r.status, StatusCode::UNSUPPORTED_MEDIA_TYPE);
// an upload to someone who does not exist
let r = app
.upload(
"/people/999999/documents",
&[("kind", "photo")],
&[("a.pdf", &scan)],
)
.await;
assert_eq!(r.status, StatusCode::NOT_FOUND);
assert_eq!(count(&pool).await, 0);
assert_eq!(stored(&app), 0);
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn several_files_at_once_next_to_their_record(pool: PgPool) {
visa::seed::demo(&pool, visa::dates::today()).await.unwrap();
let app = local(pool.clone());
let erika: i64 = sqlx::query_scalar("SELECT id FROM people WHERE surname = 'Mustermann'")
.fetch_one(&pool)
.await
.unwrap();
let arrival: i64 = sqlx::query_scalar(
"SELECT id FROM arrivals WHERE person_id = $1 ORDER BY arrived_on DESC LIMIT 1",
)
.bind(erika)
.fetch_one(&pool)
.await
.unwrap();
let link = format!("arrivals:{arrival}");
// the stay tab offers to add one to the arrival, and the form knows it
let t = app.get(&format!("/people/{erika}/stay")).await.text();
let add = format!("/people/{erika}/documents?for={link}#upload");
assert!(t.contains(&add), "{t}");
let t = app
.get(&format!("/people/{erika}/documents?for={link}"))
.await
.text();
assert!(
t.contains(&format!("<option value=\"{link}\" selected>")),
"{t}"
);
assert!(
t.contains("<option value=\"arrival-stamp\" selected>"),
"{t}"
);
let stamp = [0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10, b'J', b'F', b'I', b'F', 0];
let page2 = pdf("page 2");
let r = app
.upload(
&format!("/people/{erika}/documents"),
&[("kind", "arrival-stamp"), ("link", &link)],
&[("stamp.jpg", &stamp), ("page 2.pdf", &page2)],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
let docs = documents::list(&pool, Owner::Person(erika)).await.unwrap();
assert_eq!(docs.len(), 2);
assert!(docs.iter().all(|d| d.arrival_id == Some(arrival)));
let types: Vec<&str> = docs.iter().map(|d| d.content_type.as_str()).collect();
assert!(types.contains(&"image/jpeg") && types.contains(&"application/pdf"));
// both next to the arrival on the stay tab
let t = app.get(&format!("/people/{erika}/stay")).await.text();
for d in &docs {
assert!(
t.contains(&format!("/people/{erika}/documents/{}/file", d.id)),
"{t}"
);
}
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn a_company_keeps_its_own_documents(pool: PgPool) {
visa::seed::demo(&pool, visa::dates::today()).await.unwrap();
let app = local(pool.clone());
let company: i64 =
sqlx::query_scalar("SELECT id FROM companies WHERE name = 'Demo Engineering Co., Ltd.'")
.fetch_one(&pool)
.await
.unwrap();
let base = format!("/companies/{company}/documents");
let cert = pdf("company certificate");
// a person's kind is not a company's
let r = app
.upload(
&base,
&[("kind", "passport-photo-page")],
&[("c.pdf", &cert)],
)
.await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
assert!(r.text().contains("Choose what the document is."));
let r = app
.upload(
&base,
&[("kind", "company-certificate"), ("dated_on", "2026-10-01")],
&[("certificate.pdf", &cert)],
)
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
let did: i64 = sqlx::query_scalar("SELECT id FROM documents WHERE company_id = $1")
.bind(company)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(r.location(), format!("/companies/{company}#doc-{did}"));
let t = app.get(&format!("/companies/{company}")).await.text();
assert!(
t.contains("Company certificate") && t.contains("Oct 1, 2026"),
"{t}"
);
let r = app.get(&format!("{base}/{did}/file?download=1")).await;
assert_eq!(r.bytes, cert);
assert!(
r.header("content-disposition")
.contains("Demo Engineering Co., Ltd. - Company certificate - 2026-10-01.pdf"),
"{}",
r.header("content-disposition")
);
// another company's address does not reach it
assert_eq!(
app.get(&format!("/people/1/documents/{did}/file"))
.await
.status,
StatusCode::NOT_FOUND
);
// the audit log names the company; the activity page shows it
let (person, comp): (Option<i64>, Option<i64>) = sqlx::query_as(
"SELECT person_id, company_id FROM audit_log WHERE action = 'download' AND entity_id = $1",
)
.bind(did)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!((person, comp), (None, Some(company)));
let t = app.get("/activity").await.text();
assert!(t.contains(&format!("document {did}")), "{t}");
assert!(t.contains("Demo Engineering Co., Ltd."));
let r = app.get(&format!("{base}/{did}/edit")).await;
assert_eq!(r.status, StatusCode::OK);
let r = app.post(&format!("{base}/{did}/delete"), &[]).await;
assert_eq!(r.location(), format!("/companies/{company}"));
assert_eq!(count(&pool).await, 0);
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn a_file_cannot_pass_for_another_and_the_check_finds_it(pool: PgPool) {
let app = local(pool.clone());
let id = person(&app, "Doe").await;
let base = format!("/people/{id}/documents");
let (a, b) = (pdf("first"), pdf("second"));
let r = app
.upload(&base, &[("kind", "other")], &[("a.pdf", &a), ("b.pdf", &b)])
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
let ids: Vec<i64> = sqlx::query_scalar("SELECT id FROM documents ORDER BY id")
.fetch_all(&pool)
.await
.unwrap();
let store = app.st.files.as_ref().unwrap();
assert!(
documents::check(&pool, store)
.await
.unwrap()
.problems
.is_empty()
);
// the two files swapped on the disk
let (pa, pb) = (store.path(ids[0]), store.path(ids[1]));
let tmp = pa.with_extension("swap");
std::fs::rename(&pa, &tmp).unwrap();
std::fs::rename(&pb, &pa).unwrap();
std::fs::rename(&tmp, &pb).unwrap();
let r = app.get(&format!("{base}/{}/file", ids[0])).await;
assert_eq!(r.status, StatusCode::INTERNAL_SERVER_ERROR);
assert!(r.text().contains("cannot be opened"), "{}", r.body);
assert!(!r.bytes.windows(6).any(|w| w == b"second"));
std::fs::write(store.dir().join("77.vdoc"), b"left over").unwrap();
let check = documents::check(&pool, store).await.unwrap();
assert_eq!(check.documents, 2);
assert_eq!(check.problems.len(), 3, "{:?}", check.problems);
assert!(check.problems[0].contains("damaged, or the file of another document"));
assert!(check.problems[2].contains("77.vdoc: a file without its document"));
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn without_a_files_directory_documents_are_off(pool: PgPool) {
let cfg = Config {
files: None,
..config(Auth::Disabled)
};
let app = with_config(pool.clone(), cfg);
let id = person(&app, "Doe").await;
let r = app.get(&format!("/people/{id}/documents")).await;
assert_eq!(r.status, StatusCode::OK);
assert!(
r.text().contains("Documents are switched off"),
"{}",
r.body
);
let r = app
.upload(
&format!("/people/{id}/documents"),
&[("kind", "photo")],
&[("a.pdf", &pdf("x"))],
)
.await;
assert_eq!(r.status, StatusCode::SERVICE_UNAVAILABLE);
}
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn the_demo_documents_open_as_what_they_are(pool: PgPool) {
let today = visa::dates::today();
visa::seed::demo(&pool, today).await.unwrap();
let app = local(pool.clone());
let store = app.st.files.as_ref().unwrap();
let n = visa::seed::demo_documents(&pool, store, today)
.await
.unwrap();
assert!(n >= 8, "{n}");
assert_eq!(
visa::seed::demo_documents(&pool, store, today)
.await
.unwrap(),
0,
"seeded once"
);
let rows: Vec<(i64, Option<i64>, Option<i64>, String)> =
sqlx::query_as("SELECT id, person_id, company_id, content_type FROM documents ORDER BY id")
.fetch_all(&pool)
.await
.unwrap();
for (id, person, company, ct) in rows {
let url = match (person, company) {
(Some(p), _) => format!("/people/{p}/documents/{id}/file"),
(None, Some(c)) => format!("/companies/{c}/documents/{id}/file"),
_ => unreachable!(),
};
let r = app.get(&url).await;
assert_eq!(r.status, StatusCode::OK, "{url}");
assert_eq!(r.header("content-type"), ct);
assert_eq!(visa::files::sniff(&r.bytes), Some(ct.as_str()));
}
assert!(
documents::check(&pool, store)
.await
.unwrap()
.problems
.is_empty()
);
}
+1
View File
@@ -6,6 +6,7 @@ mod auth;
mod common;
mod companies;
mod deadlines;
mod documents;
mod pages;
mod people;
mod records;
+37 -1
View File
@@ -65,6 +65,26 @@ async fn every_page_renders_with_demo_data(pool: PgPool) {
.fetch_one(&pool)
.await
.unwrap();
let store = app.st.files.as_ref().unwrap();
assert!(
visa::seed::demo_documents(&pool, store, visa::dates::today())
.await
.unwrap()
> 0
);
let doc: i64 = sqlx::query_scalar(
"SELECT id FROM documents WHERE person_id = $1 AND kind = 'passport-photo-page'",
)
.bind(erika)
.fetch_one(&pool)
.await
.unwrap();
let company_doc: i64 =
sqlx::query_scalar("SELECT id FROM documents WHERE company_id = $1 ORDER BY id LIMIT 1")
.bind(company)
.fetch_one(&pool)
.await
.unwrap();
let mut pages = vec![
("/".to_string(), "90-day report".to_string()),
@@ -97,12 +117,24 @@ async fn every_page_renders_with_demo_data(pool: PgPool) {
("/companies/new".to_string(), "New company".to_string()),
(
format!("/companies/{company}"),
"People employed".to_string(),
"Company certificate".to_string(),
),
(
format!("/companies/{company}/edit"),
"0999999000004".to_string(),
),
(
format!("/people/{erika}/documents"),
"Passport photo page".to_string(),
),
(
format!("/people/{erika}/documents/{doc}/edit"),
"passport-photo-page.png".to_string(),
),
(
format!("/companies/{company}/documents/{company_doc}/edit"),
"About the document".to_string(),
),
];
for kind in visa::records::STAY {
pages.push((
@@ -187,6 +219,10 @@ async fn open_paths_headers_and_not_found(pool: PgPool) {
app.get("/static/nope.css").await.status,
StatusCode::NOT_FOUND
);
// an image or a PDF opened in the browser asks for the icon here
let icon = app.get("/favicon.ico").await;
assert_eq!(icon.status, StatusCode::OK);
assert_eq!(icon.headers["content-type"], "image/svg+xml");
let r = app.get("/").await;
assert_eq!(r.status, StatusCode::OK);