diff --git a/.gitignore b/.gitignore index f4f54f2..ab63ffc 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,5 @@ .env # nix build /result +# local development: the documents and their key +/.dev/ diff --git a/AGENTS.md b/AGENTS.md index 9058f2c..68d4f0c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,7 +16,14 @@ visa.buildfor.life holds passport data of real people. Read this file and changed fields (`changed_fields!` in `src/people.rs`), never their values. The table refuses `UPDATE` and `DELETE` (`migrations/0001_init.sql`). - **Every POST** goes through the same-site check and the form token - (`src/web/mod.rs`); forms carry ``. + (`src/web/mod.rs`); forms carry ``. An + upload (multipart) is the one exception in the guard: its handler checks + the token itself, which must be the form's first field, before it reads a + file (`src/web/documents.rs`). +- **Documents** are encrypted files in `VISA_FILES_DIR` (`src/files.rs`); + never write a document's file another way, and never log its contents or + its name. Opening a file is a `view` of the document, saving it a + `download`. Local files and their key live in `.dev/`, which git ignores. - **No inline script or style.** The Content Security Policy refuses them; `tests/pages.rs` checks the templates. - **Migrations** are never edited once they are on `main`; add a new file. @@ -50,7 +57,7 @@ and dark, at desktop and phone width, with `scripts/dev.sh` running. | Path | What | | --------------------- | --------------------------------------------------------------------- | -| `src/main.rs` | the commands `serve`, `migrate`, `seed-demo` | +| `src/main.rs` | the commands `serve`, `migrate`, `seed-demo`, `files-check` | | `src/config.rs` | settings from the environment and credentials | | `src/oidc.rs` | OpenID Connect against Kanidm (PKCE, nonce, ES256), from the fleet overview | | `src/session.rs` | sessions in PostgreSQL, keyed by the SHA-256 of the cookie | @@ -60,6 +67,8 @@ and dark, at desktop and phone width, with `scripts/dev.sh` running. | `src/deadlines.rs` | the deadline rules as a pure function (`assess`), and loading their facts | | `src/companies.rs` | what only companies need: list, archive, selections, employees | | `src/mrz.rs` | reading the passport's machine-readable zone (ICAO 9303, TD3) | +| `src/files.rs` | the encrypted document store: sealing, opening, checking a file's type | +| `src/documents.rs` | documents of people and companies: kinds, records, SQL, `files-check` | | `src/web/` | routes, the login gate, pages | | `templates/` | minijinja templates, compiled in by `build.rs` | | `static/` | CSS and JavaScript, compiled in; the URL carries a content hash | diff --git a/Cargo.lock b/Cargo.lock index 3fe7ad7..ecfb46f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,6 +63,7 @@ dependencies = [ "matchit", "memchr", "mime", + "multer", "percent-encoding", "pin-project-lite", "serde_core", @@ -217,6 +218,12 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -324,6 +331,20 @@ dependencies = [ "serde", ] +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -957,6 +978,29 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "num-bigint-dig" version = "0.8.6" @@ -1567,6 +1611,12 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "slab" version = "0.4.12" diff --git a/Cargo.toml b/Cargo.toml index a413fb1..d5f5aec 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,7 +23,7 @@ path = "tests/main.rs" [dependencies] anyhow = "1" -axum = "0.8" +axum = { version = "0.8", features = ["multipart"] } base64 = "0.22" chrono = { version = "0.4", default-features = false, features = ["clock", "std", "serde"] } form_urlencoded = "1" diff --git a/README.md b/README.md index d856be6..9be066d 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ view and change of a person's record goes into an append-only activity log that names the fields changed but never their values, as Thailand's Personal Data Protection Act (PDPA) asks. -## What works now (phases 1 and 2) +## What works now (phases 1 to 4) - The Deadlines page: every person's coming deadlines, the most urgent first, with a filter by employer. It covers the 90-day report with its @@ -26,10 +26,15 @@ Data Protection Act (PDPA) asks. a decision to collect, overstay, TM.30 after each arrival, the passport's and the work permit's expiry, and visas still to be used. - A list of people with a filter and each person's next deadline, and a - page per person with three tabs: the overview with personal details, + page per person with four tabs: the overview with personal details, passports and addresses; "Visa and stay" with arrivals and departures, - extensions, 90-day reports, visas, re-entry permits and work permits; and - the person's activity. + extensions, 90-day reports, visas, re-entry permits and work permits; the + person's documents; and the person's activity. +- Documents: scans and photos of the passport pages, the TDAC, receipts and + the photo, dropped on a dashed strip, several at a time, and filed under + the record they belong to. A company keeps its own documents for the + extension packs. The files are encrypted on the server, open in the + browser's viewer, and every upload, view and download is in the log. - Companies with their Thai name, registration number (the check digit is verified), address and signing director. A person's employer and the employer on a work permit are chosen from them, and a company's page adds @@ -53,8 +58,10 @@ bash scripts/dev.sh # http://127.0.0.1:8040, no login, demo pe ``` `scripts/dev.sh` runs without a login (`VISA_INSECURE_NO_LOGIN=1`, which the -app accepts only on a loopback address) and adds invented demo people. The -demo command refuses to run when a login provider is configured. +app accepts only on a loopback address) and adds invented demo people with +demo documents. The documents and their key lie in `.dev/`, which git +ignores. The demo command refuses to run when a login provider is +configured. The tests need the same database; each test gets its own: @@ -79,9 +86,17 @@ files or systemd credentials and never from a variable's value. | `VISA_OIDC_CLIENT_SECRET_FILE` | the client secret; else the credential `oidc-client-secret` | | `VISA_OIDC_GROUP` | default `visa` | | `VISA_INSECURE_NO_LOGIN` | `1` runs without a login, on loopback addresses only | +| `VISA_FILES_DIR` | where the encrypted documents lie (`/var/lib/visa/files`) | +| `VISA_FILES_KEY_FILE` | the file key, 64 hex digits; else the credential `files-key` | + +With the login on, the app does not start without the files directory and +the file key. Local development may go without them, and documents are then +switched off. The key never changes: the files cannot be read without it. `visa serve` (the default) applies pending migrations before it listens, -`visa migrate` applies them alone, and `visa seed-demo` adds the demo people. +`visa migrate` applies them alone, `visa seed-demo` adds the demo people and +documents, and `visa files-check` reads every document's file back, compares +it with its upload and lists files that belong to no document. ## Where it runs diff --git a/docs/PLAN.md b/docs/PLAN.md index c4f3564..5003bf1 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -1,7 +1,8 @@ # visa.buildfor.life: plan -> Phases 1 to 3 built on November 17, 2026; the app is live at -> https://visa.buildfor.life. **Resume here: phase 4.** +> Phases 1 to 3 built on November 17, 2026, and phase 4's app side on +> November 18, 2026; the app is live at https://visa.buildfor.life. **Resume +> here: task 4.6, the fleet side of the documents, then phase 5.** visa.buildfor.life keeps the immigration records of the foreigners that B4L looks after: their passports, addresses in Thailand, arrivals with the Thailand @@ -57,6 +58,15 @@ inline script or style. (PDPA). Every view of a person and every change is written to `audit_log` with the login, the record and the names of the changed fields, never their values. The table refuses updates and deletes. The Activity page lists it. +- **Documents.** Scans and photos lie in a files directory on the server, + one file per document, encrypted by the app with AES-256-GCM. Each file has + a key of its own, derived with HKDF-SHA256 from the app's file key and a + random salt in the file's header, and the document's id is authenticated + with it, so a file renamed to another document's id does not open. The + file key is a systemd credential that is never in the database, so neither + the files nor their backups can be read without it. The database holds what + is known about each file: its kind, the record it belongs to, the date on + it, a note, its name, type, size and SHA-256. - **Passport data entry.** The two lines of the machine-readable zone (MRZ) at the bottom of the photo page fill the name, nationality, date of birth, sex, passport number, issuing state and expiry date. Their check digits @@ -81,7 +91,7 @@ made of. | `reentry_permits` | TM.8 permits, single or multiple, valid until | 2 | | `ninety_day_reports` | the report date, the way it was filed, the receipt and the next due date printed on it | 2 | | `work_permits` | number, employer (a company), position, validity | 2 | -| `documents` | encrypted uploads tied to a person and a record | 4 | +| `documents` | uploads of a person (tied to one of their records, or none) or of a company: kind, date on the document, note, file name, type, size, SHA-256; the file itself is encrypted on disk | 4 | ## Deadline rules @@ -158,7 +168,7 @@ dark at desktop and phone width, a commit and a push. | 1 | App, Kanidm login, people, passports with MRZ reading, addresses in Thailand, audit log, demo data, CI | built Nov 17, 2026 | | 2 | Companies; stays: visas, arrivals with TDAC, extensions, re-entry permits, 90-day reports, work permits; deadlines | built Nov 17, 2026 | | 3 | On cnx01: flake package, fleet module, Kanidm client and group, bkk01 site, backups; real data from here on | live Nov 17, 2026 | -| 4 | Documents: encrypted uploads (passport pages, TDAC, receipts, photo) on the dataset `zroot/visa` with a key var, viewing and download, all audited | **next** | +| 4 | Documents: encrypted uploads (passport pages, TDAC, receipts, photo) on the dataset `zroot/visa` with a key var, viewing and download, all audited | app built Nov 18, 2026; fleet next | | 5 | Filled-in forms: TM.7, STM.2, the overstay acknowledgment, TM.47, TM.8 and STM.1 as PDF | | | 6 | The Non-B extension pack: B4L's company documents, the checklist, one PDF to print | | | 7 | Reminders by Matrix room message and by email | | @@ -219,6 +229,38 @@ one `Kind`. web01, cnx01, bkk01 and control on November 17, 2026 (cnx-network-clan PR #121). +### Phase 4: documents + +- [x] 4.1 Encrypted store (`src/files.rs`): one file per document, + `.vdoc`, written to a part file and synced before it takes its + name, never replaced. The file key is 64 hex digits 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`. +- [x] 4.2 Uploads on a new Documents tab of each person: a one-line dashed + strip that takes dropped files, up to 10 files of 20 MB each and 64 MB + in all. PDF, JPEG, PNG and WebP are taken, told by their first bytes. + The kinds follow the Non-B pack, and a document may belong to one of + the person's records (passport, visa, arrival, extension, re-entry + permit, 90-day report, address, work permit). The form token is the + upload's first field and is checked before any file is read; a file + that is there already for the person is refused. +- [x] 4.3 Company documents on the company's page: the certificate, BOJ.5, + the balance sheet with PND.50, PND.1, SPS 1-10, PP.30, a map and photos + of the office, each with the date on it for phase 6's six-month rule. +- [x] 4.4 Viewing and download: a file opens in the browser's image or PDF + viewer under its own Content Security Policy, in which nothing runs, and + is never cached. A download is named after the person or company, the + kind and the date. Each record lists its documents next to its Edit + link, with "+ Document" to add one. +- [x] 4.5 Audit: upload, view (opening the file), download (a new action), + change and deletion; a company's entries carry its id + (`audit_log.company_id`). `visa files-check` reads every file back and + lists damaged, missing and stray files. `visa seed-demo` adds demo + documents: PDFs marked as demos and PNGs of shapes. +- [ ] 4.6 Fleet: the dataset `zroot/visa` at `/var/lib/visa` with the files + in `files/`, the var `visa-files` with the key, the files in cnx01's + borg backups, and the VM test uploading a scan through the login. + ## Open questions 1. B4L's BOI application: once B4L is promoted, its staff extend their stay diff --git a/migrations/0003_documents.sql b/migrations/0003_documents.sql new file mode 100644 index 0000000..13c07e4 --- /dev/null +++ b/migrations/0003_documents.sql @@ -0,0 +1,62 @@ +-- Phase 4: documents. Scans and photos of a person's papers, and a +-- company's documents for the extension packs. The file itself lies +-- encrypted in the files directory (VISA_FILES_DIR) as .vdoc; this row +-- holds what is known about it. A document belongs to a person or to a +-- company, and a person's document may belong to one of their records. +CREATE TABLE documents ( + id BIGSERIAL PRIMARY KEY, + person_id BIGINT REFERENCES people (id), + company_id BIGINT REFERENCES companies (id), + kind TEXT NOT NULL, + -- the record it belongs to, at most one; deleting the record keeps the + -- document with the person + passport_id BIGINT REFERENCES passports (id) ON DELETE SET NULL, + address_id BIGINT REFERENCES addresses (id) ON DELETE SET NULL, + visa_id BIGINT REFERENCES visas (id) ON DELETE SET NULL, + arrival_id BIGINT REFERENCES arrivals (id) ON DELETE SET NULL, + extension_id BIGINT REFERENCES extensions (id) ON DELETE SET NULL, + report_id BIGINT REFERENCES ninety_day_reports (id) ON DELETE SET NULL, + reentry_permit_id BIGINT REFERENCES reentry_permits (id) ON DELETE SET NULL, + work_permit_id BIGINT REFERENCES work_permits (id) ON DELETE SET NULL, + -- the date printed on the document: issue, certification, statement + dated_on DATE, + note TEXT NOT NULL DEFAULT '', + file_name TEXT NOT NULL, + content_type TEXT NOT NULL CHECK ( + content_type IN ('application/pdf', 'image/jpeg', 'image/png', 'image/webp') + ), + size_bytes INTEGER NOT NULL CHECK (size_bytes > 0), + -- of the file as uploaded, checked again at each download + sha256 TEXT NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), + uploaded_by TEXT NOT NULL, + uploaded_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK ((person_id IS NULL) <> (company_id IS NULL)), + CHECK ( + num_nonnulls( + passport_id, address_id, visa_id, arrival_id, extension_id, + report_id, reentry_permit_id, work_permit_id + ) <= CASE WHEN person_id IS NULL THEN 0 ELSE 1 END + ) +); +CREATE INDEX documents_person ON documents (person_id) WHERE person_id IS NOT NULL; +CREATE INDEX documents_company ON documents (company_id) WHERE company_id IS NOT NULL; + +-- A company's document names its company in the audit log, and a download +-- is told from a view. Adding a column or changing a constraint changes no +-- row, so the append-only trigger lets it through. +ALTER TABLE audit_log ADD COLUMN company_id BIGINT; +ALTER TABLE audit_log DROP CONSTRAINT audit_log_action_check; +ALTER TABLE audit_log ADD CONSTRAINT audit_log_action_check CHECK ( + action IN ( + 'view', 'create', 'update', 'delete', 'archive', 'restore', 'sign-in', 'sign-out', + 'download' + ) +); +ALTER TABLE audit_log DROP CONSTRAINT audit_log_entity_check; +ALTER TABLE audit_log ADD CONSTRAINT audit_log_entity_check CHECK ( + entity IN ( + 'person', 'passport', 'address', 'session', 'company', 'visa', 'arrival', + 'extension', 'reentry-permit', 'report', 'work-permit', 'document' + ) +); diff --git a/scripts/dev.sh b/scripts/dev.sh index 7235a8f..bea89a1 100755 --- a/scripts/dev.sh +++ b/scripts/dev.sh @@ -1,11 +1,18 @@ #!/usr/bin/env bash # The development server on http://127.0.0.1:8040 without login, with the -# invented demo people, against the database of scripts/dev-db.sh. +# invented demo people and their documents, against the database of +# scripts/dev-db.sh. The documents lie in .dev/ (git ignores it) under a file +# key made on the first run. set -euo pipefail cd "$(dirname "$0")/.." export VISA_DATABASE_URL=${VISA_DATABASE_URL:-postgres://visa:visa-dev@127.0.0.1:55438/visa} export VISA_INSECURE_NO_LOGIN=1 export VISA_LISTEN=${VISA_LISTEN:-127.0.0.1:8040} +mkdir -p .dev +[ -s .dev/files.key ] || od -An -N32 -tx1 /dev/urandom | tr -d ' \n' > .dev/files.key +# relative paths: a Windows build reads them the same +export VISA_FILES_DIR=${VISA_FILES_DIR:-.dev/files} +export VISA_FILES_KEY_FILE=${VISA_FILES_KEY_FILE:-.dev/files.key} cargo build -q ./target/debug/visa seed-demo exec ./target/debug/visa serve diff --git a/src/audit.rs b/src/audit.rs index 55d6aa4..5dedec5 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -19,6 +19,8 @@ pub enum Action { Restore, SignIn, SignOut, + /// A document's file saved to the browser's disk (opening it is a view). + Download, } impl Action { @@ -32,6 +34,7 @@ impl Action { Action::Restore => "restore", Action::SignIn => "sign-in", Action::SignOut => "sign-out", + Action::Download => "download", } } } @@ -49,6 +52,7 @@ pub enum Entity { ReentryPermit, Report, WorkPermit, + Document, } impl Entity { @@ -65,6 +69,7 @@ impl Entity { Entity::ReentryPermit => "reentry-permit", Entity::Report => "report", Entity::WorkPermit => "work-permit", + Entity::Document => "document", } } } @@ -75,6 +80,8 @@ pub struct Entry<'a> { pub entity: Entity, pub entity_id: Option, pub person_id: Option, + /// The company a company's record or document belongs to. + pub company_id: Option, pub fields: &'a [String], } @@ -85,14 +92,15 @@ where E: Executor<'e, Database = Postgres>, { sqlx::query( - "INSERT INTO audit_log (actor, action, entity, entity_id, person_id, fields) \ - VALUES ($1, $2, $3, $4, $5, $6)", + "INSERT INTO audit_log (actor, action, entity, entity_id, person_id, company_id, fields) \ + VALUES ($1, $2, $3, $4, $5, $6, $7)", ) .bind(e.actor) .bind(e.action.as_str()) .bind(e.entity.as_str()) .bind(e.entity_id) .bind(e.person_id) + .bind(e.company_id) .bind(e.fields) .execute(ex) .await?; @@ -109,6 +117,7 @@ pub async fn viewed(db: &PgPool, actor: &str, entity: Entity, id: i64, person: i entity, entity_id: Some(id), person_id: Some(person), + company_id: None, fields: &[], }, ) @@ -124,6 +133,7 @@ struct Row { entity: String, entity_id: Option, person_id: Option, + company_id: Option, fields: Vec, person_name: Option, company_name: Option, @@ -156,12 +166,15 @@ fn noun(entity: &str) -> &str { /// The newest entries first, for one person or for everyone. pub async fn recent(db: &PgPool, person: Option, limit: i64) -> Result> { let rows: Vec = sqlx::query_as( - "SELECT a.id, a.at, a.actor, a.action, a.entity, a.entity_id, a.person_id, a.fields, \ + "SELECT a.id, a.at, a.actor, a.action, a.entity, a.entity_id, a.person_id, \ + COALESCE(a.company_id, CASE WHEN a.entity = 'company' THEN a.entity_id END) \ + AS company_id, a.fields, \ CASE WHEN p.id IS NULL THEN NULL \ ELSE upper(p.surname) || ', ' || trim(p.first_name || ' ' || p.middle_name) \ END AS person_name, c.name AS company_name \ FROM audit_log a LEFT JOIN people p ON p.id = a.person_id \ - LEFT JOIN companies c ON a.entity = 'company' AND c.id = a.entity_id \ + LEFT JOIN companies c \ + ON c.id = COALESCE(a.company_id, CASE WHEN a.entity = 'company' THEN a.entity_id END) \ WHERE ($1::bigint IS NULL OR a.person_id = $1) \ ORDER BY a.id DESC LIMIT $2", ) @@ -178,7 +191,7 @@ pub async fn recent(db: &PgPool, person: Option, limit: i64) -> Result format!("{} {id}", noun(e)), (e, None) => noun(e).to_string(), }; - let company_id = (r.entity == "company").then_some(r.entity_id).flatten(); + let company_id = r.company_id; Item { id: r.id, at: dates::fmt_datetime(r.at), diff --git a/src/config.rs b/src/config.rs index 94354a3..79c7247 100644 --- a/src/config.rs +++ b/src/config.rs @@ -12,12 +12,19 @@ //! | `VISA_OIDC_CLIENT_SECRET_FILE` | else credential `oidc-client-secret` | //! | `VISA_OIDC_GROUP` | default `visa` | //! | `VISA_INSECURE_NO_LOGIN` | `1`: no login, loopback addresses only | +//! | `VISA_FILES_DIR` | where the encrypted documents lie | +//! | `VISA_FILES_KEY_FILE` | the file key (else credential `files-key`) | +//! +//! With the login on, documents are required: the files directory and the +//! file key. Local development may go without them; uploads are then off. use std::net::SocketAddr; use std::path::PathBuf; use anyhow::{Context, Result, bail, ensure}; +use crate::files::FileKey; + #[derive(Clone, Debug)] pub struct Config { pub listen: SocketAddr, @@ -26,6 +33,14 @@ pub struct Config { pub database_url: String, pub database_password: Option, pub auth: Auth, + /// Documents: off in local development without a files directory. + pub files: Option, +} + +#[derive(Clone, Debug)] +pub struct FilesConfig { + pub dir: PathBuf, + pub key: FileKey, } #[derive(Clone, Debug)] @@ -108,12 +123,35 @@ impl Config { VISA_INSECURE_NO_LOGIN=1 for local development on a loopback address" ), }; + let key = match var("VISA_FILES_KEY_FILE") { + Some(path) => Some(read_file(&PathBuf::from(path), "the file key")?), + None => credential(var, "files-key")?, + }; + let files = match (var("VISA_FILES_DIR"), key) { + (Some(dir), Some(key)) => Some(FilesConfig { + dir: PathBuf::from(dir), + key: FileKey::from_hex(&key).context("reading the file key")?, + }), + (None, None) => None, + (Some(_), None) => bail!( + "VISA_FILES_DIR is set but there is no file key: set VISA_FILES_KEY_FILE or pass \ + the credential files-key" + ), + (None, Some(_)) => bail!("there is a file key but no VISA_FILES_DIR"), + }; + if matches!(auth, Auth::Oidc(_)) && files.is_none() { + bail!( + "documents are not set up: with the login on, set VISA_FILES_DIR and the file \ + key (VISA_FILES_KEY_FILE or the credential files-key)" + ); + } Ok(Config { listen, public_url, database_url, database_password, auth, + files, }) } @@ -189,6 +227,9 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); let f = dir.join("secret"); std::fs::write(&f, "s3cret\n").unwrap(); + let key = dir.join("files.key"); + std::fs::write(&key, format!("{}\n", "ab".repeat(32))).unwrap(); + let files_dir = dir.join("files"); let c = cfg(&[ ("VISA_DATABASE_URL", "postgres://x/y"), ("VISA_PUBLIC_URL", "https://visa.example/"), @@ -197,6 +238,8 @@ mod tests { "https://id.example/oauth2/openid/visa-web/", ), ("VISA_OIDC_CLIENT_SECRET_FILE", f.to_str().unwrap()), + ("VISA_FILES_DIR", files_dir.to_str().unwrap()), + ("VISA_FILES_KEY_FILE", key.to_str().unwrap()), ]) .unwrap(); let Auth::Oidc(o) = &c.auth else { @@ -220,6 +263,59 @@ mod tests { ]) .unwrap_err(); assert!(e.to_string().contains("https"), "{e}"); + // with the login on, documents must be set up + let e = cfg(&[ + ("VISA_DATABASE_URL", "postgres://x/y"), + ("VISA_PUBLIC_URL", "https://visa.example"), + ( + "VISA_OIDC_ISSUER", + "https://id.example/oauth2/openid/visa-web", + ), + ("VISA_OIDC_CLIENT_SECRET_FILE", f.to_str().unwrap()), + ]) + .unwrap_err(); + assert!(e.to_string().contains("documents are not set up"), "{e}"); + let files = c.files.unwrap(); + assert_eq!(files.dir, files_dir); + assert!(!format!("{files:?}").contains("abab")); + std::fs::remove_dir_all(&dir).ok(); + } + + #[test] + fn documents_need_both_the_directory_and_the_key() { + let dir = std::env::temp_dir().join(format!("visa-cfg-files-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let key = dir.join("files.key"); + let base = [ + ("VISA_DATABASE_URL", "postgres://x/y"), + ("VISA_INSECURE_NO_LOGIN", "1"), + ]; + // local development may go without documents + assert!(cfg(&base).unwrap().files.is_none()); + let with = |extra: &[(&str, &str)]| { + let mut all = base.to_vec(); + all.extend_from_slice(extra); + cfg(&all) + }; + let e = with(&[("VISA_FILES_DIR", "/srv/files")]).unwrap_err(); + assert!(e.to_string().contains("no file key"), "{e}"); + std::fs::write(&key, "not hex").unwrap(); + let e = with(&[ + ("VISA_FILES_DIR", "/srv/files"), + ("VISA_FILES_KEY_FILE", key.to_str().unwrap()), + ]) + .unwrap_err(); + assert!(format!("{e:#}").contains("64 hex digits"), "{e:#}"); + // the systemd credential + std::fs::write(dir.join("files-key"), "cd".repeat(32)).unwrap(); + let c = with(&[ + ("VISA_FILES_DIR", "/srv/files"), + ("CREDENTIALS_DIRECTORY", dir.to_str().unwrap()), + ]) + .unwrap(); + assert!(c.files.is_some()); + let e = with(&[("CREDENTIALS_DIRECTORY", dir.to_str().unwrap())]).unwrap_err(); + assert!(e.to_string().contains("no VISA_FILES_DIR"), "{e}"); std::fs::remove_dir_all(&dir).ok(); } } diff --git a/src/documents.rs b/src/documents.rs new file mode 100644 index 0000000..9af7808 --- /dev/null +++ b/src/documents.rs @@ -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 { + match self { + Owner::Person(id) => Some(id), + Owner::Company(_) => None, + } + } + + pub fn company(self) -> Option { + 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, + pub company_id: Option, + pub kind: String, + pub passport_id: Option, + pub address_id: Option, + pub visa_id: Option, + pub arrival_id: Option, + pub extension_id: Option, + pub report_id: Option, + pub reentry_permit_id: Option, + pub work_permit_id: Option, + pub dated_on: Option, + 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, + pub updated_at: DateTime, +} + +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, + 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; 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 { + 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 { + 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) -> Vec { + 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> { + let docs: Vec = 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> { + 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> { + 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 { + // 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 { + 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 { + 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, +} + +/// 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 { + 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 = 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"); + } +} diff --git a/src/files.rs b/src/files.rs new file mode 100644 index 0000000..b5f20cf --- /dev/null +++ b/src/files.rs @@ -0,0 +1,410 @@ +//! The document store. Each uploaded file lies in the files directory as +//! `.vdoc`, encrypted with AES-256-GCM under a key of its own: HKDF-SHA256 +//! derives it from the app's file key and a random salt kept in the file's +//! header. The document's id is authenticated with the file, so a file +//! renamed to another id does not open. The file key is a systemd +//! credential and is never in the database or its dumps: without it the +//! files and their backups cannot be read. +//! +//! A file is `VISADOC1`, the key id (8 bytes), the salt (32 bytes), the +//! ciphertext and the tag (16 bytes). The key id names the key that sealed a +//! file, so a wrong key is reported as such and not as damage. + +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, ensure}; +use ring::aead::{self, Aad, LessSafeKey, Nonce, UnboundKey}; +use ring::rand::{SecureRandom, SystemRandom}; +use ring::{digest, hkdf}; + +const MAGIC: &[u8; 8] = b"VISADOC1"; +const KEY_ID: usize = 8; +const SALT: usize = 32; +const HEADER: usize = MAGIC.len() + KEY_ID + SALT; +const TAG: usize = 16; +const INFO: &[u8] = b"visa document v1"; +/// Each file's key is used once, so the nonce can be fixed. +const NONCE: [u8; 12] = [0; 12]; + +/// The app's file key: 32 random bytes, written as 64 hex digits in its file +/// (`openssl rand -hex 32`). +#[derive(Clone)] +pub struct FileKey([u8; 32]); + +// The key stays out of logs and panics; its id is enough to tell keys apart. +impl fmt::Debug for FileKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "FileKey(id {})", self.id_hex()) + } +} + +impl FileKey { + pub fn from_hex(text: &str) -> Result { + let t = text.trim(); + ensure!( + t.len() == 64 && t.bytes().all(|b| b.is_ascii_hexdigit()), + "the file key must be 64 hex digits (32 bytes), as `openssl rand -hex 32` writes it" + ); + let mut key = [0u8; 32]; + for (i, pair) in t.as_bytes().chunks(2).enumerate() { + key[i] = u8::from_str_radix(std::str::from_utf8(pair)?, 16)?; + } + Ok(FileKey(key)) + } + + /// A fresh key, for the tests. + pub fn random() -> FileKey { + let mut key = [0u8; 32]; + SystemRandom::new() + .fill(&mut key) + .expect("the system's random source"); + FileKey(key) + } + + /// Names the key without giving it away: the start of a hash of it. + pub fn id(&self) -> [u8; KEY_ID] { + let mut ctx = digest::Context::new(&digest::SHA256); + ctx.update(b"visa file key id:"); + ctx.update(&self.0); + let d = ctx.finish(); + let mut id = [0u8; KEY_ID]; + id.copy_from_slice(&d.as_ref()[..KEY_ID]); + id + } + + pub fn id_hex(&self) -> String { + hex(&self.id()) + } + + fn cipher(&self, salt: &[u8]) -> LessSafeKey { + let prk = hkdf::Salt::new(hkdf::HKDF_SHA256, salt).extract(&self.0); + let okm = prk + .expand(&[INFO], &aead::AES_256_GCM) + .expect("32 bytes are a valid HKDF output length"); + LessSafeKey::new(UnboundKey::from(okm)) + } +} + +pub fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +pub fn sha256_hex(bytes: &[u8]) -> String { + hex(digest::digest(&digest::SHA256, bytes).as_ref()) +} + +fn aad(id: i64) -> String { + format!("visa document {id}") +} + +/// Encrypts the file of document `id`. +pub fn seal(key: &FileKey, id: i64, plain: &[u8]) -> Vec { + let mut salt = [0u8; SALT]; + SystemRandom::new() + .fill(&mut salt) + .expect("the system's random source"); + let mut out = Vec::with_capacity(HEADER + plain.len() + TAG); + out.extend_from_slice(MAGIC); + out.extend_from_slice(&key.id()); + out.extend_from_slice(&salt); + out.extend_from_slice(plain); + let tag = key + .cipher(&salt) + .seal_in_place_separate_tag( + Nonce::assume_unique_for_key(NONCE), + Aad::from(aad(id).as_bytes()), + &mut out[HEADER..], + ) + .expect("AES-GCM seals any size the app accepts"); + out.extend_from_slice(tag.as_ref()); + out +} + +#[derive(Debug, PartialEq, Eq)] +pub enum OpenError { + /// Not a file of this store. + NotADocument, + /// Sealed with another file key. + OtherKey, + /// Changed, cut short, or the file of another document. + Damaged, +} + +impl fmt::Display for OpenError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + OpenError::NotADocument => "not a document file", + OpenError::OtherKey => "encrypted with another file key", + OpenError::Damaged => "damaged, or the file of another document", + }) + } +} + +impl std::error::Error for OpenError {} + +/// Decrypts the file of document `id`. +pub fn open(key: &FileKey, id: i64, sealed: &[u8]) -> Result, OpenError> { + if sealed.len() < HEADER + TAG || &sealed[..MAGIC.len()] != MAGIC { + return Err(OpenError::NotADocument); + } + if sealed[MAGIC.len()..MAGIC.len() + KEY_ID] != key.id() { + return Err(OpenError::OtherKey); + } + let salt = &sealed[MAGIC.len() + KEY_ID..HEADER]; + let mut buf = sealed[HEADER..].to_vec(); + let len = key + .cipher(salt) + .open_in_place( + Nonce::assume_unique_for_key(NONCE), + Aad::from(aad(id).as_bytes()), + &mut buf, + ) + .map_err(|_| OpenError::Damaged)? + .len(); + buf.truncate(len); + Ok(buf) +} + +/// The types the app takes, told by the file's first bytes: the name and the +/// browser's word for the type are not trusted. +pub fn sniff(bytes: &[u8]) -> Option<&'static str> { + // PDF allows a little before its header + let head = &bytes[..bytes.len().min(1024)]; + if head.windows(5).any(|w| w == b"%PDF-") { + Some("application/pdf") + } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + Some("image/jpeg") + } else if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + Some("image/png") + } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + Some("image/webp") + } else { + None + } +} + +/// What the page calls a type. +pub fn type_label(content_type: &str) -> &'static str { + match content_type { + "application/pdf" => "PDF", + "image/jpeg" => "JPEG", + "image/png" => "PNG", + "image/webp" => "WebP", + _ => "file", + } +} + +pub fn extension(content_type: &str) -> &'static str { + match content_type { + "application/pdf" => "pdf", + "image/jpeg" => "jpg", + "image/png" => "png", + "image/webp" => "webp", + _ => "bin", + } +} + +pub fn is_image(content_type: &str) -> bool { + content_type.starts_with("image/") +} + +/// The files directory with the key; cheap to clone into a blocking task. +#[derive(Clone, Debug)] +pub struct Store { + dir: PathBuf, + key: FileKey, +} + +impl Store { + /// The files directory, created (only its owner may enter) when missing. + pub fn open(dir: PathBuf, key: FileKey) -> Result { + fs::create_dir_all(&dir) + .with_context(|| format!("creating the files directory {}", dir.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)) + .with_context(|| format!("closing the files directory {}", dir.display()))?; + } + Ok(Store { dir, key }) + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + pub fn key_id(&self) -> String { + self.key.id_hex() + } + + pub fn path(&self, id: i64) -> PathBuf { + self.dir.join(format!("{id}.vdoc")) + } + + /// Encrypts and writes the file of document `id`: to a part file first, + /// on disk before it takes its name. An existing file is never replaced. + pub fn put(&self, id: i64, plain: &[u8]) -> Result<()> { + let path = self.path(id); + ensure!( + !path.exists(), + "{} is there already without its document (after a restore?); `visa files-check` \ + lists such files", + path.display() + ); + let sealed = seal(&self.key, id, plain); + let part = self.dir.join(format!(".{id}.vdoc.part")); + let write = || -> io::Result<()> { + let mut f = File::create(&part)?; + f.write_all(&sealed)?; + f.sync_all()?; + fs::rename(&part, &path)?; + sync_dir(&self.dir) + }; + write() + .inspect_err(|_| { + fs::remove_file(&part).ok(); + }) + .with_context(|| format!("writing {}", path.display())) + } + + /// The decrypted file of document `id`. + pub fn get(&self, id: i64) -> Result> { + let path = self.path(id); + let sealed = fs::read(&path).with_context(|| format!("reading {}", path.display()))?; + open(&self.key, id, &sealed).with_context(|| format!("opening {}", path.display())) + } + + /// Removes the file of document `id`; a file that is gone already is fine. + pub fn remove(&self, id: i64) -> Result<()> { + let path = self.path(id); + match fs::remove_file(&path) { + Ok(()) => sync_dir(&self.dir).with_context(|| format!("removing {}", path.display())), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e).with_context(|| format!("removing {}", path.display())), + } + } + + /// What lies in the directory: the documents' ids, and the names of + /// anything else (a part file left by a crash, say). + pub fn entries(&self) -> Result<(Vec, Vec)> { + let mut ids = Vec::new(); + let mut other = Vec::new(); + for entry in + fs::read_dir(&self.dir).with_context(|| format!("listing {}", self.dir.display()))? + { + let name = entry?.file_name().to_string_lossy().into_owned(); + match name + .strip_suffix(".vdoc") + .and_then(|n| n.parse::().ok()) + { + Some(id) if id > 0 => ids.push(id), + _ => other.push(name), + } + } + ids.sort_unstable(); + other.sort(); + Ok((ids, other)) + } +} + +/// A rename is on disk only once its directory is. +fn sync_dir(dir: &Path) -> io::Result<()> { + #[cfg(unix)] + File::open(dir)?.sync_all()?; + #[cfg(not(unix))] + let _ = dir; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sealed_files_open_with_their_key_and_id_only() { + let key = FileKey::random(); + let plain = b"%PDF-1.4 a scan of a passport page".to_vec(); + let sealed = seal(&key, 7, &plain); + assert_eq!(sealed.len(), HEADER + plain.len() + TAG); + assert!(!sealed.windows(9).any(|w| w == b"a scan of")); + assert_eq!(open(&key, 7, &sealed).unwrap(), plain); + // the file of document 7 does not pass for document 8 + assert_eq!(open(&key, 8, &sealed), Err(OpenError::Damaged)); + assert_eq!( + open(&FileKey::random(), 7, &sealed), + Err(OpenError::OtherKey) + ); + let mut changed = sealed.clone(); + let last = changed.len() - 20; + changed[last] ^= 1; + assert_eq!(open(&key, 7, &changed), Err(OpenError::Damaged)); + assert_eq!( + open(&key, 7, &sealed[..sealed.len() - 1]), + Err(OpenError::Damaged) + ); + assert_eq!(open(&key, 7, b"%PDF-1.4"), Err(OpenError::NotADocument)); + // two seals of the same file differ (a fresh salt each time) + assert_ne!(seal(&key, 7, &plain), sealed); + assert_eq!(open(&key, 7, &seal(&key, 7, b"")).unwrap(), b""); + } + + #[test] + fn the_key_is_64_hex_digits_and_never_printed() { + let text = "00112233445566778899aabbccddeeff00112233445566778899AABBCCDDEEFF\n"; + let key = FileKey::from_hex(text).unwrap(); + assert_eq!(key.0[1], 0x11); + assert_eq!(key.0[31], 0xff); + let shown = format!("{key:?}"); + assert!(!shown.contains("00112233"), "{shown}"); + assert!(shown.contains(&key.id_hex())); + for bad in ["", "0011", &"zz".repeat(32), &"00".repeat(33)] { + assert!(FileKey::from_hex(bad).is_err(), "{bad:?}"); + } + } + + #[test] + fn types_come_from_the_first_bytes() { + assert_eq!(sniff(b"%PDF-1.7\n"), Some("application/pdf")); + assert_eq!(sniff(b"\n\n%PDF-1.4"), Some("application/pdf")); + assert_eq!( + sniff(&[0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10]), + Some("image/jpeg") + ); + assert_eq!(sniff(b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR"), Some("image/png")); + assert_eq!(sniff(b"RIFF\x24\0\0\0WEBPVP8 "), Some("image/webp")); + for bad in [ + 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!("