Phase 4: documents, encrypted on the server
Scans and photos of a person's papers, and a company's documents for the extension packs, uploaded on a dashed strip that takes dropped files: up to 10 files of 20 MB each, 64 MB in all; PDF, JPEG, PNG and WebP, told by their first bytes. - src/files.rs: one file per document as <id>.vdoc, AES-256-GCM under a key per file (HKDF-SHA256 from the file key and a random salt in the header); the document's id is authenticated with it. The key comes from VISA_FILES_KEY_FILE or the credential files-key; with the login on, the app does not start without it and VISA_FILES_DIR. - migrations/0003: documents (a person's or a company's, the record it belongs to, kind, date on it, note, file name, type, size, SHA-256); audit_log gets company_id and the action download. - A Documents tab per person, the documents on the company's page, and each record's documents next to its Edit link with "+ Document". - An upload's form token is its first field and is checked before any file is read; the guard lets multipart through only to the two upload addresses. - Files open under their own CSP and are never cached; a download is named after the person or company, the kind and the date. Every upload, view, download, change and deletion is in the audit log. - visa files-check; demo documents in seed-demo; scripts/dev.sh keeps the local documents and their key in .dev/; /favicon.ico for image and PDF pages. Tests: 57 unit and 33 integration (8 new for documents). Edge check of the strip (choose, drop, too large), an upload, the PDF and image viewers under the file policy: no problems, no console errors.
This commit is contained in:
1 parent
d543c929e9
commit
2061e3a024
35 files changed
+4249
-51
No files matched your search
@@ -4,3 +4,5 @@
|
||||
.env
|
||||
# nix build
|
||||
/result
|
||||
# local development: the documents and their key
|
||||
/.dev/
|
||||
@@ -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 `<input type="hidden" name="csrf">`.
|
||||
(`src/web/mod.rs`); forms carry `<input type="hidden" name="csrf">`. 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 |
|
||||
|
||||
Generated
+50
@@ -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"
|
||||
|
||||
+1
-1
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+46
-4
@@ -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,
|
||||
`<id>.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
|
||||
|
||||
@@ -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 <id>.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'
|
||||
)
|
||||
);
|
||||
+8
-1
@@ -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
|
||||
+18
-5
@@ -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<i64>,
|
||||
pub person_id: Option<i64>,
|
||||
/// The company a company's record or document belongs to.
|
||||
pub company_id: Option<i64>,
|
||||
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<i64>,
|
||||
person_id: Option<i64>,
|
||||
company_id: Option<i64>,
|
||||
fields: Vec<String>,
|
||||
person_name: Option<String>,
|
||||
company_name: Option<String>,
|
||||
@@ -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<i64>, limit: i64) -> Result<Vec<Item>> {
|
||||
let rows: Vec<Row> = 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<i64>, limit: i64) -> Result<Vec<
|
||||
(e, Some(id)) => 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),
|
||||
|
||||
@@ -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<String>,
|
||||
pub auth: Auth,
|
||||
/// Documents: off in local development without a files directory.
|
||||
pub files: Option<FilesConfig>,
|
||||
}
|
||||
|
||||
#[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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,593 @@
|
||||
//! Documents: scans and photos of a person's papers, and the company
|
||||
//! documents the extension packs need. A row holds what is known about a
|
||||
//! file; the file itself lies encrypted in the store (`files.rs`). A
|
||||
//! person's document may belong to one of their records (a passport, an
|
||||
//! arrival, a 90-day report ...), and then shows next to that record too.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use anyhow::Result;
|
||||
use chrono::{DateTime, NaiveDate, Utc};
|
||||
use sqlx::{PgPool, Postgres, Transaction};
|
||||
|
||||
use crate::files::{self, Store};
|
||||
|
||||
/// Whose document it is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Owner {
|
||||
Person(i64),
|
||||
Company(i64),
|
||||
}
|
||||
|
||||
impl Owner {
|
||||
pub fn person(self) -> Option<i64> {
|
||||
match self {
|
||||
Owner::Person(id) => Some(id),
|
||||
Owner::Company(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn company(self) -> Option<i64> {
|
||||
match self {
|
||||
Owner::Company(id) => Some(id),
|
||||
Owner::Person(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The address of its documents' pages.
|
||||
pub fn base(self) -> String {
|
||||
match self {
|
||||
Owner::Person(id) => format!("/people/{id}/documents"),
|
||||
Owner::Company(id) => format!("/companies/{id}/documents"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kinds(self) -> &'static [Kind] {
|
||||
match self {
|
||||
Owner::Person(_) => PERSON_KINDS,
|
||||
Owner::Company(_) => COMPANY_KINDS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A kind of document; `record` is the kind of record it usually belongs to.
|
||||
#[derive(Debug)]
|
||||
pub struct Kind {
|
||||
pub slug: &'static str,
|
||||
pub label: &'static str,
|
||||
pub record: Option<&'static str>,
|
||||
}
|
||||
|
||||
const fn k(slug: &'static str, label: &'static str, record: Option<&'static str>) -> Kind {
|
||||
Kind {
|
||||
slug,
|
||||
label,
|
||||
record,
|
||||
}
|
||||
}
|
||||
|
||||
/// In the order of the Non-B pack (docs/PLAN.md).
|
||||
pub const PERSON_KINDS: &[Kind] = &[
|
||||
k("photo", "Photo, 4 x 6 cm", None),
|
||||
k(
|
||||
"passport-photo-page",
|
||||
"Passport photo page",
|
||||
Some("passports"),
|
||||
),
|
||||
k("visa", "Visa", Some("visas")),
|
||||
k("arrival-stamp", "Arrival stamp", Some("arrivals")),
|
||||
k("tdac", "TDAC", Some("arrivals")),
|
||||
k("extension-stamp", "Extension stamp", Some("extensions")),
|
||||
k("reentry-permit", "Re-entry permit", Some("reentry-permits")),
|
||||
k(
|
||||
"ninety-day-receipt",
|
||||
"90-day report receipt",
|
||||
Some("reports"),
|
||||
),
|
||||
k("tm30-receipt", "TM.30 receipt", Some("addresses")),
|
||||
k("work-permit", "Work permit", Some("work-permits")),
|
||||
k("pnd91", "Income tax return (PND.91)", None),
|
||||
k("other", "Other", None),
|
||||
];
|
||||
|
||||
/// The company documents of the Non-B pack, in its order.
|
||||
pub const COMPANY_KINDS: &[Kind] = &[
|
||||
k("company-certificate", "Company certificate", None),
|
||||
k("shareholders", "List of shareholders (BOJ.5)", None),
|
||||
k("balance-sheet", "Balance sheet with PND.50", None),
|
||||
k("pnd1", "Withholding tax (PND.1)", None),
|
||||
k("sps1-10", "Social security (SPS 1-10)", None),
|
||||
k("pp30", "VAT return (PP.30)", None),
|
||||
k("map", "Map to the office", None),
|
||||
k("office-photo", "Photo of the office", None),
|
||||
k("other", "Other", None),
|
||||
];
|
||||
|
||||
pub fn kind(owner: Owner, slug: &str) -> Option<&'static Kind> {
|
||||
owner.kinds().iter().find(|k| k.slug == slug)
|
||||
}
|
||||
|
||||
pub fn kind_label(owner: Owner, slug: &str) -> String {
|
||||
kind(owner, slug).map_or_else(|| slug.to_string(), |k| k.label.to_string())
|
||||
}
|
||||
|
||||
/// The first kind that belongs to a kind of record: what a document added
|
||||
/// from that record is.
|
||||
pub fn kind_for_link(link: &str) -> Option<&'static Kind> {
|
||||
PERSON_KINDS.iter().find(|k| k.record == Some(link))
|
||||
}
|
||||
|
||||
/// A kind of record a person's document may belong to; `slug` is the one of
|
||||
/// its pages (`/people/{id}/arrivals/...`).
|
||||
#[derive(Debug)]
|
||||
pub struct Link {
|
||||
pub slug: &'static str,
|
||||
pub column: &'static str,
|
||||
pub table: &'static str,
|
||||
pub title: &'static str,
|
||||
}
|
||||
|
||||
const fn l(
|
||||
slug: &'static str,
|
||||
column: &'static str,
|
||||
table: &'static str,
|
||||
title: &'static str,
|
||||
) -> Link {
|
||||
Link {
|
||||
slug,
|
||||
column,
|
||||
table,
|
||||
title,
|
||||
}
|
||||
}
|
||||
|
||||
pub const LINKS: &[Link] = &[
|
||||
l("passports", "passport_id", "passports", "Passports"),
|
||||
l("visas", "visa_id", "visas", "Visas"),
|
||||
l("arrivals", "arrival_id", "arrivals", "Arrivals"),
|
||||
l(
|
||||
"extensions",
|
||||
"extension_id",
|
||||
"extensions",
|
||||
"Extensions of stay",
|
||||
),
|
||||
l(
|
||||
"reentry-permits",
|
||||
"reentry_permit_id",
|
||||
"reentry_permits",
|
||||
"Re-entry permits",
|
||||
),
|
||||
l(
|
||||
"reports",
|
||||
"report_id",
|
||||
"ninety_day_reports",
|
||||
"90-day reports",
|
||||
),
|
||||
l(
|
||||
"addresses",
|
||||
"address_id",
|
||||
"addresses",
|
||||
"Addresses in Thailand",
|
||||
),
|
||||
l(
|
||||
"work-permits",
|
||||
"work_permit_id",
|
||||
"work_permits",
|
||||
"Work permits",
|
||||
),
|
||||
];
|
||||
|
||||
/// `arrivals:7`, as the forms send it.
|
||||
pub fn parse_link(value: &str) -> Option<(&'static Link, i64)> {
|
||||
let (slug, id) = value.split_once(':')?;
|
||||
let link = LINKS.iter().find(|l| l.slug == slug)?;
|
||||
let id: i64 = id.parse().ok().filter(|&n| n > 0)?;
|
||||
Some((link, id))
|
||||
}
|
||||
|
||||
pub fn link_value(link: Option<(&Link, i64)>) -> String {
|
||||
link.map(|(l, id)| format!("{}:{id}", l.slug))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, sqlx::FromRow)]
|
||||
pub struct Document {
|
||||
pub id: i64,
|
||||
pub person_id: Option<i64>,
|
||||
pub company_id: Option<i64>,
|
||||
pub kind: String,
|
||||
pub passport_id: Option<i64>,
|
||||
pub address_id: Option<i64>,
|
||||
pub visa_id: Option<i64>,
|
||||
pub arrival_id: Option<i64>,
|
||||
pub extension_id: Option<i64>,
|
||||
pub report_id: Option<i64>,
|
||||
pub reentry_permit_id: Option<i64>,
|
||||
pub work_permit_id: Option<i64>,
|
||||
pub dated_on: Option<NaiveDate>,
|
||||
pub note: String,
|
||||
pub file_name: String,
|
||||
pub content_type: String,
|
||||
pub size_bytes: i32,
|
||||
pub sha256: String,
|
||||
pub uploaded_by: String,
|
||||
pub uploaded_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
pub fn owner(&self) -> Owner {
|
||||
match (self.person_id, self.company_id) {
|
||||
(Some(p), _) => Owner::Person(p),
|
||||
(None, Some(c)) => Owner::Company(c),
|
||||
// the table's check rules this out
|
||||
(None, None) => Owner::Person(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The record it belongs to, if any.
|
||||
pub fn link(&self) -> Option<(&'static Link, i64)> {
|
||||
let ids = [
|
||||
self.passport_id,
|
||||
self.visa_id,
|
||||
self.arrival_id,
|
||||
self.extension_id,
|
||||
self.reentry_permit_id,
|
||||
self.report_id,
|
||||
self.address_id,
|
||||
self.work_permit_id,
|
||||
];
|
||||
LINKS
|
||||
.iter()
|
||||
.zip(ids)
|
||||
.find_map(|(l, id)| id.map(|id| (l, id)))
|
||||
}
|
||||
}
|
||||
|
||||
/// What the forms set about a document.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Meta {
|
||||
pub kind: String,
|
||||
pub link: Option<(&'static Link, i64)>,
|
||||
pub dated_on: Option<NaiveDate>,
|
||||
pub note: String,
|
||||
}
|
||||
|
||||
impl Meta {
|
||||
pub fn of(d: &Document) -> Meta {
|
||||
Meta {
|
||||
kind: d.kind.clone(),
|
||||
link: d.link(),
|
||||
dated_on: d.dated_on,
|
||||
note: d.note.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The id for each link column, in the order of `LINKS`.
|
||||
fn link_ids(&self) -> [Option<i64>; 8] {
|
||||
let mut ids = [None; 8];
|
||||
if let Some((link, id)) = self.link
|
||||
&& let Some(i) = LINKS.iter().position(|l| l.slug == link.slug)
|
||||
{
|
||||
ids[i] = Some(id);
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// The names of the fields a new document sets, for the audit log.
|
||||
pub fn set_fields(&self) -> Vec<String> {
|
||||
let mut out = vec!["kind".to_string(), "file".to_string()];
|
||||
if let Some((link, _)) = self.link {
|
||||
out.push(link.column.to_string());
|
||||
}
|
||||
if self.dated_on.is_some() {
|
||||
out.push("dated_on".into());
|
||||
}
|
||||
if !self.note.is_empty() {
|
||||
out.push("note".into());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The names of the fields a change touches.
|
||||
pub fn changed(&self, new: &Meta) -> Vec<String> {
|
||||
let mut out = BTreeSet::new();
|
||||
if self.kind != new.kind {
|
||||
out.insert("kind".to_string());
|
||||
}
|
||||
let (a, b) = (self.link_ids(), new.link_ids());
|
||||
for (i, link) in LINKS.iter().enumerate() {
|
||||
if a[i] != b[i] {
|
||||
out.insert(link.column.to_string());
|
||||
}
|
||||
}
|
||||
if self.dated_on != new.dated_on {
|
||||
out.insert("dated_on".into());
|
||||
}
|
||||
if self.note != new.note {
|
||||
out.insert("note".into());
|
||||
}
|
||||
out.into_iter().collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The file of a new document, as checked.
|
||||
pub struct NewFile<'a> {
|
||||
pub name: &'a str,
|
||||
pub content_type: &'static str,
|
||||
pub size: i32,
|
||||
pub sha256: &'a str,
|
||||
}
|
||||
|
||||
/// The newest first within each kind, the kinds in the pack's order.
|
||||
fn sorted(owner: Owner, mut docs: Vec<Document>) -> Vec<Document> {
|
||||
let rank = |d: &Document| {
|
||||
owner
|
||||
.kinds()
|
||||
.iter()
|
||||
.position(|k| k.slug == d.kind)
|
||||
.unwrap_or(usize::MAX)
|
||||
};
|
||||
docs.sort_by(|a, b| {
|
||||
rank(a)
|
||||
.cmp(&rank(b))
|
||||
.then(b.dated_on.cmp(&a.dated_on))
|
||||
.then(b.id.cmp(&a.id))
|
||||
});
|
||||
docs
|
||||
}
|
||||
|
||||
pub async fn list(db: &PgPool, owner: Owner) -> Result<Vec<Document>> {
|
||||
let docs: Vec<Document> = sqlx::query_as(
|
||||
"SELECT * FROM documents \
|
||||
WHERE person_id IS NOT DISTINCT FROM $1 AND company_id IS NOT DISTINCT FROM $2",
|
||||
)
|
||||
.bind(owner.person())
|
||||
.bind(owner.company())
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
Ok(sorted(owner, docs))
|
||||
}
|
||||
|
||||
pub async fn get(db: &PgPool, owner: Owner, id: i64) -> Result<Option<Document>> {
|
||||
Ok(sqlx::query_as(
|
||||
"SELECT * FROM documents WHERE id = $1 \
|
||||
AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(owner.person())
|
||||
.bind(owner.company())
|
||||
.fetch_optional(db)
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// The same file uploaded before for the same person or company.
|
||||
pub async fn same_file(db: &PgPool, owner: Owner, sha256: &str) -> Result<Option<Document>> {
|
||||
Ok(sqlx::query_as(
|
||||
"SELECT * FROM documents WHERE sha256 = $1 \
|
||||
AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3 \
|
||||
ORDER BY id LIMIT 1",
|
||||
)
|
||||
.bind(sha256)
|
||||
.bind(owner.person())
|
||||
.bind(owner.company())
|
||||
.fetch_optional(db)
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// Whether the record is one of this person's.
|
||||
pub async fn link_is_theirs(db: &PgPool, person: i64, link: &Link, id: i64) -> Result<bool> {
|
||||
// the table name comes from LINKS, never from the form
|
||||
let sql = format!(
|
||||
"SELECT EXISTS (SELECT 1 FROM {} WHERE id = $1 AND person_id = $2)",
|
||||
link.table
|
||||
);
|
||||
Ok(sqlx::query_scalar(&sql)
|
||||
.bind(id)
|
||||
.bind(person)
|
||||
.fetch_one(db)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub async fn insert(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
owner: Owner,
|
||||
meta: &Meta,
|
||||
file: &NewFile<'_>,
|
||||
by: &str,
|
||||
) -> Result<i64> {
|
||||
let ids = meta.link_ids();
|
||||
let id = sqlx::query_scalar(
|
||||
"INSERT INTO documents (person_id, company_id, kind, passport_id, visa_id, \
|
||||
arrival_id, extension_id, reentry_permit_id, report_id, address_id, work_permit_id, \
|
||||
dated_on, note, file_name, content_type, size_bytes, sha256, uploaded_by) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) \
|
||||
RETURNING id",
|
||||
)
|
||||
.bind(owner.person())
|
||||
.bind(owner.company())
|
||||
.bind(&meta.kind)
|
||||
.bind(ids[0])
|
||||
.bind(ids[1])
|
||||
.bind(ids[2])
|
||||
.bind(ids[3])
|
||||
.bind(ids[4])
|
||||
.bind(ids[5])
|
||||
.bind(ids[6])
|
||||
.bind(ids[7])
|
||||
.bind(meta.dated_on)
|
||||
.bind(&meta.note)
|
||||
.bind(file.name)
|
||||
.bind(file.content_type)
|
||||
.bind(file.size)
|
||||
.bind(file.sha256)
|
||||
.bind(by)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
owner: Owner,
|
||||
id: i64,
|
||||
meta: &Meta,
|
||||
) -> Result<()> {
|
||||
let ids = meta.link_ids();
|
||||
sqlx::query(
|
||||
"UPDATE documents SET kind = $4, passport_id = $5, visa_id = $6, arrival_id = $7, \
|
||||
extension_id = $8, reentry_permit_id = $9, report_id = $10, address_id = $11, \
|
||||
work_permit_id = $12, dated_on = $13, note = $14, updated_at = now() \
|
||||
WHERE id = $1 AND person_id IS NOT DISTINCT FROM $2 \
|
||||
AND company_id IS NOT DISTINCT FROM $3",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(owner.person())
|
||||
.bind(owner.company())
|
||||
.bind(&meta.kind)
|
||||
.bind(ids[0])
|
||||
.bind(ids[1])
|
||||
.bind(ids[2])
|
||||
.bind(ids[3])
|
||||
.bind(ids[4])
|
||||
.bind(ids[5])
|
||||
.bind(ids[6])
|
||||
.bind(ids[7])
|
||||
.bind(meta.dated_on)
|
||||
.bind(&meta.note)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn delete(tx: &mut Transaction<'_, Postgres>, owner: Owner, id: i64) -> Result<bool> {
|
||||
let n = sqlx::query(
|
||||
"DELETE FROM documents WHERE id = $1 \
|
||||
AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(owner.person())
|
||||
.bind(owner.company())
|
||||
.execute(&mut **tx)
|
||||
.await?
|
||||
.rows_affected();
|
||||
Ok(n == 1)
|
||||
}
|
||||
|
||||
/// The name a browser sent, without any path, control characters or
|
||||
/// excess length.
|
||||
pub fn clean_name(raw: &str) -> String {
|
||||
let base = raw.rsplit(['/', '\\']).next().unwrap_or_default();
|
||||
let name: String = base.chars().filter(|c| !c.is_control()).take(150).collect();
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
"file".into()
|
||||
} else {
|
||||
name.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// What `visa files-check` found.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Check {
|
||||
pub documents: usize,
|
||||
pub problems: Vec<String>,
|
||||
}
|
||||
|
||||
/// Reads every document's file back, decrypts it and compares it with the
|
||||
/// size and checksum recorded at the upload; lists files that belong to no
|
||||
/// document.
|
||||
pub async fn check(db: &PgPool, store: &Store) -> Result<Check> {
|
||||
let rows: Vec<(i64, i32, String)> =
|
||||
sqlx::query_as("SELECT id, size_bytes, sha256 FROM documents ORDER BY id")
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let (ids, other) = store.entries()?;
|
||||
let mut out = Check {
|
||||
documents: rows.len(),
|
||||
..Check::default()
|
||||
};
|
||||
let known: BTreeSet<i64> = rows.iter().map(|r| r.0).collect();
|
||||
for (id, size, sha) in &rows {
|
||||
match store.get(*id) {
|
||||
Ok(bytes) if bytes.len() == *size as usize && files::sha256_hex(&bytes) == *sha => {}
|
||||
Ok(_) => out.problems.push(format!(
|
||||
"document {id}: the file does not match the size and checksum of its upload"
|
||||
)),
|
||||
Err(e) => out.problems.push(format!("document {id}: {e:#}")),
|
||||
}
|
||||
}
|
||||
for id in ids.iter().filter(|id| !known.contains(id)) {
|
||||
out.problems
|
||||
.push(format!("{id}.vdoc: a file without its document"));
|
||||
}
|
||||
for name in other {
|
||||
out.problems
|
||||
.push(format!("{name}: not a file of the store"));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn links_read_back_and_kinds_know_their_record() {
|
||||
let (link, id) = parse_link("arrivals:7").unwrap();
|
||||
assert_eq!((link.column, id), ("arrival_id", 7));
|
||||
for bad in [
|
||||
"",
|
||||
"arrivals",
|
||||
"arrivals:",
|
||||
"arrivals:0",
|
||||
"arrivals:-3",
|
||||
"people:1",
|
||||
"x:1",
|
||||
] {
|
||||
assert!(parse_link(bad).is_none(), "{bad:?}");
|
||||
}
|
||||
assert_eq!(link_value(Some((link, 7))), "arrivals:7");
|
||||
assert_eq!(kind_for_link("arrivals").unwrap().slug, "arrival-stamp");
|
||||
assert_eq!(kind_for_link("addresses").unwrap().slug, "tm30-receipt");
|
||||
// every kind's record is a link, every link has a kind
|
||||
for k in PERSON_KINDS {
|
||||
if let Some(r) = k.record {
|
||||
assert!(LINKS.iter().any(|l| l.slug == r), "{}", k.slug);
|
||||
}
|
||||
}
|
||||
for l in LINKS {
|
||||
assert!(kind_for_link(l.slug).is_some(), "{}", l.slug);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_audit_names_the_changed_fields_only() {
|
||||
let (link, _) = parse_link("passports:1").unwrap();
|
||||
let a = Meta {
|
||||
kind: "passport-photo-page".into(),
|
||||
link: Some((link, 1)),
|
||||
dated_on: None,
|
||||
note: String::new(),
|
||||
};
|
||||
assert_eq!(a.set_fields(), ["kind", "file", "passport_id"]);
|
||||
assert!(a.changed(&a.clone()).is_empty());
|
||||
let b = Meta {
|
||||
link: parse_link("arrivals:4"),
|
||||
note: "page 2".into(),
|
||||
..a.clone()
|
||||
};
|
||||
assert_eq!(a.changed(&b), ["arrival_id", "note", "passport_id"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_lose_their_path_and_control_characters() {
|
||||
assert_eq!(clean_name("C:\\Users\\x\\Scan 1.pdf"), "Scan 1.pdf");
|
||||
assert_eq!(clean_name("/tmp/a/b.jpg"), "b.jpg");
|
||||
assert_eq!(clean_name("pass\nport\u{7}.png"), "passport.png");
|
||||
assert_eq!(clean_name(" "), "file");
|
||||
assert_eq!(clean_name("../"), "file");
|
||||
assert_eq!(clean_name(&"a".repeat(400)).len(), 150);
|
||||
assert_eq!(clean_name("หนังสือเดินทาง.pdf"), "หนังสือเดินทาง.pdf");
|
||||
}
|
||||
}
|
||||
+410
@@ -0,0 +1,410 @@
|
||||
//! The document store. Each uploaded file lies in the files directory as
|
||||
//! `<id>.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<FileKey> {
|
||||
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<u8> {
|
||||
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<Vec<u8>, 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<Store> {
|
||||
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<Vec<u8>> {
|
||||
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<i64>, Vec<String>)> {
|
||||
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::<i64>().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"<html><script>".as_slice(),
|
||||
b"<svg xmlns=".as_slice(),
|
||||
b"GIF89a".as_slice(),
|
||||
b"PK\x03\x04".as_slice(),
|
||||
b"".as_slice(),
|
||||
] {
|
||||
assert_eq!(sniff(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_store_writes_reads_and_removes() {
|
||||
let dir = std::env::temp_dir().join(format!("visa-store-{}", std::process::id()));
|
||||
fs::remove_dir_all(&dir).ok();
|
||||
let store = Store::open(dir.clone(), FileKey::random()).unwrap();
|
||||
store.put(3, b"%PDF-1.4 three").unwrap();
|
||||
assert_eq!(store.get(3).unwrap(), b"%PDF-1.4 three");
|
||||
let on_disk = fs::read(store.path(3)).unwrap();
|
||||
assert!(!on_disk.windows(5).any(|w| w == b"three"));
|
||||
let e = store.put(3, b"%PDF-1.4 again").unwrap_err();
|
||||
assert!(e.to_string().contains("there already"), "{e}");
|
||||
fs::write(dir.join(".9.vdoc.part"), b"left over").unwrap();
|
||||
assert_eq!(
|
||||
store.entries().unwrap(),
|
||||
(vec![3], vec![".9.vdoc.part".to_string()])
|
||||
);
|
||||
store.remove(3).unwrap();
|
||||
store.remove(3).unwrap();
|
||||
assert!(store.get(3).is_err());
|
||||
fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,9 @@ pub mod countries;
|
||||
pub mod dates;
|
||||
pub mod db;
|
||||
pub mod deadlines;
|
||||
pub mod documents;
|
||||
pub mod embedded;
|
||||
pub mod files;
|
||||
pub mod forms;
|
||||
pub mod mrz;
|
||||
pub mod oidc;
|
||||
|
||||
+45
-3
@@ -1,4 +1,5 @@
|
||||
//! `visa [serve|migrate|seed-demo|help]`: the server and its admin commands.
|
||||
//! `visa [serve|migrate|seed-demo|files-check|help]`: the server and its admin
|
||||
//! commands.
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
@@ -6,7 +7,8 @@ use anyhow::{Context, Result, bail, ensure};
|
||||
use tracing::info;
|
||||
|
||||
use visa::config::Config;
|
||||
use visa::{dates, db, seed, web};
|
||||
use visa::files::Store;
|
||||
use visa::{dates, db, documents, seed, web};
|
||||
|
||||
const USAGE: &str = "\
|
||||
visa: immigration records, deadlines and extension packs (visa.buildfor.life)
|
||||
@@ -16,7 +18,9 @@ Usage: visa [COMMAND]
|
||||
Commands:
|
||||
serve run the web server (default); applies pending migrations first
|
||||
migrate apply pending database migrations and exit
|
||||
seed-demo add invented demo people (local development only)
|
||||
seed-demo add invented demo people and documents (local development only)
|
||||
files-check read every document's file back and compare it with its upload;
|
||||
list files without a document (exit status 1 on any problem)
|
||||
help show this text
|
||||
|
||||
Settings come from the environment; see src/config.rs or README.md.";
|
||||
@@ -61,6 +65,36 @@ async fn run(cmd: &str) -> Result<()> {
|
||||
} else {
|
||||
println!("demo people are there already");
|
||||
}
|
||||
match &cfg.files {
|
||||
Some(f) => {
|
||||
let store = Store::open(f.dir.clone(), f.key.clone())?;
|
||||
let n = seed::demo_documents(&pool, &store, dates::today()).await?;
|
||||
println!("demo documents added: {n}");
|
||||
}
|
||||
None => println!("no demo documents: documents are off (no VISA_FILES_DIR)"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
"files-check" => {
|
||||
let cfg = Config::from_env()?;
|
||||
let f = cfg
|
||||
.files
|
||||
.as_ref()
|
||||
.context("documents are off here: no VISA_FILES_DIR and file key")?;
|
||||
let store = Store::open(f.dir.clone(), f.key.clone())?;
|
||||
let pool = db::connect(&cfg).await?;
|
||||
let check = documents::check(&pool, &store).await?;
|
||||
for p in &check.problems {
|
||||
println!("problem: {p}");
|
||||
}
|
||||
println!(
|
||||
"{} documents checked in {} (file key {}): {} problems",
|
||||
check.documents,
|
||||
store.dir().display(),
|
||||
store.key_id(),
|
||||
check.problems.len()
|
||||
);
|
||||
ensure!(check.problems.is_empty(), "the files need attention");
|
||||
Ok(())
|
||||
}
|
||||
"help" | "--help" | "-h" => {
|
||||
@@ -78,6 +112,14 @@ async fn serve() -> Result<()> {
|
||||
let listen = cfg.listen;
|
||||
let login = cfg.login_enabled();
|
||||
let st = web::AppState::new(cfg, pool)?;
|
||||
match &st.files {
|
||||
Some(s) => info!(
|
||||
"documents in {} (file key {})",
|
||||
s.dir().display(),
|
||||
s.key_id()
|
||||
),
|
||||
None => info!("documents are off: no VISA_FILES_DIR (local development)"),
|
||||
}
|
||||
web::spawn_background(st.clone());
|
||||
let app = web::router(st);
|
||||
let listener = tokio::net::TcpListener::bind(listen)
|
||||
|
||||
+442
@@ -9,6 +9,8 @@ use sqlx::PgPool;
|
||||
|
||||
use crate::audit::{self, Action, Entity, Entry};
|
||||
use crate::dates;
|
||||
use crate::documents::{self, Meta, NewFile, Owner};
|
||||
use crate::files::{self, Store};
|
||||
use crate::mrz;
|
||||
use crate::people::{self, AddressInput, PassportInput, PersonInput};
|
||||
use crate::records::{self, Kind, Values};
|
||||
@@ -534,6 +536,7 @@ fn seeded(action: Action, entity: Entity, id: i64, person: Option<i64>) -> Entry
|
||||
entity,
|
||||
entity_id: Some(id),
|
||||
person_id: person,
|
||||
company_id: None,
|
||||
fields: &[],
|
||||
}
|
||||
}
|
||||
@@ -616,3 +619,442 @@ pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
|
||||
tx.commit().await?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// A demo document to add: whose, its kind, its record, its date, the
|
||||
/// file's name and the file.
|
||||
type Planned = (
|
||||
Owner,
|
||||
&'static str,
|
||||
Option<String>,
|
||||
Option<NaiveDate>,
|
||||
String,
|
||||
Vec<u8>,
|
||||
);
|
||||
|
||||
/// A demo document's picture.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Picture {
|
||||
PassportPage,
|
||||
Portrait,
|
||||
Office,
|
||||
}
|
||||
|
||||
/// Adds invented documents to the demo people and companies, unless the
|
||||
/// seed added documents before: scans as PDF (text pages that say they are
|
||||
/// demos) and pictures as PNG (shapes, no one's likeness). Returns how many.
|
||||
pub async fn demo_documents(db: &PgPool, store: &Store, today: NaiveDate) -> Result<usize> {
|
||||
let present: bool =
|
||||
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM documents WHERE uploaded_by = 'seed')")
|
||||
.fetch_one(db)
|
||||
.await?;
|
||||
if present {
|
||||
return Ok(0);
|
||||
}
|
||||
let people: Vec<(i64, String, String)> = sqlx::query_as(
|
||||
"SELECT id, upper(surname), first_name FROM people \
|
||||
WHERE notes = $1 AND archived_at IS NULL ORDER BY id",
|
||||
)
|
||||
.bind(MARKER)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let latest = |table: &'static str, order: &'static str| {
|
||||
format!(
|
||||
"SELECT id FROM {table} WHERE person_id = $1 ORDER BY {order} DESC, id DESC LIMIT 1"
|
||||
)
|
||||
};
|
||||
let mut plan: Vec<Planned> = Vec::new();
|
||||
for (n, (id, surname, given)) in people.iter().enumerate() {
|
||||
let whose = format!("{surname}, {given}");
|
||||
let one = |sql: String| {
|
||||
let id = *id;
|
||||
async move {
|
||||
sqlx::query_scalar::<_, i64>(&sql)
|
||||
.bind(id)
|
||||
.fetch_optional(db)
|
||||
.await
|
||||
}
|
||||
};
|
||||
let owner = Owner::Person(*id);
|
||||
if let Some(pp) = one(latest("passports", "expires_on")).await? {
|
||||
plan.push((
|
||||
owner,
|
||||
"passport-photo-page",
|
||||
Some(format!("passports:{pp}")),
|
||||
None,
|
||||
"passport-photo-page.png".into(),
|
||||
demo_png(Picture::PassportPage),
|
||||
));
|
||||
}
|
||||
if let Some(a) = one(latest("arrivals", "arrived_on")).await? {
|
||||
plan.push((
|
||||
owner,
|
||||
"tdac",
|
||||
Some(format!("arrivals:{a}")),
|
||||
None,
|
||||
"TDAC.pdf".into(),
|
||||
demo_pdf(
|
||||
"Thailand Digital Arrival Card",
|
||||
&[
|
||||
format!("Traveller: {whose}"),
|
||||
"Arrival card number: TDAC-DEMO".into(),
|
||||
],
|
||||
),
|
||||
));
|
||||
}
|
||||
if let Some(r) = one(latest("ninety_day_reports", "reported_on")).await? {
|
||||
plan.push((
|
||||
owner,
|
||||
"ninety-day-receipt",
|
||||
Some(format!("reports:{r}")),
|
||||
None,
|
||||
"TM47 receipt.pdf".into(),
|
||||
demo_pdf(
|
||||
"Receipt of notification of staying over 90 days",
|
||||
&[format!("Name: {whose}"), "Form TM.47, filed online".into()],
|
||||
),
|
||||
));
|
||||
}
|
||||
if n == 0 {
|
||||
plan.push((
|
||||
owner,
|
||||
"photo",
|
||||
None,
|
||||
Some(today - TimeDelta::days(20)),
|
||||
"photo 4x6.png".into(),
|
||||
demo_png(Picture::Portrait),
|
||||
));
|
||||
if let Some(a) = one(latest("addresses", "moved_in_on")).await? {
|
||||
plan.push((
|
||||
owner,
|
||||
"tm30-receipt",
|
||||
Some(format!("addresses:{a}")),
|
||||
None,
|
||||
"TM30 receipt.pdf".into(),
|
||||
demo_pdf(
|
||||
"Receipt of notification of residence (TM.30)",
|
||||
&[
|
||||
format!("Foreigner: {whose}"),
|
||||
"Notified by the house master".into(),
|
||||
],
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let companies: Vec<(i64, String)> =
|
||||
sqlx::query_as("SELECT id, name FROM companies WHERE notes = $1 ORDER BY id LIMIT 1")
|
||||
.bind(MARKER)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
for (id, name) in companies {
|
||||
let owner = Owner::Company(id);
|
||||
plan.push((
|
||||
owner,
|
||||
"company-certificate",
|
||||
None,
|
||||
Some(today - TimeDelta::days(40)),
|
||||
"company certificate.pdf".into(),
|
||||
demo_pdf(
|
||||
"Company certificate (certified copy)",
|
||||
&[
|
||||
format!("Company: {name}"),
|
||||
"Certified by the registrar".into(),
|
||||
],
|
||||
),
|
||||
));
|
||||
// older than six months: out of date for the pack (phase 6)
|
||||
plan.push((
|
||||
owner,
|
||||
"shareholders",
|
||||
None,
|
||||
Some(today - TimeDelta::days(240)),
|
||||
"BOJ5.pdf".into(),
|
||||
demo_pdf(
|
||||
"List of shareholders (BOJ.5)",
|
||||
&[
|
||||
format!("Company: {name}"),
|
||||
"Shareholders as of the last meeting".into(),
|
||||
],
|
||||
),
|
||||
));
|
||||
plan.push((
|
||||
owner,
|
||||
"office-photo",
|
||||
None,
|
||||
None,
|
||||
"office outside.png".into(),
|
||||
demo_png(Picture::Office),
|
||||
));
|
||||
}
|
||||
let mut tx = db.begin().await?;
|
||||
let mut written = Vec::new();
|
||||
for (owner, kind, link, dated_on, name, bytes) in &plan {
|
||||
let meta = Meta {
|
||||
kind: (*kind).to_string(),
|
||||
link: link.as_deref().and_then(documents::parse_link),
|
||||
dated_on: *dated_on,
|
||||
note: "Demo file".into(),
|
||||
};
|
||||
let sha256 = files::sha256_hex(bytes);
|
||||
let file = NewFile {
|
||||
name,
|
||||
content_type: files::sniff(bytes).expect("demo files have a known type"),
|
||||
size: i32::try_from(bytes.len())?,
|
||||
sha256: &sha256,
|
||||
};
|
||||
let id = documents::insert(&mut tx, *owner, &meta, &file, "seed").await?;
|
||||
store.put(id, bytes)?;
|
||||
written.push(id);
|
||||
audit::record(
|
||||
&mut *tx,
|
||||
&Entry {
|
||||
actor: "seed",
|
||||
action: Action::Create,
|
||||
entity: Entity::Document,
|
||||
entity_id: Some(id),
|
||||
person_id: owner.person(),
|
||||
company_id: owner.company(),
|
||||
fields: &[],
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(written.len())
|
||||
}
|
||||
|
||||
/// A one-page PDF in the app's colours: a title, a few lines and the demo
|
||||
/// marker. ASCII text in Helvetica, so it needs no embedded font.
|
||||
pub fn demo_pdf(title: &str, lines: &[String]) -> Vec<u8> {
|
||||
let esc = |s: &str| {
|
||||
s.chars()
|
||||
.filter(char::is_ascii)
|
||||
.collect::<String>()
|
||||
.replace('\\', "\\\\")
|
||||
.replace('(', "\\(")
|
||||
.replace(')', "\\)")
|
||||
};
|
||||
let mut content =
|
||||
String::from("0.027 0.075 0.137 rg 0 762 595 80 re f\n0.961 0.753 0 rg 0 756 595 6 re f\n");
|
||||
content.push_str(&format!(
|
||||
"BT /F1 18 Tf 1 1 1 rg 48 792 Td ({}) Tj ET\n",
|
||||
esc(title)
|
||||
));
|
||||
let mut y = 700;
|
||||
for line in lines {
|
||||
content.push_str(&format!(
|
||||
"BT /F1 12 Tf 0.1 0.1 0.1 rg 48 {y} Td ({}) Tj ET\n",
|
||||
esc(line)
|
||||
));
|
||||
y -= 22;
|
||||
}
|
||||
content.push_str(&format!(
|
||||
"BT /F1 26 Tf 0.85 0.2 0.2 rg 48 520 Td (SPECIMEN) Tj ET\n\
|
||||
BT /F1 10 Tf 0.4 0.4 0.4 rg 48 60 Td ({}) Tj ET\n",
|
||||
esc(MARKER)
|
||||
));
|
||||
let objects = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] \
|
||||
/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>"
|
||||
.to_string(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"
|
||||
.to_string(),
|
||||
format!(
|
||||
"<< /Length {} >>\nstream\n{content}endstream",
|
||||
content.len()
|
||||
),
|
||||
];
|
||||
let mut out = b"%PDF-1.4\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objects.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(
|
||||
format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
|
||||
);
|
||||
for o in offsets {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(
|
||||
format!(
|
||||
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",
|
||||
objects.len() + 1
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
out
|
||||
}
|
||||
|
||||
/// A picture made of shapes, as a PNG with a palette.
|
||||
fn demo_png(picture: Picture) -> Vec<u8> {
|
||||
const PALETTE: [[u8; 3]; 8] = [
|
||||
[0xf3, 0xef, 0xe2], // paper
|
||||
[0x07, 0x13, 0x23], // navy
|
||||
[0xf5, 0xc0, 0x00], // gold
|
||||
[0x9b, 0xa8, 0xba], // grey
|
||||
[0xd8, 0xdd, 0xe5], // light grey
|
||||
[0xff, 0xff, 0xff], // white
|
||||
[0x3a, 0x45, 0x56], // ink
|
||||
[0xa9, 0xc8, 0xe8], // sky
|
||||
];
|
||||
let (w, h) = match picture {
|
||||
Picture::PassportPage => (600usize, 420usize),
|
||||
Picture::Portrait => (240, 360),
|
||||
Picture::Office => (480, 320),
|
||||
};
|
||||
let mut px = vec![0u8; w * h];
|
||||
let mut fill = |x0: usize, y0: usize, x1: usize, y1: usize, c: u8| {
|
||||
for y in y0.min(h)..y1.min(h) {
|
||||
for x in x0.min(w)..x1.min(w) {
|
||||
px[y * w + x] = c;
|
||||
}
|
||||
}
|
||||
};
|
||||
let head = |cx: f64, cy: f64, r: f64, x: usize, y: usize| {
|
||||
let (dx, dy) = (x as f64 - cx, (y as f64 - cy) * 0.85);
|
||||
dx * dx + dy * dy <= r * r
|
||||
};
|
||||
match picture {
|
||||
Picture::PassportPage => {
|
||||
fill(0, 0, w, 56, 1);
|
||||
fill(0, 56, w, 62, 2);
|
||||
fill(30, 92, 170, 282, 4);
|
||||
for (i, len) in [220usize, 160, 250, 140, 200, 120].iter().enumerate() {
|
||||
let y = 100 + i * 30;
|
||||
fill(200, y, 200 + len, y + 12, 6);
|
||||
}
|
||||
fill(0, 320, w, h, 5);
|
||||
for row in 0..2 {
|
||||
for cell in 0..44 {
|
||||
let (x, y) = (24 + cell * 12, 338 + row * 34);
|
||||
fill(x, y, x + 9, y + 18, 6);
|
||||
}
|
||||
}
|
||||
}
|
||||
Picture::Portrait => {
|
||||
fill(0, 0, w, h, 4);
|
||||
fill(40, 270, 200, h, 1);
|
||||
}
|
||||
Picture::Office => {
|
||||
fill(0, 0, w, 200, 7);
|
||||
fill(0, 260, w, h, 3);
|
||||
fill(90, 70, 390, 260, 0);
|
||||
fill(90, 62, 390, 72, 1);
|
||||
for col in 0..5 {
|
||||
for row in 0..3 {
|
||||
let (x, y) = (112 + col * 56, 92 + row * 52);
|
||||
fill(x, y, x + 32, y + 30, 1);
|
||||
}
|
||||
}
|
||||
fill(212, 200, 268, 260, 2);
|
||||
}
|
||||
}
|
||||
if let Picture::Portrait = picture {
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
if head(120.0, 150.0, 62.0, x, y) {
|
||||
px[y * w + x] = 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Picture::PassportPage = picture {
|
||||
for y in 92..282 {
|
||||
for x in 30..170 {
|
||||
if head(100.0, 160.0, 40.0, x, y) {
|
||||
px[y * w + x] = 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
for y in 230..282 {
|
||||
for x in 50..150 {
|
||||
px[y * w + x] = 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
// the image data: each row with filter 0, in stored deflate blocks
|
||||
let mut raw = Vec::with_capacity(h * (w + 1));
|
||||
for row in px.chunks(w) {
|
||||
raw.push(0);
|
||||
raw.extend_from_slice(row);
|
||||
}
|
||||
let mut z = vec![0x78, 0x01];
|
||||
let blocks: Vec<&[u8]> = raw.chunks(65_535).collect();
|
||||
for (i, b) in blocks.iter().enumerate() {
|
||||
z.push(u8::from(i + 1 == blocks.len()));
|
||||
let len = b.len() as u16;
|
||||
z.extend_from_slice(&len.to_le_bytes());
|
||||
z.extend_from_slice(&(!len).to_le_bytes());
|
||||
z.extend_from_slice(b);
|
||||
}
|
||||
z.extend_from_slice(&adler32(&raw).to_be_bytes());
|
||||
let mut ihdr = Vec::new();
|
||||
ihdr.extend_from_slice(&(w as u32).to_be_bytes());
|
||||
ihdr.extend_from_slice(&(h as u32).to_be_bytes());
|
||||
ihdr.extend_from_slice(&[8, 3, 0, 0, 0]);
|
||||
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
chunk(&mut out, b"IHDR", &ihdr);
|
||||
chunk(&mut out, b"PLTE", &PALETTE.concat());
|
||||
chunk(&mut out, b"IDAT", &z);
|
||||
chunk(&mut out, b"IEND", &[]);
|
||||
out
|
||||
}
|
||||
|
||||
fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
|
||||
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
|
||||
out.extend_from_slice(kind);
|
||||
out.extend_from_slice(data);
|
||||
let mut crc = 0xFFFF_FFFFu32;
|
||||
for &b in kind.iter().chain(data) {
|
||||
crc ^= u32::from(b);
|
||||
for _ in 0..8 {
|
||||
crc = if crc & 1 == 1 {
|
||||
(crc >> 1) ^ 0xEDB8_8320
|
||||
} else {
|
||||
crc >> 1
|
||||
};
|
||||
}
|
||||
}
|
||||
out.extend_from_slice(&(!crc).to_be_bytes());
|
||||
}
|
||||
|
||||
fn adler32(data: &[u8]) -> u32 {
|
||||
let (mut a, mut b) = (1u32, 0u32);
|
||||
for &x in data {
|
||||
a = (a + u32::from(x)) % 65_521;
|
||||
b = (b + a) % 65_521;
|
||||
}
|
||||
(b << 16) | a
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod demo_file_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn demo_files_are_what_they_say() {
|
||||
let pdf = demo_pdf("Title (demo)", &["Line".to_string()]);
|
||||
assert_eq!(files::sniff(&pdf), Some("application/pdf"));
|
||||
let text = String::from_utf8_lossy(&pdf);
|
||||
assert!(text.contains(MARKER));
|
||||
assert!(text.contains("Title \\(demo\\)"));
|
||||
// the cross-reference table points at the objects
|
||||
let xref: usize = text
|
||||
.rsplit("startxref\n")
|
||||
.next()
|
||||
.and_then(|t| t.lines().next())
|
||||
.and_then(|n| n.parse().ok())
|
||||
.unwrap();
|
||||
assert!(text[xref..].starts_with("xref"));
|
||||
for p in [Picture::PassportPage, Picture::Portrait, Picture::Office] {
|
||||
let png = demo_png(p);
|
||||
assert_eq!(files::sniff(&png), Some("image/png"));
|
||||
assert!(png.ends_with(&[0xAE, 0x42, 0x60, 0x82]), "IEND's CRC");
|
||||
}
|
||||
assert_eq!(adler32(b"Wikipedia"), 0x11E6_0398);
|
||||
}
|
||||
}
|
||||
@@ -187,6 +187,7 @@ pub async fn callback(
|
||||
entity: Entity::Session,
|
||||
entity_id: None,
|
||||
person_id: None,
|
||||
company_id: None,
|
||||
fields: &[],
|
||||
},
|
||||
)
|
||||
@@ -228,6 +229,7 @@ pub async fn logout(
|
||||
entity: Entity::Session,
|
||||
entity_id: None,
|
||||
person_id: None,
|
||||
company_id: None,
|
||||
fields: &[],
|
||||
},
|
||||
)
|
||||
|
||||
+34
-5
@@ -1,6 +1,7 @@
|
||||
//! Pages for companies: the list, a company with the people it employs, the
|
||||
//! form, archiving, and adding or removing employees.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::{Path, Query, State};
|
||||
@@ -10,11 +11,13 @@ use axum::{Extension, Form};
|
||||
use minijinja::context;
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::documents;
|
||||
use super::records::datalists;
|
||||
use super::{AppState, Res, not_found_page, page};
|
||||
use crate::audit::{self, Action, Entity, Entry};
|
||||
use crate::companies;
|
||||
use crate::dates;
|
||||
use crate::documents::Owner;
|
||||
use crate::forms::{Errors, Fields, err, get};
|
||||
use crate::records::{self, COMPANIES, Options, Values};
|
||||
use crate::session::User;
|
||||
@@ -55,6 +58,7 @@ fn company_entry<'a>(user: &'a User, action: Action, id: i64, fields: &'a [Strin
|
||||
entity: Entity::Company,
|
||||
entity_id: Some(id),
|
||||
person_id: None,
|
||||
company_id: Some(id),
|
||||
fields,
|
||||
}
|
||||
}
|
||||
@@ -160,23 +164,47 @@ pub async fn show(
|
||||
State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
) -> Res {
|
||||
company_page(
|
||||
&st,
|
||||
&user,
|
||||
id,
|
||||
&documents::Values::default(),
|
||||
&Errors::new(),
|
||||
StatusCode::OK,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// The company's page, with its documents and their upload form (and the
|
||||
/// upload's errors, when one was refused).
|
||||
pub async fn company_page(
|
||||
st: &AppState,
|
||||
user: &User,
|
||||
id: i64,
|
||||
values: &documents::Values,
|
||||
errors: &Errors,
|
||||
status: StatusCode,
|
||||
) -> Res {
|
||||
let Some(r) = records::get(&st.db, &COMPANIES, None, id).await? else {
|
||||
return Ok(not_found_page(&st));
|
||||
return Ok(not_found_page(st));
|
||||
};
|
||||
let archived_at = companies::archived_at(&st.db, id).await?.flatten();
|
||||
let c = companies::view(&r, archived_at);
|
||||
let employees = companies::employees(&st.db, id, dates::today()).await?;
|
||||
let candidates = companies::candidates(&st.db, id).await?;
|
||||
let owner = Owner::Company(id);
|
||||
let docs = documents::views(st, owner, &HashMap::new()).await?;
|
||||
let upload = documents::upload_context(st, owner, values, errors, &[]);
|
||||
let title = c.name.clone();
|
||||
Ok(page(
|
||||
&st,
|
||||
&user,
|
||||
st,
|
||||
user,
|
||||
"company.html",
|
||||
&title,
|
||||
"companies",
|
||||
StatusCode::OK,
|
||||
context! { c, employees, candidates },
|
||||
status,
|
||||
context! { c, employees, candidates, docs, upload },
|
||||
))
|
||||
}
|
||||
|
||||
@@ -272,6 +300,7 @@ fn employer_changed<'a>(user: &'a User, person: i64, fields: &'a [String]) -> En
|
||||
entity: Entity::Person,
|
||||
entity_id: Some(person),
|
||||
person_id: Some(person),
|
||||
company_id: None,
|
||||
fields,
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+126
-10
@@ -4,6 +4,7 @@ pub mod activity;
|
||||
pub mod auth;
|
||||
pub mod companies;
|
||||
pub mod dashboard;
|
||||
pub mod documents;
|
||||
pub mod people;
|
||||
pub mod records;
|
||||
|
||||
@@ -11,7 +12,7 @@ use std::sync::{Arc, RwLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::extract::{Path, Request, State};
|
||||
use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, Request, State};
|
||||
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header};
|
||||
use axum::middleware::{self, Next};
|
||||
use axum::response::{Html, IntoResponse, Redirect, Response};
|
||||
@@ -22,6 +23,8 @@ use sqlx::PgPool;
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
use crate::config::{Auth, Config};
|
||||
use crate::documents::Owner;
|
||||
use crate::files::Store;
|
||||
use crate::forms::Fields;
|
||||
use crate::session::{self, Flows, SESSION_COOKIE, User};
|
||||
use crate::{VERSION, countries, dates, embedded, oidc};
|
||||
@@ -35,6 +38,8 @@ pub struct AppState {
|
||||
provider: RwLock<Option<Arc<oidc::Provider>>>,
|
||||
/// The form token of local development, which has no sessions.
|
||||
local_csrf: String,
|
||||
/// The documents' files; none in local development without a key.
|
||||
pub files: Option<Store>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
@@ -44,8 +49,14 @@ impl AppState {
|
||||
.connect_timeout(Duration::from_secs(5))
|
||||
.user_agent(concat!("visa/", env!("CARGO_PKG_VERSION")))
|
||||
.build()?;
|
||||
let files = cfg
|
||||
.files
|
||||
.as_ref()
|
||||
.map(|f| Store::open(f.dir.clone(), f.key.clone()))
|
||||
.transpose()?;
|
||||
Ok(Arc::new(AppState {
|
||||
templates: templates()?,
|
||||
files,
|
||||
cfg,
|
||||
db,
|
||||
http,
|
||||
@@ -225,6 +236,70 @@ pub fn router(st: Arc<AppState>) -> Router {
|
||||
),
|
||||
);
|
||||
}
|
||||
// Documents of people and of companies: the upload, a file, the page
|
||||
// about one document, its change and its deletion. A person's documents
|
||||
// have their own tab; a company's are on its page.
|
||||
r = r.route("/people/{id}/documents", get(documents::person_tab));
|
||||
type OwnerOf = fn(i64) -> Owner;
|
||||
let owners: [(&str, OwnerOf); 2] = [("people", Owner::Person), ("companies", Owner::Company)];
|
||||
for (prefix, owner) in owners {
|
||||
let base = format!("/{prefix}/{{id}}/documents");
|
||||
r = r
|
||||
.route(
|
||||
&base,
|
||||
post(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path(id): Path<i64>,
|
||||
mp: Multipart| {
|
||||
documents::upload(st, user, owner(id), mp)
|
||||
},
|
||||
)
|
||||
.layer(DefaultBodyLimit::max(documents::UPLOAD_LIMIT)),
|
||||
)
|
||||
.route(
|
||||
&format!("{base}/{{did}}/file"),
|
||||
get(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, did)): Path<(i64, i64)>,
|
||||
Query(q): Query<documents::FileQuery>| {
|
||||
documents::file(st, user, owner(id), did, q)
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{base}/{{did}}/edit"),
|
||||
get(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, did)): Path<(i64, i64)>| {
|
||||
documents::edit_form(st, user, owner(id), did)
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{base}/{{did}}"),
|
||||
post(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, did)): Path<(i64, i64)>,
|
||||
Form(f): Form<Fields>| {
|
||||
documents::update(st, user, owner(id), did, f)
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{base}/{{did}}/delete"),
|
||||
post(
|
||||
move |State(st): State<Arc<AppState>>,
|
||||
Extension(user): Extension<User>,
|
||||
Path((id, did)): Path<(i64, i64)>| {
|
||||
documents::delete(st, user, owner(id), did)
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
r.route("/activity", get(activity::page))
|
||||
.route("/login", get(auth::login))
|
||||
.route("/auth/callback", get(auth::callback))
|
||||
@@ -232,6 +307,11 @@ pub fn router(st: Arc<AppState>) -> Router {
|
||||
.route("/signed-out", get(auth::signed_out))
|
||||
.route("/healthz", get(healthz))
|
||||
.route("/static/{*path}", get(static_file))
|
||||
// asked for by pages without their own icon: an image or a PDF
|
||||
.route(
|
||||
"/favicon.ico",
|
||||
get(|| static_file(Path("favicon.svg".to_string()))),
|
||||
)
|
||||
.fallback(not_found)
|
||||
.layer(middleware::from_fn_with_state(st.clone(), forms_guard))
|
||||
.layer(middleware::from_fn_with_state(st.clone(), gate))
|
||||
@@ -243,7 +323,7 @@ pub fn router(st: Arc<AppState>) -> Router {
|
||||
fn is_public(path: &str) -> bool {
|
||||
matches!(
|
||||
path,
|
||||
"/healthz" | "/login" | "/auth/callback" | "/signed-out"
|
||||
"/healthz" | "/login" | "/auth/callback" | "/signed-out" | "/favicon.ico"
|
||||
) || path.starts_with("/static/")
|
||||
}
|
||||
|
||||
@@ -309,6 +389,23 @@ async fn forms_guard(State(st): State<Arc<AppState>>, req: Request, next: Next)
|
||||
// public paths take no forms
|
||||
return next.run(req).await;
|
||||
};
|
||||
let multipart = req
|
||||
.headers()
|
||||
.get(header::CONTENT_TYPE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.is_some_and(|ct| ct.to_ascii_lowercase().starts_with("multipart/form-data"));
|
||||
if multipart {
|
||||
// An upload checks its token itself, as the form's first field, so
|
||||
// that its files are not held here.
|
||||
if is_upload(req.uri().path()) {
|
||||
return next.run(req).await;
|
||||
}
|
||||
return (
|
||||
StatusCode::UNSUPPORTED_MEDIA_TYPE,
|
||||
"This address takes no uploads.",
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let (parts, body) = req.into_parts();
|
||||
let bytes = match axum::body::to_bytes(body, FORM_LIMIT).await {
|
||||
Ok(b) => b,
|
||||
@@ -334,19 +431,35 @@ async fn forms_guard(State(st): State<Arc<AppState>>, req: Request, next: Next)
|
||||
};
|
||||
if !token.is_some_and(|t| session::same_token(&t, &user.csrf)) {
|
||||
warn!("refused a form without a valid token from {}", user.login);
|
||||
return message(
|
||||
&st,
|
||||
StatusCode::FORBIDDEN,
|
||||
"The form has expired",
|
||||
"The page was older than your current session. Go back, reload the page and send \
|
||||
the form again.",
|
||||
("/", "Open the app"),
|
||||
);
|
||||
return expired(&st);
|
||||
}
|
||||
next.run(Request::from_parts(parts, Body::from(bytes)))
|
||||
.await
|
||||
}
|
||||
|
||||
/// The addresses that take uploads: `/people/{id}/documents` and
|
||||
/// `/companies/{id}/documents`.
|
||||
fn is_upload(path: &str) -> bool {
|
||||
let parts: Vec<&str> = path.split('/').collect();
|
||||
matches!(
|
||||
parts.as_slice(),
|
||||
["", "people" | "companies", id, "documents"]
|
||||
if !id.is_empty() && id.bytes().all(|b| b.is_ascii_digit())
|
||||
)
|
||||
}
|
||||
|
||||
/// A form without the session's token.
|
||||
pub fn expired(st: &AppState) -> Response {
|
||||
message(
|
||||
st,
|
||||
StatusCode::FORBIDDEN,
|
||||
"The form has expired",
|
||||
"The page was older than your current session. Go back, reload the page and send the \
|
||||
form again.",
|
||||
("/", "Open the app"),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn same_site(st: &AppState, headers: &HeaderMap) -> bool {
|
||||
match headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) {
|
||||
Some(v) => v == "same-origin",
|
||||
@@ -360,6 +473,8 @@ pub fn same_site(st: &AppState, headers: &HeaderMap) -> bool {
|
||||
async fn security_headers(req: Request, next: Next) -> Response {
|
||||
let mut resp = next.run(req).await;
|
||||
let h = resp.headers_mut();
|
||||
// a document's file brings its own, stricter policy
|
||||
if !h.contains_key(header::CONTENT_SECURITY_POLICY) {
|
||||
h.insert(
|
||||
header::CONTENT_SECURITY_POLICY,
|
||||
HeaderValue::from_static(
|
||||
@@ -367,6 +482,7 @@ async fn security_headers(req: Request, next: Next) -> Response {
|
||||
connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
||||
),
|
||||
);
|
||||
}
|
||||
h.insert(
|
||||
header::X_CONTENT_TYPE_OPTIONS,
|
||||
HeaderValue::from_static("nosniff"),
|
||||
|
||||
@@ -193,6 +193,7 @@ fn log<'a>(
|
||||
entity,
|
||||
entity_id: Some(id),
|
||||
person_id: Some(person),
|
||||
company_id: None,
|
||||
fields,
|
||||
}
|
||||
}
|
||||
@@ -322,6 +323,7 @@ pub async fn show(
|
||||
let assessment = deadlines::for_person(&st.db, id, today).await?;
|
||||
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
|
||||
let recent = audit::recent(&st.db, Some(id), 6).await?;
|
||||
let docs = super::documents::chips(&st, id).await?;
|
||||
let title = view.name.clone();
|
||||
Ok(page(
|
||||
&st,
|
||||
@@ -335,6 +337,7 @@ pub async fn show(
|
||||
tab => "overview",
|
||||
passports,
|
||||
addresses,
|
||||
docs,
|
||||
recent,
|
||||
stay => assessment.stay,
|
||||
deadlines => assessment.items,
|
||||
|
||||
@@ -86,6 +86,7 @@ pub async fn stay(st: Arc<AppState>, user: User, id: i64) -> Res {
|
||||
});
|
||||
}
|
||||
let assessment = deadlines::for_person(&st.db, id, today).await?;
|
||||
let docs = super::documents::chips(&st, id).await?;
|
||||
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
|
||||
let title = format!("Visa and stay: {}", view.name);
|
||||
Ok(page(
|
||||
@@ -99,6 +100,7 @@ pub async fn stay(st: Arc<AppState>, user: User, id: i64) -> Res {
|
||||
p => view,
|
||||
tab => "stay",
|
||||
sections,
|
||||
docs,
|
||||
stay => assessment.stay,
|
||||
deadlines => assessment.items,
|
||||
},
|
||||
@@ -235,6 +237,7 @@ fn entry<'a>(
|
||||
entity: kind.entity,
|
||||
entity_id: Some(record),
|
||||
person_id: Some(person),
|
||||
company_id: None,
|
||||
fields,
|
||||
}
|
||||
}
|
||||
|
||||
+195
-1
@@ -547,10 +547,19 @@ main {
|
||||
}
|
||||
.rowactions {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 14px;
|
||||
font-size: 13px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
/* a record's documents, next to its Edit */
|
||||
.rowactions .doclink {
|
||||
padding: 0 7px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 5px;
|
||||
background: var(--panel2);
|
||||
color: var(--fg);
|
||||
}
|
||||
.empty-inline {
|
||||
margin: 0;
|
||||
color: var(--mute);
|
||||
@@ -695,6 +704,16 @@ textarea.mrz {
|
||||
color: var(--hd);
|
||||
border-bottom-color: var(--accent);
|
||||
}
|
||||
/* four tabs fit a phone */
|
||||
@media (max-width: 560px) {
|
||||
.tabs {
|
||||
gap: 0;
|
||||
}
|
||||
.tabs a {
|
||||
padding: 8px 9px;
|
||||
font-size: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- status and deadlines */
|
||||
.stayline {
|
||||
@@ -796,6 +815,178 @@ textarea.mrz {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* ---- documents: the upload strip, the list, a preview */
|
||||
.vh {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.upload {
|
||||
margin: 0 0 16px;
|
||||
}
|
||||
.upload .notice {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.drop {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 10px;
|
||||
padding: 9px 14px;
|
||||
border: 1.5px dashed var(--stroke);
|
||||
border-radius: 10px;
|
||||
background: var(--field);
|
||||
color: var(--mute);
|
||||
}
|
||||
.drop:hover,
|
||||
.drop.over {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent-s);
|
||||
color: var(--fg);
|
||||
}
|
||||
.drop:focus-within {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.drop.has-err {
|
||||
border-color: var(--bad);
|
||||
}
|
||||
/* the file input covers the strip: a click opens the chooser, and files
|
||||
dropped anywhere on it land in the input, with or without script */
|
||||
.drop input[type="file"] {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
opacity: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
.drop label {
|
||||
font-size: 14px;
|
||||
}
|
||||
.drop label b {
|
||||
color: var(--link);
|
||||
}
|
||||
.drop .hint {
|
||||
margin: 0 0 0 auto;
|
||||
}
|
||||
.drop-icon {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 6px;
|
||||
background: var(--accent-s);
|
||||
color: var(--hd);
|
||||
font-weight: 800;
|
||||
line-height: 1;
|
||||
}
|
||||
.drop-names {
|
||||
color: var(--fg);
|
||||
font-size: 13.5px;
|
||||
font-weight: 650;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.drop-names:empty {
|
||||
display: none;
|
||||
}
|
||||
.drop-names.bad {
|
||||
color: var(--bad);
|
||||
}
|
||||
.upload-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(150px, 1fr) minmax(200px, 1.5fr) 165px minmax(140px, 1fr) auto;
|
||||
gap: 10px 12px;
|
||||
align-items: end;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.upload-row.company {
|
||||
grid-template-columns: minmax(200px, 1.3fr) 165px minmax(160px, 1.4fr) auto;
|
||||
}
|
||||
@media (max-width: 1060px) {
|
||||
.upload-row,
|
||||
.upload-row.company {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
.upload-row,
|
||||
.upload-row.company {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
.upload-row .field {
|
||||
min-width: 0;
|
||||
}
|
||||
/* the list runs to the card's edges */
|
||||
.tblwrap.bleed {
|
||||
margin: 0 -20px -18px;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
/* a kind's name on one or two lines, not broken before its last word */
|
||||
.docs .docname {
|
||||
min-width: 190px;
|
||||
}
|
||||
.docs .acts {
|
||||
white-space: nowrap;
|
||||
text-align: right;
|
||||
font-size: 13px;
|
||||
}
|
||||
.docs .acts a + a {
|
||||
margin-left: 12px;
|
||||
}
|
||||
.docs .fname {
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.docs .ps {
|
||||
display: none;
|
||||
}
|
||||
.tbl tbody tr:target td {
|
||||
background: var(--accent-s);
|
||||
}
|
||||
.ftype {
|
||||
display: inline-block;
|
||||
padding: 0 5px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 4px;
|
||||
background: var(--panel2);
|
||||
color: var(--mute);
|
||||
font: 700 10.5px/1.5 var(--mono);
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.docs .ps {
|
||||
display: block;
|
||||
}
|
||||
.docs .acts a + a {
|
||||
margin-left: 8px;
|
||||
}
|
||||
}
|
||||
.card > header .actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
.preview {
|
||||
display: block;
|
||||
margin: 0 0 14px;
|
||||
}
|
||||
.preview img {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
max-height: 420px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
background: var(--panel2);
|
||||
}
|
||||
|
||||
/* ---- a page outside the frame */
|
||||
.solo {
|
||||
max-width: 560px;
|
||||
@@ -846,6 +1037,9 @@ textarea.mrz {
|
||||
.card {
|
||||
padding: 14px;
|
||||
}
|
||||
.tblwrap.bleed {
|
||||
margin: 0 -14px -14px;
|
||||
}
|
||||
.kv {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 2px;
|
||||
|
||||
+76
-2
@@ -1,5 +1,6 @@
|
||||
// Theme switch, the list filter and delete confirmations. Event delegation
|
||||
// and no inline handlers: the Content Security Policy allows no inline script.
|
||||
// Theme switch, the list filter, delete confirmations and the upload strip.
|
||||
// Event delegation and no inline handlers: the Content Security Policy
|
||||
// allows no inline script.
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
@@ -65,4 +66,77 @@
|
||||
}
|
||||
});
|
||||
document.addEventListener("DOMContentLoaded", applyFilter);
|
||||
|
||||
// ---- uploads: the file input covers the dashed strip, so a click or a
|
||||
// drop lands on it; this shows the chosen names (and any too large), lights
|
||||
// the strip while files are dragged over it, and keeps a file dropped
|
||||
// beside it from replacing the page.
|
||||
function showFiles(input) {
|
||||
var strip = input.closest(".drop");
|
||||
var out = strip && strip.querySelector("[data-drop-names]");
|
||||
if (!out) return;
|
||||
var max = parseInt(strip.getAttribute("data-max"), 10) || 0;
|
||||
var names = [];
|
||||
var big = [];
|
||||
Array.prototype.forEach.call(input.files || [], function (f) {
|
||||
names.push(f.name);
|
||||
if (max && f.size > max) big.push(f.name);
|
||||
});
|
||||
out.textContent = big.length
|
||||
? big.join(", ") + (big.length === 1 ? " is" : " are") + " too large"
|
||||
: names.join(", ");
|
||||
out.classList.toggle("bad", big.length > 0);
|
||||
}
|
||||
document.addEventListener("change", function (ev) {
|
||||
var t = ev.target;
|
||||
if (t && t.matches && t.matches(".drop input[type=file]")) showFiles(t);
|
||||
});
|
||||
function stripOf(ev) {
|
||||
return ev.target && ev.target.closest ? ev.target.closest(".drop") : null;
|
||||
}
|
||||
document.addEventListener("dragover", function (ev) {
|
||||
var s = stripOf(ev);
|
||||
if (s) {
|
||||
s.classList.add("over");
|
||||
} else if (document.querySelector(".drop")) {
|
||||
ev.preventDefault();
|
||||
ev.dataTransfer.dropEffect = "none";
|
||||
}
|
||||
});
|
||||
document.addEventListener("dragleave", function (ev) {
|
||||
var s = stripOf(ev);
|
||||
if (s) s.classList.remove("over");
|
||||
});
|
||||
document.addEventListener("drop", function (ev) {
|
||||
var s = stripOf(ev);
|
||||
if (s) {
|
||||
s.classList.remove("over");
|
||||
// the files go to the input here, the same in every browser
|
||||
var input = s.querySelector("input[type=file]");
|
||||
var dropped = ev.dataTransfer && ev.dataTransfer.files;
|
||||
if (input && dropped && dropped.length) {
|
||||
ev.preventDefault();
|
||||
input.files = dropped;
|
||||
showFiles(input);
|
||||
}
|
||||
} else if (document.querySelector(".drop")) {
|
||||
ev.preventDefault();
|
||||
}
|
||||
});
|
||||
// one upload at a time: the button waits for the answer
|
||||
document.addEventListener("submit", function (ev) {
|
||||
var f = ev.target;
|
||||
if (ev.defaultPrevented || !f.classList || !f.classList.contains("upload")) return;
|
||||
var b = f.querySelector("button[type=submit]");
|
||||
if (b) {
|
||||
b.disabled = true;
|
||||
b.textContent = "Uploading...";
|
||||
}
|
||||
});
|
||||
window.addEventListener("pageshow", function () {
|
||||
document.querySelectorAll(".upload button[type=submit]").forEach(function (b) {
|
||||
b.disabled = false;
|
||||
b.textContent = "Upload";
|
||||
});
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,85 @@
|
||||
{#- Documents: the upload with what the files are, and the list. A person's
|
||||
Documents tab and a company's page use them. -#}
|
||||
{% import "_fields.html" as fm %}
|
||||
|
||||
{#- The record a person's document belongs to, by kind of record. -#}
|
||||
{% macro belongs(value, groups, err="") -%}
|
||||
<div class="field{% if err %} has-err{% endif %}">
|
||||
<label for="f-link">Belongs to</label>
|
||||
<select id="f-link" name="link"{% if err %} aria-invalid="true" aria-describedby="e-link"{% endif %}>
|
||||
<option value="">The person, no record</option>
|
||||
{%- for g in groups %}
|
||||
<optgroup label="{{ g.title }}">
|
||||
{%- for o in g.options %}
|
||||
<option value="{{ o[0] }}"{% if o[0] == value %} selected{% endif %}>{{ o[1] }}</option>
|
||||
{%- endfor %}
|
||||
</optgroup>
|
||||
{%- endfor %}
|
||||
</select>
|
||||
{%- if err %}
|
||||
<p class="err" id="e-link">{{ err }}</p>
|
||||
{%- endif %}
|
||||
</div>
|
||||
{%- endmacro %}
|
||||
|
||||
{#- The upload: a one-line strip that takes dropped files (the file input
|
||||
covers it) and the fields that say what they are. The form token comes
|
||||
first: the server checks it before it reads any file. -#}
|
||||
{% macro upload(u, csrf, person=true) -%}
|
||||
{%- if u.files_on %}
|
||||
<form method="post" action="{{ u.action }}" enctype="multipart/form-data" class="upload" id="upload">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
{%- if u.errors %}
|
||||
<div class="notice warn">Nothing was uploaded. Correct what is marked and choose the files again.</div>
|
||||
{%- endif %}
|
||||
<div class="drop{% if u.errors.file %} has-err{% endif %}" data-max="{{ u.file_limit }}">
|
||||
<input type="file" id="f-file" name="file" multiple required accept="application/pdf,image/jpeg,image/png,image/webp" aria-describedby="h-file{% if u.errors.file %} e-file{% endif %}">
|
||||
<span class="drop-icon" aria-hidden="true">+</span>
|
||||
<label for="f-file"><b>Choose files</b> or drop them here</label>
|
||||
<span class="drop-names" data-drop-names></span>
|
||||
<span class="hint" id="h-file">PDF, JPEG, PNG or WebP, up to {{ u.file_limit_mb }} MB each, {{ u.max_files }} at once</span>
|
||||
</div>
|
||||
{%- if u.errors.file %}
|
||||
<p class="err" id="e-file">{{ u.errors.file }}</p>
|
||||
{%- endif %}
|
||||
<div class="upload-row{% if not person %} company{% endif %}">
|
||||
{{ fm.select("kind", "What it is", u.values.kind, u.kinds, err=u.errors.kind, blank="Choose", req=true) }}
|
||||
{%- if person %}
|
||||
{{ belongs(u.values.link, u.groups, err=u.errors.link) }}
|
||||
{%- endif %}
|
||||
{{ fm.text("dated_on", "Date on the document", u.values.dated_on, err=u.errors.dated_on, type="date") }}
|
||||
{{ fm.text("note", "Note", u.values.note, err=u.errors.note, ph="page 2, certified copy") }}
|
||||
<div class="upload-go"><button type="submit" class="btn pri" id="upload-btn">Upload</button></div>
|
||||
</div>
|
||||
</form>
|
||||
{%- else %}
|
||||
<div class="notice warn">Documents are switched off on this server: it has no files directory and file key (VISA_FILES_DIR and VISA_FILES_KEY_FILE).</div>
|
||||
{%- endif %}
|
||||
{%- endmacro %}
|
||||
|
||||
{#- The list. On phones the date, type and size move under the name. -#}
|
||||
{% macro table(docs, person=true) -%}
|
||||
<div class="tblwrap bleed">
|
||||
<table class="tbl docs" id="doc-list">
|
||||
<thead><tr><th>Document</th>{% if person %}<th class="hs">Belongs to</th>{% endif %}<th class="hs">Dated</th><th class="hs">File</th><th class="hs">Added</th><th><span class="vh">Actions</span></th></tr></thead>
|
||||
<tbody>
|
||||
{%- for d in docs %}
|
||||
<tr id="doc-{{ d.id }}">
|
||||
<td class="docname">
|
||||
<a class="strong" href="{{ d.href }}" target="_blank" rel="noopener">{{ d.kind_label }}</a>
|
||||
{%- if d.note %}<div class="muted small">{{ d.note }}</div>{% endif %}
|
||||
<div class="muted small ps">{% if d.dated_on %}{{ d.dated_on }} · {% endif %}{{ d.type_label }}, {{ d.size }}</div>
|
||||
</td>
|
||||
{%- if person %}
|
||||
<td class="hs">{% if d.link_label %}<a href="{{ d.link_href }}">{{ d.link_label }}</a>{% else %}<span class="muted">the person</span>{% endif %}</td>
|
||||
{%- endif %}
|
||||
<td class="hs nowrap">{{ d.dated_on }}</td>
|
||||
<td class="hs"><span class="ftype">{{ d.type_label }}</span> <span class="muted">{{ d.size }}</span><div class="muted small fname" title="{{ d.file_name }}">{{ d.file_name }}</div></td>
|
||||
<td class="hs nowrap">{{ d.uploaded }}<div class="muted small">{{ d.uploaded_by }}</div></td>
|
||||
<td class="acts"><a href="{{ d.href }}" target="_blank" rel="noopener">View</a><a href="{{ d.href }}?download=1">Download</a><a href="{{ d.edit }}">Edit</a></td>
|
||||
</tr>
|
||||
{%- endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{%- endmacro %}
|
||||
@@ -19,8 +19,9 @@
|
||||
{%- if p.employer %}<span class="sep">·</span><a href="/companies/{{ p.employer_id }}">{{ p.employer }}</a>{% endif %}
|
||||
</p>
|
||||
<nav class="tabs" aria-label="About {{ p.name }}">
|
||||
<a href="/people/{{ p.id }}"{% if tab != "stay" and tab != "activity" %} class="on" aria-current="page"{% endif %}>Overview</a>
|
||||
<a href="/people/{{ p.id }}"{% if tab not in ["stay", "documents", "activity"] %} class="on" aria-current="page"{% endif %}>Overview</a>
|
||||
<a href="/people/{{ p.id }}/stay"{% if tab == "stay" %} class="on" aria-current="page"{% endif %}>Visa and stay</a>
|
||||
<a href="/people/{{ p.id }}/documents"{% if tab == "documents" %} class="on" aria-current="page"{% endif %}>Documents</a>
|
||||
<a href="/people/{{ p.id }}/activity"{% if tab == "activity" %} class="on" aria-current="page"{% endif %}>Activity</a>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<h1>Activity{% if person %}: <a href="/people/{{ person.id }}">{{ person.name }}</a>{% endif %}</h1>
|
||||
{% if person %}<div class="actions"><a class="btn sm ghost" href="/activity">Everyone</a></div>{% endif %}
|
||||
</div>
|
||||
<p class="muted">Every view and change of a person's record, newest first: who, when and which fields changed (never their values). The log cannot be edited.</p>
|
||||
<p class="muted">Every view and change of a record or document, newest first: who, when and which fields changed (never their values). The log cannot be edited.</p>
|
||||
{% if items %}
|
||||
<div class="card flush">
|
||||
<div class="tblwrap">
|
||||
@@ -16,7 +16,7 @@
|
||||
<td class="mono">{{ e.at }}</td>
|
||||
<td>{{ e.actor }}</td>
|
||||
<td>{{ e.action }}</td>
|
||||
<td>{% if e.person_id %}<a href="/people/{{ e.person_id }}">{{ e.person_name or ("person " ~ e.person_id) }}</a> <span class="muted">{{ e.what }}</span>{% elif e.company_id %}<a href="/companies/{{ e.company_id }}">{{ e.company_name or ("company " ~ e.company_id) }}</a> <span class="muted">company</span>{% else %}<span class="muted">{{ e.what }}</span>{% endif %}</td>
|
||||
<td>{% if e.person_id %}<a href="/people/{{ e.person_id }}">{{ e.person_name or ("person " ~ e.person_id) }}</a> <span class="muted">{{ e.what }}</span>{% elif e.company_id %}<a href="/companies/{{ e.company_id }}">{{ e.company_name or ("company " ~ e.company_id) }}</a> <span class="muted">{{ e.what or "company" }}</span>{% else %}<span class="muted">{{ e.what }}</span>{% endif %}</td>
|
||||
<td class="hs muted">{{ e.fields }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "_documents.html" as dm %}
|
||||
{% block main %}
|
||||
<div class="phead">
|
||||
<div class="crumbs"><a href="/companies">Companies</a></div>
|
||||
@@ -66,5 +67,14 @@
|
||||
</form>
|
||||
{% endif %}
|
||||
</section>
|
||||
<section class="card span2" id="documents">
|
||||
<header><h2>Company documents</h2><span class="muted small">for the extension packs of the people employed here</span></header>
|
||||
{{ dm.upload(upload, csrf, person=false) }}
|
||||
{%- if docs %}
|
||||
{{ dm.table(docs, person=false) }}
|
||||
{%- else %}
|
||||
<p class="empty-inline">No company documents yet: the company certificate and the list of shareholders (certified within six months), the tax and social security returns, a map and photos of the office.</p>
|
||||
{%- endif %}
|
||||
</section>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,52 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "_fields.html" as fm %}
|
||||
{% import "_documents.html" as dm %}
|
||||
{% block main %}
|
||||
{% if p %}
|
||||
{% include "_person_head.html" %}
|
||||
{% else %}
|
||||
<div class="phead">
|
||||
<div class="crumbs"><a href="/companies">Companies</a> / <a href="/companies/{{ company.id }}">{{ company.name }}</a></div>
|
||||
<div class="pagehead"><h1>{{ doc.kind_label }}</h1></div>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="cols">
|
||||
<form method="post" action="{{ action }}" class="form card" id="document-form">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
<header><h2>{% if p %}{{ doc.kind_label }}{% else %}About the document{% endif %}</h2></header>
|
||||
<div class="grid">
|
||||
{{ fm.select("kind", "What it is", values.kind, kinds, err=errors.kind, blank="Choose", req=true) }}
|
||||
{%- if p %}
|
||||
{{ dm.belongs(values.link, groups, err=errors.link) }}
|
||||
{%- endif %}
|
||||
{{ fm.text("dated_on", "Date on the document", values.dated_on, err=errors.dated_on, type="date", hint="The issue, certification or filing date.") }}
|
||||
{{ fm.text("note", "Note", values.note, err=errors.note, cls="wide") }}
|
||||
</div>
|
||||
<div class="formactions">
|
||||
<button type="submit" class="btn pri" id="save">Save</button>
|
||||
<a class="btn ghost" href="{{ cancel }}">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
<section class="card" id="file">
|
||||
<header><h2>The file</h2><div class="actions"><a class="btn sm" href="{{ doc.href }}" target="_blank" rel="noopener">View</a><a class="btn sm ghost" href="{{ doc.href }}?download=1">Download</a></div></header>
|
||||
{%- if doc.image %}
|
||||
<a class="preview" href="{{ doc.href }}" target="_blank" rel="noopener"><img src="{{ doc.href }}" alt="{{ doc.kind_label }}"></a>
|
||||
{%- endif %}
|
||||
<dl class="kv">
|
||||
<dt>Name</dt><dd>{{ doc.file_name }}</dd>
|
||||
<dt>Type and size</dt><dd>{{ doc.type_label }}, {{ doc.size }}</dd>
|
||||
<dt>Added</dt><dd>{{ doc.uploaded }} by {{ doc.uploaded_by }}</dd>
|
||||
{%- if doc.updated %}
|
||||
<dt>Changed</dt><dd>{{ doc.updated }}</dd>
|
||||
{%- endif %}
|
||||
<dt>SHA-256</dt><dd class="mono small">{{ doc.sha256 }}</dd>
|
||||
</dl>
|
||||
<p class="hint">Encrypted on the server. Each view and download is in the activity log.</p>
|
||||
</section>
|
||||
</div>
|
||||
<form method="post" action="{{ action }}/delete" class="dangerzone" data-confirm="Delete this document and its file from the server?">
|
||||
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||
<button type="submit" class="btn sm danger">Delete this document</button>
|
||||
<span class="muted small">The file is deleted from the server. The activity log keeps a note that it existed.</span>
|
||||
</form>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,14 @@
|
||||
{% extends "base.html" %}
|
||||
{% import "_documents.html" as dm %}
|
||||
{% block main %}
|
||||
{% include "_person_head.html" %}
|
||||
<section class="card" id="documents">
|
||||
<header><h2>Documents</h2>{% if docs %}<span class="muted small">{{ docs|length }} {% if docs|length == 1 %}document{% else %}documents{% endif %}, encrypted on the server</span>{% endif %}</header>
|
||||
{{ dm.upload(upload, csrf) }}
|
||||
{%- if docs %}
|
||||
{{ dm.table(docs) }}
|
||||
{%- else %}
|
||||
<p class="empty-inline">No documents yet. Scans or photos of the passport pages, the TDAC and the receipts go here, each with the record it belongs to.</p>
|
||||
{%- endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -35,7 +35,7 @@
|
||||
<dt>Valid until</dt><dd>{{ pp.expires_on }}{% if pp.status %} <span class="chip {{ pp.status.level }}">{{ pp.status.label }}</span>{% endif %}</dd>
|
||||
<dt>Zone</dt><dd>{% if pp.has_mrz %}read, check digits matched{% else %}<span class="muted">typed in by hand</span>{% endif %}</dd>
|
||||
</dl>
|
||||
<div class="rowactions"><a href="/people/{{ p.id }}/passports/{{ pp.id }}/edit">Edit</a></div>
|
||||
<div class="rowactions"><a href="/people/{{ p.id }}/passports/{{ pp.id }}/edit">Edit</a>{% for d in docs["passports:" ~ pp.id] %}<a class="doclink" href="{{ d.href }}" target="_blank" rel="noopener">{{ d.label }}</a>{% endfor %}<a href="/people/{{ p.id }}/documents?for=passports:{{ pp.id }}#upload">+ Document</a></div>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty-inline">No passport recorded yet. Add it with + New passport; the two lines at the bottom of the photo page fill the form in.</p>
|
||||
@@ -56,7 +56,7 @@
|
||||
<dt>TM.30</dt><dd>{% if a.tm30_reported_on %}reported {{ a.tm30_reported_on }}{% if a.tm30_receipt_no %}, receipt <span class="mono">{{ a.tm30_receipt_no }}</span>{% endif %}{% else %}<span class="muted">no receipt recorded</span>{% endif %}
|
||||
{% if a.tm30 %}<div><span class="chip {{ a.tm30.level }}">{{ a.tm30.label }}</span></div>{% endif %}</dd>
|
||||
</dl>
|
||||
<div class="rowactions"><a href="/people/{{ p.id }}/addresses/{{ a.id }}/edit">Edit</a></div>
|
||||
<div class="rowactions"><a href="/people/{{ p.id }}/addresses/{{ a.id }}/edit">Edit</a>{% for d in docs["addresses:" ~ a.id] %}<a class="doclink" href="{{ d.href }}" target="_blank" rel="noopener">{{ d.label }}</a>{% endfor %}<a href="/people/{{ p.id }}/documents?for=addresses:{{ a.id }}#upload">+ Document</a></div>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty-inline">No address recorded yet. The TM.30 receipt of the current address goes with it.</p>
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@
|
||||
{%- endfor %}
|
||||
</dl>
|
||||
{% endif %}
|
||||
<div class="rowactions"><a href="/people/{{ p.id }}/{{ s.slug }}/{{ r.id }}/edit">Edit</a></div>
|
||||
<div class="rowactions"><a href="/people/{{ p.id }}/{{ s.slug }}/{{ r.id }}/edit">Edit</a>{% for d in docs[s.slug ~ ":" ~ r.id] %}<a class="doclink" href="{{ d.href }}" target="_blank" rel="noopener">{{ d.label }}</a>{% endfor %}<a href="/people/{{ p.id }}/documents?for={{ s.slug }}:{{ r.id }}#upload">+ Document</a></div>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty-inline">No {{ s.one }} recorded yet.</p>
|
||||
|
||||
+133
-3
@@ -1,6 +1,8 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::Body;
|
||||
@@ -9,9 +11,21 @@ use chrono::NaiveDate;
|
||||
use http_body_util::BodyExt;
|
||||
use sqlx::PgPool;
|
||||
use tower::ServiceExt;
|
||||
use visa::config::{Auth, Config, OidcConfig};
|
||||
use visa::config::{Auth, Config, FilesConfig, OidcConfig};
|
||||
use visa::files::FileKey;
|
||||
use visa::web::{self, AppState};
|
||||
|
||||
/// A files directory of its own for each app, under the target directory.
|
||||
fn files_dir() -> PathBuf {
|
||||
static N: AtomicUsize = AtomicUsize::new(0);
|
||||
PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!(
|
||||
"files-{}-{}",
|
||||
std::process::id(),
|
||||
N.fetch_add(1, Ordering::Relaxed)
|
||||
))
|
||||
}
|
||||
|
||||
/// Documents on, in a fresh directory with a fresh key.
|
||||
pub fn config(auth: Auth) -> Config {
|
||||
Config {
|
||||
listen: "127.0.0.1:0".parse().unwrap(),
|
||||
@@ -19,6 +33,10 @@ pub fn config(auth: Auth) -> Config {
|
||||
database_url: "postgres://unused".into(),
|
||||
database_password: None,
|
||||
auth,
|
||||
files: Some(FilesConfig {
|
||||
dir: files_dir(),
|
||||
key: FileKey::random(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,13 +55,26 @@ pub struct App {
|
||||
pub pool: PgPool,
|
||||
}
|
||||
|
||||
// The test's files go with it.
|
||||
impl Drop for App {
|
||||
fn drop(&mut self) {
|
||||
if let Some(dir) = self.st.cfg.files.as_ref().map(|f| f.dir.clone()) {
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Local development mode: no login, everyone is "local".
|
||||
pub fn local(pool: PgPool) -> App {
|
||||
with_auth(pool, Auth::Disabled)
|
||||
}
|
||||
|
||||
pub fn with_auth(pool: PgPool, auth: Auth) -> App {
|
||||
let st = AppState::new(config(auth), pool.clone()).unwrap();
|
||||
with_config(pool, config(auth))
|
||||
}
|
||||
|
||||
pub fn with_config(pool: PgPool, cfg: Config) -> App {
|
||||
let st = AppState::new(cfg, pool.clone()).unwrap();
|
||||
App {
|
||||
router: web::router(st.clone()),
|
||||
st,
|
||||
@@ -55,12 +86,18 @@ pub struct Resp {
|
||||
pub status: StatusCode,
|
||||
pub headers: HeaderMap,
|
||||
pub body: String,
|
||||
/// The body as it came, for files.
|
||||
pub bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Resp {
|
||||
pub fn location(&self) -> &str {
|
||||
self.header("location")
|
||||
}
|
||||
|
||||
pub fn header(&self, name: &str) -> &str {
|
||||
self.headers
|
||||
.get("location")
|
||||
.get(name)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("")
|
||||
}
|
||||
@@ -92,6 +129,7 @@ impl App {
|
||||
status,
|
||||
headers,
|
||||
body: String::from_utf8_lossy(&bytes).into_owned(),
|
||||
bytes: bytes.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,6 +168,98 @@ impl App {
|
||||
self.call(req.body(Body::from(form_body(form))).unwrap())
|
||||
.await
|
||||
}
|
||||
|
||||
/// An upload as the page sends it: the form token first, then the
|
||||
/// fields, then the files.
|
||||
pub async fn upload(
|
||||
&self,
|
||||
uri: &str,
|
||||
fields: &[(&str, &str)],
|
||||
files: &[(&str, &[u8])],
|
||||
) -> Resp {
|
||||
let csrf = self.st.local_csrf().to_string();
|
||||
let mut parts = vec![Part::field("csrf", csrf.as_bytes())];
|
||||
for (k, v) in fields {
|
||||
parts.push(Part::field(k, v.as_bytes()));
|
||||
}
|
||||
for (name, data) in files {
|
||||
parts.push(Part::file(name, data));
|
||||
}
|
||||
self.upload_raw(uri, &parts, &[("sec-fetch-site", "same-origin")])
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn upload_raw(
|
||||
&self,
|
||||
uri: &str,
|
||||
parts: &[Part<'_>],
|
||||
headers: &[(&str, &str)],
|
||||
) -> Resp {
|
||||
let mut req = Request::post(uri).header(
|
||||
"content-type",
|
||||
format!("multipart/form-data; boundary={BOUNDARY}"),
|
||||
);
|
||||
for (k, v) in headers {
|
||||
req = req.header(*k, *v);
|
||||
}
|
||||
self.call(req.body(Body::from(multipart_body(parts))).unwrap())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
const BOUNDARY: &str = "----visa-test-7d1f0c";
|
||||
|
||||
/// One part of a multipart form.
|
||||
pub struct Part<'a> {
|
||||
pub name: &'a str,
|
||||
pub file_name: Option<&'a str>,
|
||||
pub data: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> Part<'a> {
|
||||
pub fn field(name: &'a str, data: &'a [u8]) -> Part<'a> {
|
||||
Part {
|
||||
name,
|
||||
file_name: None,
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn file(file_name: &'a str, data: &'a [u8]) -> Part<'a> {
|
||||
Part {
|
||||
name: "file",
|
||||
file_name: Some(file_name),
|
||||
data,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn multipart_body(parts: &[Part<'_>]) -> Vec<u8> {
|
||||
let mut body = Vec::new();
|
||||
for p in parts {
|
||||
body.extend_from_slice(format!("--{BOUNDARY}\r\n").as_bytes());
|
||||
let head = match p.file_name {
|
||||
Some(f) => format!(
|
||||
"Content-Disposition: form-data; name=\"{}\"; filename=\"{f}\"\r\n\
|
||||
Content-Type: application/octet-stream\r\n\r\n",
|
||||
p.name
|
||||
),
|
||||
None => format!(
|
||||
"Content-Disposition: form-data; name=\"{}\"\r\n\r\n",
|
||||
p.name
|
||||
),
|
||||
};
|
||||
body.extend_from_slice(head.as_bytes());
|
||||
body.extend_from_slice(p.data);
|
||||
body.extend_from_slice(b"\r\n");
|
||||
}
|
||||
body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
|
||||
body
|
||||
}
|
||||
|
||||
/// A small PDF that says what it is.
|
||||
pub fn pdf(text: &str) -> Vec<u8> {
|
||||
format!("%PDF-1.4\n% {text}\n%%EOF\n").into_bytes()
|
||||
}
|
||||
|
||||
pub fn d(s: &str) -> NaiveDate {
|
||||
|
||||
@@ -0,0 +1,612 @@
|
||||
//! Documents: uploads into the encrypted store, opening and downloading,
|
||||
//! changes, deletion, company documents, the checks before anything is
|
||||
//! stored, and the audit trail of every step.
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use sqlx::PgPool;
|
||||
use visa::config::{Auth, Config};
|
||||
use visa::documents::{self, Owner};
|
||||
use visa::web::documents::FILE_LIMIT;
|
||||
|
||||
use crate::common::{App, Part, config, id_from, local, pdf, with_config};
|
||||
|
||||
async fn person(app: &App, surname: &str) -> i64 {
|
||||
let r = app
|
||||
.post(
|
||||
"/people",
|
||||
&[
|
||||
("action", "save"),
|
||||
("surname", surname),
|
||||
("first_name", "Jane"),
|
||||
("nationality", "USA"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
id_from(r.location())
|
||||
}
|
||||
|
||||
async fn passport(app: &App, person: i64, number: &str) -> i64 {
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/people/{person}/passports"),
|
||||
&[
|
||||
("number", number),
|
||||
("issuing_country", "USA"),
|
||||
("expires_on", "2034-05-01"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
sqlx::query_scalar("SELECT id FROM passports WHERE person_id = $1 AND number = $2")
|
||||
.bind(person)
|
||||
.bind(number)
|
||||
.fetch_one(&app.pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// The audit entries about documents: action, id and field names.
|
||||
async fn trail(pool: &PgPool) -> Vec<String> {
|
||||
sqlx::query_scalar(
|
||||
"SELECT action || ' ' || entity_id || ' ' || array_to_string(fields, ',') \
|
||||
FROM audit_log WHERE entity = 'document' ORDER BY id",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn count(pool: &PgPool) -> i64 {
|
||||
sqlx::query_scalar("SELECT count(*) FROM documents")
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// An upload that is refused: its fields, its files and what the page says.
|
||||
type Refusal<'a> = (Vec<(&'a str, &'a str)>, Vec<(&'a str, &'a [u8])>, &'a str);
|
||||
|
||||
/// A forged upload: its parts, its headers, the answer and what it says.
|
||||
type Forged<'a> = (Vec<Part<'a>>, &'a [(&'a str, &'a str)], StatusCode, &'a str);
|
||||
|
||||
fn stored(app: &App) -> usize {
|
||||
let store = app.st.files.as_ref().unwrap();
|
||||
let (ids, other) = store.entries().unwrap();
|
||||
ids.len() + other.len()
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn a_scan_is_stored_encrypted_and_every_step_is_audited(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let id = person(&app, "Doe").await;
|
||||
let pp = passport(&app, id, "X1234567").await;
|
||||
let scan = pdf("the photo page of a passport");
|
||||
let link = format!("passports:{pp}");
|
||||
let r = app
|
||||
.upload(
|
||||
&format!("/people/{id}/documents"),
|
||||
&[
|
||||
("kind", "passport-photo-page"),
|
||||
("link", &link),
|
||||
("dated_on", ""),
|
||||
("note", "front cover too"),
|
||||
],
|
||||
&[("C:\\Scans\\pass port.pdf", &scan)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
let did: i64 = sqlx::query_scalar("SELECT id FROM documents WHERE person_id = $1")
|
||||
.bind(id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.location(), format!("/people/{id}/documents#doc-{did}"));
|
||||
|
||||
// on the disk only encrypted, under the document's id
|
||||
let store = app.st.files.as_ref().unwrap();
|
||||
let on_disk = std::fs::read(store.path(did)).unwrap();
|
||||
assert!(on_disk.starts_with(b"VISADOC1"));
|
||||
assert!(!on_disk.windows(10).any(|w| w == b"photo page"));
|
||||
|
||||
// listed on the tab, and next to its passport on the overview
|
||||
let t = app.get(&format!("/people/{id}/documents")).await.text();
|
||||
for want in [
|
||||
"Passport photo page",
|
||||
"pass port.pdf",
|
||||
"Passport: X1234567",
|
||||
"front cover too",
|
||||
] {
|
||||
assert!(t.contains(want), "{want}: {t}");
|
||||
}
|
||||
let file = format!("/people/{id}/documents/{did}/file");
|
||||
let t = app.get(&format!("/people/{id}")).await.text();
|
||||
assert!(t.contains(&format!("href=\"{file}\"")), "{t}");
|
||||
|
||||
// opened: the same bytes, its own policy, not kept in caches
|
||||
let r = app.get(&file).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert_eq!(r.bytes, scan);
|
||||
assert_eq!(r.header("content-type"), "application/pdf");
|
||||
assert!(
|
||||
r.header("content-disposition")
|
||||
.starts_with("inline; filename=\"DOE Jane - Passport photo page - "),
|
||||
"{}",
|
||||
r.header("content-disposition")
|
||||
);
|
||||
assert_eq!(r.header("cache-control"), "private, no-store");
|
||||
assert!(
|
||||
r.header("content-security-policy")
|
||||
.starts_with("default-src 'none'")
|
||||
);
|
||||
assert_eq!(r.header("x-content-type-options"), "nosniff");
|
||||
let r = app.get(&format!("{file}?download=1")).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert!(r.header("content-disposition").starts_with("attachment; "));
|
||||
|
||||
// the page about it, and a change
|
||||
let r = app.get(&format!("/people/{id}/documents/{did}/edit")).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert!(r.text().contains("Delete this document"), "{}", r.body);
|
||||
let r = app
|
||||
.post(
|
||||
&format!("/people/{id}/documents/{did}"),
|
||||
&[
|
||||
("kind", "other"),
|
||||
("link", ""),
|
||||
("dated_on", "2026-11-02"),
|
||||
("note", "front cover too"),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
assert_eq!(r.location(), format!("/people/{id}/documents#doc-{did}"));
|
||||
|
||||
// deleted: the row and the file
|
||||
let r = app
|
||||
.post(&format!("/people/{id}/documents/{did}/delete"), &[])
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||
assert!(!store.path(did).exists());
|
||||
assert_eq!(count(&pool).await, 0);
|
||||
assert_eq!(app.get(&file).await.status, StatusCode::NOT_FOUND);
|
||||
|
||||
assert_eq!(
|
||||
trail(&pool).await,
|
||||
[
|
||||
format!("create {did} kind,file,passport_id,note"),
|
||||
format!("view {did} file"),
|
||||
format!("download {did} file"),
|
||||
format!("view {did} "),
|
||||
format!("update {did} dated_on,kind,passport_id"),
|
||||
format!("delete {did} "),
|
||||
]
|
||||
);
|
||||
// names of fields only, never what they hold
|
||||
let logged: Vec<String> =
|
||||
sqlx::query_scalar("SELECT array_to_string(fields, ',') FROM audit_log")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
!logged
|
||||
.iter()
|
||||
.any(|f| f.contains("front") || f.contains("port.pdf"))
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn uploads_are_checked_before_anything_is_stored(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let id = person(&app, "Doe").await;
|
||||
let other = person(&app, "Roe").await;
|
||||
let theirs = format!("passports:{}", passport(&app, other, "Y7654321").await);
|
||||
let base = format!("/people/{id}/documents");
|
||||
let scan = pdf("a receipt");
|
||||
let mut big = pdf("large");
|
||||
big.resize(FILE_LIMIT + 1, b' ');
|
||||
let html = b"<html><script>alert(1)</script></html>".to_vec();
|
||||
let cases: Vec<Refusal> = vec![
|
||||
(vec![("kind", "photo")], vec![], "Choose a file to upload."),
|
||||
(
|
||||
vec![("kind", "photo")],
|
||||
vec![("scan.pdf", html.as_slice())],
|
||||
"scan.pdf is not a PDF, JPEG, PNG or WebP file.",
|
||||
),
|
||||
(
|
||||
vec![("kind", "photo")],
|
||||
vec![("empty.pdf", &b""[..])],
|
||||
"empty.pdf is empty.",
|
||||
),
|
||||
(
|
||||
vec![("kind", "photo")],
|
||||
vec![("big.pdf", big.as_slice())],
|
||||
"big.pdf is larger than 20 MB.",
|
||||
),
|
||||
(
|
||||
vec![("kind", "photo")],
|
||||
vec![("a.pdf", scan.as_slice()), ("b.pdf", scan.as_slice())],
|
||||
"b.pdf is in this upload twice.",
|
||||
),
|
||||
(
|
||||
vec![("kind", "passport")],
|
||||
vec![("a.pdf", scan.as_slice())],
|
||||
"Choose what the document is.",
|
||||
),
|
||||
(
|
||||
vec![("kind", "company-certificate")],
|
||||
vec![("a.pdf", scan.as_slice())],
|
||||
"Choose what the document is.",
|
||||
),
|
||||
(
|
||||
vec![("kind", "passport-photo-page"), ("link", &theirs)],
|
||||
vec![("a.pdf", scan.as_slice())],
|
||||
"Choose one of this person's records, or none.",
|
||||
),
|
||||
(
|
||||
vec![("kind", "photo"), ("link", "people:1")],
|
||||
vec![("a.pdf", scan.as_slice())],
|
||||
"Choose one of this person's records, or none.",
|
||||
),
|
||||
(
|
||||
vec![("kind", "photo"), ("dated_on", "0026-11-12")],
|
||||
vec![("a.pdf", scan.as_slice())],
|
||||
"Enter a year from 1900 to 2100.",
|
||||
),
|
||||
];
|
||||
for (fields, files, want) in &cases {
|
||||
let r = app.upload(&base, fields, files).await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY, "{want}");
|
||||
let t = r.text();
|
||||
assert!(t.contains(want), "{want}: {t}");
|
||||
assert!(t.contains("Nothing was uploaded"), "{want}");
|
||||
}
|
||||
assert_eq!(count(&pool).await, 0);
|
||||
assert_eq!(stored(&app), 0);
|
||||
|
||||
// the same file again for the same person
|
||||
let r = app
|
||||
.upload(&base, &[("kind", "tm30-receipt")], &[("a.pdf", &scan)])
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
let r = app
|
||||
.upload(&base, &[("kind", "other")], &[("copy.pdf", &scan)])
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert!(
|
||||
r.text()
|
||||
.contains("copy.pdf is here already: TM.30 receipt, added"),
|
||||
"{}",
|
||||
r.text()
|
||||
);
|
||||
// another person may have the same file
|
||||
let r = app
|
||||
.upload(
|
||||
&format!("/people/{other}/documents"),
|
||||
&[("kind", "other")],
|
||||
&[("a.pdf", &scan)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
assert_eq!(count(&pool).await, 2);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn an_upload_needs_the_form_token_first_and_this_site(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let id = person(&app, "Doe").await;
|
||||
let base = format!("/people/{id}/documents");
|
||||
let scan = pdf("a scan");
|
||||
let token = app.st.local_csrf().to_string();
|
||||
let same = [("sec-fetch-site", "same-origin")];
|
||||
let refused: Vec<Forged> = vec![
|
||||
// no token
|
||||
(
|
||||
vec![Part::field("kind", b"photo"), Part::file("a.pdf", &scan)],
|
||||
&same,
|
||||
StatusCode::FORBIDDEN,
|
||||
"has expired",
|
||||
),
|
||||
// the token after a file: the file would be read first
|
||||
(
|
||||
vec![
|
||||
Part::file("a.pdf", &scan),
|
||||
Part::field("csrf", token.as_bytes()),
|
||||
Part::field("kind", b"photo"),
|
||||
],
|
||||
&same,
|
||||
StatusCode::FORBIDDEN,
|
||||
"has expired",
|
||||
),
|
||||
// a wrong token
|
||||
(
|
||||
vec![
|
||||
Part::field("csrf", b"not-the-token"),
|
||||
Part::field("kind", b"photo"),
|
||||
Part::file("a.pdf", &scan),
|
||||
],
|
||||
&same,
|
||||
StatusCode::FORBIDDEN,
|
||||
"has expired",
|
||||
),
|
||||
// from another site, with the right token
|
||||
(
|
||||
vec![
|
||||
Part::field("csrf", token.as_bytes()),
|
||||
Part::field("kind", b"photo"),
|
||||
Part::file("a.pdf", &scan),
|
||||
],
|
||||
&[("sec-fetch-site", "cross-site")],
|
||||
StatusCode::FORBIDDEN,
|
||||
"from another site",
|
||||
),
|
||||
];
|
||||
for (parts, headers, status, want) in &refused {
|
||||
let r = app.upload_raw(&base, parts, headers).await;
|
||||
assert_eq!(r.status, *status, "{want}: {}", r.body);
|
||||
assert!(r.text().contains(want), "{want}: {}", r.body);
|
||||
}
|
||||
// an address that takes no uploads
|
||||
let parts = [
|
||||
Part::field("csrf", token.as_bytes()),
|
||||
Part::field("surname", b"Roe"),
|
||||
];
|
||||
let r = app.upload_raw("/people", &parts, &same).await;
|
||||
assert_eq!(r.status, StatusCode::UNSUPPORTED_MEDIA_TYPE);
|
||||
// an upload to someone who does not exist
|
||||
let r = app
|
||||
.upload(
|
||||
"/people/999999/documents",
|
||||
&[("kind", "photo")],
|
||||
&[("a.pdf", &scan)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||
assert_eq!(count(&pool).await, 0);
|
||||
assert_eq!(stored(&app), 0);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn several_files_at_once_next_to_their_record(pool: PgPool) {
|
||||
visa::seed::demo(&pool, visa::dates::today()).await.unwrap();
|
||||
let app = local(pool.clone());
|
||||
let erika: i64 = sqlx::query_scalar("SELECT id FROM people WHERE surname = 'Mustermann'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let arrival: i64 = sqlx::query_scalar(
|
||||
"SELECT id FROM arrivals WHERE person_id = $1 ORDER BY arrived_on DESC LIMIT 1",
|
||||
)
|
||||
.bind(erika)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let link = format!("arrivals:{arrival}");
|
||||
|
||||
// the stay tab offers to add one to the arrival, and the form knows it
|
||||
let t = app.get(&format!("/people/{erika}/stay")).await.text();
|
||||
let add = format!("/people/{erika}/documents?for={link}#upload");
|
||||
assert!(t.contains(&add), "{t}");
|
||||
let t = app
|
||||
.get(&format!("/people/{erika}/documents?for={link}"))
|
||||
.await
|
||||
.text();
|
||||
assert!(
|
||||
t.contains(&format!("<option value=\"{link}\" selected>")),
|
||||
"{t}"
|
||||
);
|
||||
assert!(
|
||||
t.contains("<option value=\"arrival-stamp\" selected>"),
|
||||
"{t}"
|
||||
);
|
||||
|
||||
let stamp = [0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10, b'J', b'F', b'I', b'F', 0];
|
||||
let page2 = pdf("page 2");
|
||||
let r = app
|
||||
.upload(
|
||||
&format!("/people/{erika}/documents"),
|
||||
&[("kind", "arrival-stamp"), ("link", &link)],
|
||||
&[("stamp.jpg", &stamp), ("page 2.pdf", &page2)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
let docs = documents::list(&pool, Owner::Person(erika)).await.unwrap();
|
||||
assert_eq!(docs.len(), 2);
|
||||
assert!(docs.iter().all(|d| d.arrival_id == Some(arrival)));
|
||||
let types: Vec<&str> = docs.iter().map(|d| d.content_type.as_str()).collect();
|
||||
assert!(types.contains(&"image/jpeg") && types.contains(&"application/pdf"));
|
||||
|
||||
// both next to the arrival on the stay tab
|
||||
let t = app.get(&format!("/people/{erika}/stay")).await.text();
|
||||
for d in &docs {
|
||||
assert!(
|
||||
t.contains(&format!("/people/{erika}/documents/{}/file", d.id)),
|
||||
"{t}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn a_company_keeps_its_own_documents(pool: PgPool) {
|
||||
visa::seed::demo(&pool, visa::dates::today()).await.unwrap();
|
||||
let app = local(pool.clone());
|
||||
let company: i64 =
|
||||
sqlx::query_scalar("SELECT id FROM companies WHERE name = 'Demo Engineering Co., Ltd.'")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let base = format!("/companies/{company}/documents");
|
||||
let cert = pdf("company certificate");
|
||||
// a person's kind is not a company's
|
||||
let r = app
|
||||
.upload(
|
||||
&base,
|
||||
&[("kind", "passport-photo-page")],
|
||||
&[("c.pdf", &cert)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||
assert!(r.text().contains("Choose what the document is."));
|
||||
let r = app
|
||||
.upload(
|
||||
&base,
|
||||
&[("kind", "company-certificate"), ("dated_on", "2026-10-01")],
|
||||
&[("certificate.pdf", &cert)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
let did: i64 = sqlx::query_scalar("SELECT id FROM documents WHERE company_id = $1")
|
||||
.bind(company)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(r.location(), format!("/companies/{company}#doc-{did}"));
|
||||
|
||||
let t = app.get(&format!("/companies/{company}")).await.text();
|
||||
assert!(
|
||||
t.contains("Company certificate") && t.contains("Oct 1, 2026"),
|
||||
"{t}"
|
||||
);
|
||||
let r = app.get(&format!("{base}/{did}/file?download=1")).await;
|
||||
assert_eq!(r.bytes, cert);
|
||||
assert!(
|
||||
r.header("content-disposition")
|
||||
.contains("Demo Engineering Co., Ltd. - Company certificate - 2026-10-01.pdf"),
|
||||
"{}",
|
||||
r.header("content-disposition")
|
||||
);
|
||||
// another company's address does not reach it
|
||||
assert_eq!(
|
||||
app.get(&format!("/people/1/documents/{did}/file"))
|
||||
.await
|
||||
.status,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
|
||||
// the audit log names the company; the activity page shows it
|
||||
let (person, comp): (Option<i64>, Option<i64>) = sqlx::query_as(
|
||||
"SELECT person_id, company_id FROM audit_log WHERE action = 'download' AND entity_id = $1",
|
||||
)
|
||||
.bind(did)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((person, comp), (None, Some(company)));
|
||||
let t = app.get("/activity").await.text();
|
||||
assert!(t.contains(&format!("document {did}")), "{t}");
|
||||
assert!(t.contains("Demo Engineering Co., Ltd."));
|
||||
|
||||
let r = app.get(&format!("{base}/{did}/edit")).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
let r = app.post(&format!("{base}/{did}/delete"), &[]).await;
|
||||
assert_eq!(r.location(), format!("/companies/{company}"));
|
||||
assert_eq!(count(&pool).await, 0);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn a_file_cannot_pass_for_another_and_the_check_finds_it(pool: PgPool) {
|
||||
let app = local(pool.clone());
|
||||
let id = person(&app, "Doe").await;
|
||||
let base = format!("/people/{id}/documents");
|
||||
let (a, b) = (pdf("first"), pdf("second"));
|
||||
let r = app
|
||||
.upload(&base, &[("kind", "other")], &[("a.pdf", &a), ("b.pdf", &b)])
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||
let ids: Vec<i64> = sqlx::query_scalar("SELECT id FROM documents ORDER BY id")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let store = app.st.files.as_ref().unwrap();
|
||||
assert!(
|
||||
documents::check(&pool, store)
|
||||
.await
|
||||
.unwrap()
|
||||
.problems
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
// the two files swapped on the disk
|
||||
let (pa, pb) = (store.path(ids[0]), store.path(ids[1]));
|
||||
let tmp = pa.with_extension("swap");
|
||||
std::fs::rename(&pa, &tmp).unwrap();
|
||||
std::fs::rename(&pb, &pa).unwrap();
|
||||
std::fs::rename(&tmp, &pb).unwrap();
|
||||
let r = app.get(&format!("{base}/{}/file", ids[0])).await;
|
||||
assert_eq!(r.status, StatusCode::INTERNAL_SERVER_ERROR);
|
||||
assert!(r.text().contains("cannot be opened"), "{}", r.body);
|
||||
assert!(!r.bytes.windows(6).any(|w| w == b"second"));
|
||||
std::fs::write(store.dir().join("77.vdoc"), b"left over").unwrap();
|
||||
let check = documents::check(&pool, store).await.unwrap();
|
||||
assert_eq!(check.documents, 2);
|
||||
assert_eq!(check.problems.len(), 3, "{:?}", check.problems);
|
||||
assert!(check.problems[0].contains("damaged, or the file of another document"));
|
||||
assert!(check.problems[2].contains("77.vdoc: a file without its document"));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn without_a_files_directory_documents_are_off(pool: PgPool) {
|
||||
let cfg = Config {
|
||||
files: None,
|
||||
..config(Auth::Disabled)
|
||||
};
|
||||
let app = with_config(pool.clone(), cfg);
|
||||
let id = person(&app, "Doe").await;
|
||||
let r = app.get(&format!("/people/{id}/documents")).await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
assert!(
|
||||
r.text().contains("Documents are switched off"),
|
||||
"{}",
|
||||
r.body
|
||||
);
|
||||
let r = app
|
||||
.upload(
|
||||
&format!("/people/{id}/documents"),
|
||||
&[("kind", "photo")],
|
||||
&[("a.pdf", &pdf("x"))],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(r.status, StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||
async fn the_demo_documents_open_as_what_they_are(pool: PgPool) {
|
||||
let today = visa::dates::today();
|
||||
visa::seed::demo(&pool, today).await.unwrap();
|
||||
let app = local(pool.clone());
|
||||
let store = app.st.files.as_ref().unwrap();
|
||||
let n = visa::seed::demo_documents(&pool, store, today)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(n >= 8, "{n}");
|
||||
assert_eq!(
|
||||
visa::seed::demo_documents(&pool, store, today)
|
||||
.await
|
||||
.unwrap(),
|
||||
0,
|
||||
"seeded once"
|
||||
);
|
||||
let rows: Vec<(i64, Option<i64>, Option<i64>, String)> =
|
||||
sqlx::query_as("SELECT id, person_id, company_id, content_type FROM documents ORDER BY id")
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
for (id, person, company, ct) in rows {
|
||||
let url = match (person, company) {
|
||||
(Some(p), _) => format!("/people/{p}/documents/{id}/file"),
|
||||
(None, Some(c)) => format!("/companies/{c}/documents/{id}/file"),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let r = app.get(&url).await;
|
||||
assert_eq!(r.status, StatusCode::OK, "{url}");
|
||||
assert_eq!(r.header("content-type"), ct);
|
||||
assert_eq!(visa::files::sniff(&r.bytes), Some(ct.as_str()));
|
||||
}
|
||||
assert!(
|
||||
documents::check(&pool, store)
|
||||
.await
|
||||
.unwrap()
|
||||
.problems
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ mod auth;
|
||||
mod common;
|
||||
mod companies;
|
||||
mod deadlines;
|
||||
mod documents;
|
||||
mod pages;
|
||||
mod people;
|
||||
mod records;
|
||||
|
||||
+37
-1
@@ -65,6 +65,26 @@ async fn every_page_renders_with_demo_data(pool: PgPool) {
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let store = app.st.files.as_ref().unwrap();
|
||||
assert!(
|
||||
visa::seed::demo_documents(&pool, store, visa::dates::today())
|
||||
.await
|
||||
.unwrap()
|
||||
> 0
|
||||
);
|
||||
let doc: i64 = sqlx::query_scalar(
|
||||
"SELECT id FROM documents WHERE person_id = $1 AND kind = 'passport-photo-page'",
|
||||
)
|
||||
.bind(erika)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let company_doc: i64 =
|
||||
sqlx::query_scalar("SELECT id FROM documents WHERE company_id = $1 ORDER BY id LIMIT 1")
|
||||
.bind(company)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut pages = vec![
|
||||
("/".to_string(), "90-day report".to_string()),
|
||||
@@ -97,12 +117,24 @@ async fn every_page_renders_with_demo_data(pool: PgPool) {
|
||||
("/companies/new".to_string(), "New company".to_string()),
|
||||
(
|
||||
format!("/companies/{company}"),
|
||||
"People employed".to_string(),
|
||||
"Company certificate".to_string(),
|
||||
),
|
||||
(
|
||||
format!("/companies/{company}/edit"),
|
||||
"0999999000004".to_string(),
|
||||
),
|
||||
(
|
||||
format!("/people/{erika}/documents"),
|
||||
"Passport photo page".to_string(),
|
||||
),
|
||||
(
|
||||
format!("/people/{erika}/documents/{doc}/edit"),
|
||||
"passport-photo-page.png".to_string(),
|
||||
),
|
||||
(
|
||||
format!("/companies/{company}/documents/{company_doc}/edit"),
|
||||
"About the document".to_string(),
|
||||
),
|
||||
];
|
||||
for kind in visa::records::STAY {
|
||||
pages.push((
|
||||
@@ -187,6 +219,10 @@ async fn open_paths_headers_and_not_found(pool: PgPool) {
|
||||
app.get("/static/nope.css").await.status,
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
// an image or a PDF opened in the browser asks for the icon here
|
||||
let icon = app.get("/favicon.ico").await;
|
||||
assert_eq!(icon.status, StatusCode::OK);
|
||||
assert_eq!(icon.headers["content-type"], "image/svg+xml");
|
||||
|
||||
let r = app.get("/").await;
|
||||
assert_eq!(r.status, StatusCode::OK);
|
||||
|
||||
Reference in new issue
Block a user