Phase 4: documents, encrypted on the server
CI / secret scan (push) Successful in 5s
CI / fmt, clippy, tests (push) Successful in 53s

Scans and photos of a person's papers, and a company's documents for the
extension packs, uploaded on a dashed strip that takes dropped files: up to
10 files of 20 MB each, 64 MB in all; PDF, JPEG, PNG and WebP, told by their
first bytes.

- src/files.rs: one file per document as <id>.vdoc, AES-256-GCM under a key
  per file (HKDF-SHA256 from the file key and a random salt in the header);
  the document's id is authenticated with it. The key comes from
  VISA_FILES_KEY_FILE or the credential files-key; with the login on, the
  app does not start without it and VISA_FILES_DIR.
- migrations/0003: documents (a person's or a company's, the record it
  belongs to, kind, date on it, note, file name, type, size, SHA-256);
  audit_log gets company_id and the action download.
- A Documents tab per person, the documents on the company's page, and each
  record's documents next to its Edit link with "+ Document".
- An upload's form token is its first field and is checked before any file
  is read; the guard lets multipart through only to the two upload addresses.
- Files open under their own CSP and are never cached; a download is named
  after the person or company, the kind and the date. Every upload, view,
  download, change and deletion is in the audit log.
- visa files-check; demo documents in seed-demo; scripts/dev.sh keeps the
  local documents and their key in .dev/; /favicon.ico for image and PDF
  pages.

Tests: 57 unit and 33 integration (8 new for documents). Edge check of the
strip (choose, drop, too large), an upload, the PDF and image viewers under
the file policy: no problems, no console errors.
This commit is contained in:
grabowski committed 2026-11-18 10:23:41 +07:00
1 parent d543c929e9
commit 2061e3a024
35 files changed
+4256 -58

No files matched your search

+18 -5
View File
@@ -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),
+96
View File
@@ -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();
}
}
+593
View File
@@ -0,0 +1,593 @@
//! Documents: scans and photos of a person's papers, and the company
//! documents the extension packs need. A row holds what is known about a
//! file; the file itself lies encrypted in the store (`files.rs`). A
//! person's document may belong to one of their records (a passport, an
//! arrival, a 90-day report ...), and then shows next to that record too.
use std::collections::BTreeSet;
use anyhow::Result;
use chrono::{DateTime, NaiveDate, Utc};
use sqlx::{PgPool, Postgres, Transaction};
use crate::files::{self, Store};
/// Whose document it is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Owner {
Person(i64),
Company(i64),
}
impl Owner {
pub fn person(self) -> Option<i64> {
match self {
Owner::Person(id) => Some(id),
Owner::Company(_) => None,
}
}
pub fn company(self) -> Option<i64> {
match self {
Owner::Company(id) => Some(id),
Owner::Person(_) => None,
}
}
/// The address of its documents' pages.
pub fn base(self) -> String {
match self {
Owner::Person(id) => format!("/people/{id}/documents"),
Owner::Company(id) => format!("/companies/{id}/documents"),
}
}
pub fn kinds(self) -> &'static [Kind] {
match self {
Owner::Person(_) => PERSON_KINDS,
Owner::Company(_) => COMPANY_KINDS,
}
}
}
/// A kind of document; `record` is the kind of record it usually belongs to.
#[derive(Debug)]
pub struct Kind {
pub slug: &'static str,
pub label: &'static str,
pub record: Option<&'static str>,
}
const fn k(slug: &'static str, label: &'static str, record: Option<&'static str>) -> Kind {
Kind {
slug,
label,
record,
}
}
/// In the order of the Non-B pack (docs/PLAN.md).
pub const PERSON_KINDS: &[Kind] = &[
k("photo", "Photo, 4 x 6 cm", None),
k(
"passport-photo-page",
"Passport photo page",
Some("passports"),
),
k("visa", "Visa", Some("visas")),
k("arrival-stamp", "Arrival stamp", Some("arrivals")),
k("tdac", "TDAC", Some("arrivals")),
k("extension-stamp", "Extension stamp", Some("extensions")),
k("reentry-permit", "Re-entry permit", Some("reentry-permits")),
k(
"ninety-day-receipt",
"90-day report receipt",
Some("reports"),
),
k("tm30-receipt", "TM.30 receipt", Some("addresses")),
k("work-permit", "Work permit", Some("work-permits")),
k("pnd91", "Income tax return (PND.91)", None),
k("other", "Other", None),
];
/// The company documents of the Non-B pack, in its order.
pub const COMPANY_KINDS: &[Kind] = &[
k("company-certificate", "Company certificate", None),
k("shareholders", "List of shareholders (BOJ.5)", None),
k("balance-sheet", "Balance sheet with PND.50", None),
k("pnd1", "Withholding tax (PND.1)", None),
k("sps1-10", "Social security (SPS 1-10)", None),
k("pp30", "VAT return (PP.30)", None),
k("map", "Map to the office", None),
k("office-photo", "Photo of the office", None),
k("other", "Other", None),
];
pub fn kind(owner: Owner, slug: &str) -> Option<&'static Kind> {
owner.kinds().iter().find(|k| k.slug == slug)
}
pub fn kind_label(owner: Owner, slug: &str) -> String {
kind(owner, slug).map_or_else(|| slug.to_string(), |k| k.label.to_string())
}
/// The first kind that belongs to a kind of record: what a document added
/// from that record is.
pub fn kind_for_link(link: &str) -> Option<&'static Kind> {
PERSON_KINDS.iter().find(|k| k.record == Some(link))
}
/// A kind of record a person's document may belong to; `slug` is the one of
/// its pages (`/people/{id}/arrivals/...`).
#[derive(Debug)]
pub struct Link {
pub slug: &'static str,
pub column: &'static str,
pub table: &'static str,
pub title: &'static str,
}
const fn l(
slug: &'static str,
column: &'static str,
table: &'static str,
title: &'static str,
) -> Link {
Link {
slug,
column,
table,
title,
}
}
pub const LINKS: &[Link] = &[
l("passports", "passport_id", "passports", "Passports"),
l("visas", "visa_id", "visas", "Visas"),
l("arrivals", "arrival_id", "arrivals", "Arrivals"),
l(
"extensions",
"extension_id",
"extensions",
"Extensions of stay",
),
l(
"reentry-permits",
"reentry_permit_id",
"reentry_permits",
"Re-entry permits",
),
l(
"reports",
"report_id",
"ninety_day_reports",
"90-day reports",
),
l(
"addresses",
"address_id",
"addresses",
"Addresses in Thailand",
),
l(
"work-permits",
"work_permit_id",
"work_permits",
"Work permits",
),
];
/// `arrivals:7`, as the forms send it.
pub fn parse_link(value: &str) -> Option<(&'static Link, i64)> {
let (slug, id) = value.split_once(':')?;
let link = LINKS.iter().find(|l| l.slug == slug)?;
let id: i64 = id.parse().ok().filter(|&n| n > 0)?;
Some((link, id))
}
pub fn link_value(link: Option<(&Link, i64)>) -> String {
link.map(|(l, id)| format!("{}:{id}", l.slug))
.unwrap_or_default()
}
#[derive(Clone, Debug, sqlx::FromRow)]
pub struct Document {
pub id: i64,
pub person_id: Option<i64>,
pub company_id: Option<i64>,
pub kind: String,
pub passport_id: Option<i64>,
pub address_id: Option<i64>,
pub visa_id: Option<i64>,
pub arrival_id: Option<i64>,
pub extension_id: Option<i64>,
pub report_id: Option<i64>,
pub reentry_permit_id: Option<i64>,
pub work_permit_id: Option<i64>,
pub dated_on: Option<NaiveDate>,
pub note: String,
pub file_name: String,
pub content_type: String,
pub size_bytes: i32,
pub sha256: String,
pub uploaded_by: String,
pub uploaded_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
impl Document {
pub fn owner(&self) -> Owner {
match (self.person_id, self.company_id) {
(Some(p), _) => Owner::Person(p),
(None, Some(c)) => Owner::Company(c),
// the table's check rules this out
(None, None) => Owner::Person(0),
}
}
/// The record it belongs to, if any.
pub fn link(&self) -> Option<(&'static Link, i64)> {
let ids = [
self.passport_id,
self.visa_id,
self.arrival_id,
self.extension_id,
self.reentry_permit_id,
self.report_id,
self.address_id,
self.work_permit_id,
];
LINKS
.iter()
.zip(ids)
.find_map(|(l, id)| id.map(|id| (l, id)))
}
}
/// What the forms set about a document.
#[derive(Clone, Debug, Default)]
pub struct Meta {
pub kind: String,
pub link: Option<(&'static Link, i64)>,
pub dated_on: Option<NaiveDate>,
pub note: String,
}
impl Meta {
pub fn of(d: &Document) -> Meta {
Meta {
kind: d.kind.clone(),
link: d.link(),
dated_on: d.dated_on,
note: d.note.clone(),
}
}
/// The id for each link column, in the order of `LINKS`.
fn link_ids(&self) -> [Option<i64>; 8] {
let mut ids = [None; 8];
if let Some((link, id)) = self.link
&& let Some(i) = LINKS.iter().position(|l| l.slug == link.slug)
{
ids[i] = Some(id);
}
ids
}
/// The names of the fields a new document sets, for the audit log.
pub fn set_fields(&self) -> Vec<String> {
let mut out = vec!["kind".to_string(), "file".to_string()];
if let Some((link, _)) = self.link {
out.push(link.column.to_string());
}
if self.dated_on.is_some() {
out.push("dated_on".into());
}
if !self.note.is_empty() {
out.push("note".into());
}
out
}
/// The names of the fields a change touches.
pub fn changed(&self, new: &Meta) -> Vec<String> {
let mut out = BTreeSet::new();
if self.kind != new.kind {
out.insert("kind".to_string());
}
let (a, b) = (self.link_ids(), new.link_ids());
for (i, link) in LINKS.iter().enumerate() {
if a[i] != b[i] {
out.insert(link.column.to_string());
}
}
if self.dated_on != new.dated_on {
out.insert("dated_on".into());
}
if self.note != new.note {
out.insert("note".into());
}
out.into_iter().collect()
}
}
/// The file of a new document, as checked.
pub struct NewFile<'a> {
pub name: &'a str,
pub content_type: &'static str,
pub size: i32,
pub sha256: &'a str,
}
/// The newest first within each kind, the kinds in the pack's order.
fn sorted(owner: Owner, mut docs: Vec<Document>) -> Vec<Document> {
let rank = |d: &Document| {
owner
.kinds()
.iter()
.position(|k| k.slug == d.kind)
.unwrap_or(usize::MAX)
};
docs.sort_by(|a, b| {
rank(a)
.cmp(&rank(b))
.then(b.dated_on.cmp(&a.dated_on))
.then(b.id.cmp(&a.id))
});
docs
}
pub async fn list(db: &PgPool, owner: Owner) -> Result<Vec<Document>> {
let docs: Vec<Document> = sqlx::query_as(
"SELECT * FROM documents \
WHERE person_id IS NOT DISTINCT FROM $1 AND company_id IS NOT DISTINCT FROM $2",
)
.bind(owner.person())
.bind(owner.company())
.fetch_all(db)
.await?;
Ok(sorted(owner, docs))
}
pub async fn get(db: &PgPool, owner: Owner, id: i64) -> Result<Option<Document>> {
Ok(sqlx::query_as(
"SELECT * FROM documents WHERE id = $1 \
AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3",
)
.bind(id)
.bind(owner.person())
.bind(owner.company())
.fetch_optional(db)
.await?)
}
/// The same file uploaded before for the same person or company.
pub async fn same_file(db: &PgPool, owner: Owner, sha256: &str) -> Result<Option<Document>> {
Ok(sqlx::query_as(
"SELECT * FROM documents WHERE sha256 = $1 \
AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3 \
ORDER BY id LIMIT 1",
)
.bind(sha256)
.bind(owner.person())
.bind(owner.company())
.fetch_optional(db)
.await?)
}
/// Whether the record is one of this person's.
pub async fn link_is_theirs(db: &PgPool, person: i64, link: &Link, id: i64) -> Result<bool> {
// the table name comes from LINKS, never from the form
let sql = format!(
"SELECT EXISTS (SELECT 1 FROM {} WHERE id = $1 AND person_id = $2)",
link.table
);
Ok(sqlx::query_scalar(&sql)
.bind(id)
.bind(person)
.fetch_one(db)
.await?)
}
pub async fn insert(
tx: &mut Transaction<'_, Postgres>,
owner: Owner,
meta: &Meta,
file: &NewFile<'_>,
by: &str,
) -> Result<i64> {
let ids = meta.link_ids();
let id = sqlx::query_scalar(
"INSERT INTO documents (person_id, company_id, kind, passport_id, visa_id, \
arrival_id, extension_id, reentry_permit_id, report_id, address_id, work_permit_id, \
dated_on, note, file_name, content_type, size_bytes, sha256, uploaded_by) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18) \
RETURNING id",
)
.bind(owner.person())
.bind(owner.company())
.bind(&meta.kind)
.bind(ids[0])
.bind(ids[1])
.bind(ids[2])
.bind(ids[3])
.bind(ids[4])
.bind(ids[5])
.bind(ids[6])
.bind(ids[7])
.bind(meta.dated_on)
.bind(&meta.note)
.bind(file.name)
.bind(file.content_type)
.bind(file.size)
.bind(file.sha256)
.bind(by)
.fetch_one(&mut **tx)
.await?;
Ok(id)
}
pub async fn update(
tx: &mut Transaction<'_, Postgres>,
owner: Owner,
id: i64,
meta: &Meta,
) -> Result<()> {
let ids = meta.link_ids();
sqlx::query(
"UPDATE documents SET kind = $4, passport_id = $5, visa_id = $6, arrival_id = $7, \
extension_id = $8, reentry_permit_id = $9, report_id = $10, address_id = $11, \
work_permit_id = $12, dated_on = $13, note = $14, updated_at = now() \
WHERE id = $1 AND person_id IS NOT DISTINCT FROM $2 \
AND company_id IS NOT DISTINCT FROM $3",
)
.bind(id)
.bind(owner.person())
.bind(owner.company())
.bind(&meta.kind)
.bind(ids[0])
.bind(ids[1])
.bind(ids[2])
.bind(ids[3])
.bind(ids[4])
.bind(ids[5])
.bind(ids[6])
.bind(ids[7])
.bind(meta.dated_on)
.bind(&meta.note)
.execute(&mut **tx)
.await?;
Ok(())
}
pub async fn delete(tx: &mut Transaction<'_, Postgres>, owner: Owner, id: i64) -> Result<bool> {
let n = sqlx::query(
"DELETE FROM documents WHERE id = $1 \
AND person_id IS NOT DISTINCT FROM $2 AND company_id IS NOT DISTINCT FROM $3",
)
.bind(id)
.bind(owner.person())
.bind(owner.company())
.execute(&mut **tx)
.await?
.rows_affected();
Ok(n == 1)
}
/// The name a browser sent, without any path, control characters or
/// excess length.
pub fn clean_name(raw: &str) -> String {
let base = raw.rsplit(['/', '\\']).next().unwrap_or_default();
let name: String = base.chars().filter(|c| !c.is_control()).take(150).collect();
let name = name.trim();
if name.is_empty() {
"file".into()
} else {
name.to_string()
}
}
/// What `visa files-check` found.
#[derive(Debug, Default)]
pub struct Check {
pub documents: usize,
pub problems: Vec<String>,
}
/// Reads every document's file back, decrypts it and compares it with the
/// size and checksum recorded at the upload; lists files that belong to no
/// document.
pub async fn check(db: &PgPool, store: &Store) -> Result<Check> {
let rows: Vec<(i64, i32, String)> =
sqlx::query_as("SELECT id, size_bytes, sha256 FROM documents ORDER BY id")
.fetch_all(db)
.await?;
let (ids, other) = store.entries()?;
let mut out = Check {
documents: rows.len(),
..Check::default()
};
let known: BTreeSet<i64> = rows.iter().map(|r| r.0).collect();
for (id, size, sha) in &rows {
match store.get(*id) {
Ok(bytes) if bytes.len() == *size as usize && files::sha256_hex(&bytes) == *sha => {}
Ok(_) => out.problems.push(format!(
"document {id}: the file does not match the size and checksum of its upload"
)),
Err(e) => out.problems.push(format!("document {id}: {e:#}")),
}
}
for id in ids.iter().filter(|id| !known.contains(id)) {
out.problems
.push(format!("{id}.vdoc: a file without its document"));
}
for name in other {
out.problems
.push(format!("{name}: not a file of the store"));
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn links_read_back_and_kinds_know_their_record() {
let (link, id) = parse_link("arrivals:7").unwrap();
assert_eq!((link.column, id), ("arrival_id", 7));
for bad in [
"",
"arrivals",
"arrivals:",
"arrivals:0",
"arrivals:-3",
"people:1",
"x:1",
] {
assert!(parse_link(bad).is_none(), "{bad:?}");
}
assert_eq!(link_value(Some((link, 7))), "arrivals:7");
assert_eq!(kind_for_link("arrivals").unwrap().slug, "arrival-stamp");
assert_eq!(kind_for_link("addresses").unwrap().slug, "tm30-receipt");
// every kind's record is a link, every link has a kind
for k in PERSON_KINDS {
if let Some(r) = k.record {
assert!(LINKS.iter().any(|l| l.slug == r), "{}", k.slug);
}
}
for l in LINKS {
assert!(kind_for_link(l.slug).is_some(), "{}", l.slug);
}
}
#[test]
fn the_audit_names_the_changed_fields_only() {
let (link, _) = parse_link("passports:1").unwrap();
let a = Meta {
kind: "passport-photo-page".into(),
link: Some((link, 1)),
dated_on: None,
note: String::new(),
};
assert_eq!(a.set_fields(), ["kind", "file", "passport_id"]);
assert!(a.changed(&a.clone()).is_empty());
let b = Meta {
link: parse_link("arrivals:4"),
note: "page 2".into(),
..a.clone()
};
assert_eq!(a.changed(&b), ["arrival_id", "note", "passport_id"]);
}
#[test]
fn names_lose_their_path_and_control_characters() {
assert_eq!(clean_name("C:\\Users\\x\\Scan 1.pdf"), "Scan 1.pdf");
assert_eq!(clean_name("/tmp/a/b.jpg"), "b.jpg");
assert_eq!(clean_name("pass\nport\u{7}.png"), "passport.png");
assert_eq!(clean_name(" "), "file");
assert_eq!(clean_name("../"), "file");
assert_eq!(clean_name(&"a".repeat(400)).len(), 150);
assert_eq!(clean_name("หนังสือเดินทาง.pdf"), "หนังสือเดินทาง.pdf");
}
}
+410
View File
@@ -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();
}
}
+2
View File
@@ -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
View File
@@ -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
View File
@@ -9,6 +9,8 @@ use sqlx::PgPool;
use crate::audit::{self, Action, Entity, Entry};
use crate::dates;
use crate::documents::{self, Meta, NewFile, Owner};
use crate::files::{self, Store};
use crate::mrz;
use crate::people::{self, AddressInput, PassportInput, PersonInput};
use crate::records::{self, Kind, Values};
@@ -534,6 +536,7 @@ fn seeded(action: Action, entity: Entity, id: i64, person: Option<i64>) -> Entry
entity,
entity_id: Some(id),
person_id: person,
company_id: None,
fields: &[],
}
}
@@ -616,3 +619,442 @@ pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
tx.commit().await?;
Ok(true)
}
/// A demo document to add: whose, its kind, its record, its date, the
/// file's name and the file.
type Planned = (
Owner,
&'static str,
Option<String>,
Option<NaiveDate>,
String,
Vec<u8>,
);
/// A demo document's picture.
#[derive(Clone, Copy)]
enum Picture {
PassportPage,
Portrait,
Office,
}
/// Adds invented documents to the demo people and companies, unless the
/// seed added documents before: scans as PDF (text pages that say they are
/// demos) and pictures as PNG (shapes, no one's likeness). Returns how many.
pub async fn demo_documents(db: &PgPool, store: &Store, today: NaiveDate) -> Result<usize> {
let present: bool =
sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM documents WHERE uploaded_by = 'seed')")
.fetch_one(db)
.await?;
if present {
return Ok(0);
}
let people: Vec<(i64, String, String)> = sqlx::query_as(
"SELECT id, upper(surname), first_name FROM people \
WHERE notes = $1 AND archived_at IS NULL ORDER BY id",
)
.bind(MARKER)
.fetch_all(db)
.await?;
let latest = |table: &'static str, order: &'static str| {
format!(
"SELECT id FROM {table} WHERE person_id = $1 ORDER BY {order} DESC, id DESC LIMIT 1"
)
};
let mut plan: Vec<Planned> = Vec::new();
for (n, (id, surname, given)) in people.iter().enumerate() {
let whose = format!("{surname}, {given}");
let one = |sql: String| {
let id = *id;
async move {
sqlx::query_scalar::<_, i64>(&sql)
.bind(id)
.fetch_optional(db)
.await
}
};
let owner = Owner::Person(*id);
if let Some(pp) = one(latest("passports", "expires_on")).await? {
plan.push((
owner,
"passport-photo-page",
Some(format!("passports:{pp}")),
None,
"passport-photo-page.png".into(),
demo_png(Picture::PassportPage),
));
}
if let Some(a) = one(latest("arrivals", "arrived_on")).await? {
plan.push((
owner,
"tdac",
Some(format!("arrivals:{a}")),
None,
"TDAC.pdf".into(),
demo_pdf(
"Thailand Digital Arrival Card",
&[
format!("Traveller: {whose}"),
"Arrival card number: TDAC-DEMO".into(),
],
),
));
}
if let Some(r) = one(latest("ninety_day_reports", "reported_on")).await? {
plan.push((
owner,
"ninety-day-receipt",
Some(format!("reports:{r}")),
None,
"TM47 receipt.pdf".into(),
demo_pdf(
"Receipt of notification of staying over 90 days",
&[format!("Name: {whose}"), "Form TM.47, filed online".into()],
),
));
}
if n == 0 {
plan.push((
owner,
"photo",
None,
Some(today - TimeDelta::days(20)),
"photo 4x6.png".into(),
demo_png(Picture::Portrait),
));
if let Some(a) = one(latest("addresses", "moved_in_on")).await? {
plan.push((
owner,
"tm30-receipt",
Some(format!("addresses:{a}")),
None,
"TM30 receipt.pdf".into(),
demo_pdf(
"Receipt of notification of residence (TM.30)",
&[
format!("Foreigner: {whose}"),
"Notified by the house master".into(),
],
),
));
}
}
}
let companies: Vec<(i64, String)> =
sqlx::query_as("SELECT id, name FROM companies WHERE notes = $1 ORDER BY id LIMIT 1")
.bind(MARKER)
.fetch_all(db)
.await?;
for (id, name) in companies {
let owner = Owner::Company(id);
plan.push((
owner,
"company-certificate",
None,
Some(today - TimeDelta::days(40)),
"company certificate.pdf".into(),
demo_pdf(
"Company certificate (certified copy)",
&[
format!("Company: {name}"),
"Certified by the registrar".into(),
],
),
));
// older than six months: out of date for the pack (phase 6)
plan.push((
owner,
"shareholders",
None,
Some(today - TimeDelta::days(240)),
"BOJ5.pdf".into(),
demo_pdf(
"List of shareholders (BOJ.5)",
&[
format!("Company: {name}"),
"Shareholders as of the last meeting".into(),
],
),
));
plan.push((
owner,
"office-photo",
None,
None,
"office outside.png".into(),
demo_png(Picture::Office),
));
}
let mut tx = db.begin().await?;
let mut written = Vec::new();
for (owner, kind, link, dated_on, name, bytes) in &plan {
let meta = Meta {
kind: (*kind).to_string(),
link: link.as_deref().and_then(documents::parse_link),
dated_on: *dated_on,
note: "Demo file".into(),
};
let sha256 = files::sha256_hex(bytes);
let file = NewFile {
name,
content_type: files::sniff(bytes).expect("demo files have a known type"),
size: i32::try_from(bytes.len())?,
sha256: &sha256,
};
let id = documents::insert(&mut tx, *owner, &meta, &file, "seed").await?;
store.put(id, bytes)?;
written.push(id);
audit::record(
&mut *tx,
&Entry {
actor: "seed",
action: Action::Create,
entity: Entity::Document,
entity_id: Some(id),
person_id: owner.person(),
company_id: owner.company(),
fields: &[],
},
)
.await?;
}
tx.commit().await?;
Ok(written.len())
}
/// A one-page PDF in the app's colours: a title, a few lines and the demo
/// marker. ASCII text in Helvetica, so it needs no embedded font.
pub fn demo_pdf(title: &str, lines: &[String]) -> Vec<u8> {
let esc = |s: &str| {
s.chars()
.filter(char::is_ascii)
.collect::<String>()
.replace('\\', "\\\\")
.replace('(', "\\(")
.replace(')', "\\)")
};
let mut content =
String::from("0.027 0.075 0.137 rg 0 762 595 80 re f\n0.961 0.753 0 rg 0 756 595 6 re f\n");
content.push_str(&format!(
"BT /F1 18 Tf 1 1 1 rg 48 792 Td ({}) Tj ET\n",
esc(title)
));
let mut y = 700;
for line in lines {
content.push_str(&format!(
"BT /F1 12 Tf 0.1 0.1 0.1 rg 48 {y} Td ({}) Tj ET\n",
esc(line)
));
y -= 22;
}
content.push_str(&format!(
"BT /F1 26 Tf 0.85 0.2 0.2 rg 48 520 Td (SPECIMEN) Tj ET\n\
BT /F1 10 Tf 0.4 0.4 0.4 rg 48 60 Td ({}) Tj ET\n",
esc(MARKER)
));
let objects = [
"<< /Type /Catalog /Pages 2 0 R >>".to_string(),
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(),
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] \
/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>"
.to_string(),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>"
.to_string(),
format!(
"<< /Length {} >>\nstream\n{content}endstream",
content.len()
),
];
let mut out = b"%PDF-1.4\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objects.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
}
let xref = out.len();
out.extend_from_slice(
format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
);
for o in offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n",
objects.len() + 1
)
.as_bytes(),
);
out
}
/// A picture made of shapes, as a PNG with a palette.
fn demo_png(picture: Picture) -> Vec<u8> {
const PALETTE: [[u8; 3]; 8] = [
[0xf3, 0xef, 0xe2], // paper
[0x07, 0x13, 0x23], // navy
[0xf5, 0xc0, 0x00], // gold
[0x9b, 0xa8, 0xba], // grey
[0xd8, 0xdd, 0xe5], // light grey
[0xff, 0xff, 0xff], // white
[0x3a, 0x45, 0x56], // ink
[0xa9, 0xc8, 0xe8], // sky
];
let (w, h) = match picture {
Picture::PassportPage => (600usize, 420usize),
Picture::Portrait => (240, 360),
Picture::Office => (480, 320),
};
let mut px = vec![0u8; w * h];
let mut fill = |x0: usize, y0: usize, x1: usize, y1: usize, c: u8| {
for y in y0.min(h)..y1.min(h) {
for x in x0.min(w)..x1.min(w) {
px[y * w + x] = c;
}
}
};
let head = |cx: f64, cy: f64, r: f64, x: usize, y: usize| {
let (dx, dy) = (x as f64 - cx, (y as f64 - cy) * 0.85);
dx * dx + dy * dy <= r * r
};
match picture {
Picture::PassportPage => {
fill(0, 0, w, 56, 1);
fill(0, 56, w, 62, 2);
fill(30, 92, 170, 282, 4);
for (i, len) in [220usize, 160, 250, 140, 200, 120].iter().enumerate() {
let y = 100 + i * 30;
fill(200, y, 200 + len, y + 12, 6);
}
fill(0, 320, w, h, 5);
for row in 0..2 {
for cell in 0..44 {
let (x, y) = (24 + cell * 12, 338 + row * 34);
fill(x, y, x + 9, y + 18, 6);
}
}
}
Picture::Portrait => {
fill(0, 0, w, h, 4);
fill(40, 270, 200, h, 1);
}
Picture::Office => {
fill(0, 0, w, 200, 7);
fill(0, 260, w, h, 3);
fill(90, 70, 390, 260, 0);
fill(90, 62, 390, 72, 1);
for col in 0..5 {
for row in 0..3 {
let (x, y) = (112 + col * 56, 92 + row * 52);
fill(x, y, x + 32, y + 30, 1);
}
}
fill(212, 200, 268, 260, 2);
}
}
if let Picture::Portrait = picture {
for y in 0..h {
for x in 0..w {
if head(120.0, 150.0, 62.0, x, y) {
px[y * w + x] = 3;
}
}
}
}
if let Picture::PassportPage = picture {
for y in 92..282 {
for x in 30..170 {
if head(100.0, 160.0, 40.0, x, y) {
px[y * w + x] = 3;
}
}
}
for y in 230..282 {
for x in 50..150 {
px[y * w + x] = 3;
}
}
}
// the image data: each row with filter 0, in stored deflate blocks
let mut raw = Vec::with_capacity(h * (w + 1));
for row in px.chunks(w) {
raw.push(0);
raw.extend_from_slice(row);
}
let mut z = vec![0x78, 0x01];
let blocks: Vec<&[u8]> = raw.chunks(65_535).collect();
for (i, b) in blocks.iter().enumerate() {
z.push(u8::from(i + 1 == blocks.len()));
let len = b.len() as u16;
z.extend_from_slice(&len.to_le_bytes());
z.extend_from_slice(&(!len).to_le_bytes());
z.extend_from_slice(b);
}
z.extend_from_slice(&adler32(&raw).to_be_bytes());
let mut ihdr = Vec::new();
ihdr.extend_from_slice(&(w as u32).to_be_bytes());
ihdr.extend_from_slice(&(h as u32).to_be_bytes());
ihdr.extend_from_slice(&[8, 3, 0, 0, 0]);
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
chunk(&mut out, b"IHDR", &ihdr);
chunk(&mut out, b"PLTE", &PALETTE.concat());
chunk(&mut out, b"IDAT", &z);
chunk(&mut out, b"IEND", &[]);
out
}
fn chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(kind);
out.extend_from_slice(data);
let mut crc = 0xFFFF_FFFFu32;
for &b in kind.iter().chain(data) {
crc ^= u32::from(b);
for _ in 0..8 {
crc = if crc & 1 == 1 {
(crc >> 1) ^ 0xEDB8_8320
} else {
crc >> 1
};
}
}
out.extend_from_slice(&(!crc).to_be_bytes());
}
fn adler32(data: &[u8]) -> u32 {
let (mut a, mut b) = (1u32, 0u32);
for &x in data {
a = (a + u32::from(x)) % 65_521;
b = (b + a) % 65_521;
}
(b << 16) | a
}
#[cfg(test)]
mod demo_file_tests {
use super::*;
#[test]
fn demo_files_are_what_they_say() {
let pdf = demo_pdf("Title (demo)", &["Line".to_string()]);
assert_eq!(files::sniff(&pdf), Some("application/pdf"));
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains(MARKER));
assert!(text.contains("Title \\(demo\\)"));
// the cross-reference table points at the objects
let xref: usize = text
.rsplit("startxref\n")
.next()
.and_then(|t| t.lines().next())
.and_then(|n| n.parse().ok())
.unwrap();
assert!(text[xref..].starts_with("xref"));
for p in [Picture::PassportPage, Picture::Portrait, Picture::Office] {
let png = demo_png(p);
assert_eq!(files::sniff(&png), Some("image/png"));
assert!(png.ends_with(&[0xAE, 0x42, 0x60, 0x82]), "IEND's CRC");
}
assert_eq!(adler32(b"Wikipedia"), 0x11E6_0398);
}
}
+2
View File
@@ -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
View File
@@ -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,
}
}
+1051
View File
File diff suppressed because it is too large. Load diff
+133 -17
View File
@@ -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,13 +473,16 @@ 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();
h.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(
"default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \
connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
),
);
// 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(
"default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; \
connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
),
);
}
h.insert(
header::X_CONTENT_TYPE_OPTIONS,
HeaderValue::from_static("nosniff"),
+3
View File
@@ -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,
+3
View File
@@ -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,
}
}