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

+593
View File
@@ -0,0 +1,593 @@
//! Documents: scans and photos of a person's papers, and the company
//! documents the extension packs need. A row holds what is known about a
//! file; the file itself lies encrypted in the store (`files.rs`). A
//! person's document may belong to one of their records (a passport, an
//! arrival, a 90-day report ...), and then shows next to that record too.
use std::collections::BTreeSet;
use anyhow::Result;
use chrono::{DateTime, NaiveDate, Utc};
use sqlx::{PgPool, Postgres, Transaction};
use crate::files::{self, Store};
/// Whose document it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Owner {
Person(i64),
Company(i64),
}
impl Owner {
pub fn person(self) -> Option<i64> {
match self {
Owner::Person(id) => Some(id),
Owner::Company(_) => None,
}
}
pub fn company(self) -> Option<i64> {
match self {
Owner::Company(id) => Some(id),
Owner::Person(_) => None,
}
}
/// The address of its documents' pages.
pub fn base(self) -> String {
match self {
Owner::Person(id) => format!("/people/{id}/documents"),
Owner::Company(id) => format!("/companies/{id}/documents"),
}
}
pub fn kinds(self) -> &'static [Kind] {
match self {
Owner::Person(_) => PERSON_KINDS,
Owner::Company(_) => COMPANY_KINDS,
}
}
}
/// A kind of document; `record` is the kind of record it usually belongs to.
#[derive(Debug)]
pub struct Kind {
pub slug: &'static str,
pub label: &'static str,
pub record: Option<&'static str>,
}
const fn k(slug: &'static str, label: &'static str, record: Option<&'static str>) -> Kind {
Kind {
slug,
label,
record,
}
}
/// In the order of the Non-B pack (docs/PLAN.md).
pub const PERSON_KINDS: &[Kind] = &[
k("photo", "Photo, 4 x 6 cm", None),
k(
"passport-photo-page",
"Passport photo page",
Some("passports"),
),
k("visa", "Visa", Some("visas")),
k("arrival-stamp", "Arrival stamp", Some("arrivals")),
k("tdac", "TDAC", Some("arrivals")),
k("extension-stamp", "Extension stamp", Some("extensions")),
k("reentry-permit", "Re-entry permit", Some("reentry-permits")),
k(
"ninety-day-receipt",
"90-day report receipt",
Some("reports"),
),
k("tm30-receipt", "TM.30 receipt", Some("addresses")),
k("work-permit", "Work permit", Some("work-permits")),
k("pnd91", "Income tax return (PND.91)", None),
k("other", "Other", None),
];
/// The company documents of the Non-B pack, in its order.
pub const COMPANY_KINDS: &[Kind] = &[
k("company-certificate", "Company certificate", None),
k("shareholders", "List of shareholders (BOJ.5)", None),
k("balance-sheet", "Balance sheet with PND.50", None),
k("pnd1", "Withholding tax (PND.1)", None),
k("sps1-10", "Social security (SPS 1-10)", None),
k("pp30", "VAT return (PP.30)", None),
k("map", "Map to the office", None),
k("office-photo", "Photo of the office", None),
k("other", "Other", None),
];
pub fn kind(owner: Owner, slug: &str) -> Option<&'static Kind> {
owner.kinds().iter().find(|k| k.slug == slug)
}
pub fn kind_label(owner: Owner, slug: &str) -> String {
kind(owner, slug).map_or_else(|| slug.to_string(), |k| k.label.to_string())
}
/// The first kind that belongs to a kind of record: what a document added
/// from that record is.
pub fn kind_for_link(link: &str) -> Option<&'static Kind> {
PERSON_KINDS.iter().find(|k| k.record == Some(link))
}
/// A kind of record a person's document may belong to; `slug` is the one of
/// its pages (`/people/{id}/arrivals/...`).
#[derive(Debug)]
pub struct Link {
pub slug: &'static str,
pub column: &'static str,
pub table: &'static str,
pub title: &'static str,
}
const fn l(
slug: &'static str,
column: &'static str,
table: &'static str,
title: &'static str,
) -> Link {
Link {
slug,
column,
table,
title,
}
}
pub const LINKS: &[Link] = &[
l("passports", "passport_id", "passports", "Passports"),
l("visas", "visa_id", "visas", "Visas"),
l("arrivals", "arrival_id", "arrivals", "Arrivals"),
l(
"extensions",
"extension_id",
"extensions",
"Extensions of stay",
),
l(
"reentry-permits",
"reentry_permit_id",
"reentry_permits",
"Re-entry permits",
),
l(
"reports",
"report_id",
"ninety_day_reports",
"90-day reports",
),
l(
"addresses",
"address_id",
"addresses",
"Addresses in Thailand",
),
l(
"work-permits",
"work_permit_id",
"work_permits",
"Work permits",
),
];
/// `arrivals:7`, as the forms send it.
pub fn parse_link(value: &str) -> Option<(&'static Link, i64)> {
let (slug, id) = value.split_once(':')?;
let link = LINKS.iter().find(|l| l.slug == slug)?;
let id: i64 = id.parse().ok().filter(|&n| n > 0)?;
Some((link, id))
}
pub fn link_value(link: Option<(&Link, i64)>) -> String {
link.map(|(l, id)| format!("{}:{id}", l.slug))
.unwrap_or_default()
}
#[derive(Clone, Debug, sqlx::FromRow)]
pub struct Document {
pub id: i64,
pub person_id: Option<i64>,
pub company_id: Option<i64>,
pub kind: String,
pub passport_id: Option<i64>,
pub address_id: Option<i64>,
pub visa_id: Option<i64>,
pub arrival_id: Option<i64>,
pub extension_id: Option<i64>,
pub report_id: Option<i64>,
pub reentry_permit_id: Option<i64>,
pub work_permit_id: Option<i64>,
pub dated_on: Option<NaiveDate>,
pub note: String,
pub file_name: String,
pub content_type: String,
pub size_bytes: i32,
pub sha256: String,
pub uploaded_by: String,
pub uploaded_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
impl Document {
pub fn owner(&self) -> Owner {
match (self.person_id, self.company_id) {
(Some(p), _) => Owner::Person(p),
(None, Some(c)) => Owner::Company(c),
// the table's check rules this out
(None, None) => Owner::Person(0),
}
}
/// The record it belongs to, if any.
pub fn link(&self) -> Option<(&'static Link, i64)> {
let ids = [
self.passport_id,
self.visa_id,
self.arrival_id,
self.extension_id,
self.reentry_permit_id,
self.report_id,
self.address_id,
self.work_permit_id,
];
LINKS
.iter()
.zip(ids)
.find_map(|(l, id)| id.map(|id| (l, id)))
}
}
/// What the forms set about a document.
#[derive(Clone, Debug, Default)]
pub struct Meta {
pub kind: String,
pub link: Option<(&'static Link, i64)>,
pub dated_on: Option<NaiveDate>,
pub note: String,
}
impl Meta {
pub fn of(d: &Document) -> Meta {
Meta {
kind: d.kind.clone(),
link: d.link(),
dated_on: d.dated_on,
note: d.note.clone(),
}
}
/// The id for each link column, in the order of `LINKS`.
fn link_ids(&self) -> [Option<i64>; 8] {
let mut ids = [None; 8];
if let Some((link, id)) = self.link
&& let Some(i) = LINKS.iter().position(|l| l.slug == link.slug)
{
ids[i] = Some(id);
}
ids
}
/// The names of the fields a new document sets, for the audit log.
pub fn set_fields(&self) -> Vec<String> {
let mut out = vec!["kind".to_string(), "file".to_string()];
if let Some((link, _)) = self.link {
out.push(link.column.to_string());
}
if self.dated_on.is_some() {
out.push("dated_on".into());
}
if !self.note.is_empty() {
out.push("note".into());
}
out
}
/// The names of the fields a change touches.
pub fn changed(&self, new: &Meta) -> Vec<String> {
let mut out = BTreeSet::new();
if self.kind != new.kind {
out.insert("kind".to_string());
}
let (a, b) = (self.link_ids(), new.link_ids());
for (i, link) in LINKS.iter().enumerate() {
if a[i] != b[i] {
out.insert(link.column.to_string());
}
}
if self.dated_on != new.dated_on {
out.insert("dated_on".into());
}
if self.note != new.note {
out.insert("note".into());
}
out.into_iter().collect()
}
}
/// The file of a new document, as checked.
pub struct NewFile<'a> {
pub name: &'a str,
pub content_type: &'static str,
pub size: i32,
pub sha256: &'a str,
}
/// The newest first within each kind, the kinds in the pack's order.
fn sorted(owner: Owner, mut docs: Vec<Document>) -> Vec<Document> {
let rank = |d: &Document| {
owner
.kinds()
.iter()
.position(|k| k.slug == d.kind)
.unwrap_or(usize::MAX)
};
docs.sort_by(|a, b| {
rank(a)
.cmp(&rank(b))
.then(b.dated_on.cmp(&a.dated_on))
.then(b.id.cmp(&a.id))
});
docs
}
pub async fn list(db: &PgPool, owner: Owner) -> Result<Vec<Document>> {
let docs: Vec<Document> = sqlx::query_as(
"SELECT * FROM documents \
WHERE person_id IS NOT DISTINCT FROM $1 AND company_id IS NOT DISTINCT FROM $2",
)
.bind(owner.person())
.bind(owner.company())
.fetch_all(db)
.await?;
Ok(sorted(owner, docs))
}
pub async fn get(db: &PgPool, owner: Owner, id: i64) -> Result<Option<Document>> {
Ok(sqlx::query_as(
"SELECT * FROM documents WHERE id = $1 \
AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3",
)
.bind(id)
.bind(owner.person())
.bind(owner.company())
.fetch_optional(db)
.await?)
}
/// The same file uploaded before for the same person or company.
pub async fn same_file(db: &PgPool, owner: Owner, sha256: &str) -> Result<Option<Document>> {
Ok(sqlx::query_as(
"SELECT * FROM documents WHERE sha256 = $1 \
AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3 \
ORDER BY id LIMIT 1",
)
.bind(sha256)
.bind(owner.person())
.bind(owner.company())
.fetch_optional(db)
.await?)
}
/// Whether the record is one of this person's.
pub async fn link_is_theirs(db: &PgPool, person: i64, link: &Link, id: i64) -> Result<bool> {
// the table name comes from LINKS, never from the form
let sql = format!(
"SELECT EXISTS (SELECT 1 FROM {} WHERE id = $1 AND person_id = $2)",
link.table
);
Ok(sqlx::query_scalar(&sql)
.bind(id)
.bind(person)
.fetch_one(db)
.await?)
}
pub async fn insert(
tx: &mut Transaction<'_, Postgres>,
owner: Owner,
meta: &Meta,
file: &NewFile<'_>,
by: &str,
) -> Result<i64> {
let ids = meta.link_ids();
let id = sqlx::query_scalar(
"INSERT INTO documents (person_id, company_id, kind, passport_id, visa_id, \
arrival_id, extension_id, reentry_permit_id, report_id, address_id, work_permit_id, \
dated_on, note, file_name, content_type, size_bytes, sha256, uploaded_by) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) \
RETURNING id",
)
.bind(owner.person())
.bind(owner.company())
.bind(&meta.kind)
.bind(ids[0])
.bind(ids[1])
.bind(ids[2])
.bind(ids[3])
.bind(ids[4])
.bind(ids[5])
.bind(ids[6])
.bind(ids[7])
.bind(meta.dated_on)
.bind(&meta.note)
.bind(file.name)
.bind(file.content_type)
.bind(file.size)
.bind(file.sha256)
.bind(by)
.fetch_one(&mut **tx)
.await?;
Ok(id)
}
pub async fn update(
tx: &mut Transaction<'_, Postgres>,
owner: Owner,
id: i64,
meta: &Meta,
) -> Result<()> {
let ids = meta.link_ids();
sqlx::query(
"UPDATE documents SET kind = $4, passport_id = $5, visa_id = $6, arrival_id = $7, \
extension_id = $8, reentry_permit_id = $9, report_id = $10, address_id = $11, \
work_permit_id = $12, dated_on = $13, note = $14, updated_at = now() \
WHERE id = $1 AND person_id IS NOT DISTINCT FROM $2 \
AND company_id IS NOT DISTINCT FROM $3",
)
.bind(id)
.bind(owner.person())
.bind(owner.company())
.bind(&meta.kind)
.bind(ids[0])
.bind(ids[1])
.bind(ids[2])
.bind(ids[3])
.bind(ids[4])
.bind(ids[5])
.bind(ids[6])
.bind(ids[7])
.bind(meta.dated_on)
.bind(&meta.note)
.execute(&mut **tx)
.await?;
Ok(())
}
pub async fn delete(tx: &mut Transaction<'_, Postgres>, owner: Owner, id: i64) -> Result<bool> {
let n = sqlx::query(
"DELETE FROM documents WHERE id = $1 \
AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3",
)
.bind(id)
.bind(owner.person())
.bind(owner.company())
.execute(&mut **tx)
.await?
.rows_affected();
Ok(n == 1)
}
/// The name a browser sent, without any path, control characters or
/// excess length.
pub fn clean_name(raw: &str) -> String {
let base = raw.rsplit(['/', '\\']).next().unwrap_or_default();
let name: String = base.chars().filter(|c| !c.is_control()).take(150).collect();
let name = name.trim();
if name.is_empty() {
"file".into()
} else {
name.to_string()
}
}
/// What `visa files-check` found.
#[derive(Debug, Default)]
pub struct Check {
pub documents: usize,
pub problems: Vec<String>,
}
/// Reads every document's file back, decrypts it and compares it with the
/// size and checksum recorded at the upload; lists files that belong to no
/// document.
pub async fn check(db: &PgPool, store: &Store) -> Result<Check> {
let rows: Vec<(i64, i32, String)> =
sqlx::query_as("SELECT id, size_bytes, sha256 FROM documents ORDER BY id")
.fetch_all(db)
.await?;
let (ids, other) = store.entries()?;
let mut out = Check {
documents: rows.len(),
..Check::default()
};
let known: BTreeSet<i64> = rows.iter().map(|r| r.0).collect();
for (id, size, sha) in &rows {
match store.get(*id) {
Ok(bytes) if bytes.len() == *size as usize && files::sha256_hex(&bytes) == *sha => {}
Ok(_) => out.problems.push(format!(
"document {id}: the file does not match the size and checksum of its upload"
)),
Err(e) => out.problems.push(format!("document {id}: {e:#}")),
}
}
for id in ids.iter().filter(|id| !known.contains(id)) {
out.problems
.push(format!("{id}.vdoc: a file without its document"));
}
for name in other {
out.problems
.push(format!("{name}: not a file of the store"));
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn links_read_back_and_kinds_know_their_record() {
let (link, id) = parse_link("arrivals:7").unwrap();
assert_eq!((link.column, id), ("arrival_id", 7));
for bad in [
"",
"arrivals",
"arrivals:",
"arrivals:0",
"arrivals:-3",
"people:1",
"x:1",
] {
assert!(parse_link(bad).is_none(), "{bad:?}");
}
assert_eq!(link_value(Some((link, 7))), "arrivals:7");
assert_eq!(kind_for_link("arrivals").unwrap().slug, "arrival-stamp");
assert_eq!(kind_for_link("addresses").unwrap().slug, "tm30-receipt");
// every kind's record is a link, every link has a kind
for k in PERSON_KINDS {
if let Some(r) = k.record {
assert!(LINKS.iter().any(|l| l.slug == r), "{}", k.slug);
}
}
for l in LINKS {
assert!(kind_for_link(l.slug).is_some(), "{}", l.slug);
}
}
#[test]
fn the_audit_names_the_changed_fields_only() {
let (link, _) = parse_link("passports:1").unwrap();
let a = Meta {
kind: "passport-photo-page".into(),
link: Some((link, 1)),
dated_on: None,
note: String::new(),
};
assert_eq!(a.set_fields(), ["kind", "file", "passport_id"]);
assert!(a.changed(&a.clone()).is_empty());
let b = Meta {
link: parse_link("arrivals:4"),
note: "page 2".into(),
..a.clone()
};
assert_eq!(a.changed(&b), ["arrival_id", "note", "passport_id"]);
}
#[test]
fn names_lose_their_path_and_control_characters() {
assert_eq!(clean_name("C:\\Users\\x\\Scan 1.pdf"), "Scan 1.pdf");
assert_eq!(clean_name("/tmp/a/b.jpg"), "b.jpg");
assert_eq!(clean_name("pass\nport\u{7}.png"), "passport.png");
assert_eq!(clean_name(" "), "file");
assert_eq!(clean_name("../"), "file");
assert_eq!(clean_name(&"a".repeat(400)).len(), 150);
assert_eq!(clean_name("หนังสือเดินทาง.pdf"), "หนังสือเดินทาง.pdf");
}
}