//! 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 { 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>, &'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 = 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"".to_vec(); let cases: Vec = 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 = 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!("