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

+442
View File
@@ -9,6 +9,8 @@ use sqlx::PgPool;
use crate::audit::{self, Action, Entity, Entry};
use crate::dates;
use crate::documents::{self, Meta, NewFile, Owner};
use crate::files::{self, Store};
use crate::mrz;
use crate::people::{self, AddressInput, PassportInput, PersonInput};
use crate::records::{self, Kind, Values};
@@ -534,6 +536,7 @@ fn seeded(action: Action, entity: Entity, id: i64, person: Option<i64>) -> Entry
entity,
entity_id: Some(id),
person_id: person,
company_id: None,
fields: &[],
}
}
@@ -616,3 +619,442 @@ pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
tx.commit().await?;
Ok(true)
}
/// A demo document to add: whose, its kind, its record, its date, the
/// file's name and the file.
type Planned = (
Owner,
&'static str,
Option<String>,
Option<NaiveDate>,
String,
Vec<u8>,
);
/// A demo document's picture.
#[derive(Clone, Copy)]
enum Picture {
PassportPage,
Portrait,
Office,
}
/// Adds invented documents to the demo people and companies, unless the
/// seed added documents before: scans as PDF (text pages that say they are
/// demos) and pictures as PNG (shapes, no one's likeness). Returns how many.
pub async fn demo_documents(db: &PgPool, store: &Store, today: NaiveDate) -> Result<usize> {
let present: bool =
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM documents WHERE uploaded_by = 'seed')")
.fetch_one(db)
.await?;
if present {
return Ok(0);
}
let people: Vec<(i64, String, String)> = sqlx::query_as(
"SELECT id, upper(surname), first_name FROM people \
WHERE notes = $1 AND archived_at IS NULL ORDER BY id",
)
.bind(MARKER)
.fetch_all(db)
.await?;
let latest = |table: &'static str, order: &'static str| {
format!(
"SELECT id FROM {table} WHERE person_id = $1 ORDER BY {order} DESC, id DESC LIMIT 1"
)
};
let mut plan: Vec<Planned> = Vec::new();
for (n, (id, surname, given)) in people.iter().enumerate() {
let whose = format!("{surname}, {given}");
let one = |sql: String| {
let id = *id;
async move {
sqlx::query_scalar::<_, i64>(&sql)
.bind(id)
.fetch_optional(db)
.await
}
};
let owner = Owner::Person(*id);
if let Some(pp) = one(latest("passports", "expires_on")).await? {
plan.push((
owner,
"passport-photo-page",
Some(format!("passports:{pp}")),
None,
"passport-photo-page.png".into(),
demo_png(Picture::PassportPage),
));
}
if let Some(a) = one(latest("arrivals", "arrived_on")).await? {
plan.push((
owner,
"tdac",
Some(format!("arrivals:{a}")),
None,
"TDAC.pdf".into(),
demo_pdf(
"Thailand Digital Arrival Card",
&[
format!("Traveller: {whose}"),
"Arrival card number: TDAC-DEMO".into(),
],
),
));
}
if let Some(r) = one(latest("ninety_day_reports", "reported_on")).await? {
plan.push((
owner,
"ninety-day-receipt",
Some(format!("reports:{r}")),
None,
"TM47 receipt.pdf".into(),
demo_pdf(
"Receipt of notification of staying over 90 days",
&[format!("Name: {whose}"), "Form TM.47, filed online".into()],
),
));
}
if n == 0 {
plan.push((
owner,
"photo",
None,
Some(today - TimeDelta::days(20)),
"photo 4x6.png".into(),
demo_png(Picture::Portrait),
));
if let Some(a) = one(latest("addresses", "moved_in_on")).await? {
plan.push((
owner,
"tm30-receipt",
Some(format!("addresses:{a}")),
None,
"TM30 receipt.pdf".into(),
demo_pdf(
"Receipt of notification of residence (TM.30)",
&[
format!("Foreigner: {whose}"),
"Notified by the house master".into(),
],
),
));
}
}
}
let companies: Vec<(i64, String)> =
sqlx::query_as("SELECT id, name FROM companies WHERE notes = $1 ORDER BY id LIMIT 1")
.bind(MARKER)
.fetch_all(db)
.await?;
for (id, name) in companies {
let owner = Owner::Company(id);
plan.push((
owner,
"company-certificate",
None,
Some(today - TimeDelta::days(40)),
"company certificate.pdf".into(),
demo_pdf(
"Company certificate (certified copy)",
&[
format!("Company: {name}"),
"Certified by the registrar".into(),
],
),
));
// older than six months: out of date for the pack (phase 6)
plan.push((
owner,
"shareholders",
None,
Some(today - TimeDelta::days(240)),
"BOJ5.pdf".into(),
demo_pdf(
"List of shareholders (BOJ.5)",
&[
format!("Company: {name}"),
"Shareholders as of the last meeting".into(),
],
),
));
plan.push((
owner,
"office-photo",
None,
None,
"office outside.png".into(),
demo_png(Picture::Office),
));
}
let mut tx = db.begin().await?;
let mut written = Vec::new();
for (owner, kind, link, dated_on, name, bytes) in &plan {
let meta = Meta {
kind: (*kind).to_string(),
link: link.as_deref().and_then(documents::parse_link),
dated_on: *dated_on,
note: "Demo file".into(),
};
let sha256 = files::sha256_hex(bytes);
let file = NewFile {
name,
content_type: files::sniff(bytes).expect("demo files have a known type"),
size: i32::try_from(bytes.len())?,
sha256: &sha256,
};
let id = documents::insert(&mut tx, *owner, &meta, &file, "seed").await?;
store.put(id, bytes)?;
written.push(id);
audit::record(
&mut *tx,
&Entry {
actor: "seed",
action: Action::Create,
entity: Entity::Document,
entity_id: Some(id),
person_id: owner.person(),
company_id: owner.company(),
fields: &[],
},
)
.await?;
}
tx.commit().await?;
Ok(written.len())
}
/// A one-page PDF in the app's colours: a title, a few lines and the demo
/// marker. ASCII text in Helvetica, so it needs no embedded font.
pub fn demo_pdf(title: &str, lines: &[String]) -> Vec<u8> {
let esc = |s: &str| {
s.chars()
.filter(char::is_ascii)
.collect::<String>()
.replace('\\', "\\\\")
.replace('(', "\\(")
.replace(')', "\\)")
};
let mut content =
String::from("0.027 0.075 0.137 rg 0 762 595 80 re f\n0.961 0.753 0 rg 0 756 595 6 re f\n");
content.push_str(&format!(
"BT /F1 18 Tf 1 1 1 rg 48 792 Td ({}) Tj ET\n",
esc(title)
));
let mut y = 700;
for line in lines {
content.push_str(&format!(
"BT /F1 12 Tf 0.1 0.1 0.1 rg 48 {y} Td ({}) Tj ET\n",
esc(line)
));
y -= 22;
}
content.push_str(&format!(
"BT /F1 26 Tf 0.85 0.2 0.2 rg 48 520 Td (SPECIMEN) Tj ET\n\
BT /F1 10 Tf 0.4 0.4 0.4 rg 48 60 Td ({}) Tj ET\n",
esc(MARKER)
));
let objects = [
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] \
/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>"
.to_string(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"
.to_string(),
format!(
"<< /Length {} >>\nstream\n{content}endstream",
content.len()
),
];
let mut out = b"%PDF-1.4\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objects.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
}
let xref = out.len();
out.extend_from_slice(
format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
);
for o in offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",
objects.len() + 1
)
.as_bytes(),
);
out
}
/// A picture made of shapes, as a PNG with a palette.
fn demo_png(picture: Picture) -> Vec<u8> {
const PALETTE: [[u8; 3]; 8] = [
[0xf3, 0xef, 0xe2], // paper
[0x07, 0x13, 0x23], // navy
[0xf5, 0xc0, 0x00], // gold
[0x9b, 0xa8, 0xba], // grey
[0xd8, 0xdd, 0xe5], // light grey
[0xff, 0xff, 0xff], // white
[0x3a, 0x45, 0x56], // ink
[0xa9, 0xc8, 0xe8], // sky
];
let (w, h) = match picture {
Picture::PassportPage => (600usize, 420usize),
Picture::Portrait => (240, 360),
Picture::Office => (480, 320),
};
let mut px = vec![0u8; w * h];
let mut fill = |x0: usize, y0: usize, x1: usize, y1: usize, c: u8| {
for y in y0.min(h)..y1.min(h) {
for x in x0.min(w)..x1.min(w) {
px[y * w + x] = c;
}
}
};
let head = |cx: f64, cy: f64, r: f64, x: usize, y: usize| {
let (dx, dy) = (x as f64 - cx, (y as f64 - cy) * 0.85);
dx * dx + dy * dy <= r * r
};
match picture {
Picture::PassportPage => {
fill(0, 0, w, 56, 1);
fill(0, 56, w, 62, 2);
fill(30, 92, 170, 282, 4);
for (i, len) in [220usize, 160, 250, 140, 200, 120].iter().enumerate() {
let y = 100 + i * 30;
fill(200, y, 200 + len, y + 12, 6);
}
fill(0, 320, w, h, 5);
for row in 0..2 {
for cell in 0..44 {
let (x, y) = (24 + cell * 12, 338 + row * 34);
fill(x, y, x + 9, y + 18, 6);
}
}
}
Picture::Portrait => {
fill(0, 0, w, h, 4);
fill(40, 270, 200, h, 1);
}
Picture::Office => {
fill(0, 0, w, 200, 7);
fill(0, 260, w, h, 3);
fill(90, 70, 390, 260, 0);
fill(90, 62, 390, 72, 1);
for col in 0..5 {
for row in 0..3 {
let (x, y) = (112 + col * 56, 92 + row * 52);
fill(x, y, x + 32, y + 30, 1);
}
}
fill(212, 200, 268, 260, 2);
}
}
if let Picture::Portrait = picture {
for y in 0..h {
for x in 0..w {
if head(120.0, 150.0, 62.0, x, y) {
px[y * w + x] = 3;
}
}
}
}
if let Picture::PassportPage = picture {
for y in 92..282 {
for x in 30..170 {
if head(100.0, 160.0, 40.0, x, y) {
px[y * w + x] = 3;
}
}
}
for y in 230..282 {
for x in 50..150 {
px[y * w + x] = 3;
}
}
}
// the image data: each row with filter 0, in stored deflate blocks
let mut raw = Vec::with_capacity(h * (w + 1));
for row in px.chunks(w) {
raw.push(0);
raw.extend_from_slice(row);
}
let mut z = vec![0x78, 0x01];
let blocks: Vec<&[u8]> = raw.chunks(65_535).collect();
for (i, b) in blocks.iter().enumerate() {
z.push(u8::from(i + 1 == blocks.len()));
let len = b.len() as u16;
z.extend_from_slice(&len.to_le_bytes());
z.extend_from_slice(&(!len).to_le_bytes());
z.extend_from_slice(b);
}
z.extend_from_slice(&adler32(&raw).to_be_bytes());
let mut ihdr = Vec::new();
ihdr.extend_from_slice(&(w as u32).to_be_bytes());
ihdr.extend_from_slice(&(h as u32).to_be_bytes());
ihdr.extend_from_slice(&[8, 3, 0, 0, 0]);
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
chunk(&mut out, b"IHDR", &ihdr);
chunk(&mut out, b"PLTE", &PALETTE.concat());
chunk(&mut out, b"IDAT", &z);
chunk(&mut out, b"IEND", &[]);
out
}
fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(kind);
out.extend_from_slice(data);
let mut crc = 0xFFFF_FFFFu32;
for &b in kind.iter().chain(data) {
crc ^= u32::from(b);
for _ in 0..8 {
crc = if crc & 1 == 1 {
(crc >> 1) ^ 0xEDB8_8320
} else {
crc >> 1
};
}
}
out.extend_from_slice(&(!crc).to_be_bytes());
}
fn adler32(data: &[u8]) -> u32 {
let (mut a, mut b) = (1u32, 0u32);
for &x in data {
a = (a + u32::from(x)) % 65_521;
b = (b + a) % 65_521;
}
(b << 16) | a
}
#[cfg(test)]
mod demo_file_tests {
use super::*;
#[test]
fn demo_files_are_what_they_say() {
let pdf = demo_pdf("Title (demo)", &["Line".to_string()]);
assert_eq!(files::sniff(&pdf), Some("application/pdf"));
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains(MARKER));
assert!(text.contains("Title \\(demo\\)"));
// the cross-reference table points at the objects
let xref: usize = text
.rsplit("startxref\n")
.next()
.and_then(|t| t.lines().next())
.and_then(|n| n.parse().ok())
.unwrap();
assert!(text[xref..].starts_with("xref"));
for p in [Picture::PassportPage, Picture::Portrait, Picture::Office] {
let png = demo_png(p);
assert_eq!(files::sniff(&png), Some("image/png"));
assert!(png.ends_with(&[0xAE, 0x42, 0x60, 0x82]), "IEND's CRC");
}
assert_eq!(adler32(b"Wikipedia"), 0x11E6_0398);
}
}