Files
visa/tests/documents.rs
T
grabowski 0370e0154f
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 52s
Documents in a bucket of Garage, still encrypted by the app
Asked for on November 19, 2026: the uploaded files land in an S3 bucket of
the fleet's Garage instead of a directory on cnx01, as the fleet's other
apps keep theirs. The app encrypts each file exactly as before (AES-256-GCM
under a key from HKDF, the document's id authenticated), so the bucket holds
the same VISADOC1 files and Garage never sees a key or a document in the
clear. Garage's SSE-C stays off: its key would come from the same secret.

src/s3.rs is a small S3 client on reqwest and ring, as in proplan: SigV4
(checked against AWS's two published examples), path-style PUT, GET, HEAD,
DELETE and ListObjectsV2 page by page, three attempts when the server is
away or busy. It asks before it writes, so no object is replaced; it sends
If-None-Match: * as well, which Garage 2.5 ignores (seen in tests/garage.rs).

The store (src/files.rs) keeps the files as documents/<id>.vdoc in the
bucket, or as <id>.vdoc in a directory for development and the tests. Its
calls are async now. VISA_S3_BUCKET, _ENDPOINT, _REGION and _ACCESS_KEY_ID
name the bucket, the secret comes from VISA_S3_SECRET_ACCESS_KEY_FILE or the
credential s3-secret; the bucket and a directory together are refused. At
the start the app checks the bucket in the background and only warns.

New commands: `visa files-migrate --from DIR` copies the files of a
directory into the store, each opened and compared with its upload before
and after, and may run again; `visa files-mirror --to DIR` makes a
directory hold exactly the bucket's files, still encrypted, for the
backups, and a restore is files-migrate from it.

Tests: an S3 server inside the test process that checks every request's
signature and pages its listings (tests/common/fake_s3.rs); uploads, views,
downloads and deletions through it, the check finding swapped, missing and
stray objects, the move from a directory (again, missing, other bytes,
damaged), the mirror and a restore from it, a busy server and a wrong key.
tests/garage.rs runs the store against Garage 2.5.0, the version cnx01 runs,
which scripts/dev-garage.sh starts in Docker; VISA_DEV_S3=1 scripts/dev.sh
runs the dev server on it. The 14 demo documents moved into it with
files-migrate and a browser upload landed there.
2026-11-19 20:35:32 +07:00

690 lines
24 KiB
Rust

//! 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};
pub 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);
async fn stored(app: &App) -> usize {
let store = app.st.files.as_ref().unwrap();
let e = store.entries().await.unwrap();
e.files.len() + e.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.dir().unwrap().join(format!("{did}.vdoc"))).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.get_sealed(did).await.unwrap().is_none());
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).await, 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).await, 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 dir = store.dir().unwrap();
let (pa, pb) = (
dir.join(format!("{}.vdoc", ids[0])),
dir.join(format!("{}.vdoc", 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(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()
);
}
/// A 1 x 1 PNG.
const DOT_PNG: &[u8] = &[
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00,
0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae,
0x42, 0x60, 0x82,
];
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
async fn the_office_card_takes_a_photo_and_shows_it(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 office = [("kind", "office-photo"), ("back", "office")];
// refused from the card: the card says so, the documents' strip does not
let r = app.upload(&base, &office, &[("office.png", b"")]).await;
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
let t = r.text();
let (card, list) = (
t.find("id=\"office\"").unwrap(),
t.find("id=\"documents\"").unwrap(),
);
let notice = t
.find("Nothing was uploaded")
.expect("the card has the notice");
assert!(
card < notice && notice < list,
"the notice is on the office card"
);
assert_eq!(t.matches("Nothing was uploaded").count(), 1, "{t}");
let r = app.upload(&base, &office, &[("office.png", DOT_PNG)]).await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
assert_eq!(r.location(), format!("/companies/{company}#office"));
let did: i64 = sqlx::query_scalar("SELECT id FROM documents WHERE company_id = $1")
.bind(company)
.fetch_one(&pool)
.await
.unwrap();
let t = app.get(&format!("/companies/{company}")).await.text();
assert!(
t.contains(&format!("<img src=\"{base}/{did}/file\"")),
"the card shows the photo: {t}"
);
assert!(t.contains("Add a newer photo"));
assert!(
t.contains("18.796500, 99.008200"),
"the demo office's position"
);
let r = app.get(&format!("{base}/{did}/file")).await;
assert_eq!(r.bytes, DOT_PNG);
assert_eq!(r.header("content-type"), "image/png");
// a PDF of the office is listed, but the card shows only pictures
let r = app
.upload(&base, &office, &[("office.pdf", &pdf("office plan"))])
.await;
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
let t = app.get(&format!("/companies/{company}")).await.text();
assert!(
t.contains(&format!("<img src=\"{base}/{did}/file\"")),
"{t}"
);
assert!(t.contains("1 more under"), "{t}");
}