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