Phase 1: app, Kanidm login, people, passports, addresses, audit log
visa.buildfor.life keeps the immigration records of the foreigners B4L looks after. This first phase is the base the deadlines and extension packs build on (docs/PLAN.md, phases 2 to 7). - One Rust binary (axum 0.8, minijinja, sqlx on PostgreSQL) with its templates, static files and migrations compiled in. - Login through Kanidm (OpenID Connect with PKCE and a nonce, ES256), client visa-web, group visa; sessions in PostgreSQL keyed by the SHA-256 of the cookie. VISA_INSECURE_NO_LOGIN=1 for loopback development only. - Same-site check and form token on every POST; a CSP without inline script or style; security headers. - People: list with filter, page, create, edit, archive, restore. - Passports from the machine-readable zone with check digits (ICAO 9303 TD3); expiry warnings at 12 and 6 months. - Addresses in Thailand in the order Thai forms use, with the house master and the TM.30 receipt. - Append-only audit log of every view and change, with the names of the changed fields but never their values (PDPA); the Activity page. - Invented demo people (visa seed-demo, refused when login is on). - 40 tests: unit tests, pages with demo data, the forms, the audit log and the whole login against a fake OpenID provider. - CI: gitleaks over the history, fmt, clippy and the tests against PostgreSQL 18; the pre-commit secret scan.
This commit is contained in:
commit
2e009700a9
56 files changed
+11193
No files matched your search
@@ -0,0 +1,9 @@
|
|||||||
|
# sqlx checksums migration files byte for byte: a CRLF checkout on Windows
|
||||||
|
# would no longer match a database migrated from an LF checkout.
|
||||||
|
migrations/*.sql text eol=lf
|
||||||
|
# Scripts run by bash, also from a Windows checkout.
|
||||||
|
*.sh text eol=lf
|
||||||
|
.githooks/* text eol=lf
|
||||||
|
.gitea/scripts/* text eol=lf
|
||||||
|
*.png binary
|
||||||
|
*.pdf binary
|
||||||
Executable
+18
@@ -0,0 +1,18 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Secret scan for CI (copy to .gitea/scripts/gitleaks.sh): gitleaks over the
|
||||||
|
# whole history of every branch the checkout has, with .gitleaks.toml and
|
||||||
|
# .gitleaksignore. A full scan of a few hundred commits takes about a second,
|
||||||
|
# so every push checks every commit. Exit 1 on a finding; --redact keeps the
|
||||||
|
# value out of the log. Bump VERSION and SHA256 together (checksums.txt of
|
||||||
|
# the release, line for linux_x64.tar.gz).
|
||||||
|
set -euo pipefail
|
||||||
|
VERSION=8.30.1
|
||||||
|
SHA256=551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb # linux_x64
|
||||||
|
dir=$(mktemp -d)
|
||||||
|
tarball="gitleaks_${VERSION}_linux_x64.tar.gz"
|
||||||
|
curl -fsSL --retry 3 -o "$dir/$tarball" \
|
||||||
|
"https://github.com/gitleaks/gitleaks/releases/download/v${VERSION}/${tarball}"
|
||||||
|
echo "$SHA256 $dir/$tarball" | sha256sum -c --quiet -
|
||||||
|
tar -xzf "$dir/$tarball" -C "$dir" gitleaks
|
||||||
|
"$dir/gitleaks" git . --redact --no-banner --verbose --exit-code 1 \
|
||||||
|
--log-opts="--all"
|
||||||
Executable
+24
@@ -0,0 +1,24 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# CI: install the given Rust toolchain (with clippy and rustfmt) through
|
||||||
|
# rustup and make it the default. Installs rustup and a C compiler first when
|
||||||
|
# the job image has none (ring compiles C).
|
||||||
|
# bash .gitea/scripts/rust-toolchain.sh 1.98.1
|
||||||
|
set -euo pipefail
|
||||||
|
tc=${1:?toolchain, e.g. 1.98.1}
|
||||||
|
need=()
|
||||||
|
command -v cc >/dev/null || need+=(gcc libc6-dev)
|
||||||
|
command -v curl >/dev/null || need+=(curl ca-certificates)
|
||||||
|
if [ ${#need[@]} -gt 0 ]; then
|
||||||
|
SUDO=$(command -v sudo || true)
|
||||||
|
$SUDO apt-get update -qq
|
||||||
|
$SUDO apt-get install -y -qq "${need[@]}"
|
||||||
|
fi
|
||||||
|
if ! command -v rustup >/dev/null && [ ! -x "$HOME/.cargo/bin/rustup" ]; then
|
||||||
|
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain none
|
||||||
|
fi
|
||||||
|
export PATH="$HOME/.cargo/bin:$PATH"
|
||||||
|
[ -n "${GITHUB_PATH:-}" ] && echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
|
||||||
|
rustup toolchain install "$tc" --profile minimal -c clippy -c rustfmt
|
||||||
|
rustup default "$tc"
|
||||||
|
rustc --version
|
||||||
|
cargo --version
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
# visa CI on git.b4l.co.th (Gitea Actions).
|
||||||
|
#
|
||||||
|
# leaks: gitleaks over the whole history on every push and pull request
|
||||||
|
# (.gitea/scripts/gitleaks.sh, rules in .gitleaks.toml). The pull
|
||||||
|
# request trigger covers AGit pull requests, whose commits arrive
|
||||||
|
# without a branch push. The pre-commit hook in .githooks/ scans the
|
||||||
|
# staged changes before they leave a computer.
|
||||||
|
# check: cargo fmt, clippy and the tests against a throwaway PostgreSQL 18,
|
||||||
|
# the version on cnx01 (each #[sqlx::test] creates its own database).
|
||||||
|
name: CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
pull_request:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ci-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
CARGO_TERM_COLOR: always
|
||||||
|
CARGO_INCREMENTAL: "0"
|
||||||
|
RUST_TOOLCHAIN: "1.98.1"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
leaks:
|
||||||
|
name: secret scan
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 10
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: gitleaks
|
||||||
|
run: bash .gitea/scripts/gitleaks.sh
|
||||||
|
|
||||||
|
check:
|
||||||
|
name: fmt, clippy, tests
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 60
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:18
|
||||||
|
env:
|
||||||
|
POSTGRES_USER: visa
|
||||||
|
POSTGRES_PASSWORD: visa-ci
|
||||||
|
POSTGRES_DB: visa
|
||||||
|
options: >-
|
||||||
|
--health-cmd "pg_isready -U visa"
|
||||||
|
--health-interval 5s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 20
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgres://visa:visa-ci@postgres:5432/visa
|
||||||
|
# the tests wait on the database more than on the CPU
|
||||||
|
RUST_TEST_THREADS: "16"
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Rust toolchain
|
||||||
|
run: bash .gitea/scripts/rust-toolchain.sh "$RUST_TOOLCHAIN"
|
||||||
|
|
||||||
|
- uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cargo/registry/index
|
||||||
|
~/.cargo/registry/cache
|
||||||
|
~/.cargo/git/db
|
||||||
|
target
|
||||||
|
key: check-${{ runner.os }}-${{ env.RUST_TOOLCHAIN }}-${{ hashFiles('Cargo.lock') }}
|
||||||
|
restore-keys: check-${{ runner.os }}-${{ env.RUST_TOOLCHAIN }}-
|
||||||
|
|
||||||
|
- name: Format
|
||||||
|
run: cargo fmt --all --check
|
||||||
|
|
||||||
|
- name: Clippy
|
||||||
|
run: cargo clippy --all-targets --locked -- -D warnings
|
||||||
|
|
||||||
|
- name: Tests
|
||||||
|
run: cargo test --locked
|
||||||
Executable
+11
@@ -0,0 +1,11 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Secret scan of the staged changes before each commit (gitleaks, rules in
|
||||||
|
# .gitleaks.toml). `git config core.hooksPath .githooks` turns it on per
|
||||||
|
# clone. Without gitleaks it warns and lets the commit through: CI scans every
|
||||||
|
# push again (.gitea/scripts/gitleaks.sh).
|
||||||
|
PATH="$PATH:$HOME/bin"
|
||||||
|
if ! command -v gitleaks >/dev/null 2>&1; then
|
||||||
|
echo "pre-commit: gitleaks not found; install it (https://github.com/gitleaks/gitleaks/releases) to scan commits before they leave this machine" >&2
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
exec gitleaks git --pre-commit --staged --redact --no-banner --verbose
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
/target
|
||||||
|
/tests/e2e/shots/
|
||||||
|
*.log
|
||||||
|
.env
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Secret scan (gitleaks): CI runs it over the whole history on every push
|
||||||
|
# and pull request (.gitea/workflows/ci.yml, .gitea/scripts/gitleaks.sh), and
|
||||||
|
# the pre-commit hook over what is staged (.githooks/pre-commit; `git config
|
||||||
|
# core.hooksPath .githooks` turns it on). The default rules apply. A false
|
||||||
|
# positive in one place goes into .gitleaksignore by its fingerprint (gitleaks
|
||||||
|
# prints it), never a broad rule here.
|
||||||
|
title = "visa"
|
||||||
|
|
||||||
|
[extend]
|
||||||
|
useDefault = true
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
# Working on this repository (for agents and people)
|
||||||
|
|
||||||
|
visa.buildfor.life holds passport data of real people. Read this file and
|
||||||
|
[docs/PLAN.md](docs/PLAN.md) before changing anything.
|
||||||
|
|
||||||
|
## Rules
|
||||||
|
|
||||||
|
- **No real personal data** in the repo, in tests, in demo data or in
|
||||||
|
screenshots. Demo people are invented (`src/seed.rs`) and carry the note
|
||||||
|
"Demo record, invented for development." Test passports use invented
|
||||||
|
numbers such as `C01X00T47`.
|
||||||
|
- **No secrets** in the repo. Secrets reach the app as files or systemd
|
||||||
|
credentials (`src/config.rs`); the pre-commit hook and CI run gitleaks.
|
||||||
|
- **The audit log stays complete.** Every handler that shows a person's record
|
||||||
|
writes a `view` row, and every change writes a row with the names of the
|
||||||
|
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">`.
|
||||||
|
- **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.
|
||||||
|
- **Dates** are shown as "Nov 17, 2026" in Chiang Mai time (`src/dates.rs`);
|
||||||
|
countries are ISO 3166-1 alpha-3 codes as in the passport's zone
|
||||||
|
(`src/countries.rs`, generated by `scripts/gen_countries.py`).
|
||||||
|
- **Writing** for people (pages, docs) follows the house style: plain American
|
||||||
|
English in whole sentences, no em dashes, "Nov 17, 2026" in tables.
|
||||||
|
|
||||||
|
## Checks before a push
|
||||||
|
|
||||||
|
```sh
|
||||||
|
eval "$(bash scripts/dev-db.sh)"
|
||||||
|
cargo fmt --all --check
|
||||||
|
cargo clippy --all-targets -- -D warnings
|
||||||
|
cargo test
|
||||||
|
```
|
||||||
|
|
||||||
|
CI (`.gitea/workflows/ci.yml`) runs the same against PostgreSQL 18, plus the
|
||||||
|
secret scan over the whole history. For a page change, look at it in light
|
||||||
|
and dark, at desktop and phone width, with `scripts/dev.sh` running.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
| Path | What |
|
||||||
|
| --------------------- | --------------------------------------------------------------------- |
|
||||||
|
| `src/main.rs` | the commands `serve`, `migrate`, `seed-demo` |
|
||||||
|
| `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 |
|
||||||
|
| `src/audit.rs` | the activity log |
|
||||||
|
| `src/people.rs` | people, passports, addresses: validation and SQL |
|
||||||
|
| `src/mrz.rs` | reading the passport's machine-readable zone (ICAO 9303, TD3) |
|
||||||
|
| `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 |
|
||||||
|
| `migrations/` | SQL migrations, compiled in |
|
||||||
|
| `tests/` | integration tests, one binary (`tests/main.rs` declares each file) |
|
||||||
Generated
+2585
File diff suppressed because it is too large.
Load diff
+57
@@ -0,0 +1,57 @@
|
|||||||
|
[package]
|
||||||
|
name = "visa"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
rust-version = "1.95"
|
||||||
|
description = "visa.buildfor.life: immigration records, deadlines and extension packs for foreigners in Thailand"
|
||||||
|
publish = false
|
||||||
|
# Integration tests are one binary: tests/main.rs declares every tests/*.rs
|
||||||
|
# as a module, so the suite links once.
|
||||||
|
autotests = false
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
doctest = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "visa"
|
||||||
|
path = "src/main.rs"
|
||||||
|
test = false
|
||||||
|
|
||||||
|
[[test]]
|
||||||
|
name = "integration"
|
||||||
|
path = "tests/main.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1"
|
||||||
|
axum = "0.8"
|
||||||
|
base64 = "0.22"
|
||||||
|
chrono = { version = "0.4", default-features = false, features = ["clock", "std", "serde"] }
|
||||||
|
form_urlencoded = "1"
|
||||||
|
minijinja = "2"
|
||||||
|
# The login service's certificate is checked against the system's CA bundle
|
||||||
|
# (native roots), so a NixOS VM test can bring its own CA.
|
||||||
|
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls-native-roots", "json"] }
|
||||||
|
# ID token signatures (ES256 from Kanidm, RS256 accepted), PKCE, random tokens
|
||||||
|
# and the session hashes, as in proplan and the fleet overview.
|
||||||
|
ring = "0.17"
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "postgres", "chrono", "migrate", "macros"] }
|
||||||
|
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync", "time"] }
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
http-body-util = "0.1"
|
||||||
|
tower = { version = "0.5", features = ["util"] }
|
||||||
|
|
||||||
|
[profile.dev]
|
||||||
|
# Line tables keep file:line in panics at a fraction of full debug info.
|
||||||
|
debug = "line-tables-only"
|
||||||
|
|
||||||
|
[profile.dev.package."*"]
|
||||||
|
debug = false
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
lto = "thin"
|
||||||
|
strip = true
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# visa.buildfor.life
|
||||||
|
|
||||||
|
visa.buildfor.life keeps the immigration records of the foreigners that B4L
|
||||||
|
looks after in Thailand: their passports, addresses and TM.30 receipts, and
|
||||||
|
from phase 2 their visas, arrivals with the TDAC, extensions of stay,
|
||||||
|
re-entry permits, 90-day reports and work permits. From those records it will
|
||||||
|
work out every deadline and prepare the documents for the next extension of
|
||||||
|
stay at Chiang Mai Immigration with the forms filled in.
|
||||||
|
|
||||||
|
B4L's own staff use it first. The data model treats everyone as a client of
|
||||||
|
an agency whose staff see all records, so it can grow into the internal tool
|
||||||
|
of the visa agency planned in `grabowski/julia`. [docs/PLAN.md](docs/PLAN.md)
|
||||||
|
holds the decisions, the deadline rules, the data model and the phases.
|
||||||
|
|
||||||
|
Only members of the Kanidm group `visa` at id.cnx.network can sign in. Every
|
||||||
|
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 (phase 1)
|
||||||
|
|
||||||
|
- A list of people with a filter, and a page per person with personal
|
||||||
|
details, passports and addresses in Thailand.
|
||||||
|
- New people and passports from the passport's machine-readable zone: paste
|
||||||
|
the two lines at the bottom of the photo page and the form fills itself in.
|
||||||
|
The check digits catch typing errors.
|
||||||
|
- Warnings when a passport has under 12 months left, and under six, since an
|
||||||
|
extension never runs past the passport's expiry. A missing TM.30 receipt is
|
||||||
|
flagged too.
|
||||||
|
- Archiving and restoring a person, and the Activity page with the log.
|
||||||
|
|
||||||
|
## Try it
|
||||||
|
|
||||||
|
You need Rust 1.95 or newer and Docker for the local PostgreSQL.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
git config core.hooksPath .githooks # the secret scan before each commit
|
||||||
|
eval "$(bash scripts/dev-db.sh)" # PostgreSQL 18 on 127.0.0.1:55438
|
||||||
|
bash scripts/dev.sh # http://127.0.0.1:8040, no login, demo people
|
||||||
|
```
|
||||||
|
|
||||||
|
`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.
|
||||||
|
|
||||||
|
The tests need the same database; each test gets its own:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
eval "$(bash scripts/dev-db.sh)"
|
||||||
|
cargo fmt --all --check && cargo clippy --all-targets -- -D warnings && cargo test
|
||||||
|
```
|
||||||
|
|
||||||
|
## Settings
|
||||||
|
|
||||||
|
The server reads its settings from the environment. Secrets are read from
|
||||||
|
files or systemd credentials and never from a variable's value.
|
||||||
|
|
||||||
|
| Variable | Meaning |
|
||||||
|
| ------------------------------ | -------------------------------------------------------------- |
|
||||||
|
| `VISA_LISTEN` | address to listen on, default `127.0.0.1:8040` |
|
||||||
|
| `VISA_PUBLIC_URL` | `https://visa.buildfor.life`, for the login's redirect |
|
||||||
|
| `VISA_DATABASE_URL` | `postgres://visa@host/visa` |
|
||||||
|
| `VISA_DATABASE_PASSWORD_FILE` | the role's password; else the credential `db-password` |
|
||||||
|
| `VISA_OIDC_ISSUER` | `https://id.cnx.network/oauth2/openid/visa-web` |
|
||||||
|
| `VISA_OIDC_CLIENT_ID` | default `visa-web` |
|
||||||
|
| `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 serve` (the default) applies pending migrations before it listens,
|
||||||
|
`visa migrate` applies them alone, and `visa seed-demo` adds the demo people.
|
||||||
|
|
||||||
|
## Where it runs
|
||||||
|
|
||||||
|
From phase 3 the app runs on cnx01 in the office, like proplan and
|
||||||
|
lampbench-web: the database `visa` on cnx01's PostgreSQL, uploads encrypted
|
||||||
|
by the app, backups by borg, and bkk01 publishing visa.buildfor.life. Passport
|
||||||
|
data stays on B4L's own servers.
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
//! Lists every file of templates/ and static/ for `src/embedded.rs`: one
|
||||||
|
//! `(name, include_bytes!(..))` pair per file, sorted by name, so the binary
|
||||||
|
//! carries its pages and needs no files next to it. Also a short hash of the
|
||||||
|
//! static files for cache busting (`/static/app.css?v=<hash>`).
|
||||||
|
|
||||||
|
use std::fmt::Write as _;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
println!("cargo:rerun-if-changed=build.rs");
|
||||||
|
let root = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap());
|
||||||
|
let mut out = String::from("// Generated by build.rs.\n");
|
||||||
|
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
|
||||||
|
for (name, dir) in [("TEMPLATES", "templates"), ("STATIC", "static")] {
|
||||||
|
// A directory here makes cargo rerun this script when a file in it
|
||||||
|
// is added or removed; each file is listed below for edits.
|
||||||
|
println!("cargo:rerun-if-changed={dir}");
|
||||||
|
let base = root.join(dir);
|
||||||
|
let mut files = Vec::new();
|
||||||
|
walk(&base, &base, &mut files);
|
||||||
|
files.sort();
|
||||||
|
writeln!(out, "pub static {name}: &[(&str, &[u8])] = &[").unwrap();
|
||||||
|
for (rel, abs) in &files {
|
||||||
|
println!("cargo:rerun-if-changed={abs}");
|
||||||
|
if dir == "static" {
|
||||||
|
// FNV-1a over names and contents
|
||||||
|
for b in rel.bytes().chain(std::fs::read(abs).unwrap()) {
|
||||||
|
hash ^= u64::from(b);
|
||||||
|
hash = hash.wrapping_mul(0x0100_0000_01b3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeln!(out, " ({rel:?}, include_bytes!({abs:?})),").unwrap();
|
||||||
|
}
|
||||||
|
writeln!(out, "];").unwrap();
|
||||||
|
}
|
||||||
|
writeln!(
|
||||||
|
out,
|
||||||
|
"pub const STATIC_HASH: &str = \"{:012x}\";",
|
||||||
|
hash >> 16
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let dest = Path::new(&std::env::var_os("OUT_DIR").unwrap()).join("embedded.rs");
|
||||||
|
std::fs::write(dest, out).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn walk(base: &Path, dir: &Path, out: &mut Vec<(String, String)>) {
|
||||||
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
if path.is_dir() {
|
||||||
|
walk(base, &path, out);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let rel = path
|
||||||
|
.strip_prefix(base)
|
||||||
|
.unwrap()
|
||||||
|
.components()
|
||||||
|
.map(|c| c.as_os_str().to_string_lossy().into_owned())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("/");
|
||||||
|
out.push((rel, path.to_string_lossy().into_owned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
+209
@@ -0,0 +1,209 @@
|
|||||||
|
# visa.buildfor.life: plan
|
||||||
|
|
||||||
|
> Phase 1 built on November 17, 2026. **Resume here: phase 2, task 2.1.**
|
||||||
|
|
||||||
|
visa.buildfor.life keeps the immigration records of the foreigners that B4L
|
||||||
|
looks after: their passports, addresses in Thailand, arrivals with the Thailand
|
||||||
|
Digital Arrival Card (TDAC), visas, extensions of stay, re-entry permits,
|
||||||
|
90-day reports and work permits. From those records it works out every
|
||||||
|
deadline, such as the next 90-day report with its filing windows or the day the
|
||||||
|
window for the next extension opens, and it prepares the documents for the
|
||||||
|
next extension of stay with the forms filled in from the records.
|
||||||
|
|
||||||
|
B4L's own foreign staff use it first. It is meant to grow into the internal
|
||||||
|
tool of a visa agency in Chiang Mai, the one planned in the business plan in
|
||||||
|
`grabowski/julia` (`C:\dev\visa_service_plan`), so the data model treats
|
||||||
|
everyone as a client of an agency whose staff see all records.
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
The first round of questions was answered on November 17, 2026.
|
||||||
|
|
||||||
|
| Question | Decision |
|
||||||
|
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| Where it runs | cnx01, installed on the host like proplan and lampbench: database `visa` on cnx01's PostgreSQL, files in a ZFS dataset, encrypted by the app, borg backups to control |
|
||||||
|
| How it is published | bkk01 publishes `visa.buildfor.life` through a `modules/web-sites` app entry |
|
||||||
|
| Login | Kanidm at id.cnx.network, OAuth2 client `visa-web`, group `visa` with grabowski and oltmanns |
|
||||||
|
| Who sees what | every member of `visa` sees and edits every record, as agency staff would; a view for clients comes later |
|
||||||
|
| First extension pack | Non-B with a work permit, employer B4L, at Chiang Mai Immigration |
|
||||||
|
| Reminders | the dashboard first; later a Matrix room message and an email to the person concerned |
|
||||||
|
| Repository | private `B4L/visa`; the fleet then needs a read token for its flake input |
|
||||||
|
|
||||||
|
Kanidm keeps persons, groups and OAuth2 clients in one namespace, so the
|
||||||
|
client cannot be called `visa` like the group. It is `visa-web`, as
|
||||||
|
lampbench's client is `lampbench-web`.
|
||||||
|
|
||||||
|
## How it is built
|
||||||
|
|
||||||
|
The stack is the one of proplan, the fleet overview and lampbench-web: one
|
||||||
|
Rust binary (axum 0.8, minijinja templates, sqlx on PostgreSQL) with its
|
||||||
|
templates, static files and migrations compiled in. Pages are rendered on the
|
||||||
|
server and work without JavaScript; `static/app.js` only switches the theme,
|
||||||
|
filters lists and asks before a delete. The Content Security Policy allows no
|
||||||
|
inline script or style.
|
||||||
|
|
||||||
|
- **Login.** OpenID Connect with PKCE and a nonce against Kanidm, ported from
|
||||||
|
the fleet overview (`src/oidc.rs`). Only members of `visa` get a session.
|
||||||
|
Without a login provider the app starts only with `VISA_INSECURE_NO_LOGIN=1`
|
||||||
|
on a loopback address, for development.
|
||||||
|
- **Sessions.** In PostgreSQL, keyed by the SHA-256 of the cookie's value, so
|
||||||
|
a deploy does not sign anyone out and a database dump holds no usable
|
||||||
|
session. The cookie is `__Host-visa` (Secure, HttpOnly, SameSite=Lax).
|
||||||
|
- **Forms.** Every POST must come from this site (`Sec-Fetch-Site`, else
|
||||||
|
`Origin`) and carry the session's form token (`csrf`).
|
||||||
|
- **Audit.** Personal data falls under Thailand's Personal Data Protection Act
|
||||||
|
(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.
|
||||||
|
- **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
|
||||||
|
catch typing errors (ICAO Doc 9303, part 4).
|
||||||
|
|
||||||
|
## Data model
|
||||||
|
|
||||||
|
Phase 1 holds people, passports and addresses; phase 2 adds what a stay is
|
||||||
|
made of.
|
||||||
|
|
||||||
|
| Table | Holds | Phase |
|
||||||
|
| -------------------- | --------------------------------------------------------------------------------------------------------------------------- | ----- |
|
||||||
|
| `people` | names as in the passport, title, sex, birth date and place, nationality, occupation, employer, phone, email, notes; archiving | 1 |
|
||||||
|
| `passports` | number, issuing state, issue and expiry dates, issuing authority, the MRZ as read; the current one has the latest expiry | 1 |
|
||||||
|
| `addresses` | the address in Thailand in the order Thai forms use, moving dates, the house master and the TM.30 receipt | 1 |
|
||||||
|
| `sessions` | signed-in sessions | 1 |
|
||||||
|
| `audit_log` | who viewed or changed which record, append-only | 1 |
|
||||||
|
| `visas` | visa category (Non-B, Non-O, DTV and others), number, place and date of issue, validity, entries | 2 |
|
||||||
|
| `entries` | arrival date, port, flight, visa used, permitted-until date, TDAC number; departure date when the person left | 2 |
|
||||||
|
| `extensions` | extensions of stay: approval date, new permitted-until date, reason, office, receipt | 2 |
|
||||||
|
| `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, position, validity | 2 |
|
||||||
|
| `documents` | encrypted uploads tied to a person and a record | 4 |
|
||||||
|
|
||||||
|
## Deadline rules
|
||||||
|
|
||||||
|
The rules below come from the Immigration Bureau's pages. Where the receipt
|
||||||
|
or the stamp shows a date, that date wins over any calculation, and the app
|
||||||
|
shows a calculated date as an estimate until a receipt confirms it.
|
||||||
|
|
||||||
|
- **90-day report (TM.47).** The day of arrival counts as day 1, so the first
|
||||||
|
report is due on the arrival date plus 89 days. After each report the
|
||||||
|
receipt names the next date. Leaving Thailand ends the count; after the
|
||||||
|
next arrival it starts again from day 1. A report in person, or by someone
|
||||||
|
the person authorizes, is accepted from 15 days before to 7 days after the
|
||||||
|
due date. Online it is accepted from 15 days before to 8 days before, and
|
||||||
|
never after a new passport until one report was made in person. A late
|
||||||
|
report costs 2,000 THB; being caught without one, up to 5,000 THB. The
|
||||||
|
Immigration Bureau treats a first extension of stay as the first report.
|
||||||
|
- **Extension of stay (TM.7).** The application must be made before the
|
||||||
|
permitted-until date. Chiang Mai accepts it from 30 days before (some
|
||||||
|
categories 45); the app opens the window 30 days before and counts down to
|
||||||
|
the last working day. An overstay costs 500 THB a day.
|
||||||
|
- **Passport.** An extension never runs past the passport's expiry, so the
|
||||||
|
app warns 12 months before expiry and marks a passport with less than six
|
||||||
|
months left.
|
||||||
|
- **Re-entry permit (TM.8).** Leaving without one cancels the extension of
|
||||||
|
stay; a planned trip without a valid permit raises a warning.
|
||||||
|
- **TM.30.** The house master reports the person's address within 24 hours
|
||||||
|
of arrival, also after a trip abroad; extensions and 90-day reports ask for
|
||||||
|
the receipt.
|
||||||
|
- **TDAC.** Submitted online within the three days before each arrival; its
|
||||||
|
number replaces the old TM.6 card number on the forms.
|
||||||
|
|
||||||
|
Sources: Immigration Bureau, TM.47 online manual
|
||||||
|
(bangkok.immigration.go.th/en/tm47online-manual); Immigration Division 1 form
|
||||||
|
downloads (bangkok.immigration.go.th/en/downloads_en); thailand.go.th,
|
||||||
|
"Business visa extension for foreigners working in Thailand"; TDAC manual
|
||||||
|
(tdac.immigration.go.th/manual/en).
|
||||||
|
|
||||||
|
## The Non-B extension pack (phase 6)
|
||||||
|
|
||||||
|
For an extension of stay based on work, Chiang Mai Immigration asks for the
|
||||||
|
following. The pack lists each item with its state (generated, uploaded,
|
||||||
|
missing or out of date) and prints them in this order.
|
||||||
|
|
||||||
|
1. TM.7 with a 4 x 6 cm photo, the acknowledgment of overstay penalties and
|
||||||
|
STM.2, all filled in from the records.
|
||||||
|
2. STM.1, the employer's certificate of employment.
|
||||||
|
3. Copies of the passport: the photo page, the visa, the latest arrival stamp,
|
||||||
|
earlier extensions, and the TDAC.
|
||||||
|
4. The last 90-day receipt and the TM.30 receipt.
|
||||||
|
5. The work permit and its copy.
|
||||||
|
6. B4L's company documents: the company certificate and the list of
|
||||||
|
shareholders (BOJ.5), both certified within six months; the latest
|
||||||
|
balance sheet with PND.50; PND.1 withholding tax and SPS 1-10 social
|
||||||
|
security for the last three months; PP.30 VAT returns; the applicant's
|
||||||
|
PND.91; a map; photos of the office outside and inside. Every page carries
|
||||||
|
the company seal and the director's signature, in two sets.
|
||||||
|
|
||||||
|
The company documents are shared by every employee's pack, so they are kept
|
||||||
|
once per company with their own expiry (a certification older than six months
|
||||||
|
counts as out of date).
|
||||||
|
|
||||||
|
## Phases
|
||||||
|
|
||||||
|
Each phase ends with the tests, clippy, formatting, screenshots in light and
|
||||||
|
dark at desktop and phone width, a commit and a push.
|
||||||
|
|
||||||
|
| Phase | Content | Status |
|
||||||
|
| ----- | --------------------------------------------------------------------------------------------------------------- | ---------------------------- |
|
||||||
|
| 1 | App, Kanidm login, people, passports with MRZ reading, addresses in Thailand, audit log, demo data, CI | built Nov 17, 2026 |
|
||||||
|
| 2 | Stays: visas, arrivals with TDAC, extensions, re-entry permits, 90-day reports, work permits; deadlines | **next** |
|
||||||
|
| 3 | On cnx01: flake package, fleet module, Kanidm client and group, bkk01 site, backups; real data from here on | |
|
||||||
|
| 4 | Documents: encrypted uploads (passport pages, TDAC, receipts, photo), viewing and download, all audited | |
|
||||||
|
| 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 | |
|
||||||
|
| later | Thai user interface, agency cases and fees, a view for clients, other visa categories' packs | |
|
||||||
|
|
||||||
|
### Phase 1: app, login, people
|
||||||
|
|
||||||
|
- [x] 1.1 Repository: Cargo crate `visa`, templates and static files compiled
|
||||||
|
in, migrations, CI (secret scan, format, clippy, tests against
|
||||||
|
PostgreSQL 18), pre-commit secret scan.
|
||||||
|
- [x] 1.2 Login through Kanidm (OIDC with PKCE), sessions in PostgreSQL,
|
||||||
|
group `visa`; `VISA_INSECURE_NO_LOGIN=1` for loopback development.
|
||||||
|
- [x] 1.3 Same-site check and form token on every POST; security headers.
|
||||||
|
- [x] 1.4 People: list with filter, page, create, edit, archive, restore.
|
||||||
|
- [x] 1.5 Passports: add, edit, delete; the current one marked; expiry
|
||||||
|
warnings at 12 and 6 months.
|
||||||
|
- [x] 1.6 MRZ reading with check digits, on the new person and the new
|
||||||
|
passport forms.
|
||||||
|
- [x] 1.7 Addresses in Thailand with house master and TM.30 receipt.
|
||||||
|
- [x] 1.8 Audit log with the Activity page.
|
||||||
|
- [x] 1.9 Demo data with invented people (`visa seed-demo`, development only).
|
||||||
|
|
||||||
|
### Phase 2: stays and deadlines
|
||||||
|
|
||||||
|
- [ ] 2.1 Visas and arrivals: arrival date, port, flight, visa used,
|
||||||
|
permitted-until date, TDAC number and date; departures.
|
||||||
|
- [ ] 2.2 Extensions of stay and re-entry permits.
|
||||||
|
- [ ] 2.3 90-day reports with the next due date from the receipt.
|
||||||
|
- [ ] 2.4 Work permits.
|
||||||
|
- [ ] 2.5 The deadline engine as pure functions with unit tests for every
|
||||||
|
rule above (arrival plus 89 days, the windows, a trip resetting the
|
||||||
|
count, the extension window, passport and work permit expiry).
|
||||||
|
- [ ] 2.6 Dashboard at `/`: every person's next deadlines sorted by urgency;
|
||||||
|
a timeline on the person page.
|
||||||
|
|
||||||
|
### Phase 3: on cnx01
|
||||||
|
|
||||||
|
- [ ] 3.1 `flake.nix` with `packages.visa` (crane), built in WSL against the
|
||||||
|
fleet's nixpkgs.
|
||||||
|
- [ ] 3.2 Fleet module `modules/visa` (roles `enable` on cnx01 and
|
||||||
|
`kanidmClient` on web01), database `visa`, dataset `zroot/visa`, vars
|
||||||
|
`visa-oidc` and the file key, `visa-admin`, VM test `checks.visa`;
|
||||||
|
group `visa` in `identity/`.
|
||||||
|
- [ ] 3.3 The flake input needs a read token for the private repository:
|
||||||
|
decide between a Nix `access-tokens` clan var and a CI-published
|
||||||
|
package.
|
||||||
|
- [ ] 3.4 `sites.nix` entry `visa` on bkk01, the A record, deploys on Alex's
|
||||||
|
go.
|
||||||
|
|
||||||
|
## Open questions
|
||||||
|
|
||||||
|
1. B4L's BOI application: once B4L is promoted, its staff extend their stay
|
||||||
|
through the BOI's One Start One Stop center, which changes phase 6's pack.
|
||||||
|
2. Which Chiang Mai office handles B4L's cases (the main office at 71 Moo 3
|
||||||
|
Airport Road or the branch at Central Chiangmai) only matters for the
|
||||||
|
cover sheet; to be settled in phase 6.
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
-- visa.buildfor.life, phase 1: people, passports, addresses in Thailand,
|
||||||
|
-- sessions and the audit log (docs/PLAN.md "Data model").
|
||||||
|
--
|
||||||
|
-- Optional text is NOT NULL DEFAULT '' so the code has one empty value;
|
||||||
|
-- dates are NULL when unknown.
|
||||||
|
|
||||||
|
CREATE TABLE people (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
-- as printed in the passport
|
||||||
|
surname TEXT NOT NULL,
|
||||||
|
first_name TEXT NOT NULL,
|
||||||
|
middle_name TEXT NOT NULL DEFAULT '',
|
||||||
|
title TEXT NOT NULL DEFAULT '' CHECK (title IN ('', 'Mr', 'Mrs', 'Ms', 'Miss')),
|
||||||
|
sex TEXT NOT NULL DEFAULT '' CHECK (sex IN ('', 'F', 'M', 'X')),
|
||||||
|
date_of_birth DATE,
|
||||||
|
place_of_birth TEXT NOT NULL DEFAULT '',
|
||||||
|
-- ISO 3166-1 alpha-3, as in the passport's machine-readable zone
|
||||||
|
nationality TEXT NOT NULL DEFAULT '',
|
||||||
|
occupation TEXT NOT NULL DEFAULT '',
|
||||||
|
employer TEXT NOT NULL DEFAULT '',
|
||||||
|
phone TEXT NOT NULL DEFAULT '',
|
||||||
|
email TEXT NOT NULL DEFAULT '',
|
||||||
|
notes TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
archived_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE passports (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
person_id BIGINT NOT NULL REFERENCES people (id),
|
||||||
|
number TEXT NOT NULL,
|
||||||
|
issuing_country TEXT NOT NULL,
|
||||||
|
issued_on DATE,
|
||||||
|
expires_on DATE NOT NULL,
|
||||||
|
-- the issuing authority or place as printed ("issued at" on TM.7)
|
||||||
|
issued_at TEXT NOT NULL DEFAULT '',
|
||||||
|
-- the machine-readable zone as read, two lines
|
||||||
|
mrz TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CHECK (issued_on IS NULL OR issued_on < expires_on)
|
||||||
|
);
|
||||||
|
CREATE UNIQUE INDEX passports_number_key ON passports (issuing_country, number);
|
||||||
|
CREATE INDEX passports_person ON passports (person_id);
|
||||||
|
|
||||||
|
CREATE TABLE addresses (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
person_id BIGINT NOT NULL REFERENCES people (id),
|
||||||
|
-- in the order Thai forms use
|
||||||
|
house_no TEXT NOT NULL DEFAULT '',
|
||||||
|
moo TEXT NOT NULL DEFAULT '',
|
||||||
|
building TEXT NOT NULL DEFAULT '',
|
||||||
|
soi TEXT NOT NULL DEFAULT '',
|
||||||
|
road TEXT NOT NULL DEFAULT '',
|
||||||
|
subdistrict TEXT NOT NULL DEFAULT '',
|
||||||
|
district TEXT NOT NULL DEFAULT '',
|
||||||
|
province TEXT NOT NULL DEFAULT '',
|
||||||
|
postal_code TEXT NOT NULL DEFAULT '',
|
||||||
|
moved_in_on DATE,
|
||||||
|
moved_out_on DATE,
|
||||||
|
-- the owner or landlord who files TM.30
|
||||||
|
house_master TEXT NOT NULL DEFAULT '',
|
||||||
|
house_master_phone TEXT NOT NULL DEFAULT '',
|
||||||
|
tm30_reported_on DATE,
|
||||||
|
tm30_receipt_no TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CHECK (moved_out_on IS NULL OR moved_in_on IS NULL OR moved_in_on <= moved_out_on)
|
||||||
|
);
|
||||||
|
CREATE INDEX addresses_person ON addresses (person_id);
|
||||||
|
|
||||||
|
-- Signed-in sessions. The key is the SHA-256 of the cookie's value, so a dump
|
||||||
|
-- of this table holds no usable session.
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
id_hash BYTEA PRIMARY KEY,
|
||||||
|
login TEXT NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
csrf TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX sessions_expires ON sessions (expires_at);
|
||||||
|
|
||||||
|
-- Who viewed or changed which record (PDPA). The names of changed fields
|
||||||
|
-- only, never their values. Append-only.
|
||||||
|
CREATE TABLE audit_log (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
actor TEXT NOT NULL,
|
||||||
|
action TEXT NOT NULL CHECK (
|
||||||
|
action IN ('view', 'create', 'update', 'delete', 'archive', 'restore', 'sign-in', 'sign-out')
|
||||||
|
),
|
||||||
|
entity TEXT NOT NULL CHECK (entity IN ('person', 'passport', 'address', 'session')),
|
||||||
|
entity_id BIGINT,
|
||||||
|
person_id BIGINT,
|
||||||
|
fields TEXT[] NOT NULL DEFAULT '{}'
|
||||||
|
);
|
||||||
|
CREATE INDEX audit_log_person ON audit_log (person_id, at);
|
||||||
|
|
||||||
|
CREATE FUNCTION audit_log_append_only() RETURNS trigger
|
||||||
|
LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
RAISE EXCEPTION 'audit_log is append-only';
|
||||||
|
END
|
||||||
|
$$;
|
||||||
|
|
||||||
|
CREATE TRIGGER audit_log_no_change
|
||||||
|
BEFORE UPDATE OR DELETE ON audit_log
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION audit_log_append_only();
|
||||||
Executable
+13
@@ -0,0 +1,13 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# The local database: PostgreSQL 18 (as on cnx01) in the docker container
|
||||||
|
# visa-pg on 127.0.0.1:55438. Development and tests only; the password is
|
||||||
|
# not a secret.
|
||||||
|
set -euo pipefail
|
||||||
|
if docker inspect visa-pg >/dev/null 2>&1; then
|
||||||
|
docker start visa-pg >/dev/null
|
||||||
|
else
|
||||||
|
docker run -d --name visa-pg -e POSTGRES_USER=visa -e POSTGRES_PASSWORD=visa-dev \
|
||||||
|
-e POSTGRES_DB=visa -p 127.0.0.1:55438:5432 postgres:18 >/dev/null
|
||||||
|
fi
|
||||||
|
until docker exec visa-pg pg_isready -U visa >/dev/null 2>&1; do sleep 1; done
|
||||||
|
echo "export DATABASE_URL=postgres://visa:visa-dev@127.0.0.1:55438/visa"
|
||||||
Executable
+11
@@ -0,0 +1,11 @@
|
|||||||
|
#!/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.
|
||||||
|
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}
|
||||||
|
cargo build -q
|
||||||
|
./target/debug/visa seed-demo
|
||||||
|
exec ./target/debug/visa serve
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# /// script
|
||||||
|
# dependencies = ["pycountry"]
|
||||||
|
# ///
|
||||||
|
"""Writes src/countries.rs: ISO 3166-1 alpha-3 codes with English short names.
|
||||||
|
|
||||||
|
uv run scripts/gen_countries.py > src/countries_data.rs
|
||||||
|
|
||||||
|
The names come from pycountry (Debian's iso-codes); `common_name` wins where
|
||||||
|
iso-codes has one ("Bolivia" instead of "Bolivia, Plurinational State of").
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pycountry
|
||||||
|
|
||||||
|
rows = sorted(
|
||||||
|
(c.alpha_3, getattr(c, "common_name", None) or c.name) for c in pycountry.countries
|
||||||
|
)
|
||||||
|
print("// Generated by scripts/gen_countries.py from pycountry; do not edit by hand.")
|
||||||
|
print("pub static COUNTRIES: &[(&str, &str)] = &[")
|
||||||
|
for code, name in rows:
|
||||||
|
print(f" ({json.dumps(code)}, {json.dumps(name, ensure_ascii=False)}),")
|
||||||
|
print("];")
|
||||||
+164
@@ -0,0 +1,164 @@
|
|||||||
|
//! The audit log (PDPA): who viewed or changed which record. It holds the
|
||||||
|
//! names of changed fields, never their values, and the table refuses
|
||||||
|
//! updates and deletes (migrations/0001_init.sql).
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use serde::Serialize;
|
||||||
|
use sqlx::{Executor, PgPool, Postgres};
|
||||||
|
|
||||||
|
use crate::dates;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Action {
|
||||||
|
View,
|
||||||
|
Create,
|
||||||
|
Update,
|
||||||
|
Delete,
|
||||||
|
Archive,
|
||||||
|
Restore,
|
||||||
|
SignIn,
|
||||||
|
SignOut,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Action {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Action::View => "view",
|
||||||
|
Action::Create => "create",
|
||||||
|
Action::Update => "update",
|
||||||
|
Action::Delete => "delete",
|
||||||
|
Action::Archive => "archive",
|
||||||
|
Action::Restore => "restore",
|
||||||
|
Action::SignIn => "sign-in",
|
||||||
|
Action::SignOut => "sign-out",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Entity {
|
||||||
|
Person,
|
||||||
|
Passport,
|
||||||
|
Address,
|
||||||
|
Session,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Entity {
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Entity::Person => "person",
|
||||||
|
Entity::Passport => "passport",
|
||||||
|
Entity::Address => "address",
|
||||||
|
Entity::Session => "session",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Entry<'a> {
|
||||||
|
pub actor: &'a str,
|
||||||
|
pub action: Action,
|
||||||
|
pub entity: Entity,
|
||||||
|
pub entity_id: Option<i64>,
|
||||||
|
pub person_id: Option<i64>,
|
||||||
|
pub fields: &'a [String],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes one entry; pass the transaction (`&mut *tx`) when the change it
|
||||||
|
/// records is in one, so both commit or roll back together.
|
||||||
|
pub async fn record<'e, E>(ex: E, e: &Entry<'_>) -> Result<()>
|
||||||
|
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)",
|
||||||
|
)
|
||||||
|
.bind(e.actor)
|
||||||
|
.bind(e.action.as_str())
|
||||||
|
.bind(e.entity.as_str())
|
||||||
|
.bind(e.entity_id)
|
||||||
|
.bind(e.person_id)
|
||||||
|
.bind(e.fields)
|
||||||
|
.execute(ex)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A view of a person's record.
|
||||||
|
pub async fn viewed(db: &PgPool, actor: &str, entity: Entity, id: i64, person: i64) -> Result<()> {
|
||||||
|
record(
|
||||||
|
db,
|
||||||
|
&Entry {
|
||||||
|
actor,
|
||||||
|
action: Action::View,
|
||||||
|
entity,
|
||||||
|
entity_id: Some(id),
|
||||||
|
person_id: Some(person),
|
||||||
|
fields: &[],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, sqlx::FromRow)]
|
||||||
|
struct Row {
|
||||||
|
id: i64,
|
||||||
|
at: DateTime<Utc>,
|
||||||
|
actor: String,
|
||||||
|
action: String,
|
||||||
|
entity: String,
|
||||||
|
entity_id: Option<i64>,
|
||||||
|
person_id: Option<i64>,
|
||||||
|
fields: Vec<String>,
|
||||||
|
person_name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct Item {
|
||||||
|
pub id: i64,
|
||||||
|
pub at: String,
|
||||||
|
pub actor: String,
|
||||||
|
pub action: String,
|
||||||
|
pub what: String,
|
||||||
|
pub person_id: Option<i64>,
|
||||||
|
pub person_name: Option<String>,
|
||||||
|
pub fields: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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, \
|
||||||
|
CASE WHEN p.id IS NULL THEN NULL \
|
||||||
|
ELSE upper(p.surname) || ', ' || trim(p.first_name || ' ' || p.middle_name) \
|
||||||
|
END AS person_name \
|
||||||
|
FROM audit_log a LEFT JOIN people p ON p.id = a.person_id \
|
||||||
|
WHERE ($1::bigint IS NULL OR a.person_id = $1) \
|
||||||
|
ORDER BY a.id DESC LIMIT $2",
|
||||||
|
)
|
||||||
|
.bind(person)
|
||||||
|
.bind(limit)
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|r| {
|
||||||
|
let what = match (r.entity.as_str(), r.entity_id) {
|
||||||
|
("session", _) => String::new(),
|
||||||
|
(e, Some(id)) => format!("{e} {id}"),
|
||||||
|
(e, None) => e.to_string(),
|
||||||
|
};
|
||||||
|
Item {
|
||||||
|
id: r.id,
|
||||||
|
at: dates::fmt_datetime(r.at),
|
||||||
|
actor: r.actor,
|
||||||
|
action: r.action,
|
||||||
|
what,
|
||||||
|
person_id: r.person_id,
|
||||||
|
person_name: r.person_name,
|
||||||
|
fields: r.fields.join(", ").replace('_', " "),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
+225
@@ -0,0 +1,225 @@
|
|||||||
|
//! Settings from the environment. The NixOS module sets them; secrets come as
|
||||||
|
//! files or systemd credentials, never as values in the environment.
|
||||||
|
//!
|
||||||
|
//! | Variable | Meaning |
|
||||||
|
//! | -------------------------------- | ------------------------------------------------ |
|
||||||
|
//! | `VISA_LISTEN` | address to listen on, default 127.0.0.1:8040 |
|
||||||
|
//! | `VISA_PUBLIC_URL` | https://visa.buildfor.life (login redirects) |
|
||||||
|
//! | `VISA_DATABASE_URL` | postgres://user@host/db |
|
||||||
|
//! | `VISA_DATABASE_PASSWORD_FILE` | the role's password (else credential `db-password`) |
|
||||||
|
//! | `VISA_OIDC_ISSUER` | https://id.cnx.network/oauth2/openid/visa-web |
|
||||||
|
//! | `VISA_OIDC_CLIENT_ID` | default `visa-web` |
|
||||||
|
//! | `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 |
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, bail, ensure};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Config {
|
||||||
|
pub listen: SocketAddr,
|
||||||
|
/// Without a trailing slash.
|
||||||
|
pub public_url: String,
|
||||||
|
pub database_url: String,
|
||||||
|
pub database_password: Option<String>,
|
||||||
|
pub auth: Auth,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum Auth {
|
||||||
|
Oidc(OidcConfig),
|
||||||
|
/// Local development: everyone is "local"; loopback addresses only.
|
||||||
|
Disabled,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct OidcConfig {
|
||||||
|
pub issuer: String,
|
||||||
|
pub client_id: String,
|
||||||
|
pub client_secret: String,
|
||||||
|
pub group: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
// The secret stays out of logs and panics.
|
||||||
|
impl std::fmt::Debug for OidcConfig {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("OidcConfig")
|
||||||
|
.field("issuer", &self.issuer)
|
||||||
|
.field("client_id", &self.client_id)
|
||||||
|
.field(
|
||||||
|
"client_secret",
|
||||||
|
&format_args!("<{} bytes>", self.client_secret.len()),
|
||||||
|
)
|
||||||
|
.field("group", &self.group)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
pub fn from_env() -> Result<Config> {
|
||||||
|
Self::from_lookup(&|k| std::env::var(k).ok().filter(|v| !v.is_empty()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_lookup(var: &dyn Fn(&str) -> Option<String>) -> Result<Config> {
|
||||||
|
let listen: SocketAddr = var("VISA_LISTEN")
|
||||||
|
.unwrap_or_else(|| "127.0.0.1:8040".into())
|
||||||
|
.parse()
|
||||||
|
.context("VISA_LISTEN is not an address:port")?;
|
||||||
|
let public_url = var("VISA_PUBLIC_URL")
|
||||||
|
.unwrap_or_else(|| format!("http://{listen}"))
|
||||||
|
.trim_end_matches('/')
|
||||||
|
.to_string();
|
||||||
|
let database_url = var("VISA_DATABASE_URL").context("VISA_DATABASE_URL is not set")?;
|
||||||
|
let database_password = match var("VISA_DATABASE_PASSWORD_FILE") {
|
||||||
|
Some(path) => Some(read_file(&PathBuf::from(path), "the database password")?),
|
||||||
|
None => credential(var, "db-password")?,
|
||||||
|
};
|
||||||
|
let auth = match var("VISA_OIDC_ISSUER") {
|
||||||
|
Some(issuer) => {
|
||||||
|
ensure!(
|
||||||
|
public_url.starts_with("https://"),
|
||||||
|
"VISA_PUBLIC_URL must be https:// when the login is on (the session cookie is Secure)"
|
||||||
|
);
|
||||||
|
let client_secret = match var("VISA_OIDC_CLIENT_SECRET_FILE") {
|
||||||
|
Some(path) => read_file(&PathBuf::from(path), "the OIDC client secret")?,
|
||||||
|
None => credential(var, "oidc-client-secret")?.context(
|
||||||
|
"no OIDC client secret: set VISA_OIDC_CLIENT_SECRET_FILE or pass the \
|
||||||
|
credential oidc-client-secret",
|
||||||
|
)?,
|
||||||
|
};
|
||||||
|
Auth::Oidc(OidcConfig {
|
||||||
|
issuer: issuer.trim_end_matches('/').to_string(),
|
||||||
|
client_id: var("VISA_OIDC_CLIENT_ID").unwrap_or_else(|| "visa-web".into()),
|
||||||
|
client_secret,
|
||||||
|
group: var("VISA_OIDC_GROUP").unwrap_or_else(|| "visa".into()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
None if var("VISA_INSECURE_NO_LOGIN").as_deref() == Some("1") => {
|
||||||
|
if !listen.ip().is_loopback() {
|
||||||
|
bail!("VISA_INSECURE_NO_LOGIN=1 works only with a loopback VISA_LISTEN");
|
||||||
|
}
|
||||||
|
Auth::Disabled
|
||||||
|
}
|
||||||
|
None => bail!(
|
||||||
|
"no login configured: set VISA_OIDC_ISSUER and the client settings, or \
|
||||||
|
VISA_INSECURE_NO_LOGIN=1 for local development on a loopback address"
|
||||||
|
),
|
||||||
|
};
|
||||||
|
Ok(Config {
|
||||||
|
listen,
|
||||||
|
public_url,
|
||||||
|
database_url,
|
||||||
|
database_password,
|
||||||
|
auth,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn redirect_uri(&self) -> String {
|
||||||
|
format!("{}/auth/callback", self.public_url)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn login_enabled(&self) -> bool {
|
||||||
|
matches!(self.auth, Auth::Oidc(_))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A systemd credential (`LoadCredential=`), when the unit passes one.
|
||||||
|
fn credential(var: &dyn Fn(&str) -> Option<String>, name: &str) -> Result<Option<String>> {
|
||||||
|
let Some(dir) = var("CREDENTIALS_DIRECTORY") else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let path = PathBuf::from(dir).join(name);
|
||||||
|
if !path.exists() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
read_file(&path, name).map(Some)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_file(path: &PathBuf, what: &str) -> Result<String> {
|
||||||
|
let text = std::fs::read_to_string(path)
|
||||||
|
.with_context(|| format!("reading {what} from {}", path.display()))?;
|
||||||
|
let value = text.trim().to_string();
|
||||||
|
ensure!(!value.is_empty(), "{} is empty", path.display());
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
fn cfg(pairs: &[(&str, &str)]) -> Result<Config> {
|
||||||
|
let m: HashMap<String, String> = pairs
|
||||||
|
.iter()
|
||||||
|
.map(|(k, v)| (k.to_string(), v.to_string()))
|
||||||
|
.collect();
|
||||||
|
Config::from_lookup(&|k| m.get(k).cloned())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn refuses_to_start_without_a_login() {
|
||||||
|
let e = cfg(&[("VISA_DATABASE_URL", "postgres://x/y")]).unwrap_err();
|
||||||
|
assert!(e.to_string().contains("no login configured"), "{e}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_login_only_on_loopback() {
|
||||||
|
let ok = cfg(&[
|
||||||
|
("VISA_DATABASE_URL", "postgres://x/y"),
|
||||||
|
("VISA_INSECURE_NO_LOGIN", "1"),
|
||||||
|
])
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(ok.auth, Auth::Disabled));
|
||||||
|
assert_eq!(ok.public_url, "http://127.0.0.1:8040");
|
||||||
|
let e = cfg(&[
|
||||||
|
("VISA_DATABASE_URL", "postgres://x/y"),
|
||||||
|
("VISA_INSECURE_NO_LOGIN", "1"),
|
||||||
|
("VISA_LISTEN", "0.0.0.0:8040"),
|
||||||
|
])
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(e.to_string().contains("loopback"), "{e}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn oidc_reads_the_secret_from_a_file() {
|
||||||
|
let dir = std::env::temp_dir().join(format!("visa-cfg-{}", std::process::id()));
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
let f = dir.join("secret");
|
||||||
|
std::fs::write(&f, "s3cret\n").unwrap();
|
||||||
|
let c = 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();
|
||||||
|
let Auth::Oidc(o) = &c.auth else {
|
||||||
|
panic!("login expected")
|
||||||
|
};
|
||||||
|
assert_eq!(o.client_secret, "s3cret");
|
||||||
|
assert_eq!(o.client_id, "visa-web");
|
||||||
|
assert_eq!(o.group, "visa");
|
||||||
|
assert_eq!(o.issuer, "https://id.example/oauth2/openid/visa-web");
|
||||||
|
assert_eq!(c.redirect_uri(), "https://visa.example/auth/callback");
|
||||||
|
assert!(!format!("{o:?}").contains("s3cret"));
|
||||||
|
// a plain-http public URL cannot carry the Secure cookie
|
||||||
|
let e = cfg(&[
|
||||||
|
("VISA_DATABASE_URL", "postgres://x/y"),
|
||||||
|
("VISA_PUBLIC_URL", "http://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("https"), "{e}");
|
||||||
|
std::fs::remove_dir_all(&dir).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
//! Countries by ISO 3166-1 alpha-3 code (as passports' machine-readable
|
||||||
|
//! zones write them) and Thailand's provinces.
|
||||||
|
|
||||||
|
mod data {
|
||||||
|
include!("countries_data.rs");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub use data::COUNTRIES;
|
||||||
|
|
||||||
|
/// The English short name of an alpha-3 code.
|
||||||
|
pub fn name(code: &str) -> Option<&'static str> {
|
||||||
|
COUNTRIES
|
||||||
|
.binary_search_by(|(c, _)| (*c).cmp(code))
|
||||||
|
.ok()
|
||||||
|
.map(|i| COUNTRIES[i].1)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_known(code: &str) -> bool {
|
||||||
|
name(code).is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `(code, "Name")` pairs sorted by name, for a select.
|
||||||
|
pub fn options() -> Vec<(&'static str, &'static str)> {
|
||||||
|
let mut v: Vec<(&str, &str)> = COUNTRIES.to_vec();
|
||||||
|
v.sort_by(|a, b| a.1.cmp(b.1));
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The 77 provinces (76 and Bangkok) in the spelling the Department of
|
||||||
|
/// Provincial Administration uses in English.
|
||||||
|
pub static PROVINCES: &[&str] = &[
|
||||||
|
"Amnat Charoen",
|
||||||
|
"Ang Thong",
|
||||||
|
"Bangkok",
|
||||||
|
"Bueng Kan",
|
||||||
|
"Buriram",
|
||||||
|
"Chachoengsao",
|
||||||
|
"Chai Nat",
|
||||||
|
"Chaiyaphum",
|
||||||
|
"Chanthaburi",
|
||||||
|
"Chiang Mai",
|
||||||
|
"Chiang Rai",
|
||||||
|
"Chonburi",
|
||||||
|
"Chumphon",
|
||||||
|
"Kalasin",
|
||||||
|
"Kamphaeng Phet",
|
||||||
|
"Kanchanaburi",
|
||||||
|
"Khon Kaen",
|
||||||
|
"Krabi",
|
||||||
|
"Lampang",
|
||||||
|
"Lamphun",
|
||||||
|
"Loei",
|
||||||
|
"Lopburi",
|
||||||
|
"Mae Hong Son",
|
||||||
|
"Maha Sarakham",
|
||||||
|
"Mukdahan",
|
||||||
|
"Nakhon Nayok",
|
||||||
|
"Nakhon Pathom",
|
||||||
|
"Nakhon Phanom",
|
||||||
|
"Nakhon Ratchasima",
|
||||||
|
"Nakhon Sawan",
|
||||||
|
"Nakhon Si Thammarat",
|
||||||
|
"Nan",
|
||||||
|
"Narathiwat",
|
||||||
|
"Nong Bua Lamphu",
|
||||||
|
"Nong Khai",
|
||||||
|
"Nonthaburi",
|
||||||
|
"Pathum Thani",
|
||||||
|
"Pattani",
|
||||||
|
"Phang Nga",
|
||||||
|
"Phatthalung",
|
||||||
|
"Phayao",
|
||||||
|
"Phetchabun",
|
||||||
|
"Phetchaburi",
|
||||||
|
"Phichit",
|
||||||
|
"Phitsanulok",
|
||||||
|
"Phra Nakhon Si Ayutthaya",
|
||||||
|
"Phrae",
|
||||||
|
"Phuket",
|
||||||
|
"Prachinburi",
|
||||||
|
"Prachuap Khiri Khan",
|
||||||
|
"Ranong",
|
||||||
|
"Ratchaburi",
|
||||||
|
"Rayong",
|
||||||
|
"Roi Et",
|
||||||
|
"Sa Kaeo",
|
||||||
|
"Sakon Nakhon",
|
||||||
|
"Samut Prakan",
|
||||||
|
"Samut Sakhon",
|
||||||
|
"Samut Songkhram",
|
||||||
|
"Saraburi",
|
||||||
|
"Satun",
|
||||||
|
"Sing Buri",
|
||||||
|
"Sisaket",
|
||||||
|
"Songkhla",
|
||||||
|
"Sukhothai",
|
||||||
|
"Suphan Buri",
|
||||||
|
"Surat Thani",
|
||||||
|
"Surin",
|
||||||
|
"Tak",
|
||||||
|
"Trang",
|
||||||
|
"Trat",
|
||||||
|
"Ubon Ratchathani",
|
||||||
|
"Udon Thani",
|
||||||
|
"Uthai Thani",
|
||||||
|
"Uttaradit",
|
||||||
|
"Yala",
|
||||||
|
"Yasothon",
|
||||||
|
];
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sorted_and_complete() {
|
||||||
|
assert!(
|
||||||
|
COUNTRIES.windows(2).all(|w| w[0].0 < w[1].0),
|
||||||
|
"sorted by code"
|
||||||
|
);
|
||||||
|
assert!(COUNTRIES.len() >= 249);
|
||||||
|
assert_eq!(name("DEU"), Some("Germany"));
|
||||||
|
assert_eq!(name("THA"), Some("Thailand"));
|
||||||
|
assert_eq!(name("D"), None);
|
||||||
|
assert_eq!(PROVINCES.len(), 77);
|
||||||
|
assert!(
|
||||||
|
PROVINCES.windows(2).all(|w| w[0] < w[1]),
|
||||||
|
"provinces sorted"
|
||||||
|
);
|
||||||
|
assert_eq!(options()[0].1, "Afghanistan");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
// Generated by scripts/gen_countries.py from pycountry; do not edit by hand.
|
||||||
|
pub static COUNTRIES: &[(&str, &str)] = &[
|
||||||
|
("ABW", "Aruba"),
|
||||||
|
("AFG", "Afghanistan"),
|
||||||
|
("AGO", "Angola"),
|
||||||
|
("AIA", "Anguilla"),
|
||||||
|
("ALA", "Åland Islands"),
|
||||||
|
("ALB", "Albania"),
|
||||||
|
("AND", "Andorra"),
|
||||||
|
("ARE", "United Arab Emirates"),
|
||||||
|
("ARG", "Argentina"),
|
||||||
|
("ARM", "Armenia"),
|
||||||
|
("ASM", "American Samoa"),
|
||||||
|
("ATA", "Antarctica"),
|
||||||
|
("ATF", "French Southern Territories"),
|
||||||
|
("ATG", "Antigua and Barbuda"),
|
||||||
|
("AUS", "Australia"),
|
||||||
|
("AUT", "Austria"),
|
||||||
|
("AZE", "Azerbaijan"),
|
||||||
|
("BDI", "Burundi"),
|
||||||
|
("BEL", "Belgium"),
|
||||||
|
("BEN", "Benin"),
|
||||||
|
("BES", "Bonaire, Sint Eustatius and Saba"),
|
||||||
|
("BFA", "Burkina Faso"),
|
||||||
|
("BGD", "Bangladesh"),
|
||||||
|
("BGR", "Bulgaria"),
|
||||||
|
("BHR", "Bahrain"),
|
||||||
|
("BHS", "Bahamas"),
|
||||||
|
("BIH", "Bosnia and Herzegovina"),
|
||||||
|
("BLM", "Saint Barthélemy"),
|
||||||
|
("BLR", "Belarus"),
|
||||||
|
("BLZ", "Belize"),
|
||||||
|
("BMU", "Bermuda"),
|
||||||
|
("BOL", "Bolivia"),
|
||||||
|
("BRA", "Brazil"),
|
||||||
|
("BRB", "Barbados"),
|
||||||
|
("BRN", "Brunei Darussalam"),
|
||||||
|
("BTN", "Bhutan"),
|
||||||
|
("BVT", "Bouvet Island"),
|
||||||
|
("BWA", "Botswana"),
|
||||||
|
("CAF", "Central African Republic"),
|
||||||
|
("CAN", "Canada"),
|
||||||
|
("CCK", "Cocos (Keeling) Islands"),
|
||||||
|
("CHE", "Switzerland"),
|
||||||
|
("CHL", "Chile"),
|
||||||
|
("CHN", "China"),
|
||||||
|
("CIV", "Côte d'Ivoire"),
|
||||||
|
("CMR", "Cameroon"),
|
||||||
|
("COD", "Congo, The Democratic Republic of the"),
|
||||||
|
("COG", "Congo"),
|
||||||
|
("COK", "Cook Islands"),
|
||||||
|
("COL", "Colombia"),
|
||||||
|
("COM", "Comoros"),
|
||||||
|
("CPV", "Cabo Verde"),
|
||||||
|
("CRI", "Costa Rica"),
|
||||||
|
("CUB", "Cuba"),
|
||||||
|
("CUW", "Curaçao"),
|
||||||
|
("CXR", "Christmas Island"),
|
||||||
|
("CYM", "Cayman Islands"),
|
||||||
|
("CYP", "Cyprus"),
|
||||||
|
("CZE", "Czechia"),
|
||||||
|
("DEU", "Germany"),
|
||||||
|
("DJI", "Djibouti"),
|
||||||
|
("DMA", "Dominica"),
|
||||||
|
("DNK", "Denmark"),
|
||||||
|
("DOM", "Dominican Republic"),
|
||||||
|
("DZA", "Algeria"),
|
||||||
|
("ECU", "Ecuador"),
|
||||||
|
("EGY", "Egypt"),
|
||||||
|
("ERI", "Eritrea"),
|
||||||
|
("ESH", "Western Sahara"),
|
||||||
|
("ESP", "Spain"),
|
||||||
|
("EST", "Estonia"),
|
||||||
|
("ETH", "Ethiopia"),
|
||||||
|
("FIN", "Finland"),
|
||||||
|
("FJI", "Fiji"),
|
||||||
|
("FLK", "Falkland Islands (Malvinas)"),
|
||||||
|
("FRA", "France"),
|
||||||
|
("FRO", "Faroe Islands"),
|
||||||
|
("FSM", "Micronesia, Federated States of"),
|
||||||
|
("GAB", "Gabon"),
|
||||||
|
("GBR", "United Kingdom"),
|
||||||
|
("GEO", "Georgia"),
|
||||||
|
("GGY", "Guernsey"),
|
||||||
|
("GHA", "Ghana"),
|
||||||
|
("GIB", "Gibraltar"),
|
||||||
|
("GIN", "Guinea"),
|
||||||
|
("GLP", "Guadeloupe"),
|
||||||
|
("GMB", "Gambia"),
|
||||||
|
("GNB", "Guinea-Bissau"),
|
||||||
|
("GNQ", "Equatorial Guinea"),
|
||||||
|
("GRC", "Greece"),
|
||||||
|
("GRD", "Grenada"),
|
||||||
|
("GRL", "Greenland"),
|
||||||
|
("GTM", "Guatemala"),
|
||||||
|
("GUF", "French Guiana"),
|
||||||
|
("GUM", "Guam"),
|
||||||
|
("GUY", "Guyana"),
|
||||||
|
("HKG", "Hong Kong"),
|
||||||
|
("HMD", "Heard Island and McDonald Islands"),
|
||||||
|
("HND", "Honduras"),
|
||||||
|
("HRV", "Croatia"),
|
||||||
|
("HTI", "Haiti"),
|
||||||
|
("HUN", "Hungary"),
|
||||||
|
("IDN", "Indonesia"),
|
||||||
|
("IMN", "Isle of Man"),
|
||||||
|
("IND", "India"),
|
||||||
|
("IOT", "British Indian Ocean Territory"),
|
||||||
|
("IRL", "Ireland"),
|
||||||
|
("IRN", "Iran"),
|
||||||
|
("IRQ", "Iraq"),
|
||||||
|
("ISL", "Iceland"),
|
||||||
|
("ISR", "Israel"),
|
||||||
|
("ITA", "Italy"),
|
||||||
|
("JAM", "Jamaica"),
|
||||||
|
("JEY", "Jersey"),
|
||||||
|
("JOR", "Jordan"),
|
||||||
|
("JPN", "Japan"),
|
||||||
|
("KAZ", "Kazakhstan"),
|
||||||
|
("KEN", "Kenya"),
|
||||||
|
("KGZ", "Kyrgyzstan"),
|
||||||
|
("KHM", "Cambodia"),
|
||||||
|
("KIR", "Kiribati"),
|
||||||
|
("KNA", "Saint Kitts and Nevis"),
|
||||||
|
("KOR", "South Korea"),
|
||||||
|
("KWT", "Kuwait"),
|
||||||
|
("LAO", "Laos"),
|
||||||
|
("LBN", "Lebanon"),
|
||||||
|
("LBR", "Liberia"),
|
||||||
|
("LBY", "Libya"),
|
||||||
|
("LCA", "Saint Lucia"),
|
||||||
|
("LIE", "Liechtenstein"),
|
||||||
|
("LKA", "Sri Lanka"),
|
||||||
|
("LSO", "Lesotho"),
|
||||||
|
("LTU", "Lithuania"),
|
||||||
|
("LUX", "Luxembourg"),
|
||||||
|
("LVA", "Latvia"),
|
||||||
|
("MAC", "Macao"),
|
||||||
|
("MAF", "Saint Martin (French part)"),
|
||||||
|
("MAR", "Morocco"),
|
||||||
|
("MCO", "Monaco"),
|
||||||
|
("MDA", "Moldova"),
|
||||||
|
("MDG", "Madagascar"),
|
||||||
|
("MDV", "Maldives"),
|
||||||
|
("MEX", "Mexico"),
|
||||||
|
("MHL", "Marshall Islands"),
|
||||||
|
("MKD", "North Macedonia"),
|
||||||
|
("MLI", "Mali"),
|
||||||
|
("MLT", "Malta"),
|
||||||
|
("MMR", "Myanmar"),
|
||||||
|
("MNE", "Montenegro"),
|
||||||
|
("MNG", "Mongolia"),
|
||||||
|
("MNP", "Northern Mariana Islands"),
|
||||||
|
("MOZ", "Mozambique"),
|
||||||
|
("MRT", "Mauritania"),
|
||||||
|
("MSR", "Montserrat"),
|
||||||
|
("MTQ", "Martinique"),
|
||||||
|
("MUS", "Mauritius"),
|
||||||
|
("MWI", "Malawi"),
|
||||||
|
("MYS", "Malaysia"),
|
||||||
|
("MYT", "Mayotte"),
|
||||||
|
("NAM", "Namibia"),
|
||||||
|
("NCL", "New Caledonia"),
|
||||||
|
("NER", "Niger"),
|
||||||
|
("NFK", "Norfolk Island"),
|
||||||
|
("NGA", "Nigeria"),
|
||||||
|
("NIC", "Nicaragua"),
|
||||||
|
("NIU", "Niue"),
|
||||||
|
("NLD", "Netherlands"),
|
||||||
|
("NOR", "Norway"),
|
||||||
|
("NPL", "Nepal"),
|
||||||
|
("NRU", "Nauru"),
|
||||||
|
("NZL", "New Zealand"),
|
||||||
|
("OMN", "Oman"),
|
||||||
|
("PAK", "Pakistan"),
|
||||||
|
("PAN", "Panama"),
|
||||||
|
("PCN", "Pitcairn"),
|
||||||
|
("PER", "Peru"),
|
||||||
|
("PHL", "Philippines"),
|
||||||
|
("PLW", "Palau"),
|
||||||
|
("PNG", "Papua New Guinea"),
|
||||||
|
("POL", "Poland"),
|
||||||
|
("PRI", "Puerto Rico"),
|
||||||
|
("PRK", "North Korea"),
|
||||||
|
("PRT", "Portugal"),
|
||||||
|
("PRY", "Paraguay"),
|
||||||
|
("PSE", "Palestine, State of"),
|
||||||
|
("PYF", "French Polynesia"),
|
||||||
|
("QAT", "Qatar"),
|
||||||
|
("REU", "Réunion"),
|
||||||
|
("ROU", "Romania"),
|
||||||
|
("RUS", "Russian Federation"),
|
||||||
|
("RWA", "Rwanda"),
|
||||||
|
("SAU", "Saudi Arabia"),
|
||||||
|
("SDN", "Sudan"),
|
||||||
|
("SEN", "Senegal"),
|
||||||
|
("SGP", "Singapore"),
|
||||||
|
("SGS", "South Georgia and the South Sandwich Islands"),
|
||||||
|
("SHN", "Saint Helena, Ascension and Tristan da Cunha"),
|
||||||
|
("SJM", "Svalbard and Jan Mayen"),
|
||||||
|
("SLB", "Solomon Islands"),
|
||||||
|
("SLE", "Sierra Leone"),
|
||||||
|
("SLV", "El Salvador"),
|
||||||
|
("SMR", "San Marino"),
|
||||||
|
("SOM", "Somalia"),
|
||||||
|
("SPM", "Saint Pierre and Miquelon"),
|
||||||
|
("SRB", "Serbia"),
|
||||||
|
("SSD", "South Sudan"),
|
||||||
|
("STP", "Sao Tome and Principe"),
|
||||||
|
("SUR", "Suriname"),
|
||||||
|
("SVK", "Slovakia"),
|
||||||
|
("SVN", "Slovenia"),
|
||||||
|
("SWE", "Sweden"),
|
||||||
|
("SWZ", "Eswatini"),
|
||||||
|
("SXM", "Sint Maarten (Dutch part)"),
|
||||||
|
("SYC", "Seychelles"),
|
||||||
|
("SYR", "Syria"),
|
||||||
|
("TCA", "Turks and Caicos Islands"),
|
||||||
|
("TCD", "Chad"),
|
||||||
|
("TGO", "Togo"),
|
||||||
|
("THA", "Thailand"),
|
||||||
|
("TJK", "Tajikistan"),
|
||||||
|
("TKL", "Tokelau"),
|
||||||
|
("TKM", "Turkmenistan"),
|
||||||
|
("TLS", "Timor-Leste"),
|
||||||
|
("TON", "Tonga"),
|
||||||
|
("TTO", "Trinidad and Tobago"),
|
||||||
|
("TUN", "Tunisia"),
|
||||||
|
("TUR", "Türkiye"),
|
||||||
|
("TUV", "Tuvalu"),
|
||||||
|
("TWN", "Taiwan"),
|
||||||
|
("TZA", "Tanzania"),
|
||||||
|
("UGA", "Uganda"),
|
||||||
|
("UKR", "Ukraine"),
|
||||||
|
("UMI", "United States Minor Outlying Islands"),
|
||||||
|
("URY", "Uruguay"),
|
||||||
|
("USA", "United States"),
|
||||||
|
("UZB", "Uzbekistan"),
|
||||||
|
("VAT", "Holy See (Vatican City State)"),
|
||||||
|
("VCT", "Saint Vincent and the Grenadines"),
|
||||||
|
("VEN", "Venezuela"),
|
||||||
|
("VGB", "Virgin Islands, British"),
|
||||||
|
("VIR", "Virgin Islands, U.S."),
|
||||||
|
("VNM", "Vietnam"),
|
||||||
|
("VUT", "Vanuatu"),
|
||||||
|
("WLF", "Wallis and Futuna"),
|
||||||
|
("WSM", "Samoa"),
|
||||||
|
("YEM", "Yemen"),
|
||||||
|
("ZAF", "South Africa"),
|
||||||
|
("ZMB", "Zambia"),
|
||||||
|
("ZWE", "Zimbabwe"),
|
||||||
|
];
|
||||||
+148
@@ -0,0 +1,148 @@
|
|||||||
|
//! Dates in Chiang Mai time (UTC+7, no daylight saving) and their display.
|
||||||
|
|
||||||
|
use chrono::{DateTime, Datelike, FixedOffset, Months, NaiveDate, Utc};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
pub fn bangkok() -> FixedOffset {
|
||||||
|
FixedOffset::east_opt(7 * 3600).expect("UTC+7 is a valid offset")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Today in Chiang Mai.
|
||||||
|
pub fn today() -> NaiveDate {
|
||||||
|
Utc::now().with_timezone(&bangkok()).date_naive()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Nov 17, 2026"
|
||||||
|
pub fn fmt_date(d: NaiveDate) -> String {
|
||||||
|
d.format("%b %-d, %Y").to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Nov 17, 2026 14:05" in Chiang Mai time.
|
||||||
|
pub fn fmt_datetime(t: DateTime<Utc>) -> String {
|
||||||
|
t.with_timezone(&bangkok())
|
||||||
|
.format("%b %-d, %Y %H:%M")
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An `<input type="date">` value.
|
||||||
|
pub fn parse_date(s: &str) -> Option<NaiveDate> {
|
||||||
|
NaiveDate::parse_from_str(s.trim(), "%Y-%m-%d").ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Full years from `born` to `on`.
|
||||||
|
pub fn age(born: NaiveDate, on: NaiveDate) -> i32 {
|
||||||
|
let mut years = on.year() - born.year();
|
||||||
|
if (on.month(), on.day()) < (born.month(), born.day()) {
|
||||||
|
years -= 1;
|
||||||
|
}
|
||||||
|
years
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "in 12 days", "in 3 months", "today", "5 days ago".
|
||||||
|
pub fn relative(from: NaiveDate, to: NaiveDate) -> String {
|
||||||
|
let days = (to - from).num_days();
|
||||||
|
let span = |d: i64| -> String {
|
||||||
|
let d = d.abs();
|
||||||
|
if d >= 60 {
|
||||||
|
let months = d / 30;
|
||||||
|
format!("{months} months")
|
||||||
|
} else if d == 1 {
|
||||||
|
"1 day".into()
|
||||||
|
} else {
|
||||||
|
format!("{d} days")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match days {
|
||||||
|
0 => "today".into(),
|
||||||
|
d if d > 0 => format!("in {}", span(d)),
|
||||||
|
d => format!("{} ago", span(d)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A state with its color class; the class is only ever shown next to the
|
||||||
|
/// label.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||||
|
pub struct Status {
|
||||||
|
/// "ok", "warn" or "bad"
|
||||||
|
pub level: &'static str,
|
||||||
|
pub label: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An extension of stay never runs past the passport's expiry, so a
|
||||||
|
/// passport is flagged a year ahead and marked with under six months left.
|
||||||
|
pub fn passport_status(expires: NaiveDate, today: NaiveDate) -> Status {
|
||||||
|
let six = today.checked_add_months(Months::new(6)).unwrap_or(today);
|
||||||
|
let twelve = today.checked_add_months(Months::new(12)).unwrap_or(today);
|
||||||
|
if expires < today {
|
||||||
|
Status {
|
||||||
|
level: "bad",
|
||||||
|
label: format!("Expired {}", relative(today, expires)),
|
||||||
|
}
|
||||||
|
} else if expires < six {
|
||||||
|
Status {
|
||||||
|
level: "bad",
|
||||||
|
label: format!("Under 6 months left, expires {}", relative(today, expires)),
|
||||||
|
}
|
||||||
|
} else if expires < twelve {
|
||||||
|
Status {
|
||||||
|
level: "warn",
|
||||||
|
label: format!("Under 12 months left, expires {}", relative(today, expires)),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Status {
|
||||||
|
level: "ok",
|
||||||
|
label: "Valid for over a year".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn d(s: &str) -> NaiveDate {
|
||||||
|
parse_date(s).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn formats() {
|
||||||
|
assert_eq!(fmt_date(d("2026-11-07")), "Nov 7, 2026");
|
||||||
|
let t = DateTime::parse_from_rfc3339("2026-11-17T20:30:00Z")
|
||||||
|
.unwrap()
|
||||||
|
.with_timezone(&Utc);
|
||||||
|
assert_eq!(fmt_datetime(t), "Nov 18, 2026 03:30");
|
||||||
|
assert_eq!(parse_date(" 2026-02-30 "), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ages() {
|
||||||
|
assert_eq!(age(d("1984-08-12"), d("2026-08-11")), 41);
|
||||||
|
assert_eq!(age(d("1984-08-12"), d("2026-08-12")), 42);
|
||||||
|
assert_eq!(age(d("2000-02-29"), d("2026-02-28")), 25);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn relative_spans() {
|
||||||
|
let t = d("2026-11-17");
|
||||||
|
assert_eq!(relative(t, t), "today");
|
||||||
|
assert_eq!(relative(t, d("2026-11-18")), "in 1 day");
|
||||||
|
assert_eq!(relative(t, d("2026-12-01")), "in 14 days");
|
||||||
|
assert_eq!(relative(t, d("2027-03-17")), "in 4 months");
|
||||||
|
assert_eq!(relative(t, d("2026-11-12")), "5 days ago");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn passport_levels() {
|
||||||
|
let t = d("2026-11-17");
|
||||||
|
assert_eq!(passport_status(d("2026-11-16"), t).level, "bad");
|
||||||
|
assert!(
|
||||||
|
passport_status(d("2026-11-16"), t)
|
||||||
|
.label
|
||||||
|
.starts_with("Expired")
|
||||||
|
);
|
||||||
|
assert_eq!(passport_status(d("2027-05-16"), t).level, "bad");
|
||||||
|
assert_eq!(passport_status(d("2027-05-17"), t).level, "warn");
|
||||||
|
assert_eq!(passport_status(d("2027-11-16"), t).level, "warn");
|
||||||
|
assert_eq!(passport_status(d("2027-11-17"), t).level, "ok");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
//! The database: connecting and the migrations compiled into the binary.
|
||||||
|
|
||||||
|
use std::str::FromStr;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use sqlx::migrate::Migrator;
|
||||||
|
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
|
||||||
|
|
||||||
|
use crate::config::Config;
|
||||||
|
|
||||||
|
pub static MIGRATOR: Migrator = sqlx::migrate!("./migrations");
|
||||||
|
|
||||||
|
pub async fn connect(cfg: &Config) -> Result<PgPool> {
|
||||||
|
let mut opts = PgConnectOptions::from_str(&cfg.database_url)
|
||||||
|
.context("VISA_DATABASE_URL is not a PostgreSQL URL")?
|
||||||
|
.application_name("visa");
|
||||||
|
if let Some(pw) = &cfg.database_password {
|
||||||
|
opts = opts.password(pw);
|
||||||
|
}
|
||||||
|
PgPoolOptions::new()
|
||||||
|
.max_connections(8)
|
||||||
|
.acquire_timeout(Duration::from_secs(10))
|
||||||
|
.connect_with(opts)
|
||||||
|
.await
|
||||||
|
.context("connecting to the database")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn migrate(pool: &PgPool) -> Result<()> {
|
||||||
|
MIGRATOR.run(pool).await.context("running the migrations")
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
//! Templates and static files compiled into the binary (build.rs).
|
||||||
|
|
||||||
|
include!(concat!(env!("OUT_DIR"), "/embedded.rs"));
|
||||||
|
|
||||||
|
pub fn static_file(path: &str) -> Option<&'static [u8]> {
|
||||||
|
STATIC
|
||||||
|
.iter()
|
||||||
|
.find(|(name, _)| *name == path)
|
||||||
|
.map(|(_, bytes)| *bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn content_type(path: &str) -> &'static str {
|
||||||
|
match path.rsplit('.').next().unwrap_or("") {
|
||||||
|
"css" => "text/css; charset=utf-8",
|
||||||
|
"js" => "text/javascript; charset=utf-8",
|
||||||
|
"svg" => "image/svg+xml",
|
||||||
|
"png" => "image/png",
|
||||||
|
"ico" => "image/x-icon",
|
||||||
|
"txt" => "text/plain; charset=utf-8",
|
||||||
|
"woff2" => "font/woff2",
|
||||||
|
_ => "application/octet-stream",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_static_file_has_a_content_type() {
|
||||||
|
for (name, _) in STATIC {
|
||||||
|
assert_ne!(
|
||||||
|
content_type(name),
|
||||||
|
"application/octet-stream",
|
||||||
|
"{name} needs a content type in embedded.rs"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(static_file("app.css").is_some());
|
||||||
|
assert_eq!(STATIC_HASH.len(), 12);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
//! Form fields as posted: everything arrives as text and is trimmed here.
|
||||||
|
|
||||||
|
use std::collections::{BTreeMap, HashMap};
|
||||||
|
|
||||||
|
pub type Fields = HashMap<String, String>;
|
||||||
|
|
||||||
|
/// Field name to message; templates read `errors.<field>`.
|
||||||
|
pub type Errors = BTreeMap<String, String>;
|
||||||
|
|
||||||
|
/// A field's value, trimmed; empty when absent.
|
||||||
|
pub fn get(f: &Fields, key: &str) -> String {
|
||||||
|
f.get(key).map(|s| s.trim().to_string()).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Upper case without inner spaces: passport numbers, codes.
|
||||||
|
pub fn compact_upper(s: &str) -> String {
|
||||||
|
s.chars()
|
||||||
|
.filter(|c| !c.is_whitespace())
|
||||||
|
.collect::<String>()
|
||||||
|
.to_uppercase()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn err(errors: &mut Errors, field: &str, msg: impl Into<String>) {
|
||||||
|
errors
|
||||||
|
.entry(field.to_string())
|
||||||
|
.or_insert_with(|| msg.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn trims_and_compacts() {
|
||||||
|
let mut f = Fields::new();
|
||||||
|
f.insert("a".into(), " x y ".into());
|
||||||
|
assert_eq!(get(&f, "a"), "x y");
|
||||||
|
assert_eq!(get(&f, "b"), "");
|
||||||
|
assert_eq!(compact_upper(" c01 x00t47 "), "C01X00T47");
|
||||||
|
let mut e = Errors::new();
|
||||||
|
err(&mut e, "a", "first");
|
||||||
|
err(&mut e, "a", "second");
|
||||||
|
assert_eq!(e["a"], "first");
|
||||||
|
}
|
||||||
|
}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
//! visa.buildfor.life: immigration records, deadlines and extension packs
|
||||||
|
//! for foreigners in Thailand (docs/PLAN.md).
|
||||||
|
|
||||||
|
pub mod audit;
|
||||||
|
pub mod config;
|
||||||
|
pub mod countries;
|
||||||
|
pub mod dates;
|
||||||
|
pub mod db;
|
||||||
|
pub mod embedded;
|
||||||
|
pub mod forms;
|
||||||
|
pub mod mrz;
|
||||||
|
pub mod oidc;
|
||||||
|
pub mod people;
|
||||||
|
pub mod seed;
|
||||||
|
pub mod session;
|
||||||
|
pub mod web;
|
||||||
|
|
||||||
|
/// The version shown in the footer.
|
||||||
|
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||||
+115
@@ -0,0 +1,115 @@
|
|||||||
|
//! `visa [serve|migrate|seed-demo|help]`: the server and its admin commands.
|
||||||
|
|
||||||
|
use std::process::ExitCode;
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, bail, ensure};
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
|
use visa::config::Config;
|
||||||
|
use visa::{dates, db, seed, web};
|
||||||
|
|
||||||
|
const USAGE: &str = "\
|
||||||
|
visa: immigration records, deadlines and extension packs (visa.buildfor.life)
|
||||||
|
|
||||||
|
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)
|
||||||
|
help show this text
|
||||||
|
|
||||||
|
Settings come from the environment; see src/config.rs or README.md.";
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> ExitCode {
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_max_level(tracing::Level::INFO)
|
||||||
|
.with_target(false)
|
||||||
|
.init();
|
||||||
|
let cmd = std::env::args().nth(1).unwrap_or_else(|| "serve".into());
|
||||||
|
match run(&cmd).await {
|
||||||
|
Ok(()) => ExitCode::SUCCESS,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("visa: {e:#}");
|
||||||
|
ExitCode::FAILURE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run(cmd: &str) -> Result<()> {
|
||||||
|
match cmd {
|
||||||
|
"serve" => serve().await,
|
||||||
|
"migrate" => {
|
||||||
|
let cfg = Config::from_env()?;
|
||||||
|
let pool = db::connect(&cfg).await?;
|
||||||
|
db::migrate(&pool).await?;
|
||||||
|
println!("migrations applied");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
"seed-demo" => {
|
||||||
|
let cfg = Config::from_env()?;
|
||||||
|
ensure!(
|
||||||
|
!cfg.login_enabled(),
|
||||||
|
"seed-demo writes invented people and runs only in local development \
|
||||||
|
(VISA_INSECURE_NO_LOGIN=1, no VISA_OIDC_ISSUER)"
|
||||||
|
);
|
||||||
|
let pool = db::connect(&cfg).await?;
|
||||||
|
db::migrate(&pool).await?;
|
||||||
|
if seed::demo(&pool, dates::today()).await? {
|
||||||
|
println!("demo people added");
|
||||||
|
} else {
|
||||||
|
println!("demo people are there already");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
"help" | "--help" | "-h" => {
|
||||||
|
println!("{USAGE}");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
other => bail!("unknown command {other:?}; `visa help` lists the commands"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn serve() -> Result<()> {
|
||||||
|
let cfg = Config::from_env()?;
|
||||||
|
let pool = db::connect(&cfg).await?;
|
||||||
|
db::migrate(&pool).await?;
|
||||||
|
let listen = cfg.listen;
|
||||||
|
let login = cfg.login_enabled();
|
||||||
|
let st = web::AppState::new(cfg, pool)?;
|
||||||
|
web::spawn_background(st.clone());
|
||||||
|
let app = web::router(st);
|
||||||
|
let listener = tokio::net::TcpListener::bind(listen)
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("cannot listen on {listen}"))?;
|
||||||
|
if !login {
|
||||||
|
info!("no login: VISA_INSECURE_NO_LOGIN is set (loopback only)");
|
||||||
|
}
|
||||||
|
info!("listening on http://{listen}");
|
||||||
|
axum::serve(listener, app)
|
||||||
|
.with_graceful_shutdown(shutdown())
|
||||||
|
.await
|
||||||
|
.context("serving")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn shutdown() {
|
||||||
|
let ctrl_c = async {
|
||||||
|
let _ = tokio::signal::ctrl_c().await;
|
||||||
|
};
|
||||||
|
#[cfg(unix)]
|
||||||
|
let term = async {
|
||||||
|
if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
||||||
|
{
|
||||||
|
s.recv().await;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
let term = std::future::pending::<()>();
|
||||||
|
tokio::select! {
|
||||||
|
_ = ctrl_c => {},
|
||||||
|
_ = term => {},
|
||||||
|
}
|
||||||
|
info!("shutting down");
|
||||||
|
}
|
||||||
+375
@@ -0,0 +1,375 @@
|
|||||||
|
//! The machine-readable zone (MRZ) of a passport: ICAO Doc 9303 part 4, the
|
||||||
|
//! TD3 format of two lines with 44 characters each.
|
||||||
|
//!
|
||||||
|
//! Line 1: `P`, a type character, the issuing state (3), then the names:
|
||||||
|
//! surname, `<<`, given names separated by `<`.
|
||||||
|
//! Line 2: number (9) and its check digit, nationality (3), birth date
|
||||||
|
//! (YYMMDD) and check, sex, expiry date and check, personal number (14) and
|
||||||
|
//! check, and a check digit over most of the line.
|
||||||
|
|
||||||
|
use chrono::{Datelike, NaiveDate};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||||
|
pub struct Mrz {
|
||||||
|
pub issuing_state: String,
|
||||||
|
pub surname: String,
|
||||||
|
pub given_names: String,
|
||||||
|
pub number: String,
|
||||||
|
pub nationality: String,
|
||||||
|
pub date_of_birth: Option<NaiveDate>,
|
||||||
|
/// "F", "M" or "X"
|
||||||
|
pub sex: String,
|
||||||
|
pub expiry_date: Option<NaiveDate>,
|
||||||
|
pub personal_number: String,
|
||||||
|
pub checks: Vec<Check>,
|
||||||
|
/// The two lines as read, joined by a newline.
|
||||||
|
pub text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||||
|
pub struct Check {
|
||||||
|
pub field: &'static str,
|
||||||
|
pub ok: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Mrz {
|
||||||
|
pub fn all_ok(&self) -> bool {
|
||||||
|
self.checks.iter().all(|c| c.ok)
|
||||||
|
&& self.date_of_birth.is_some()
|
||||||
|
&& self.expiry_date.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fields whose check digit does not match.
|
||||||
|
pub fn failed(&self) -> Vec<&'static str> {
|
||||||
|
let mut v: Vec<&'static str> = self
|
||||||
|
.checks
|
||||||
|
.iter()
|
||||||
|
.filter(|c| !c.ok)
|
||||||
|
.map(|c| c.field)
|
||||||
|
.collect();
|
||||||
|
if self.date_of_birth.is_none() {
|
||||||
|
v.push("date of birth (not a date)");
|
||||||
|
}
|
||||||
|
if self.expiry_date.is_none() {
|
||||||
|
v.push("expiry date (not a date)");
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The given names split as Thai forms want them: the first name and the
|
||||||
|
/// rest as middle names.
|
||||||
|
pub fn first_and_middle(&self) -> (String, String) {
|
||||||
|
match self.given_names.split_once(' ') {
|
||||||
|
Some((first, rest)) => (first.to_string(), rest.to_string()),
|
||||||
|
None => (self.given_names.clone(), String::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn value(b: u8) -> u32 {
|
||||||
|
match b {
|
||||||
|
b'0'..=b'9' => u32::from(b - b'0'),
|
||||||
|
b'A'..=b'Z' => u32::from(b - b'A') + 10,
|
||||||
|
_ => 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Weights 7, 3, 1 repeating; letters count 10 to 35 and `<` zero.
|
||||||
|
pub fn check_digit(field: &str) -> u32 {
|
||||||
|
const W: [u32; 3] = [7, 3, 1];
|
||||||
|
field
|
||||||
|
.bytes()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, b)| value(b) * W[i % 3])
|
||||||
|
.sum::<u32>()
|
||||||
|
% 10
|
||||||
|
}
|
||||||
|
|
||||||
|
fn digit_ok(field: &str, check: u8) -> bool {
|
||||||
|
let expected = check_digit(field);
|
||||||
|
match check {
|
||||||
|
b'0'..=b'9' => u32::from(check - b'0') == expected,
|
||||||
|
// an empty optional field may carry `<` instead of 0
|
||||||
|
b'<' => expected == 0 && field.bytes().all(|b| b == b'<'),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The two lines, upper case, without spaces. Accepts them on two lines or
|
||||||
|
/// as one run of 88 characters.
|
||||||
|
pub fn normalize(text: &str) -> Result<(String, String), String> {
|
||||||
|
let lines: Vec<String> = text
|
||||||
|
.lines()
|
||||||
|
.map(|l| {
|
||||||
|
l.chars()
|
||||||
|
.filter(|c| !c.is_whitespace())
|
||||||
|
.collect::<String>()
|
||||||
|
.to_uppercase()
|
||||||
|
})
|
||||||
|
.filter(|l| !l.is_empty())
|
||||||
|
.collect();
|
||||||
|
let (l1, l2) = match lines.as_slice() {
|
||||||
|
[a, b] => (a.clone(), b.clone()),
|
||||||
|
[one] if one.chars().count() == 88 => {
|
||||||
|
let chars: Vec<char> = one.chars().collect();
|
||||||
|
(chars[..44].iter().collect(), chars[44..].iter().collect())
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
return Err(
|
||||||
|
"Paste the two lines of 44 characters from the bottom of the photo page.".into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (n, l) in [(1, &l1), (2, &l2)] {
|
||||||
|
if let Some(c) = l
|
||||||
|
.chars()
|
||||||
|
.find(|c| !(c.is_ascii_uppercase() || c.is_ascii_digit() || *c == '<'))
|
||||||
|
{
|
||||||
|
return Err(format!(
|
||||||
|
"Line {n} contains \u{201c}{c}\u{201d}; only A to Z, 0 to 9 and < belong in it."
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let len = l.len();
|
||||||
|
if len != 44 {
|
||||||
|
return Err(format!(
|
||||||
|
"Line {n} has {len} characters; a passport's lines have 44."
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !l1.starts_with('P') {
|
||||||
|
return Err("Line 1 does not start with P, so this is not a passport.".into());
|
||||||
|
}
|
||||||
|
Ok((l1, l2))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the zone. Fails only when the text is not a passport's zone; check
|
||||||
|
/// digits that do not match are reported in `checks`.
|
||||||
|
pub fn parse(text: &str, today: NaiveDate) -> Result<Mrz, String> {
|
||||||
|
let (l1, l2) = normalize(text)?;
|
||||||
|
let b2 = l2.as_bytes();
|
||||||
|
let names = &l1[5..44];
|
||||||
|
let (sur, given) = match names.find("<<") {
|
||||||
|
Some(i) => (&names[..i], &names[i + 2..]),
|
||||||
|
None => (names, ""),
|
||||||
|
};
|
||||||
|
let number_field = &l2[0..9];
|
||||||
|
let composite = format!("{}{}{}", &l2[0..10], &l2[13..20], &l2[21..43]);
|
||||||
|
let checks = vec![
|
||||||
|
Check {
|
||||||
|
field: "passport number",
|
||||||
|
ok: digit_ok(number_field, b2[9]),
|
||||||
|
},
|
||||||
|
Check {
|
||||||
|
field: "date of birth",
|
||||||
|
ok: digit_ok(&l2[13..19], b2[19]),
|
||||||
|
},
|
||||||
|
Check {
|
||||||
|
field: "expiry date",
|
||||||
|
ok: digit_ok(&l2[21..27], b2[27]),
|
||||||
|
},
|
||||||
|
Check {
|
||||||
|
field: "personal number",
|
||||||
|
ok: digit_ok(&l2[28..42], b2[42]),
|
||||||
|
},
|
||||||
|
Check {
|
||||||
|
field: "whole line 2",
|
||||||
|
ok: digit_ok(&composite, b2[43]),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
let sex = match &l2[20..21] {
|
||||||
|
"F" => "F",
|
||||||
|
"M" => "M",
|
||||||
|
_ => "X",
|
||||||
|
};
|
||||||
|
Ok(Mrz {
|
||||||
|
issuing_state: state(&l1[2..5]),
|
||||||
|
surname: words(sur),
|
||||||
|
given_names: words(given),
|
||||||
|
number: number_field.trim_end_matches('<').to_string(),
|
||||||
|
nationality: state(&l2[10..13]),
|
||||||
|
date_of_birth: date(&l2[13..19], true, today),
|
||||||
|
sex: sex.to_string(),
|
||||||
|
expiry_date: date(&l2[21..27], false, today),
|
||||||
|
personal_number: l2[28..42].trim_end_matches('<').replace('<', " "),
|
||||||
|
checks,
|
||||||
|
text: format!("{l1}\n{l2}"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn words(s: &str) -> String {
|
||||||
|
s.split('<')
|
||||||
|
.filter(|w| !w.is_empty())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Germany writes `D<<` instead of `DEU`; everything else is alpha-3.
|
||||||
|
fn state(code: &str) -> String {
|
||||||
|
let c = code.trim_end_matches('<');
|
||||||
|
if c == "D" {
|
||||||
|
"DEU".into()
|
||||||
|
} else {
|
||||||
|
c.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// YYMMDD. A birth date lies in the past, so a year after this one belongs
|
||||||
|
/// to the 1900s; expiry dates are in the 2000s.
|
||||||
|
fn date(s: &str, past: bool, today: NaiveDate) -> Option<NaiveDate> {
|
||||||
|
let yy: i32 = s.get(0..2)?.parse().ok()?;
|
||||||
|
let mm: u32 = s.get(2..4)?.parse().ok()?;
|
||||||
|
let dd: u32 = s.get(4..6)?.parse().ok()?;
|
||||||
|
let year = if past && 2000 + yy > today.year() {
|
||||||
|
1900 + yy
|
||||||
|
} else {
|
||||||
|
2000 + yy
|
||||||
|
};
|
||||||
|
NaiveDate::from_ymd_opt(year, mm, dd)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fields of a zone to write, for demo data and tests.
|
||||||
|
pub struct Compose<'a> {
|
||||||
|
pub issuing_state: &'a str,
|
||||||
|
pub surname: &'a str,
|
||||||
|
pub given_names: &'a str,
|
||||||
|
pub number: &'a str,
|
||||||
|
pub nationality: &'a str,
|
||||||
|
pub date_of_birth: NaiveDate,
|
||||||
|
pub sex: &'a str,
|
||||||
|
pub expiry_date: NaiveDate,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes a TD3 zone with correct check digits.
|
||||||
|
pub fn compose(c: &Compose) -> String {
|
||||||
|
let fill = |s: &str, n: usize| -> String {
|
||||||
|
let mut s = s.replace(' ', "<").to_uppercase();
|
||||||
|
s.truncate(n);
|
||||||
|
format!("{s:<<n$}")
|
||||||
|
};
|
||||||
|
let names = format!("{}<<{}", c.surname, c.given_names);
|
||||||
|
let l1 = format!("P<{}{}", fill(c.issuing_state, 3), fill(&names, 39));
|
||||||
|
let number = fill(c.number, 9);
|
||||||
|
let dob = c.date_of_birth.format("%y%m%d").to_string();
|
||||||
|
let exp = c.expiry_date.format("%y%m%d").to_string();
|
||||||
|
let personal = fill("", 14);
|
||||||
|
let mut l2 = format!(
|
||||||
|
"{number}{}{}{dob}{}{}{exp}{}{personal}0",
|
||||||
|
check_digit(&number),
|
||||||
|
fill(c.nationality, 3),
|
||||||
|
check_digit(&dob),
|
||||||
|
fill(c.sex, 1),
|
||||||
|
check_digit(&exp),
|
||||||
|
);
|
||||||
|
let composite = format!("{}{}{}", &l2[0..10], &l2[13..20], &l2[21..43]);
|
||||||
|
l2.push_str(&check_digit(&composite).to_string());
|
||||||
|
format!("{l1}\n{l2}")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn d(s: &str) -> NaiveDate {
|
||||||
|
NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
const TODAY: &str = "2026-11-17";
|
||||||
|
|
||||||
|
/// The specimen in ICAO Doc 9303 part 4, appendix A.
|
||||||
|
fn specimen() -> String {
|
||||||
|
format!(
|
||||||
|
"{:<<44}\nL898902C36UTO7408122F1204159ZE184226B<<<<<10",
|
||||||
|
"P<UTOERIKSSON<<ANNA<MARIA"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reads_the_icao_specimen() {
|
||||||
|
let m = parse(&specimen(), d(TODAY)).unwrap();
|
||||||
|
assert!(m.all_ok(), "{:?}", m.failed());
|
||||||
|
assert_eq!(m.issuing_state, "UTO");
|
||||||
|
assert_eq!(m.surname, "ERIKSSON");
|
||||||
|
assert_eq!(m.given_names, "ANNA MARIA");
|
||||||
|
assert_eq!(m.first_and_middle(), ("ANNA".into(), "MARIA".into()));
|
||||||
|
assert_eq!(m.number, "L898902C3");
|
||||||
|
assert_eq!(m.nationality, "UTO");
|
||||||
|
assert_eq!(m.date_of_birth, Some(d("1974-08-12")));
|
||||||
|
assert_eq!(m.sex, "F");
|
||||||
|
assert_eq!(m.expiry_date, Some(d("2012-04-15")));
|
||||||
|
assert_eq!(m.personal_number, "ZE184226B");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn check_digits_catch_a_typo() {
|
||||||
|
// one digit of the birth date changed: 740812 -> 740813
|
||||||
|
let typo = specimen().replace("7408122F", "7408132F");
|
||||||
|
let m = parse(&typo, d(TODAY)).unwrap();
|
||||||
|
assert!(!m.all_ok());
|
||||||
|
assert_eq!(m.failed(), vec!["date of birth", "whole line 2"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn accepts_spaces_lower_case_and_one_line() {
|
||||||
|
let s = specimen();
|
||||||
|
let messy = format!(" {} ", s.to_lowercase().replace('\n', " \n "));
|
||||||
|
assert!(parse(&messy, d(TODAY)).unwrap().all_ok());
|
||||||
|
let one = s.replace('\n', "");
|
||||||
|
assert!(parse(&one, d(TODAY)).unwrap().all_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn refuses_what_is_not_a_zone() {
|
||||||
|
let today = d(TODAY);
|
||||||
|
assert!(parse("hello", today).unwrap_err().contains("two lines"));
|
||||||
|
let short = specimen().replacen("<<<<<10", "<<<<10", 1);
|
||||||
|
assert!(parse(&short, today).unwrap_err().contains("Line 2 has 43"));
|
||||||
|
let bad = specimen().replacen("ERIKSSON", "ERIK$SON", 1);
|
||||||
|
assert!(parse(&bad, today).unwrap_err().contains("Line 1 contains"));
|
||||||
|
let id_card = specimen().replacen("P<", "I<", 1);
|
||||||
|
assert!(
|
||||||
|
parse(&id_card, today)
|
||||||
|
.unwrap_err()
|
||||||
|
.contains("not a passport")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn composes_what_it_reads_and_maps_germany() {
|
||||||
|
let text = compose(&Compose {
|
||||||
|
issuing_state: "D",
|
||||||
|
surname: "MUSTERMANN",
|
||||||
|
given_names: "ERIKA",
|
||||||
|
number: "C01X00T47",
|
||||||
|
nationality: "D",
|
||||||
|
date_of_birth: d("1984-08-12"),
|
||||||
|
sex: "F",
|
||||||
|
expiry_date: d("2031-08-01"),
|
||||||
|
});
|
||||||
|
let (l1, l2) = text.split_once('\n').unwrap();
|
||||||
|
assert_eq!(l1.len(), 44);
|
||||||
|
assert_eq!(l2.len(), 44);
|
||||||
|
assert!(l1.starts_with("P<D<<MUSTERMANN<<ERIKA<"));
|
||||||
|
let m = parse(&text, d(TODAY)).unwrap();
|
||||||
|
assert!(m.all_ok(), "{:?}", m.failed());
|
||||||
|
assert_eq!(m.issuing_state, "DEU");
|
||||||
|
assert_eq!(m.nationality, "DEU");
|
||||||
|
assert_eq!(m.date_of_birth, Some(d("1984-08-12")));
|
||||||
|
assert_eq!(m.expiry_date, Some(d("2031-08-01")));
|
||||||
|
// a birth year after this year belongs to the 1900s
|
||||||
|
let old = compose(&Compose {
|
||||||
|
issuing_state: "GBR",
|
||||||
|
surname: "SAMPLE",
|
||||||
|
given_names: "OLD",
|
||||||
|
number: "123456789",
|
||||||
|
nationality: "GBR",
|
||||||
|
date_of_birth: d("1931-01-02"),
|
||||||
|
sex: "M",
|
||||||
|
expiry_date: d("2027-01-01"),
|
||||||
|
});
|
||||||
|
assert_eq!(
|
||||||
|
parse(&old, d(TODAY)).unwrap().date_of_birth,
|
||||||
|
Some(d("1931-01-02"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+498
@@ -0,0 +1,498 @@
|
|||||||
|
//! Login through Kanidm (id.cnx.network) with OpenID Connect: the
|
||||||
|
//! authorization code flow with PKCE and a nonce, ported from the fleet
|
||||||
|
//! overview (cnx-network-clan `pkgs/hosting/src/oidc.rs`), which follows
|
||||||
|
//! proplan.
|
||||||
|
//!
|
||||||
|
//! - discovery: the provider's `issuer` must equal VISA_OIDC_ISSUER
|
||||||
|
//! (Kanidm's issuer is per client: .../oauth2/openid/<client>);
|
||||||
|
//! - the token request authenticates with the client secret (HTTP Basic) and
|
||||||
|
//! sends the PKCE verifier;
|
||||||
|
//! - the ID token's signature is checked against the provider's key set
|
||||||
|
//! (ES256, Kanidm's default; RS256 accepted), then iss, aud, exp, iat,
|
||||||
|
//! nonce and sub;
|
||||||
|
//! - the groups come from the ID token, else from the userinfo endpoint.
|
||||||
|
|
||||||
|
use std::sync::RwLock;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, anyhow, bail, ensure};
|
||||||
|
use base64::Engine as _;
|
||||||
|
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
|
||||||
|
use ring::rand::SecureRandom as _;
|
||||||
|
use ring::signature;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct Discovery {
|
||||||
|
issuer: String,
|
||||||
|
authorization_endpoint: String,
|
||||||
|
token_endpoint: String,
|
||||||
|
#[serde(default)]
|
||||||
|
userinfo_endpoint: Option<String>,
|
||||||
|
jwks_uri: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Provider {
|
||||||
|
pub issuer: String,
|
||||||
|
pub authorization_endpoint: String,
|
||||||
|
pub token_endpoint: String,
|
||||||
|
pub userinfo_endpoint: Option<String>,
|
||||||
|
pub jwks_uri: String,
|
||||||
|
keys: RwLock<Keys>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Keys {
|
||||||
|
list: Vec<Jwk>,
|
||||||
|
fetched: Option<Instant>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
|
pub struct Jwk {
|
||||||
|
pub kty: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub kid: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub crv: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub x: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub y: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub n: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub e: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct JwkSet {
|
||||||
|
keys: Vec<Jwk>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct TokenResponse {
|
||||||
|
#[serde(default)]
|
||||||
|
access_token: Option<String>,
|
||||||
|
id_token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Who signed in.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Identity {
|
||||||
|
pub login: String,
|
||||||
|
pub name: String,
|
||||||
|
pub groups: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Identity {
|
||||||
|
/// Kanidm names groups by SPN (`visa@id.cnx.network`); a plain name
|
||||||
|
/// counts too.
|
||||||
|
pub fn in_group(&self, group: &str) -> bool {
|
||||||
|
self.groups.iter().any(|g| {
|
||||||
|
g == group
|
||||||
|
|| g.strip_prefix(group)
|
||||||
|
.is_some_and(|rest| rest.starts_with('@'))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Provider {
|
||||||
|
pub async fn discover(http: &reqwest::Client, issuer: &str) -> Result<Provider> {
|
||||||
|
let url = format!("{issuer}/.well-known/openid-configuration");
|
||||||
|
let d: Discovery = http
|
||||||
|
.get(&url)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("GET {url}"))?
|
||||||
|
.error_for_status()
|
||||||
|
.with_context(|| format!("GET {url}"))?
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("parsing {url}"))?;
|
||||||
|
ensure!(
|
||||||
|
d.issuer.trim_end_matches('/') == issuer.trim_end_matches('/'),
|
||||||
|
"the provider calls itself {:?}, VISA_OIDC_ISSUER is {issuer:?}",
|
||||||
|
d.issuer
|
||||||
|
);
|
||||||
|
Ok(Provider {
|
||||||
|
issuer: d.issuer,
|
||||||
|
authorization_endpoint: d.authorization_endpoint,
|
||||||
|
token_endpoint: d.token_endpoint,
|
||||||
|
userinfo_endpoint: d.userinfo_endpoint,
|
||||||
|
jwks_uri: d.jwks_uri,
|
||||||
|
keys: RwLock::new(Keys::default()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A provider from known endpoints, without discovery (tests).
|
||||||
|
pub fn from_endpoints(
|
||||||
|
issuer: &str,
|
||||||
|
authorization_endpoint: &str,
|
||||||
|
token_endpoint: &str,
|
||||||
|
jwks_uri: &str,
|
||||||
|
) -> Provider {
|
||||||
|
Provider {
|
||||||
|
issuer: issuer.to_string(),
|
||||||
|
authorization_endpoint: authorization_endpoint.to_string(),
|
||||||
|
token_endpoint: token_endpoint.to_string(),
|
||||||
|
userinfo_endpoint: None,
|
||||||
|
jwks_uri: jwks_uri.to_string(),
|
||||||
|
keys: RwLock::new(Keys::default()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn authorize_url(
|
||||||
|
&self,
|
||||||
|
client_id: &str,
|
||||||
|
redirect_uri: &str,
|
||||||
|
state: &str,
|
||||||
|
nonce: &str,
|
||||||
|
verifier: &str,
|
||||||
|
) -> Result<String> {
|
||||||
|
let mut url = reqwest::Url::parse(&self.authorization_endpoint)
|
||||||
|
.context("the provider's authorization endpoint is not a URL")?;
|
||||||
|
url.query_pairs_mut()
|
||||||
|
.append_pair("response_type", "code")
|
||||||
|
.append_pair("client_id", client_id)
|
||||||
|
.append_pair("redirect_uri", redirect_uri)
|
||||||
|
.append_pair("scope", "openid profile email groups")
|
||||||
|
.append_pair("state", state)
|
||||||
|
.append_pair("nonce", nonce)
|
||||||
|
.append_pair("code_challenge", &pkce_challenge(verifier))
|
||||||
|
.append_pair("code_challenge_method", "S256");
|
||||||
|
Ok(url.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The provider's signing keys, cached; `refresh` fetches them again
|
||||||
|
/// (at most every 30 s), for a key rotation.
|
||||||
|
async fn keys(&self, http: &reqwest::Client, refresh: bool) -> Result<Vec<Jwk>> {
|
||||||
|
{
|
||||||
|
let k = self.keys.read().unwrap_or_else(|e| e.into_inner());
|
||||||
|
let recent = k
|
||||||
|
.fetched
|
||||||
|
.is_some_and(|t| t.elapsed() < Duration::from_secs(30));
|
||||||
|
if k.fetched.is_some() && (!refresh || recent) {
|
||||||
|
return Ok(k.list.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let set: JwkSet = http
|
||||||
|
.get(&self.jwks_uri)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("GET {}", self.jwks_uri))?
|
||||||
|
.error_for_status()
|
||||||
|
.with_context(|| format!("GET {}", self.jwks_uri))?
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("parsing {}", self.jwks_uri))?;
|
||||||
|
let mut k = self.keys.write().unwrap_or_else(|e| e.into_inner());
|
||||||
|
k.list = set.keys.clone();
|
||||||
|
k.fetched = Some(Instant::now());
|
||||||
|
Ok(set.keys)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Exchange<'a> {
|
||||||
|
pub client_id: &'a str,
|
||||||
|
pub client_secret: &'a str,
|
||||||
|
pub redirect_uri: &'a str,
|
||||||
|
pub code: &'a str,
|
||||||
|
pub verifier: &'a str,
|
||||||
|
pub nonce: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Trades the code for tokens and checks them.
|
||||||
|
pub async fn finish(
|
||||||
|
http: &reqwest::Client,
|
||||||
|
p: &Provider,
|
||||||
|
x: &Exchange<'_>,
|
||||||
|
now: f64,
|
||||||
|
) -> Result<Identity> {
|
||||||
|
let resp = http
|
||||||
|
.post(&p.token_endpoint)
|
||||||
|
.basic_auth(x.client_id, Some(x.client_secret))
|
||||||
|
.form(&[
|
||||||
|
("grant_type", "authorization_code"),
|
||||||
|
("code", x.code),
|
||||||
|
("redirect_uri", x.redirect_uri),
|
||||||
|
("code_verifier", x.verifier),
|
||||||
|
])
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("POST {}", p.token_endpoint))?;
|
||||||
|
let status = resp.status();
|
||||||
|
let body = resp.bytes().await.context("reading the token response")?;
|
||||||
|
if !status.is_success() {
|
||||||
|
bail!(
|
||||||
|
"the token endpoint answered {status}: {}",
|
||||||
|
String::from_utf8_lossy(&body[..body.len().min(300)])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let tokens: TokenResponse =
|
||||||
|
serde_json::from_slice(&body).context("parsing the token response")?;
|
||||||
|
let claims = match verify_signature(&tokens.id_token, &p.keys(http, false).await?) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(_) => verify_signature(&tokens.id_token, &p.keys(http, true).await?)?,
|
||||||
|
};
|
||||||
|
check_claims(&claims, &p.issuer, x.client_id, x.nonce, now)?;
|
||||||
|
let sub = claims["sub"].as_str().unwrap_or_default();
|
||||||
|
let mut groups = strings(&claims["groups"]);
|
||||||
|
if groups.is_empty()
|
||||||
|
&& let (Some(endpoint), Some(token)) = (&p.userinfo_endpoint, &tokens.access_token)
|
||||||
|
{
|
||||||
|
let info: Value = http
|
||||||
|
.get(endpoint)
|
||||||
|
.bearer_auth(token)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("GET {endpoint}"))?
|
||||||
|
.error_for_status()
|
||||||
|
.with_context(|| format!("GET {endpoint}"))?
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.context("parsing userinfo")?;
|
||||||
|
ensure!(
|
||||||
|
info["sub"].as_str() == Some(sub),
|
||||||
|
"userinfo is about someone else"
|
||||||
|
);
|
||||||
|
groups = strings(&info["groups"]);
|
||||||
|
}
|
||||||
|
let login = claims["preferred_username"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap_or(sub)
|
||||||
|
.to_string();
|
||||||
|
let name = claims["name"].as_str().unwrap_or(&login).to_string();
|
||||||
|
Ok(Identity {
|
||||||
|
login,
|
||||||
|
name,
|
||||||
|
groups,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn strings(v: &Value) -> Vec<String> {
|
||||||
|
match v {
|
||||||
|
Value::Array(a) => a
|
||||||
|
.iter()
|
||||||
|
.filter_map(|x| x.as_str().map(str::to_string))
|
||||||
|
.collect(),
|
||||||
|
Value::String(s) => vec![s.clone()],
|
||||||
|
_ => Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn check_claims(c: &Value, issuer: &str, client_id: &str, nonce: &str, now: f64) -> Result<()> {
|
||||||
|
ensure!(
|
||||||
|
c["iss"].as_str().map(|s| s.trim_end_matches('/')) == Some(issuer.trim_end_matches('/')),
|
||||||
|
"the token comes from {:?}, not {issuer:?}",
|
||||||
|
c["iss"]
|
||||||
|
);
|
||||||
|
let for_us = match &c["aud"] {
|
||||||
|
Value::String(s) => s == client_id,
|
||||||
|
Value::Array(a) => a.iter().any(|v| v.as_str() == Some(client_id)),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
ensure!(for_us, "the token is not for client {client_id:?}");
|
||||||
|
let exp = c["exp"].as_f64().context("the token has no expiry")?;
|
||||||
|
ensure!(exp + 60.0 > now, "the token has expired");
|
||||||
|
if let Some(iat) = c["iat"].as_f64() {
|
||||||
|
ensure!(iat < now + 300.0, "the token was issued in the future");
|
||||||
|
}
|
||||||
|
ensure!(
|
||||||
|
c["nonce"].as_str() == Some(nonce),
|
||||||
|
"the nonce does not match"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
c["sub"].as_str().is_some_and(|s| !s.is_empty()),
|
||||||
|
"the token names no subject"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn b64(s: &str) -> Result<Vec<u8>> {
|
||||||
|
Ok(B64.decode(s.trim_end_matches('='))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The JWT's claims when one of the keys verifies its signature.
|
||||||
|
pub fn verify_signature(token: &str, keys: &[Jwk]) -> Result<Value> {
|
||||||
|
let parts: Vec<&str> = token.split('.').collect();
|
||||||
|
ensure!(parts.len() == 3, "the ID token is not a signed JWT");
|
||||||
|
let header: Value =
|
||||||
|
serde_json::from_slice(&b64(parts[0]).context("token header")?).context("token header")?;
|
||||||
|
let alg = header["alg"].as_str().unwrap_or("");
|
||||||
|
let kid = header["kid"].as_str();
|
||||||
|
let sig = b64(parts[2]).context("token signature")?;
|
||||||
|
let msg = &token.as_bytes()[..parts[0].len() + 1 + parts[1].len()];
|
||||||
|
let candidates: Vec<&Jwk> = keys
|
||||||
|
.iter()
|
||||||
|
.filter(|k| kid.is_none() || k.kid.as_deref() == kid)
|
||||||
|
.collect();
|
||||||
|
ensure!(
|
||||||
|
!candidates.is_empty(),
|
||||||
|
"no key {kid:?} in the provider's key set"
|
||||||
|
);
|
||||||
|
for key in candidates {
|
||||||
|
if verify_with(alg, key, msg, &sig).is_ok() {
|
||||||
|
return serde_json::from_slice(&b64(parts[1]).context("token payload")?)
|
||||||
|
.context("token payload");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bail!("the ID token's signature ({alg}) does not verify")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_with(alg: &str, key: &Jwk, msg: &[u8], sig: &[u8]) -> Result<()> {
|
||||||
|
match alg {
|
||||||
|
"ES256" => {
|
||||||
|
ensure!(
|
||||||
|
key.kty == "EC" && key.crv.as_deref() == Some("P-256"),
|
||||||
|
"not a P-256 key"
|
||||||
|
);
|
||||||
|
let x = b64(key.x.as_deref().context("key without x")?)?;
|
||||||
|
let y = b64(key.y.as_deref().context("key without y")?)?;
|
||||||
|
ensure!(x.len() == 32 && y.len() == 32, "not a P-256 point");
|
||||||
|
let mut point = Vec::with_capacity(65);
|
||||||
|
point.push(4);
|
||||||
|
point.extend_from_slice(&x);
|
||||||
|
point.extend_from_slice(&y);
|
||||||
|
signature::UnparsedPublicKey::new(&signature::ECDSA_P256_SHA256_FIXED, point)
|
||||||
|
.verify(msg, sig)
|
||||||
|
.map_err(|_| anyhow!("bad signature"))
|
||||||
|
}
|
||||||
|
"RS256" => {
|
||||||
|
ensure!(key.kty == "RSA", "not an RSA key");
|
||||||
|
let n = b64(key.n.as_deref().context("key without n")?)?;
|
||||||
|
let e = b64(key.e.as_deref().context("key without e")?)?;
|
||||||
|
signature::RsaPublicKeyComponents { n: &n, e: &e }
|
||||||
|
.verify(&signature::RSA_PKCS1_2048_8192_SHA256, msg, sig)
|
||||||
|
.map_err(|_| anyhow!("bad signature"))
|
||||||
|
}
|
||||||
|
other => bail!("unsupported signature algorithm {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 32 random bytes as base64url: state, nonce, PKCE verifier, session ids.
|
||||||
|
pub fn random_token() -> String {
|
||||||
|
let mut bytes = [0u8; 32];
|
||||||
|
ring::rand::SystemRandom::new()
|
||||||
|
.fill(&mut bytes)
|
||||||
|
.expect("the system's random source failed");
|
||||||
|
B64.encode(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// PKCE S256: base64url(SHA-256(verifier)).
|
||||||
|
pub fn pkce_challenge(verifier: &str) -> String {
|
||||||
|
B64.encode(ring::digest::digest(
|
||||||
|
&ring::digest::SHA256,
|
||||||
|
verifier.as_bytes(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub mod tests {
|
||||||
|
use super::*;
|
||||||
|
use ring::signature::{ECDSA_P256_SHA256_FIXED_SIGNING, EcdsaKeyPair, KeyPair};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
/// A P-256 key pair and its JWK, for signing test tokens.
|
||||||
|
pub struct TestKey {
|
||||||
|
pair: EcdsaKeyPair,
|
||||||
|
pub jwk: Jwk,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TestKey {
|
||||||
|
pub fn new(kid: &str) -> TestKey {
|
||||||
|
let rng = ring::rand::SystemRandom::new();
|
||||||
|
let pkcs8 =
|
||||||
|
EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, &rng).unwrap();
|
||||||
|
let pair =
|
||||||
|
EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, pkcs8.as_ref(), &rng)
|
||||||
|
.unwrap();
|
||||||
|
let public = pair.public_key().as_ref().to_vec();
|
||||||
|
let jwk = Jwk {
|
||||||
|
kty: "EC".into(),
|
||||||
|
kid: Some(kid.into()),
|
||||||
|
crv: Some("P-256".into()),
|
||||||
|
x: Some(B64.encode(&public[1..33])),
|
||||||
|
y: Some(B64.encode(&public[33..65])),
|
||||||
|
n: None,
|
||||||
|
e: None,
|
||||||
|
};
|
||||||
|
TestKey { pair, jwk }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sign(&self, claims: &Value) -> String {
|
||||||
|
let header = json!({"alg": "ES256", "typ": "JWT", "kid": self.jwk.kid});
|
||||||
|
let input = format!(
|
||||||
|
"{}.{}",
|
||||||
|
B64.encode(header.to_string()),
|
||||||
|
B64.encode(claims.to_string())
|
||||||
|
);
|
||||||
|
let rng = ring::rand::SystemRandom::new();
|
||||||
|
let sig = self.pair.sign(&rng, input.as_bytes()).unwrap();
|
||||||
|
format!("{input}.{}", B64.encode(sig.as_ref()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn claims(now: f64) -> Value {
|
||||||
|
json!({
|
||||||
|
"iss": "https://id.example/oauth2/openid/visa-web",
|
||||||
|
"aud": "visa-web",
|
||||||
|
"sub": "uuid-1",
|
||||||
|
"exp": now + 300.0,
|
||||||
|
"iat": now,
|
||||||
|
"nonce": "n1",
|
||||||
|
"preferred_username": "grabowski",
|
||||||
|
"groups": ["visa@id.example", "b4l@id.example"],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pkce_matches_rfc_7636() {
|
||||||
|
assert_eq!(
|
||||||
|
pkce_challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
|
||||||
|
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
|
||||||
|
);
|
||||||
|
assert_eq!(random_token().len(), 43);
|
||||||
|
assert_ne!(random_token(), random_token());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn verifies_es256_and_checks_claims() {
|
||||||
|
let now = 1_800_000_000.0;
|
||||||
|
let key = TestKey::new("k1");
|
||||||
|
let token = key.sign(&claims(now));
|
||||||
|
let c = verify_signature(&token, std::slice::from_ref(&key.jwk)).unwrap();
|
||||||
|
let iss = "https://id.example/oauth2/openid/visa-web";
|
||||||
|
check_claims(&c, iss, "visa-web", "n1", now).unwrap();
|
||||||
|
assert!(check_claims(&c, iss, "visa-web", "other", now).is_err());
|
||||||
|
assert!(check_claims(&c, iss, "grafana", "n1", now).is_err());
|
||||||
|
assert!(check_claims(&c, "https://evil", "visa-web", "n1", now).is_err());
|
||||||
|
assert!(check_claims(&c, iss, "visa-web", "n1", now + 3600.0).is_err());
|
||||||
|
|
||||||
|
// another key, a tampered payload, an unknown key id
|
||||||
|
let other = TestKey::new("k1");
|
||||||
|
assert!(verify_signature(&token, std::slice::from_ref(&other.jwk)).is_err());
|
||||||
|
let mut parts: Vec<String> = token.split('.').map(str::to_string).collect();
|
||||||
|
let mut forged = claims(now);
|
||||||
|
forged["groups"] = json!(["visa"]);
|
||||||
|
parts[1] = B64.encode(forged.to_string());
|
||||||
|
assert!(verify_signature(&parts.join("."), std::slice::from_ref(&key.jwk)).is_err());
|
||||||
|
let k2 = TestKey::new("k2");
|
||||||
|
let e =
|
||||||
|
verify_signature(&k2.sign(&claims(now)), std::slice::from_ref(&key.jwk)).unwrap_err();
|
||||||
|
assert!(e.to_string().contains("no key"), "{e}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn groups_by_spn_or_name() {
|
||||||
|
let id = Identity {
|
||||||
|
login: "a".into(),
|
||||||
|
name: "A".into(),
|
||||||
|
groups: vec!["visa@id.cnx.network".into(), "b4l".into()],
|
||||||
|
};
|
||||||
|
assert!(id.in_group("visa"));
|
||||||
|
assert!(id.in_group("b4l"));
|
||||||
|
assert!(!id.in_group("vis"));
|
||||||
|
assert!(!id.in_group("poy"));
|
||||||
|
}
|
||||||
|
}
|
||||||
+1213
File diff suppressed because it is too large.
Load diff
+344
@@ -0,0 +1,344 @@
|
|||||||
|
//! Demo data for development: invented people only (specimen names, numbers
|
||||||
|
//! that belong to nobody). `visa seed-demo` refuses to run when the login is
|
||||||
|
//! on, so it never writes into production.
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use chrono::NaiveDate;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
use crate::audit::{self, Action, Entity, Entry};
|
||||||
|
use crate::dates;
|
||||||
|
use crate::mrz;
|
||||||
|
use crate::people::{self, AddressInput, PassportInput, PersonInput};
|
||||||
|
|
||||||
|
pub const MARKER: &str = "Demo record, invented for development.";
|
||||||
|
|
||||||
|
fn d(s: &str) -> NaiveDate {
|
||||||
|
dates::parse_date(s).expect("demo dates are valid")
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Demo {
|
||||||
|
person: PersonInput,
|
||||||
|
passports: Vec<PassportInput>,
|
||||||
|
addresses: Vec<AddressInput>,
|
||||||
|
archived: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn person(
|
||||||
|
surname: &str,
|
||||||
|
first: &str,
|
||||||
|
middle: &str,
|
||||||
|
title: &str,
|
||||||
|
sex: &str,
|
||||||
|
born: &str,
|
||||||
|
place: &str,
|
||||||
|
nationality: &str,
|
||||||
|
occupation: &str,
|
||||||
|
employer: &str,
|
||||||
|
n: u32,
|
||||||
|
) -> PersonInput {
|
||||||
|
PersonInput {
|
||||||
|
surname: surname.into(),
|
||||||
|
first_name: first.into(),
|
||||||
|
middle_name: middle.into(),
|
||||||
|
title: title.into(),
|
||||||
|
sex: sex.into(),
|
||||||
|
date_of_birth: Some(d(born)),
|
||||||
|
place_of_birth: place.into(),
|
||||||
|
nationality: nationality.into(),
|
||||||
|
occupation: occupation.into(),
|
||||||
|
employer: employer.into(),
|
||||||
|
phone: format!("+66 80 000 000{n}"),
|
||||||
|
email: format!(
|
||||||
|
"{}.{}@example.com",
|
||||||
|
first.to_lowercase(),
|
||||||
|
surname.to_lowercase()
|
||||||
|
),
|
||||||
|
notes: MARKER.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn passport(
|
||||||
|
p: &PersonInput,
|
||||||
|
number: &str,
|
||||||
|
issued: &str,
|
||||||
|
expires: &str,
|
||||||
|
at: &str,
|
||||||
|
with_mrz: bool,
|
||||||
|
) -> PassportInput {
|
||||||
|
let given = if p.middle_name.is_empty() {
|
||||||
|
p.first_name.clone()
|
||||||
|
} else {
|
||||||
|
format!("{} {}", p.first_name, p.middle_name)
|
||||||
|
};
|
||||||
|
let mrz = if with_mrz {
|
||||||
|
mrz::compose(&mrz::Compose {
|
||||||
|
issuing_state: if p.nationality == "DEU" {
|
||||||
|
"D"
|
||||||
|
} else {
|
||||||
|
p.nationality.as_str()
|
||||||
|
},
|
||||||
|
surname: &p.surname,
|
||||||
|
given_names: &given,
|
||||||
|
number,
|
||||||
|
nationality: if p.nationality == "DEU" {
|
||||||
|
"D"
|
||||||
|
} else {
|
||||||
|
p.nationality.as_str()
|
||||||
|
},
|
||||||
|
date_of_birth: p.date_of_birth.expect("demo people have birth dates"),
|
||||||
|
sex: &p.sex,
|
||||||
|
expiry_date: d(expires),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
PassportInput {
|
||||||
|
number: number.into(),
|
||||||
|
issuing_country: p.nationality.clone(),
|
||||||
|
issued_on: Some(d(issued)),
|
||||||
|
expires_on: d(expires),
|
||||||
|
issued_at: at.into(),
|
||||||
|
mrz,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn address(
|
||||||
|
house_no: &str,
|
||||||
|
moo: &str,
|
||||||
|
building: &str,
|
||||||
|
soi: &str,
|
||||||
|
road: &str,
|
||||||
|
subdistrict: &str,
|
||||||
|
district: &str,
|
||||||
|
province: &str,
|
||||||
|
postal: &str,
|
||||||
|
moved_in: &str,
|
||||||
|
moved_out: Option<&str>,
|
||||||
|
tm30: Option<(&str, &str)>,
|
||||||
|
) -> AddressInput {
|
||||||
|
AddressInput {
|
||||||
|
house_no: house_no.into(),
|
||||||
|
moo: moo.into(),
|
||||||
|
building: building.into(),
|
||||||
|
soi: soi.into(),
|
||||||
|
road: road.into(),
|
||||||
|
subdistrict: subdistrict.into(),
|
||||||
|
district: district.into(),
|
||||||
|
province: province.into(),
|
||||||
|
postal_code: postal.into(),
|
||||||
|
moved_in_on: Some(d(moved_in)),
|
||||||
|
moved_out_on: moved_out.map(d),
|
||||||
|
house_master: "Somchai Jaidee".into(),
|
||||||
|
house_master_phone: "+66 80 000 0099".into(),
|
||||||
|
tm30_reported_on: tm30.map(|(date, _)| d(date)),
|
||||||
|
tm30_receipt_no: tm30.map(|(_, no)| no.to_string()).unwrap_or_default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dates relative to `today`, so the warnings show whenever the seed runs.
|
||||||
|
fn demos(today: NaiveDate) -> Vec<Demo> {
|
||||||
|
let plus = |days: i64| (today + chrono::TimeDelta::days(days)).to_string();
|
||||||
|
let employer = "Demo Engineering Co., Ltd.";
|
||||||
|
|
||||||
|
let erika = person(
|
||||||
|
"Mustermann",
|
||||||
|
"Erika",
|
||||||
|
"",
|
||||||
|
"Ms",
|
||||||
|
"F",
|
||||||
|
"1984-08-12",
|
||||||
|
"Berlin",
|
||||||
|
"DEU",
|
||||||
|
"Electrical engineer",
|
||||||
|
employer,
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
let erika_pp = passport(
|
||||||
|
&erika,
|
||||||
|
"C01X00T47",
|
||||||
|
"2021-08-02",
|
||||||
|
"2031-08-01",
|
||||||
|
"Stadt Koeln",
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
let jane = person(
|
||||||
|
"Doe",
|
||||||
|
"Jane",
|
||||||
|
"Marie",
|
||||||
|
"Ms",
|
||||||
|
"F",
|
||||||
|
"1990-02-14",
|
||||||
|
"Portland, Oregon",
|
||||||
|
"USA",
|
||||||
|
"Product designer",
|
||||||
|
employer,
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
let jane_old = passport(
|
||||||
|
&jane,
|
||||||
|
"Z00000017",
|
||||||
|
"2012-03-01",
|
||||||
|
"2022-02-28",
|
||||||
|
"U.S. Department of State",
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
let jane_pp = passport(
|
||||||
|
&jane,
|
||||||
|
"Z00000042",
|
||||||
|
"2017-03-01",
|
||||||
|
&plus(95),
|
||||||
|
"U.S. Department of State",
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
let tomas = person(
|
||||||
|
"Novak",
|
||||||
|
"Tomas",
|
||||||
|
"",
|
||||||
|
"Mr",
|
||||||
|
"M",
|
||||||
|
"1979-11-03",
|
||||||
|
"Brno",
|
||||||
|
"CZE",
|
||||||
|
"Accountant",
|
||||||
|
"Demo Accounting Partnership",
|
||||||
|
3,
|
||||||
|
);
|
||||||
|
let tomas_pp = passport(&tomas, "40000001", "2018-01-15", &plus(300), "Brno", true);
|
||||||
|
let old = person(
|
||||||
|
"Sample",
|
||||||
|
"Oliver",
|
||||||
|
"",
|
||||||
|
"Mr",
|
||||||
|
"M",
|
||||||
|
"1961-05-30",
|
||||||
|
"Leeds",
|
||||||
|
"GBR",
|
||||||
|
"Retired",
|
||||||
|
"",
|
||||||
|
4,
|
||||||
|
);
|
||||||
|
let old_pp = passport(&old, "100000001", "2014-01-10", "2024-01-10", "HMPO", false);
|
||||||
|
|
||||||
|
vec![
|
||||||
|
Demo {
|
||||||
|
person: erika,
|
||||||
|
passports: vec![erika_pp],
|
||||||
|
addresses: vec![
|
||||||
|
address(
|
||||||
|
"12",
|
||||||
|
"",
|
||||||
|
"Nimman Demo Residence",
|
||||||
|
"9",
|
||||||
|
"Nimmanhaemin Road",
|
||||||
|
"Suthep",
|
||||||
|
"Mueang Chiang Mai",
|
||||||
|
"Chiang Mai",
|
||||||
|
"50200",
|
||||||
|
"2025-06-01",
|
||||||
|
Some("2026-02-28"),
|
||||||
|
Some(("2025-06-02", "TM30-DEMO-0007")),
|
||||||
|
),
|
||||||
|
address(
|
||||||
|
"99/9",
|
||||||
|
"4",
|
||||||
|
"Baan Suan Demo",
|
||||||
|
"7",
|
||||||
|
"Huay Kaew Road",
|
||||||
|
"Chang Phueak",
|
||||||
|
"Mueang Chiang Mai",
|
||||||
|
"Chiang Mai",
|
||||||
|
"50300",
|
||||||
|
"2026-03-01",
|
||||||
|
None,
|
||||||
|
Some(("2026-03-02", "TM30-DEMO-0012")),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
archived: false,
|
||||||
|
},
|
||||||
|
Demo {
|
||||||
|
person: jane,
|
||||||
|
passports: vec![jane_old, jane_pp],
|
||||||
|
addresses: vec![address(
|
||||||
|
"1/23",
|
||||||
|
"",
|
||||||
|
"Demo Condominium, room 512",
|
||||||
|
"",
|
||||||
|
"Chotana Road",
|
||||||
|
"Chang Phueak",
|
||||||
|
"Mueang Chiang Mai",
|
||||||
|
"Chiang Mai",
|
||||||
|
"50300",
|
||||||
|
"2026-09-15",
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)],
|
||||||
|
archived: false,
|
||||||
|
},
|
||||||
|
Demo {
|
||||||
|
person: tomas,
|
||||||
|
passports: vec![tomas_pp],
|
||||||
|
addresses: vec![address(
|
||||||
|
"55",
|
||||||
|
"2",
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
"Ban Klang",
|
||||||
|
"Mueang Lamphun",
|
||||||
|
"Lamphun",
|
||||||
|
"51000",
|
||||||
|
"2024-11-01",
|
||||||
|
None,
|
||||||
|
Some(("2024-11-01", "TM30-DEMO-0003")),
|
||||||
|
)],
|
||||||
|
archived: false,
|
||||||
|
},
|
||||||
|
Demo {
|
||||||
|
person: old,
|
||||||
|
passports: vec![old_pp],
|
||||||
|
addresses: vec![],
|
||||||
|
archived: true,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds the demo people unless they are there already; true when it did.
|
||||||
|
pub async fn demo(db: &PgPool, today: NaiveDate) -> Result<bool> {
|
||||||
|
let present: bool = sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM people WHERE notes = $1)")
|
||||||
|
.bind(MARKER)
|
||||||
|
.fetch_one(db)
|
||||||
|
.await?;
|
||||||
|
if present {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
let mut tx = db.begin().await?;
|
||||||
|
let log = |action, entity, id, person| Entry {
|
||||||
|
actor: "seed",
|
||||||
|
action,
|
||||||
|
entity,
|
||||||
|
entity_id: Some(id),
|
||||||
|
person_id: Some(person),
|
||||||
|
fields: &[],
|
||||||
|
};
|
||||||
|
for demo in demos(today) {
|
||||||
|
let id = people::create_person(&mut tx, &demo.person).await?;
|
||||||
|
audit::record(&mut *tx, &log(Action::Create, Entity::Person, id, id)).await?;
|
||||||
|
for p in &demo.passports {
|
||||||
|
let pid = people::create_passport(&mut tx, id, p).await?;
|
||||||
|
audit::record(&mut *tx, &log(Action::Create, Entity::Passport, pid, id)).await?;
|
||||||
|
}
|
||||||
|
for a in &demo.addresses {
|
||||||
|
let aid = people::create_address(&mut tx, id, a).await?;
|
||||||
|
audit::record(&mut *tx, &log(Action::Create, Entity::Address, aid, id)).await?;
|
||||||
|
}
|
||||||
|
if demo.archived {
|
||||||
|
people::set_archived(&mut tx, id, true).await?;
|
||||||
|
audit::record(&mut *tx, &log(Action::Archive, Entity::Person, id, id)).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
+204
@@ -0,0 +1,204 @@
|
|||||||
|
//! Sessions in PostgreSQL, pending logins in memory.
|
||||||
|
//!
|
||||||
|
//! A session survives a restart (deploys do not sign anyone out). The table
|
||||||
|
//! holds the SHA-256 of the cookie's value, never the value itself.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use axum::http::header::COOKIE;
|
||||||
|
use serde::Serialize;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
use crate::oidc::random_token;
|
||||||
|
|
||||||
|
/// `__Host-`: Secure, Path=/ and no Domain, so no other name under
|
||||||
|
/// buildfor.life can set or read it.
|
||||||
|
pub const SESSION_COOKIE: &str = "__Host-visa";
|
||||||
|
/// Binds a login in progress to the browser that started it.
|
||||||
|
pub const FLOW_COOKIE: &str = "__Host-visa-login";
|
||||||
|
pub const SESSION_TTL: Duration = Duration::from_secs(12 * 3600);
|
||||||
|
pub const FLOW_TTL: Duration = Duration::from_secs(600);
|
||||||
|
const MAX_FLOWS: usize = 1000;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
pub struct User {
|
||||||
|
pub login: String,
|
||||||
|
pub name: String,
|
||||||
|
/// Local development without login.
|
||||||
|
pub local: bool,
|
||||||
|
/// The session's token for forms (CSRF); templates get it as `csrf`.
|
||||||
|
#[serde(skip)]
|
||||||
|
pub csrf: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl User {
|
||||||
|
pub fn local(csrf: &str) -> User {
|
||||||
|
User {
|
||||||
|
login: "local".into(),
|
||||||
|
name: "Local development".into(),
|
||||||
|
local: true,
|
||||||
|
csrf: csrf.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct Flow {
|
||||||
|
pub state: String,
|
||||||
|
pub nonce: String,
|
||||||
|
pub verifier: String,
|
||||||
|
/// Where to go after the login.
|
||||||
|
pub next: String,
|
||||||
|
created: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct Flows {
|
||||||
|
flows: Mutex<HashMap<String, Flow>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Flows {
|
||||||
|
/// A new login; None when too many are pending (someone hammering /login).
|
||||||
|
pub fn start(&self, next: String) -> Option<Flow> {
|
||||||
|
let mut flows = self.flows.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
flows.retain(|_, f| f.created.elapsed() < FLOW_TTL);
|
||||||
|
if flows.len() >= MAX_FLOWS {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let flow = Flow {
|
||||||
|
state: random_token(),
|
||||||
|
nonce: random_token(),
|
||||||
|
verifier: random_token(),
|
||||||
|
next,
|
||||||
|
created: Instant::now(),
|
||||||
|
};
|
||||||
|
flows.insert(flow.state.clone(), flow.clone());
|
||||||
|
Some(flow)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pending login for this state, once.
|
||||||
|
pub fn take(&self, state: &str) -> Option<Flow> {
|
||||||
|
let mut flows = self.flows.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
flows
|
||||||
|
.remove(state)
|
||||||
|
.filter(|f| f.created.elapsed() < FLOW_TTL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hash(id: &str) -> Vec<u8> {
|
||||||
|
ring::digest::digest(&ring::digest::SHA256, id.as_bytes())
|
||||||
|
.as_ref()
|
||||||
|
.to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a session; returns the cookie's value.
|
||||||
|
pub async fn create(db: &PgPool, login: &str, name: &str) -> Result<String> {
|
||||||
|
let id = random_token();
|
||||||
|
let ttl = chrono::TimeDelta::seconds(SESSION_TTL.as_secs() as i64);
|
||||||
|
sqlx::query("DELETE FROM sessions WHERE expires_at < now()")
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO sessions (id_hash, login, name, csrf, expires_at) \
|
||||||
|
VALUES ($1, $2, $3, $4, now() + $5)",
|
||||||
|
)
|
||||||
|
.bind(hash(&id))
|
||||||
|
.bind(login)
|
||||||
|
.bind(name)
|
||||||
|
.bind(random_token())
|
||||||
|
.bind(ttl)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get(db: &PgPool, id: &str) -> Result<Option<User>> {
|
||||||
|
let row: Option<(String, String, String)> = sqlx::query_as(
|
||||||
|
"SELECT login, name, csrf FROM sessions WHERE id_hash = $1 AND expires_at > now()",
|
||||||
|
)
|
||||||
|
.bind(hash(id))
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await?;
|
||||||
|
Ok(row.map(|(login, name, csrf)| User {
|
||||||
|
login,
|
||||||
|
name,
|
||||||
|
local: false,
|
||||||
|
csrf,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn remove(db: &PgPool, id: &str) -> Result<()> {
|
||||||
|
sqlx::query("DELETE FROM sessions WHERE id_hash = $1")
|
||||||
|
.bind(hash(id))
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||||
|
for value in headers.get_all(COOKIE) {
|
||||||
|
let Ok(text) = value.to_str() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for part in text.split(';') {
|
||||||
|
if let Some((k, v)) = part.trim().split_once('=')
|
||||||
|
&& k == name
|
||||||
|
{
|
||||||
|
return Some(v.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_cookie(name: &str, value: &str, max_age: Duration) -> String {
|
||||||
|
format!(
|
||||||
|
"{name}={value}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age={}",
|
||||||
|
max_age.as_secs()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear_cookie(name: &str) -> String {
|
||||||
|
format!("{name}=; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=0")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compares two tokens in time independent of where they differ.
|
||||||
|
pub fn same_token(a: &str, b: &str) -> bool {
|
||||||
|
let (a, b) = (a.as_bytes(), b.as_bytes());
|
||||||
|
if a.len() != b.len() || a.is_empty() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use axum::http::HeaderValue;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn flows_are_single_use() {
|
||||||
|
let f = Flows::default();
|
||||||
|
let flow = f.start("/people/3".into()).unwrap();
|
||||||
|
assert_eq!(f.take(&flow.state).unwrap().next, "/people/3");
|
||||||
|
assert!(f.take(&flow.state).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cookies_and_tokens() {
|
||||||
|
let mut h = HeaderMap::new();
|
||||||
|
h.append(COOKIE, HeaderValue::from_static("a=1; __Host-visa=abc"));
|
||||||
|
assert_eq!(cookie_value(&h, SESSION_COOKIE).as_deref(), Some("abc"));
|
||||||
|
assert_eq!(cookie_value(&h, FLOW_COOKIE), None);
|
||||||
|
assert!(set_cookie(SESSION_COOKIE, "x", SESSION_TTL).contains("Max-Age=43200"));
|
||||||
|
assert!(same_token("abc", "abc"));
|
||||||
|
assert!(!same_token("abc", "abd"));
|
||||||
|
assert!(!same_token("abc", "ab"));
|
||||||
|
assert!(!same_token("", ""));
|
||||||
|
assert_eq!(hash("x").len(), 32);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
//! The Activity page: the audit log, newest first.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Extension;
|
||||||
|
use axum::extract::{Query, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use minijinja::context;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use super::{AppState, Res};
|
||||||
|
use crate::audit;
|
||||||
|
use crate::people;
|
||||||
|
use crate::session::User;
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct ActivityQuery {
|
||||||
|
#[serde(default)]
|
||||||
|
person: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn page(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Query(q): Query<ActivityQuery>,
|
||||||
|
) -> Res {
|
||||||
|
let items = audit::recent(&st.db, q.person, 300).await?;
|
||||||
|
let person = match q.person {
|
||||||
|
Some(id) => people::get_person(&st.db, id)
|
||||||
|
.await?
|
||||||
|
.map(|p| context! { id => p.id, name => p.display_name() }),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
Ok(super::page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
"activity.html",
|
||||||
|
"Activity",
|
||||||
|
"activity",
|
||||||
|
StatusCode::OK,
|
||||||
|
context! { items, person },
|
||||||
|
))
|
||||||
|
}
|
||||||
+252
@@ -0,0 +1,252 @@
|
|||||||
|
//! Signing in through Kanidm and out again.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Extension;
|
||||||
|
use axum::extract::{Query, State};
|
||||||
|
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
|
||||||
|
use axum::response::{IntoResponse, Redirect, Response};
|
||||||
|
use tracing::{info, warn};
|
||||||
|
|
||||||
|
use super::{AppError, AppState, message, safe_next};
|
||||||
|
use crate::audit::{self, Action, Entity, Entry};
|
||||||
|
use crate::config::Auth;
|
||||||
|
use crate::oidc;
|
||||||
|
use crate::session::{self, FLOW_COOKIE, SESSION_COOKIE, User};
|
||||||
|
|
||||||
|
fn cookie_header(value: &str) -> HeaderValue {
|
||||||
|
HeaderValue::from_str(value).expect("cookie values are base64url")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now() -> f64 {
|
||||||
|
std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs_f64())
|
||||||
|
.unwrap_or(0.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn login(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Query(q): Query<HashMap<String, String>>,
|
||||||
|
) -> Response {
|
||||||
|
let Auth::Oidc(oc) = &st.cfg.auth else {
|
||||||
|
return Redirect::to("/").into_response();
|
||||||
|
};
|
||||||
|
let Some(provider) = st.provider() else {
|
||||||
|
return message(
|
||||||
|
&st,
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE,
|
||||||
|
"The login service is not reachable yet",
|
||||||
|
"visa.buildfor.life fetches id.cnx.network's settings when it starts and keeps \
|
||||||
|
trying. Try again in a minute.",
|
||||||
|
("/", "Try again"),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let Some(flow) = st.flows.start(safe_next(q.get("next"))) else {
|
||||||
|
return message(
|
||||||
|
&st,
|
||||||
|
StatusCode::TOO_MANY_REQUESTS,
|
||||||
|
"Too many logins at once",
|
||||||
|
"Wait a few minutes and try again.",
|
||||||
|
("/", "Try again"),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let url = match provider.authorize_url(
|
||||||
|
&oc.client_id,
|
||||||
|
&st.cfg.redirect_uri(),
|
||||||
|
&flow.state,
|
||||||
|
&flow.nonce,
|
||||||
|
&flow.verifier,
|
||||||
|
) {
|
||||||
|
Ok(u) => u,
|
||||||
|
Err(e) => {
|
||||||
|
warn!("login: {e:#}");
|
||||||
|
return message(
|
||||||
|
&st,
|
||||||
|
StatusCode::BAD_GATEWAY,
|
||||||
|
"The login service sent unusable settings",
|
||||||
|
"The server log has the details.",
|
||||||
|
("/", "Try again"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut resp = Redirect::to(&url).into_response();
|
||||||
|
resp.headers_mut().append(
|
||||||
|
header::SET_COOKIE,
|
||||||
|
cookie_header(&session::set_cookie(
|
||||||
|
FLOW_COOKIE,
|
||||||
|
&flow.state,
|
||||||
|
session::FLOW_TTL,
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
resp
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn callback(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
Query(q): Query<HashMap<String, String>>,
|
||||||
|
) -> Result<Response, AppError> {
|
||||||
|
let Auth::Oidc(oc) = &st.cfg.auth else {
|
||||||
|
return Ok(Redirect::to("/").into_response());
|
||||||
|
};
|
||||||
|
if let Some(err) = q.get("error") {
|
||||||
|
let detail = q.get("error_description").cloned().unwrap_or_default();
|
||||||
|
warn!("login refused by the provider: {err} {detail}");
|
||||||
|
return Ok(message(
|
||||||
|
&st,
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"id.cnx.network did not sign you in",
|
||||||
|
&format!(
|
||||||
|
"It answered \u{201c}{err}\u{201d}{}. Only members of the group {} may open \
|
||||||
|
this site.",
|
||||||
|
if detail.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
format!(": {detail}")
|
||||||
|
},
|
||||||
|
oc.group
|
||||||
|
),
|
||||||
|
("/", "Try again"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let (Some(code), Some(state)) = (q.get("code"), q.get("state")) else {
|
||||||
|
return Ok(message(
|
||||||
|
&st,
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"Incomplete login answer",
|
||||||
|
"The address lacks the code or the state. Start again.",
|
||||||
|
("/", "Start again"),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
if session::cookie_value(&headers, FLOW_COOKIE).as_deref() != Some(state.as_str()) {
|
||||||
|
return Ok(message(
|
||||||
|
&st,
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"This login was started elsewhere",
|
||||||
|
"The login answer does not belong to this browser. Start again.",
|
||||||
|
("/", "Start again"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let (Some(flow), Some(provider)) = (st.flows.take(state), st.provider()) else {
|
||||||
|
return Ok(message(
|
||||||
|
&st,
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"The login took too long",
|
||||||
|
"Logins must finish within ten minutes. Start again.",
|
||||||
|
("/", "Start again"),
|
||||||
|
));
|
||||||
|
};
|
||||||
|
let redirect_uri = st.cfg.redirect_uri();
|
||||||
|
let exchange = oidc::Exchange {
|
||||||
|
client_id: &oc.client_id,
|
||||||
|
client_secret: &oc.client_secret,
|
||||||
|
redirect_uri: &redirect_uri,
|
||||||
|
code,
|
||||||
|
verifier: &flow.verifier,
|
||||||
|
nonce: &flow.nonce,
|
||||||
|
};
|
||||||
|
let identity = match oidc::finish(&st.http, &provider, &exchange, now()).await {
|
||||||
|
Ok(i) => i,
|
||||||
|
Err(e) => {
|
||||||
|
warn!("login failed: {e:#}");
|
||||||
|
return Ok(message(
|
||||||
|
&st,
|
||||||
|
StatusCode::BAD_GATEWAY,
|
||||||
|
"The login could not be finished",
|
||||||
|
"id.cnx.network's answer did not check out. The server log says why.",
|
||||||
|
("/", "Start again"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if !identity.in_group(&oc.group) {
|
||||||
|
warn!(
|
||||||
|
"{} signed in but is not in group {}",
|
||||||
|
identity.login, oc.group
|
||||||
|
);
|
||||||
|
return Ok(message(
|
||||||
|
&st,
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"No access",
|
||||||
|
&format!(
|
||||||
|
"You are signed in as {}, who is not in the group {}. Members are set in \
|
||||||
|
identity/people.nix of the fleet repository.",
|
||||||
|
identity.login, oc.group
|
||||||
|
),
|
||||||
|
("/signed-out", "OK"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
info!("{} signed in", identity.login);
|
||||||
|
let id = session::create(&st.db, &identity.login, &identity.name).await?;
|
||||||
|
audit::record(
|
||||||
|
&st.db,
|
||||||
|
&Entry {
|
||||||
|
actor: &identity.login,
|
||||||
|
action: Action::SignIn,
|
||||||
|
entity: Entity::Session,
|
||||||
|
entity_id: None,
|
||||||
|
person_id: None,
|
||||||
|
fields: &[],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let mut resp = Redirect::to(&flow.next).into_response();
|
||||||
|
let h = resp.headers_mut();
|
||||||
|
h.append(
|
||||||
|
header::SET_COOKIE,
|
||||||
|
cookie_header(&session::set_cookie(
|
||||||
|
SESSION_COOKIE,
|
||||||
|
&id,
|
||||||
|
session::SESSION_TTL,
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
h.append(
|
||||||
|
header::SET_COOKIE,
|
||||||
|
cookie_header(&session::clear_cookie(FLOW_COOKIE)),
|
||||||
|
);
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST only; the forms guard has checked the site and the token.
|
||||||
|
pub async fn logout(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Result<Response, AppError> {
|
||||||
|
if user.local {
|
||||||
|
return Ok(Redirect::to("/").into_response());
|
||||||
|
}
|
||||||
|
if let Some(id) = session::cookie_value(&headers, SESSION_COOKIE) {
|
||||||
|
session::remove(&st.db, &id).await?;
|
||||||
|
}
|
||||||
|
audit::record(
|
||||||
|
&st.db,
|
||||||
|
&Entry {
|
||||||
|
actor: &user.login,
|
||||||
|
action: Action::SignOut,
|
||||||
|
entity: Entity::Session,
|
||||||
|
entity_id: None,
|
||||||
|
person_id: None,
|
||||||
|
fields: &[],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let mut resp = Redirect::to("/signed-out").into_response();
|
||||||
|
resp.headers_mut().append(
|
||||||
|
header::SET_COOKIE,
|
||||||
|
cookie_header(&session::clear_cookie(SESSION_COOKIE)),
|
||||||
|
);
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn signed_out(State(st): State<Arc<AppState>>) -> Response {
|
||||||
|
message(
|
||||||
|
&st,
|
||||||
|
StatusCode::OK,
|
||||||
|
"Signed out",
|
||||||
|
"You are signed out of visa.buildfor.life. Your session at id.cnx.network stays open \
|
||||||
|
until you sign out there.",
|
||||||
|
("/", "Sign in again"),
|
||||||
|
)
|
||||||
|
}
|
||||||
+454
@@ -0,0 +1,454 @@
|
|||||||
|
//! The web side: state, routes, the login gate, form checks, rendering.
|
||||||
|
|
||||||
|
pub mod activity;
|
||||||
|
pub mod auth;
|
||||||
|
pub mod people;
|
||||||
|
|
||||||
|
use std::sync::{Arc, RwLock};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use axum::Router;
|
||||||
|
use axum::body::Body;
|
||||||
|
use axum::extract::{Path, Request, State};
|
||||||
|
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header};
|
||||||
|
use axum::middleware::{self, Next};
|
||||||
|
use axum::response::{Html, IntoResponse, Redirect, Response};
|
||||||
|
use axum::routing::{get, post};
|
||||||
|
use minijinja::{Environment, Value, context};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use tracing::{error, info, warn};
|
||||||
|
|
||||||
|
use crate::config::{Auth, Config};
|
||||||
|
use crate::session::{self, Flows, SESSION_COOKIE, User};
|
||||||
|
use crate::{VERSION, countries, dates, embedded, oidc};
|
||||||
|
|
||||||
|
pub struct AppState {
|
||||||
|
pub cfg: Config,
|
||||||
|
pub db: PgPool,
|
||||||
|
pub http: reqwest::Client,
|
||||||
|
templates: Environment<'static>,
|
||||||
|
pub flows: Flows,
|
||||||
|
provider: RwLock<Option<Arc<oidc::Provider>>>,
|
||||||
|
/// The form token of local development, which has no sessions.
|
||||||
|
local_csrf: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub fn new(cfg: Config, db: PgPool) -> anyhow::Result<Arc<AppState>> {
|
||||||
|
let http = reqwest::Client::builder()
|
||||||
|
.timeout(Duration::from_secs(15))
|
||||||
|
.connect_timeout(Duration::from_secs(5))
|
||||||
|
.user_agent(concat!("visa/", env!("CARGO_PKG_VERSION")))
|
||||||
|
.build()?;
|
||||||
|
Ok(Arc::new(AppState {
|
||||||
|
templates: templates()?,
|
||||||
|
cfg,
|
||||||
|
db,
|
||||||
|
http,
|
||||||
|
flows: Flows::default(),
|
||||||
|
provider: RwLock::new(None),
|
||||||
|
local_csrf: oidc::random_token(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The form token in local development (tests post with it).
|
||||||
|
pub fn local_csrf(&self) -> &str {
|
||||||
|
&self.local_csrf
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn provider(&self) -> Option<Arc<oidc::Provider>> {
|
||||||
|
self.provider
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_provider(&self, p: oidc::Provider) {
|
||||||
|
*self.provider.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(p));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn templates() -> anyhow::Result<Environment<'static>> {
|
||||||
|
let mut env = Environment::new();
|
||||||
|
for &(name, bytes) in embedded::TEMPLATES {
|
||||||
|
env.add_template(name, std::str::from_utf8(bytes)?)?;
|
||||||
|
}
|
||||||
|
env.add_filter("date", |v: Option<String>| -> String {
|
||||||
|
v.as_deref()
|
||||||
|
.and_then(dates::parse_date)
|
||||||
|
.map(dates::fmt_date)
|
||||||
|
.unwrap_or_default()
|
||||||
|
});
|
||||||
|
env.add_filter("country", |v: Option<String>| -> String {
|
||||||
|
let code = v.unwrap_or_default();
|
||||||
|
countries::name(&code).map(str::to_string).unwrap_or(code)
|
||||||
|
});
|
||||||
|
Ok(env)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The login provider's discovery, retried until Kanidm answers (it may
|
||||||
|
/// start after this service).
|
||||||
|
pub fn spawn_background(st: Arc<AppState>) {
|
||||||
|
let Auth::Oidc(o) = &st.cfg.auth else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let issuer = o.issuer.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut wait = Duration::from_secs(2);
|
||||||
|
loop {
|
||||||
|
match oidc::Provider::discover(&st.http, &issuer).await {
|
||||||
|
Ok(p) => {
|
||||||
|
info!("login provider ready: {}", p.issuer);
|
||||||
|
st.set_provider(p);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
warn!("login provider not reachable yet: {e:#}");
|
||||||
|
tokio::time::sleep(wait).await;
|
||||||
|
wait = (wait * 2).min(Duration::from_secs(60));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn router(st: Arc<AppState>) -> Router {
|
||||||
|
use people as p;
|
||||||
|
Router::new()
|
||||||
|
.route("/", get(|| async { Redirect::to("/people") }))
|
||||||
|
.route("/people", get(p::list).post(p::create))
|
||||||
|
.route("/people/new", get(p::new_form))
|
||||||
|
.route("/people/{id}", get(p::show).post(p::update))
|
||||||
|
.route("/people/{id}/edit", get(p::edit_form))
|
||||||
|
.route("/people/{id}/archive", post(p::archive))
|
||||||
|
.route("/people/{id}/restore", post(p::restore))
|
||||||
|
.route("/people/{id}/passports", post(p::passport_create))
|
||||||
|
.route("/people/{id}/passports/new", get(p::passport_new))
|
||||||
|
.route("/people/{id}/passports/{pid}", post(p::passport_update))
|
||||||
|
.route("/people/{id}/passports/{pid}/edit", get(p::passport_edit))
|
||||||
|
.route(
|
||||||
|
"/people/{id}/passports/{pid}/delete",
|
||||||
|
post(p::passport_delete),
|
||||||
|
)
|
||||||
|
.route("/people/{id}/addresses", post(p::address_create))
|
||||||
|
.route("/people/{id}/addresses/new", get(p::address_new))
|
||||||
|
.route("/people/{id}/addresses/{aid}", post(p::address_update))
|
||||||
|
.route("/people/{id}/addresses/{aid}/edit", get(p::address_edit))
|
||||||
|
.route(
|
||||||
|
"/people/{id}/addresses/{aid}/delete",
|
||||||
|
post(p::address_delete),
|
||||||
|
)
|
||||||
|
.route("/activity", get(activity::page))
|
||||||
|
.route("/login", get(auth::login))
|
||||||
|
.route("/auth/callback", get(auth::callback))
|
||||||
|
.route("/logout", post(auth::logout))
|
||||||
|
.route("/signed-out", get(auth::signed_out))
|
||||||
|
.route("/healthz", get(healthz))
|
||||||
|
.route("/static/{*path}", get(static_file))
|
||||||
|
.fallback(not_found)
|
||||||
|
.layer(middleware::from_fn_with_state(st.clone(), forms_guard))
|
||||||
|
.layer(middleware::from_fn_with_state(st.clone(), gate))
|
||||||
|
.layer(middleware::from_fn(security_headers))
|
||||||
|
.with_state(st)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Paths open without a session.
|
||||||
|
fn is_public(path: &str) -> bool {
|
||||||
|
matches!(
|
||||||
|
path,
|
||||||
|
"/healthz" | "/login" | "/auth/callback" | "/signed-out"
|
||||||
|
) || path.starts_with("/static/")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lets a request through with its user, or sends the browser to the login.
|
||||||
|
async fn gate(State(st): State<Arc<AppState>>, mut req: Request, next: Next) -> Response {
|
||||||
|
if is_public(req.uri().path()) {
|
||||||
|
return next.run(req).await;
|
||||||
|
}
|
||||||
|
let user = match &st.cfg.auth {
|
||||||
|
Auth::Disabled => Some(User::local(&st.local_csrf)),
|
||||||
|
Auth::Oidc(_) => match session::cookie_value(req.headers(), SESSION_COOKIE) {
|
||||||
|
Some(id) => match session::get(&st.db, &id).await {
|
||||||
|
Ok(u) => u,
|
||||||
|
Err(e) => return AppError(e).into_response(),
|
||||||
|
},
|
||||||
|
None => None,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if let Some(user) = user {
|
||||||
|
req.extensions_mut().insert(user);
|
||||||
|
return next.run(req).await;
|
||||||
|
}
|
||||||
|
let target = req
|
||||||
|
.uri()
|
||||||
|
.path_and_query()
|
||||||
|
.map(|p| p.as_str().to_string())
|
||||||
|
.unwrap_or_else(|| "/".into());
|
||||||
|
let login = format!("/login?next={}", percent_encode(&target));
|
||||||
|
if req.headers().contains_key("hx-request") {
|
||||||
|
let mut resp = StatusCode::OK.into_response();
|
||||||
|
if let Ok(v) = HeaderValue::from_str(&login) {
|
||||||
|
resp.headers_mut().insert("hx-redirect", v);
|
||||||
|
}
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
Redirect::to(&login).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The largest form body read; uploads (phase 4) get their own limit.
|
||||||
|
const FORM_LIMIT: usize = 256 * 1024;
|
||||||
|
|
||||||
|
/// Every request that changes something must come from this site and carry
|
||||||
|
/// the session's form token (`csrf` in the form, or `X-CSRF-Token`).
|
||||||
|
async fn forms_guard(State(st): State<Arc<AppState>>, req: Request, next: Next) -> Response {
|
||||||
|
if matches!(*req.method(), Method::GET | Method::HEAD | Method::OPTIONS) {
|
||||||
|
return next.run(req).await;
|
||||||
|
}
|
||||||
|
if !same_site(&st, req.headers()) {
|
||||||
|
warn!(
|
||||||
|
"refused a {} to {} from another site",
|
||||||
|
req.method(),
|
||||||
|
req.uri().path()
|
||||||
|
);
|
||||||
|
return message(
|
||||||
|
&st,
|
||||||
|
StatusCode::FORBIDDEN,
|
||||||
|
"Refused",
|
||||||
|
"This form was sent from another site. Open visa.buildfor.life and try again there.",
|
||||||
|
("/", "Open the app"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let Some(user) = req.extensions().get::<User>().cloned() else {
|
||||||
|
// public paths take no forms
|
||||||
|
return next.run(req).await;
|
||||||
|
};
|
||||||
|
let (parts, body) = req.into_parts();
|
||||||
|
let bytes = match axum::body::to_bytes(body, FORM_LIMIT).await {
|
||||||
|
Ok(b) => b,
|
||||||
|
Err(_) => {
|
||||||
|
return (StatusCode::PAYLOAD_TOO_LARGE, "The form is too large.").into_response();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let is_form = parts
|
||||||
|
.headers
|
||||||
|
.get(header::CONTENT_TYPE)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.is_some_and(|ct| ct.starts_with("application/x-www-form-urlencoded"));
|
||||||
|
let token = if is_form {
|
||||||
|
form_urlencoded::parse(&bytes)
|
||||||
|
.find(|(k, _)| k == "csrf")
|
||||||
|
.map(|(_, v)| v.into_owned())
|
||||||
|
} else {
|
||||||
|
parts
|
||||||
|
.headers
|
||||||
|
.get("x-csrf-token")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(str::to_string)
|
||||||
|
};
|
||||||
|
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"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
next.run(Request::from_parts(parts, Body::from(bytes)))
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
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",
|
||||||
|
None => {
|
||||||
|
headers.get(header::ORIGIN).and_then(|v| v.to_str().ok())
|
||||||
|
== Some(st.cfg.public_url.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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'",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
h.insert(
|
||||||
|
header::X_CONTENT_TYPE_OPTIONS,
|
||||||
|
HeaderValue::from_static("nosniff"),
|
||||||
|
);
|
||||||
|
h.insert(
|
||||||
|
header::REFERRER_POLICY,
|
||||||
|
HeaderValue::from_static("same-origin"),
|
||||||
|
);
|
||||||
|
h.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
|
||||||
|
h.insert(
|
||||||
|
HeaderName::from_static("x-robots-tag"),
|
||||||
|
HeaderValue::from_static("noindex, nofollow"),
|
||||||
|
);
|
||||||
|
h.insert(
|
||||||
|
HeaderName::from_static("permissions-policy"),
|
||||||
|
HeaderValue::from_static("camera=(), microphone=(), geolocation=()"),
|
||||||
|
);
|
||||||
|
resp
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn percent_encode(s: &str) -> String {
|
||||||
|
let mut out = String::with_capacity(s.len());
|
||||||
|
for b in s.bytes() {
|
||||||
|
match b {
|
||||||
|
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
|
||||||
|
out.push(b as char)
|
||||||
|
}
|
||||||
|
_ => out.push_str(&format!("%{b:02X}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Only paths on this site, and never back into the login itself.
|
||||||
|
pub fn safe_next(next: Option<&String>) -> String {
|
||||||
|
match next {
|
||||||
|
Some(n)
|
||||||
|
if n.starts_with('/')
|
||||||
|
&& !n.starts_with("//")
|
||||||
|
&& !n.contains('\\')
|
||||||
|
&& !n.starts_with("/login")
|
||||||
|
&& !n.starts_with("/auth/") =>
|
||||||
|
{
|
||||||
|
n.clone()
|
||||||
|
}
|
||||||
|
_ => "/".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render(st: &AppState, name: &str, ctx: Value, status: StatusCode) -> Response {
|
||||||
|
match st.templates.get_template(name).and_then(|t| t.render(ctx)) {
|
||||||
|
Ok(html) => (status, [(header::CACHE_CONTROL, "no-store")], Html(html)).into_response(),
|
||||||
|
Err(e) => {
|
||||||
|
error!("rendering {name}: {e:#}");
|
||||||
|
let body = if cfg!(debug_assertions) {
|
||||||
|
format!("could not render {name}: {e:#}")
|
||||||
|
} else {
|
||||||
|
"The page could not be shown; the server log has the details.".to_string()
|
||||||
|
};
|
||||||
|
(StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A page in the app's frame.
|
||||||
|
pub fn page(
|
||||||
|
st: &AppState,
|
||||||
|
user: &User,
|
||||||
|
name: &str,
|
||||||
|
title: &str,
|
||||||
|
nav: &str,
|
||||||
|
status: StatusCode,
|
||||||
|
ctx: Value,
|
||||||
|
) -> Response {
|
||||||
|
let full = context! {
|
||||||
|
title => title,
|
||||||
|
nav => nav,
|
||||||
|
user => user,
|
||||||
|
csrf => &user.csrf,
|
||||||
|
v => embedded::STATIC_HASH,
|
||||||
|
version => VERSION,
|
||||||
|
..ctx
|
||||||
|
};
|
||||||
|
render(st, name, full, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A page outside the frame: login problems, sign-out, refusals, not found.
|
||||||
|
pub fn message(
|
||||||
|
st: &AppState,
|
||||||
|
status: StatusCode,
|
||||||
|
title: &str,
|
||||||
|
text: &str,
|
||||||
|
link: (&str, &str),
|
||||||
|
) -> Response {
|
||||||
|
render(
|
||||||
|
st,
|
||||||
|
"message.html",
|
||||||
|
context! {
|
||||||
|
title => title,
|
||||||
|
text => text,
|
||||||
|
href => link.0,
|
||||||
|
link => link.1,
|
||||||
|
v => embedded::STATIC_HASH,
|
||||||
|
},
|
||||||
|
status,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn not_found_page(st: &AppState) -> Response {
|
||||||
|
message(
|
||||||
|
st,
|
||||||
|
StatusCode::NOT_FOUND,
|
||||||
|
"Not found",
|
||||||
|
"There is no page or record at this address.",
|
||||||
|
("/people", "Back to the people"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn not_found(State(st): State<Arc<AppState>>) -> Response {
|
||||||
|
not_found_page(&st)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn healthz(State(st): State<Arc<AppState>>) -> Response {
|
||||||
|
match sqlx::query_scalar::<_, i32>("SELECT 1")
|
||||||
|
.fetch_one(&st.db)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => "ok".into_response(),
|
||||||
|
Err(e) => {
|
||||||
|
warn!("health check: {e}");
|
||||||
|
(StatusCode::SERVICE_UNAVAILABLE, "database unreachable").into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn static_file(Path(path): Path<String>) -> Response {
|
||||||
|
match embedded::static_file(&path) {
|
||||||
|
Some(bytes) => (
|
||||||
|
[
|
||||||
|
(header::CONTENT_TYPE, embedded::content_type(&path)),
|
||||||
|
(header::CACHE_CONTROL, "public, max-age=86400"),
|
||||||
|
],
|
||||||
|
bytes,
|
||||||
|
)
|
||||||
|
.into_response(),
|
||||||
|
None => StatusCode::NOT_FOUND.into_response(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An unexpected failure: logged, and in debug builds its cause is in the
|
||||||
|
/// body so a test shows why.
|
||||||
|
pub struct AppError(pub anyhow::Error);
|
||||||
|
|
||||||
|
impl<E: Into<anyhow::Error>> From<E> for AppError {
|
||||||
|
fn from(e: E) -> Self {
|
||||||
|
AppError(e.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for AppError {
|
||||||
|
fn into_response(self) -> Response {
|
||||||
|
error!("{:#}", self.0);
|
||||||
|
let body = if cfg!(debug_assertions) {
|
||||||
|
format!("Internal error: {:#}", self.0)
|
||||||
|
} else {
|
||||||
|
"Something went wrong; the server log has the details.".to_string()
|
||||||
|
};
|
||||||
|
(StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type Res = Result<Response, AppError>;
|
||||||
@@ -0,0 +1,970 @@
|
|||||||
|
//! Pages for people, their passports and their addresses.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::extract::{Path, Query, State};
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::response::{IntoResponse, Redirect, Response};
|
||||||
|
use axum::{Extension, Form};
|
||||||
|
use chrono::NaiveDate;
|
||||||
|
use minijinja::context;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use super::{AppState, Res, not_found_page, page};
|
||||||
|
use crate::audit::{self, Action, Entity, Entry};
|
||||||
|
use crate::countries;
|
||||||
|
use crate::dates::{self, Status};
|
||||||
|
use crate::forms::{Errors, Fields, err, get};
|
||||||
|
use crate::mrz::{self, Mrz};
|
||||||
|
use crate::people::{
|
||||||
|
self, Address, AddressForm, AddressInput, PassportForm, PassportInput, Person, PersonForm,
|
||||||
|
PersonInput, SEXES, TITLES,
|
||||||
|
};
|
||||||
|
use crate::session::User;
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------- views
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct PersonView {
|
||||||
|
pub id: i64,
|
||||||
|
pub name: String,
|
||||||
|
pub surname: String,
|
||||||
|
pub given: String,
|
||||||
|
pub title: String,
|
||||||
|
pub sex: String,
|
||||||
|
pub dob: String,
|
||||||
|
pub age: Option<i32>,
|
||||||
|
pub place_of_birth: String,
|
||||||
|
pub nationality: String,
|
||||||
|
pub nationality_name: String,
|
||||||
|
pub occupation: String,
|
||||||
|
pub employer: String,
|
||||||
|
pub phone: String,
|
||||||
|
pub email: String,
|
||||||
|
pub notes: String,
|
||||||
|
pub archived: bool,
|
||||||
|
pub archived_on: String,
|
||||||
|
pub current_passport: String,
|
||||||
|
pub updated: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn person_view(p: &Person, current_passport: Option<&str>, today: NaiveDate) -> PersonView {
|
||||||
|
PersonView {
|
||||||
|
id: p.id,
|
||||||
|
name: p.display_name(),
|
||||||
|
surname: p.surname.to_uppercase(),
|
||||||
|
given: p.given_names(),
|
||||||
|
title: p.title.clone(),
|
||||||
|
sex: people::sex_label(&p.sex).to_string(),
|
||||||
|
dob: p.date_of_birth.map(dates::fmt_date).unwrap_or_default(),
|
||||||
|
age: p.date_of_birth.map(|d| dates::age(d, today)),
|
||||||
|
place_of_birth: p.place_of_birth.clone(),
|
||||||
|
nationality: p.nationality.clone(),
|
||||||
|
nationality_name: countries::name(&p.nationality)
|
||||||
|
.unwrap_or(&p.nationality)
|
||||||
|
.to_string(),
|
||||||
|
occupation: p.occupation.clone(),
|
||||||
|
employer: p.employer.clone(),
|
||||||
|
phone: p.phone.clone(),
|
||||||
|
email: p.email.clone(),
|
||||||
|
notes: p.notes.clone(),
|
||||||
|
archived: p.archived_at.is_some(),
|
||||||
|
archived_on: p
|
||||||
|
.archived_at
|
||||||
|
.map(|t| dates::fmt_date(t.with_timezone(&dates::bangkok()).date_naive()))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
current_passport: current_passport.unwrap_or_default().to_string(),
|
||||||
|
updated: dates::fmt_datetime(p.updated_at),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
struct PassportView {
|
||||||
|
id: i64,
|
||||||
|
number: String,
|
||||||
|
country: String,
|
||||||
|
country_name: String,
|
||||||
|
issued_on: String,
|
||||||
|
expires_on: String,
|
||||||
|
issued_at: String,
|
||||||
|
current: bool,
|
||||||
|
status: Option<Status>,
|
||||||
|
has_mrz: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
struct AddressView {
|
||||||
|
id: i64,
|
||||||
|
line: String,
|
||||||
|
current: bool,
|
||||||
|
moved_in_on: String,
|
||||||
|
moved_out_on: String,
|
||||||
|
house_master: String,
|
||||||
|
house_master_phone: String,
|
||||||
|
tm30_reported_on: String,
|
||||||
|
tm30_receipt_no: String,
|
||||||
|
tm30: Option<Status>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn address_view(a: &Address) -> AddressView {
|
||||||
|
let current = a.moved_out_on.is_none();
|
||||||
|
let tm30 = current.then(|| match a.tm30_reported_on {
|
||||||
|
Some(d) => Status {
|
||||||
|
level: "ok",
|
||||||
|
label: format!("TM.30 reported {}", dates::fmt_date(d)),
|
||||||
|
},
|
||||||
|
None => Status {
|
||||||
|
level: "warn",
|
||||||
|
label: "No TM.30 receipt recorded".into(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
let fmt = |d: Option<NaiveDate>| d.map(dates::fmt_date).unwrap_or_default();
|
||||||
|
AddressView {
|
||||||
|
id: a.id,
|
||||||
|
line: people::address_line(&AddressInput::from(a)),
|
||||||
|
current,
|
||||||
|
moved_in_on: fmt(a.moved_in_on),
|
||||||
|
moved_out_on: fmt(a.moved_out_on),
|
||||||
|
house_master: a.house_master.clone(),
|
||||||
|
house_master_phone: a.house_master_phone.clone(),
|
||||||
|
tm30_reported_on: fmt(a.tm30_reported_on),
|
||||||
|
tm30_receipt_no: a.tm30_receipt_no.clone(),
|
||||||
|
tm30,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The person with the number of their current passport, for the header
|
||||||
|
/// every page of the person shares.
|
||||||
|
async fn load_person(st: &AppState, id: i64) -> anyhow::Result<Option<(Person, PersonView)>> {
|
||||||
|
let Some(p) = people::get_person(&st.db, id).await? else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let pps = people::passports(&st.db, id).await?;
|
||||||
|
let view = person_view(&p, pps.first().map(|x| x.number.as_str()), dates::today());
|
||||||
|
Ok(Some((p, view)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn select_lists() -> minijinja::Value {
|
||||||
|
context! {
|
||||||
|
titles => TITLES,
|
||||||
|
sexes => SEXES,
|
||||||
|
countries => countries::options(),
|
||||||
|
provinces => countries::PROVINCES,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status_for(errors: &Errors) -> StatusCode {
|
||||||
|
if errors.is_empty() {
|
||||||
|
StatusCode::OK
|
||||||
|
} else {
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn log<'a>(
|
||||||
|
user: &'a User,
|
||||||
|
action: Action,
|
||||||
|
entity: Entity,
|
||||||
|
id: i64,
|
||||||
|
person: i64,
|
||||||
|
fields: &'a [String],
|
||||||
|
) -> Entry<'a> {
|
||||||
|
Entry {
|
||||||
|
actor: &user.login,
|
||||||
|
action,
|
||||||
|
entity,
|
||||||
|
entity_id: Some(id),
|
||||||
|
person_id: Some(person),
|
||||||
|
fields,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the zone typed into a form; a text that is no zone becomes a
|
||||||
|
/// field error.
|
||||||
|
fn read_zone(text: &str, today: NaiveDate, errors: &mut Errors) -> Option<Mrz> {
|
||||||
|
if text.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
match mrz::parse(text, today) {
|
||||||
|
Ok(m) => Some(m),
|
||||||
|
Err(msg) => {
|
||||||
|
err(errors, "mrz", msg);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn zone_note(m: &Mrz, errors: &mut Errors) -> Option<String> {
|
||||||
|
if m.all_ok() {
|
||||||
|
Some("Filled in from the machine-readable zone; every check digit matches.".into())
|
||||||
|
} else {
|
||||||
|
err(
|
||||||
|
errors,
|
||||||
|
"mrz",
|
||||||
|
format!(
|
||||||
|
"Filled in, but the check digits do not match for: {}. Compare the lines with \
|
||||||
|
the passport.",
|
||||||
|
m.failed().join(", ")
|
||||||
|
),
|
||||||
|
);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ the list
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct ListQuery {
|
||||||
|
#[serde(default)]
|
||||||
|
archived: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Query(q): Query<ListQuery>,
|
||||||
|
) -> Res {
|
||||||
|
let archived = q.archived.as_deref() == Some("1");
|
||||||
|
let rows = people::list(&st.db, archived, dates::today()).await?;
|
||||||
|
let (n_active, n_archived) = people::counts(&st.db).await?;
|
||||||
|
Ok(page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
"people.html",
|
||||||
|
if archived {
|
||||||
|
"Archived people"
|
||||||
|
} else {
|
||||||
|
"People"
|
||||||
|
},
|
||||||
|
"people",
|
||||||
|
StatusCode::OK,
|
||||||
|
context! { people => rows, archived, n_active, n_archived },
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------- one person
|
||||||
|
|
||||||
|
pub async fn show(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path(id): Path<i64>,
|
||||||
|
) -> Res {
|
||||||
|
let Some((_, view)) = load_person(&st, id).await? else {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
};
|
||||||
|
let today = dates::today();
|
||||||
|
let passports: Vec<PassportView> = people::passports(&st.db, id)
|
||||||
|
.await?
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, p)| PassportView {
|
||||||
|
id: p.id,
|
||||||
|
number: p.number.clone(),
|
||||||
|
country: p.issuing_country.clone(),
|
||||||
|
country_name: countries::name(&p.issuing_country)
|
||||||
|
.unwrap_or(&p.issuing_country)
|
||||||
|
.to_string(),
|
||||||
|
issued_on: p.issued_on.map(dates::fmt_date).unwrap_or_default(),
|
||||||
|
expires_on: dates::fmt_date(p.expires_on),
|
||||||
|
issued_at: p.issued_at.clone(),
|
||||||
|
current: i == 0,
|
||||||
|
status: (i == 0).then(|| dates::passport_status(p.expires_on, today)),
|
||||||
|
has_mrz: !p.mrz.is_empty(),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let addresses: Vec<AddressView> = people::addresses(&st.db, id)
|
||||||
|
.await?
|
||||||
|
.iter()
|
||||||
|
.map(address_view)
|
||||||
|
.collect();
|
||||||
|
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
|
||||||
|
let recent = audit::recent(&st.db, Some(id), 6).await?;
|
||||||
|
let title = view.name.clone();
|
||||||
|
Ok(page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
"person.html",
|
||||||
|
&title,
|
||||||
|
"people",
|
||||||
|
StatusCode::OK,
|
||||||
|
context! { p => view, passports, addresses, recent },
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn person_form_page(
|
||||||
|
st: &AppState,
|
||||||
|
user: &User,
|
||||||
|
p: Option<&PersonView>,
|
||||||
|
f: &PersonForm,
|
||||||
|
pf: &PassportForm,
|
||||||
|
errors: &Errors,
|
||||||
|
mrz_note: Option<String>,
|
||||||
|
status: StatusCode,
|
||||||
|
) -> Response {
|
||||||
|
let (title, mode, action) = match p {
|
||||||
|
Some(p) => (
|
||||||
|
format!("Edit {}", p.name),
|
||||||
|
"edit",
|
||||||
|
format!("/people/{}", p.id),
|
||||||
|
),
|
||||||
|
None => ("New person".to_string(), "new", "/people".to_string()),
|
||||||
|
};
|
||||||
|
page(
|
||||||
|
st,
|
||||||
|
user,
|
||||||
|
"person_form.html",
|
||||||
|
&title,
|
||||||
|
"people",
|
||||||
|
status,
|
||||||
|
context! { p, f, pf, errors, mrz_note, mode, action, ..select_lists() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn new_form(State(st): State<Arc<AppState>>, Extension(user): Extension<User>) -> Res {
|
||||||
|
Ok(person_form_page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
None,
|
||||||
|
&PersonForm::default(),
|
||||||
|
&PassportForm::default(),
|
||||||
|
&Errors::new(),
|
||||||
|
None,
|
||||||
|
StatusCode::OK,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Form(f): Form<Fields>,
|
||||||
|
) -> Res {
|
||||||
|
let today = dates::today();
|
||||||
|
let mut pf = PersonForm::from_fields(&f);
|
||||||
|
let mut ppf = PassportForm::from_fields(&f);
|
||||||
|
let mut errors = Errors::new();
|
||||||
|
let zone = read_zone(&ppf.mrz, today, &mut errors);
|
||||||
|
|
||||||
|
if get(&f, "action") == "read-mrz" {
|
||||||
|
let mut note = None;
|
||||||
|
match &zone {
|
||||||
|
Some(m) => {
|
||||||
|
pf.take_mrz(m, true);
|
||||||
|
ppf.take_mrz(m, true);
|
||||||
|
note = zone_note(m, &mut errors);
|
||||||
|
}
|
||||||
|
None if ppf.mrz.is_empty() => {
|
||||||
|
err(&mut errors, "mrz", "Paste the two lines first.");
|
||||||
|
}
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
let status = status_for(&errors);
|
||||||
|
return Ok(person_form_page(
|
||||||
|
&st, &user, None, &pf, &ppf, &errors, note, status,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(m) = &zone {
|
||||||
|
pf.take_mrz(m, false);
|
||||||
|
ppf.take_mrz(m, false);
|
||||||
|
}
|
||||||
|
let person = pf.validate(today);
|
||||||
|
let passport = (!ppf.is_blank()).then(|| ppf.validate(zone.as_ref()));
|
||||||
|
for e in [
|
||||||
|
person.as_ref().err(),
|
||||||
|
passport.as_ref().and_then(|p| p.as_ref().err()),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
{
|
||||||
|
for (k, v) in e {
|
||||||
|
err(&mut errors, k, v.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (Ok(person), true) = (person, errors.is_empty()) else {
|
||||||
|
return Ok(person_form_page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
None,
|
||||||
|
&pf,
|
||||||
|
&ppf,
|
||||||
|
&errors,
|
||||||
|
None,
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
));
|
||||||
|
};
|
||||||
|
let passport: Option<PassportInput> = passport.and_then(Result::ok);
|
||||||
|
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
if let Some(pp) = &passport
|
||||||
|
&& people::passport_taken(&mut tx, pp, None).await?
|
||||||
|
{
|
||||||
|
err(
|
||||||
|
&mut errors,
|
||||||
|
"number",
|
||||||
|
"A passport with this number from this country is already recorded.",
|
||||||
|
);
|
||||||
|
return Ok(person_form_page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
None,
|
||||||
|
&pf,
|
||||||
|
&ppf,
|
||||||
|
&errors,
|
||||||
|
None,
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let id = people::create_person(&mut tx, &person).await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(&user, Action::Create, Entity::Person, id, id, &[]),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
if let Some(pp) = &passport {
|
||||||
|
let pid = people::create_passport(&mut tx, id, pp).await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(&user, Action::Create, Entity::Passport, pid, id, &[]),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Redirect::to(&format!("/people/{id}")).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn edit_form(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path(id): Path<i64>,
|
||||||
|
) -> Res {
|
||||||
|
let Some((p, view)) = load_person(&st, id).await? else {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
};
|
||||||
|
audit::viewed(&st.db, &user.login, Entity::Person, id, id).await?;
|
||||||
|
Ok(person_form_page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
Some(&view),
|
||||||
|
&PersonForm::from_person(&p),
|
||||||
|
&PassportForm::default(),
|
||||||
|
&Errors::new(),
|
||||||
|
None,
|
||||||
|
StatusCode::OK,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path(id): Path<i64>,
|
||||||
|
Form(f): Form<Fields>,
|
||||||
|
) -> Res {
|
||||||
|
let Some((_, view)) = load_person(&st, id).await? else {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
};
|
||||||
|
let pf = PersonForm::from_fields(&f);
|
||||||
|
let input = match pf.validate(dates::today()) {
|
||||||
|
Ok(i) => i,
|
||||||
|
Err(errors) => {
|
||||||
|
return Ok(person_form_page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
Some(&view),
|
||||||
|
&pf,
|
||||||
|
&PassportForm::default(),
|
||||||
|
&errors,
|
||||||
|
None,
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
let Some(old) = people::get_person_in(&mut tx, id).await? else {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
};
|
||||||
|
let changed = input.changed_from(&PersonInput::from(&old));
|
||||||
|
if !changed.is_empty() {
|
||||||
|
people::update_person(&mut tx, id, &input).await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(&user, Action::Update, Entity::Person, id, id, &changed),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Redirect::to(&format!("/people/{id}")).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_archived(st: &AppState, user: &User, id: i64, archived: bool) -> Res {
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
if people::get_person_in(&mut tx, id).await?.is_none() {
|
||||||
|
return Ok(not_found_page(st));
|
||||||
|
}
|
||||||
|
if people::set_archived(&mut tx, id, archived).await? {
|
||||||
|
let action = if archived {
|
||||||
|
Action::Archive
|
||||||
|
} else {
|
||||||
|
Action::Restore
|
||||||
|
};
|
||||||
|
audit::record(&mut *tx, &log(user, action, Entity::Person, id, id, &[])).await?;
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Redirect::to(&format!("/people/{id}")).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn archive(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path(id): Path<i64>,
|
||||||
|
) -> Res {
|
||||||
|
set_archived(&st, &user, id, true).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn restore(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path(id): Path<i64>,
|
||||||
|
) -> Res {
|
||||||
|
set_archived(&st, &user, id, false).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ passports
|
||||||
|
|
||||||
|
/// What reading the zone found: the check digits matched, or the names
|
||||||
|
/// differ from the record's.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Notes {
|
||||||
|
mrz_note: Option<String>,
|
||||||
|
name_hint: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn passport_form_page(
|
||||||
|
st: &AppState,
|
||||||
|
user: &User,
|
||||||
|
p: &PersonView,
|
||||||
|
passport_id: Option<i64>,
|
||||||
|
pf: &PassportForm,
|
||||||
|
errors: &Errors,
|
||||||
|
notes: Notes,
|
||||||
|
status: StatusCode,
|
||||||
|
) -> Response {
|
||||||
|
let Notes {
|
||||||
|
mrz_note,
|
||||||
|
name_hint,
|
||||||
|
} = notes;
|
||||||
|
let (title, mode, action) = match passport_id {
|
||||||
|
Some(pid) => (
|
||||||
|
"Edit passport",
|
||||||
|
"edit",
|
||||||
|
format!("/people/{}/passports/{pid}", p.id),
|
||||||
|
),
|
||||||
|
None => ("New passport", "new", format!("/people/{}/passports", p.id)),
|
||||||
|
};
|
||||||
|
page(
|
||||||
|
st,
|
||||||
|
user,
|
||||||
|
"passport_form.html",
|
||||||
|
&format!("{title}: {}", p.name),
|
||||||
|
"people",
|
||||||
|
status,
|
||||||
|
context! { p, pf, errors, mrz_note, name_hint, mode, action, heading => title, ..select_lists() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn passport_new(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path(id): Path<i64>,
|
||||||
|
) -> Res {
|
||||||
|
let Some((p, view)) = load_person(&st, id).await? else {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
};
|
||||||
|
// a new passport is usually from the same country as the last one
|
||||||
|
let pf = PassportForm {
|
||||||
|
issuing_country: p.nationality.clone(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
Ok(passport_form_page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
&view,
|
||||||
|
None,
|
||||||
|
&pf,
|
||||||
|
&Errors::new(),
|
||||||
|
Notes::default(),
|
||||||
|
StatusCode::OK,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The names in the zone against the record's, as a hint (transliteration
|
||||||
|
/// and long names make them differ legitimately).
|
||||||
|
fn name_hint(m: &Mrz, p: &Person) -> Option<String> {
|
||||||
|
let record = format!("{} {}", p.surname, p.given_names()).to_uppercase();
|
||||||
|
let zone = format!("{} {}", m.surname, m.given_names);
|
||||||
|
(record.split_whitespace().collect::<Vec<_>>() != zone.split_whitespace().collect::<Vec<_>>())
|
||||||
|
.then(|| {
|
||||||
|
format!(
|
||||||
|
"The zone names {}, {}; the record says {}. Check that this is the right person.",
|
||||||
|
m.surname,
|
||||||
|
m.given_names,
|
||||||
|
p.display_name()
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn passport_save(
|
||||||
|
st: &AppState,
|
||||||
|
user: &User,
|
||||||
|
id: i64,
|
||||||
|
passport_id: Option<i64>,
|
||||||
|
f: &Fields,
|
||||||
|
) -> Res {
|
||||||
|
let Some((person, view)) = load_person(st, id).await? else {
|
||||||
|
return Ok(not_found_page(st));
|
||||||
|
};
|
||||||
|
if let Some(pid) = passport_id
|
||||||
|
&& people::passport(&st.db, id, pid).await?.is_none()
|
||||||
|
{
|
||||||
|
return Ok(not_found_page(st));
|
||||||
|
}
|
||||||
|
let today = dates::today();
|
||||||
|
let mut pf = PassportForm::from_fields(f);
|
||||||
|
let mut errors = Errors::new();
|
||||||
|
let zone = read_zone(&pf.mrz, today, &mut errors);
|
||||||
|
let mut notes = Notes::default();
|
||||||
|
|
||||||
|
if get(f, "action") == "read-mrz" {
|
||||||
|
match &zone {
|
||||||
|
Some(m) => {
|
||||||
|
pf.take_mrz(m, true);
|
||||||
|
notes.mrz_note = zone_note(m, &mut errors);
|
||||||
|
notes.name_hint = name_hint(m, &person);
|
||||||
|
}
|
||||||
|
None if pf.mrz.is_empty() => err(&mut errors, "mrz", "Paste the two lines first."),
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
let status = status_for(&errors);
|
||||||
|
return Ok(passport_form_page(
|
||||||
|
st,
|
||||||
|
user,
|
||||||
|
&view,
|
||||||
|
passport_id,
|
||||||
|
&pf,
|
||||||
|
&errors,
|
||||||
|
notes,
|
||||||
|
status,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(m) = &zone {
|
||||||
|
pf.take_mrz(m, false);
|
||||||
|
}
|
||||||
|
let input = match pf.validate(zone.as_ref()) {
|
||||||
|
Ok(i) if errors.is_empty() => i,
|
||||||
|
Ok(_) => {
|
||||||
|
return Ok(passport_form_page(
|
||||||
|
st,
|
||||||
|
user,
|
||||||
|
&view,
|
||||||
|
passport_id,
|
||||||
|
&pf,
|
||||||
|
&errors,
|
||||||
|
notes,
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
for (k, v) in e {
|
||||||
|
err(&mut errors, &k, v);
|
||||||
|
}
|
||||||
|
return Ok(passport_form_page(
|
||||||
|
st,
|
||||||
|
user,
|
||||||
|
&view,
|
||||||
|
passport_id,
|
||||||
|
&pf,
|
||||||
|
&errors,
|
||||||
|
notes,
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
if people::passport_taken(&mut tx, &input, passport_id).await? {
|
||||||
|
err(
|
||||||
|
&mut errors,
|
||||||
|
"number",
|
||||||
|
"A passport with this number from this country is already recorded.",
|
||||||
|
);
|
||||||
|
return Ok(passport_form_page(
|
||||||
|
st,
|
||||||
|
user,
|
||||||
|
&view,
|
||||||
|
passport_id,
|
||||||
|
&pf,
|
||||||
|
&errors,
|
||||||
|
notes,
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
match passport_id {
|
||||||
|
None => {
|
||||||
|
let pid = people::create_passport(&mut tx, id, &input).await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(user, Action::Create, Entity::Passport, pid, id, &[]),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
Some(pid) => {
|
||||||
|
let old = people::passport(&st.db, id, pid)
|
||||||
|
.await?
|
||||||
|
.map(|p| PassportInput::from(&p));
|
||||||
|
let changed = old.map(|o| input.changed_from(&o)).unwrap_or_default();
|
||||||
|
if !changed.is_empty() {
|
||||||
|
people::update_passport(&mut tx, pid, &input).await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(user, Action::Update, Entity::Passport, pid, id, &changed),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Redirect::to(&format!("/people/{id}#passports")).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn passport_create(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path(id): Path<i64>,
|
||||||
|
Form(f): Form<Fields>,
|
||||||
|
) -> Res {
|
||||||
|
passport_save(&st, &user, id, None, &f).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn passport_edit(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path((id, pid)): Path<(i64, i64)>,
|
||||||
|
) -> Res {
|
||||||
|
let Some((_, view)) = load_person(&st, id).await? else {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
};
|
||||||
|
let Some(pp) = people::passport(&st.db, id, pid).await? else {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
};
|
||||||
|
audit::viewed(&st.db, &user.login, Entity::Passport, pid, id).await?;
|
||||||
|
Ok(passport_form_page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
&view,
|
||||||
|
Some(pid),
|
||||||
|
&PassportForm::from_passport(&pp),
|
||||||
|
&Errors::new(),
|
||||||
|
Notes::default(),
|
||||||
|
StatusCode::OK,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn passport_update(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path((id, pid)): Path<(i64, i64)>,
|
||||||
|
Form(f): Form<Fields>,
|
||||||
|
) -> Res {
|
||||||
|
passport_save(&st, &user, id, Some(pid), &f).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn passport_delete(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path((id, pid)): Path<(i64, i64)>,
|
||||||
|
) -> Res {
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
if !people::delete_passport(&mut tx, id, pid).await? {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
}
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(&user, Action::Delete, Entity::Passport, pid, id, &[]),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Redirect::to(&format!("/people/{id}#passports")).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ addresses
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn address_form_page(
|
||||||
|
st: &AppState,
|
||||||
|
user: &User,
|
||||||
|
p: &PersonView,
|
||||||
|
address_id: Option<i64>,
|
||||||
|
af: &AddressForm,
|
||||||
|
errors: &Errors,
|
||||||
|
status: StatusCode,
|
||||||
|
) -> Response {
|
||||||
|
let (heading, mode, action) = match address_id {
|
||||||
|
Some(aid) => (
|
||||||
|
"Edit address",
|
||||||
|
"edit",
|
||||||
|
format!("/people/{}/addresses/{aid}", p.id),
|
||||||
|
),
|
||||||
|
None => ("New address", "new", format!("/people/{}/addresses", p.id)),
|
||||||
|
};
|
||||||
|
page(
|
||||||
|
st,
|
||||||
|
user,
|
||||||
|
"address_form.html",
|
||||||
|
&format!("{heading}: {}", p.name),
|
||||||
|
"people",
|
||||||
|
status,
|
||||||
|
context! { p, af, errors, mode, action, heading, ..select_lists() },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn address_new(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path(id): Path<i64>,
|
||||||
|
) -> Res {
|
||||||
|
let Some((_, view)) = load_person(&st, id).await? else {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
};
|
||||||
|
let af = AddressForm {
|
||||||
|
province: "Chiang Mai".into(),
|
||||||
|
moved_in_on: dates::today().to_string(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
Ok(address_form_page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
&view,
|
||||||
|
None,
|
||||||
|
&af,
|
||||||
|
&Errors::new(),
|
||||||
|
StatusCode::OK,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn address_save(
|
||||||
|
st: &AppState,
|
||||||
|
user: &User,
|
||||||
|
id: i64,
|
||||||
|
address_id: Option<i64>,
|
||||||
|
f: &Fields,
|
||||||
|
) -> Res {
|
||||||
|
let Some((_, view)) = load_person(st, id).await? else {
|
||||||
|
return Ok(not_found_page(st));
|
||||||
|
};
|
||||||
|
let old = match address_id {
|
||||||
|
Some(aid) => match people::address(&st.db, id, aid).await? {
|
||||||
|
Some(a) => Some(AddressInput::from(&a)),
|
||||||
|
None => return Ok(not_found_page(st)),
|
||||||
|
},
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
let af = AddressForm::from_fields(f);
|
||||||
|
let input = match af.validate(dates::today()) {
|
||||||
|
Ok(i) => i,
|
||||||
|
Err(errors) => {
|
||||||
|
return Ok(address_form_page(
|
||||||
|
st,
|
||||||
|
user,
|
||||||
|
&view,
|
||||||
|
address_id,
|
||||||
|
&af,
|
||||||
|
&errors,
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
match (address_id, old) {
|
||||||
|
(Some(aid), Some(old)) => {
|
||||||
|
let changed = input.changed_from(&old);
|
||||||
|
if !changed.is_empty() {
|
||||||
|
people::update_address(&mut tx, aid, &input).await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(user, Action::Update, Entity::Address, aid, id, &changed),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let aid = people::create_address(&mut tx, id, &input).await?;
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(user, Action::Create, Entity::Address, aid, id, &[]),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Redirect::to(&format!("/people/{id}#addresses")).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn address_create(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path(id): Path<i64>,
|
||||||
|
Form(f): Form<Fields>,
|
||||||
|
) -> Res {
|
||||||
|
address_save(&st, &user, id, None, &f).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn address_edit(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path((id, aid)): Path<(i64, i64)>,
|
||||||
|
) -> Res {
|
||||||
|
let Some((_, view)) = load_person(&st, id).await? else {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
};
|
||||||
|
let Some(a) = people::address(&st.db, id, aid).await? else {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
};
|
||||||
|
audit::viewed(&st.db, &user.login, Entity::Address, aid, id).await?;
|
||||||
|
Ok(address_form_page(
|
||||||
|
&st,
|
||||||
|
&user,
|
||||||
|
&view,
|
||||||
|
Some(aid),
|
||||||
|
&AddressForm::from_address(&a),
|
||||||
|
&Errors::new(),
|
||||||
|
StatusCode::OK,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn address_update(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path((id, aid)): Path<(i64, i64)>,
|
||||||
|
Form(f): Form<Fields>,
|
||||||
|
) -> Res {
|
||||||
|
address_save(&st, &user, id, Some(aid), &f).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn address_delete(
|
||||||
|
State(st): State<Arc<AppState>>,
|
||||||
|
Extension(user): Extension<User>,
|
||||||
|
Path((id, aid)): Path<(i64, i64)>,
|
||||||
|
) -> Res {
|
||||||
|
let mut tx = st.db.begin().await?;
|
||||||
|
if !people::delete_address(&mut tx, id, aid).await? {
|
||||||
|
return Ok(not_found_page(&st));
|
||||||
|
}
|
||||||
|
audit::record(
|
||||||
|
&mut *tx,
|
||||||
|
&log(&user, Action::Delete, Entity::Address, aid, id, &[]),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(Redirect::to(&format!("/people/{id}#addresses")).into_response())
|
||||||
|
}
|
||||||
+721
@@ -0,0 +1,721 @@
|
|||||||
|
/* visa.buildfor.life: the buildfor.life colors, navy #071323 and gold
|
||||||
|
#f5c000, with tints of both. Status colors (--ok, --warn, --bad) appear
|
||||||
|
only on chips and notes that carry a text label. No inline styles: the
|
||||||
|
Content Security Policy allows none. */
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--bg: #071323;
|
||||||
|
--panel: #0d1d33;
|
||||||
|
--panel2: #12284a;
|
||||||
|
--line: rgba(229, 236, 245, 0.12);
|
||||||
|
--stroke: rgba(229, 236, 245, 0.24);
|
||||||
|
--field: #0a182c;
|
||||||
|
--fg: #e6ebf2;
|
||||||
|
--hd: #ffffff;
|
||||||
|
--mute: #9ba8ba;
|
||||||
|
--accent: #f5c000;
|
||||||
|
--accent-s: rgba(245, 192, 0, 0.14);
|
||||||
|
--on-accent: #071323;
|
||||||
|
--link: #f5c000;
|
||||||
|
--ok: #4cc38a;
|
||||||
|
--ok-s: rgba(76, 195, 138, 0.15);
|
||||||
|
--warn: #ffb547;
|
||||||
|
--warn-s: rgba(255, 181, 71, 0.15);
|
||||||
|
--bad: #ff7a7a;
|
||||||
|
--bad-s: rgba(255, 107, 107, 0.15);
|
||||||
|
--shadow: 0 1px 2px rgba(0, 0, 0, 0.35);
|
||||||
|
--mono: ui-monospace, "Cascadia Mono", Consolas, "SF Mono", monospace;
|
||||||
|
--side: 220px;
|
||||||
|
--toph: 56px;
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
html[data-theme="light"] {
|
||||||
|
--bg: #f4f6f9;
|
||||||
|
--panel: #ffffff;
|
||||||
|
--panel2: #eef2f7;
|
||||||
|
--line: #e1e6ee;
|
||||||
|
--stroke: #c4ccd8;
|
||||||
|
--field: #ffffff;
|
||||||
|
--fg: #13202f;
|
||||||
|
--hd: #071323;
|
||||||
|
--mute: #566375;
|
||||||
|
--accent-s: rgba(245, 192, 0, 0.2);
|
||||||
|
--link: #0b3a78;
|
||||||
|
--ok: #17784a;
|
||||||
|
--ok-s: #e2f2e9;
|
||||||
|
--warn: #8f5300;
|
||||||
|
--warn-s: #fdf0d5;
|
||||||
|
--bad: #b42318;
|
||||||
|
--bad-s: #fce8e6;
|
||||||
|
--shadow: 0 1px 2px rgba(7, 19, 35, 0.06);
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
|
||||||
|
[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--fg);
|
||||||
|
font:
|
||||||
|
15px/1.5 system-ui,
|
||||||
|
-apple-system,
|
||||||
|
"Segoe UI",
|
||||||
|
Roboto,
|
||||||
|
"Helvetica Neue",
|
||||||
|
"Noto Sans Thai",
|
||||||
|
Tahoma,
|
||||||
|
sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
}
|
||||||
|
a {
|
||||||
|
color: var(--link);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
a:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
html[data-theme="light"] main p a,
|
||||||
|
html[data-theme="light"] main dd a {
|
||||||
|
text-decoration: underline;
|
||||||
|
text-underline-offset: 2px;
|
||||||
|
}
|
||||||
|
:focus-visible {
|
||||||
|
outline: 2px solid var(--accent);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3 {
|
||||||
|
color: var(--hd);
|
||||||
|
line-height: 1.25;
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
font-size: 24px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
h1 a {
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
h2 {
|
||||||
|
font-size: 16px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.muted {
|
||||||
|
color: var(--mute);
|
||||||
|
}
|
||||||
|
.small {
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.mono {
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
font-size: 0.94em;
|
||||||
|
}
|
||||||
|
.strong {
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
.sub {
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--mute);
|
||||||
|
}
|
||||||
|
.pre {
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- top bar */
|
||||||
|
.top {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 20;
|
||||||
|
height: var(--toph);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 0 20px;
|
||||||
|
background: #071323;
|
||||||
|
border-bottom: 1px solid rgba(245, 192, 0, 0.35);
|
||||||
|
}
|
||||||
|
.brand {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
color: #ffffff;
|
||||||
|
}
|
||||||
|
.brand:hover {
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.mark {
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
.brand .nm {
|
||||||
|
font-weight: 800;
|
||||||
|
font-size: 17px;
|
||||||
|
letter-spacing: 0.01em;
|
||||||
|
}
|
||||||
|
.brand .sub {
|
||||||
|
color: #f5c000;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.1em;
|
||||||
|
}
|
||||||
|
.ib {
|
||||||
|
width: 34px;
|
||||||
|
height: 34px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.28);
|
||||||
|
background: transparent;
|
||||||
|
color: #ffffff;
|
||||||
|
font-size: 16px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.ib:hover {
|
||||||
|
border-color: #f5c000;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- frame */
|
||||||
|
.app {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: var(--side) minmax(0, 1fr);
|
||||||
|
min-height: calc(100vh - var(--toph));
|
||||||
|
}
|
||||||
|
.side {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 18px;
|
||||||
|
padding: 18px 12px;
|
||||||
|
background: var(--panel);
|
||||||
|
border-right: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.nav {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
.nav a {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border-radius: 8px;
|
||||||
|
color: var(--fg);
|
||||||
|
font-weight: 560;
|
||||||
|
}
|
||||||
|
.nav a:hover {
|
||||||
|
background: var(--panel2);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.nav a.on {
|
||||||
|
background: var(--accent-s);
|
||||||
|
color: var(--hd);
|
||||||
|
box-shadow: inset 3px 0 0 var(--accent);
|
||||||
|
}
|
||||||
|
.who {
|
||||||
|
margin-top: auto;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--mute);
|
||||||
|
padding: 0 12px;
|
||||||
|
}
|
||||||
|
.who .k {
|
||||||
|
display: block;
|
||||||
|
font-size: 11px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
}
|
||||||
|
.who b {
|
||||||
|
display: block;
|
||||||
|
color: var(--hd);
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.who p {
|
||||||
|
margin: 2px 0 10px;
|
||||||
|
}
|
||||||
|
main {
|
||||||
|
padding: 24px 28px 40px;
|
||||||
|
min-width: 0;
|
||||||
|
max-width: 1200px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.ft {
|
||||||
|
margin-top: 28px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--mute);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- page heads */
|
||||||
|
.crumbs {
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--mute);
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
.pagehead {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
.pagehead .actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.phead {
|
||||||
|
margin-bottom: 18px;
|
||||||
|
padding-bottom: 14px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.phead .pagehead {
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
.meta {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--mute);
|
||||||
|
}
|
||||||
|
.meta .sep {
|
||||||
|
margin: 0 6px;
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- buttons */
|
||||||
|
.btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 8px 14px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid var(--stroke);
|
||||||
|
background: var(--panel);
|
||||||
|
color: var(--fg);
|
||||||
|
font: inherit;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.2;
|
||||||
|
cursor: pointer;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.btn:hover {
|
||||||
|
border-color: var(--accent);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.btn.pri {
|
||||||
|
background: var(--accent);
|
||||||
|
border-color: var(--accent);
|
||||||
|
color: var(--on-accent);
|
||||||
|
}
|
||||||
|
.btn.pri:hover {
|
||||||
|
filter: brightness(1.06);
|
||||||
|
}
|
||||||
|
.btn.sm {
|
||||||
|
padding: 5px 10px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.btn.ghost {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
.btn.danger {
|
||||||
|
color: var(--bad);
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
.btn.danger:hover {
|
||||||
|
border-color: var(--bad);
|
||||||
|
background: var(--bad-s);
|
||||||
|
}
|
||||||
|
.inline-form {
|
||||||
|
display: inline;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
/* the first submit button of a form with two actions: Enter saves */
|
||||||
|
.default-submit {
|
||||||
|
position: absolute;
|
||||||
|
left: -9999px;
|
||||||
|
width: 1px;
|
||||||
|
height: 1px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- cards */
|
||||||
|
.card {
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 18px 20px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.card > header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.card.flush {
|
||||||
|
padding: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.cols {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 16px;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.cols > .card {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
.cols .span2 {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
}
|
||||||
|
@media (max-width: 1060px) {
|
||||||
|
.cols {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.kv {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 150px minmax(0, 1fr);
|
||||||
|
gap: 6px 14px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.kv dt {
|
||||||
|
color: var(--mute);
|
||||||
|
font-size: 13px;
|
||||||
|
padding-top: 1px;
|
||||||
|
}
|
||||||
|
.kv dd {
|
||||||
|
margin: 0;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chip {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 1px 9px;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
background: var(--panel2);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.chip.ok {
|
||||||
|
background: var(--ok-s);
|
||||||
|
color: var(--ok);
|
||||||
|
border-color: transparent;
|
||||||
|
}
|
||||||
|
.chip.warn {
|
||||||
|
background: var(--warn-s);
|
||||||
|
color: var(--warn);
|
||||||
|
border-color: transparent;
|
||||||
|
}
|
||||||
|
.chip.bad {
|
||||||
|
background: var(--bad-s);
|
||||||
|
color: var(--bad);
|
||||||
|
border-color: transparent;
|
||||||
|
}
|
||||||
|
.tag {
|
||||||
|
display: inline-block;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
padding: 1px 7px;
|
||||||
|
border-radius: 5px;
|
||||||
|
background: var(--accent-s);
|
||||||
|
color: var(--hd);
|
||||||
|
}
|
||||||
|
.tag.plain {
|
||||||
|
background: var(--panel2);
|
||||||
|
color: var(--mute);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- notes */
|
||||||
|
.notice {
|
||||||
|
padding: 10px 14px;
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--panel2);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
margin: 0 0 14px;
|
||||||
|
}
|
||||||
|
.notice.warn {
|
||||||
|
background: var(--warn-s);
|
||||||
|
border-color: transparent;
|
||||||
|
}
|
||||||
|
.notice.ok {
|
||||||
|
background: var(--ok-s);
|
||||||
|
border-color: transparent;
|
||||||
|
}
|
||||||
|
.okline {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--ok);
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.hintline {
|
||||||
|
margin: 8px 0 0;
|
||||||
|
color: var(--warn);
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- tables */
|
||||||
|
.toolbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.toolbar .filter {
|
||||||
|
flex: 1 1 240px;
|
||||||
|
max-width: 440px;
|
||||||
|
}
|
||||||
|
.tblwrap {
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
.tbl {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
}
|
||||||
|
.tbl th {
|
||||||
|
text-align: left;
|
||||||
|
font-size: 11.5px;
|
||||||
|
font-weight: 700;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.05em;
|
||||||
|
color: var(--mute);
|
||||||
|
background: var(--panel2);
|
||||||
|
padding: 9px 14px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.tbl td {
|
||||||
|
padding: 10px 14px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
vertical-align: top;
|
||||||
|
}
|
||||||
|
.tbl tbody tr:last-child td {
|
||||||
|
border-bottom: 0;
|
||||||
|
}
|
||||||
|
.tbl tbody tr:hover {
|
||||||
|
background: var(--panel2);
|
||||||
|
}
|
||||||
|
.filter-empty {
|
||||||
|
margin: 0;
|
||||||
|
padding: 14px;
|
||||||
|
color: var(--mute);
|
||||||
|
}
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.tbl .hs {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
.tbl th,
|
||||||
|
.tbl td {
|
||||||
|
padding: 9px 10px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- record lists inside cards */
|
||||||
|
.item {
|
||||||
|
padding: 12px 0;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.item:first-of-type {
|
||||||
|
border-top: 0;
|
||||||
|
padding-top: 0;
|
||||||
|
}
|
||||||
|
.item.old {
|
||||||
|
opacity: 0.78;
|
||||||
|
}
|
||||||
|
.item .row {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
.rowactions {
|
||||||
|
display: flex;
|
||||||
|
gap: 14px;
|
||||||
|
font-size: 13px;
|
||||||
|
margin-top: 6px;
|
||||||
|
}
|
||||||
|
.empty-inline {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--mute);
|
||||||
|
}
|
||||||
|
.addr {
|
||||||
|
margin: 0 0 8px;
|
||||||
|
}
|
||||||
|
.log {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.log li {
|
||||||
|
display: flex;
|
||||||
|
gap: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
padding: 6px 0;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.log li:first-child {
|
||||||
|
border-top: 0;
|
||||||
|
}
|
||||||
|
.log .when {
|
||||||
|
color: var(--mute);
|
||||||
|
min-width: 140px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- forms */
|
||||||
|
.form .grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 14px 16px;
|
||||||
|
}
|
||||||
|
.form .wide {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
}
|
||||||
|
@media (max-width: 700px) {
|
||||||
|
.form .grid {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.field label {
|
||||||
|
display: block;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 650;
|
||||||
|
color: var(--hd);
|
||||||
|
margin-bottom: 4px;
|
||||||
|
}
|
||||||
|
input,
|
||||||
|
select,
|
||||||
|
textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 8px 10px;
|
||||||
|
border: 1px solid var(--stroke);
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--field);
|
||||||
|
color: var(--fg);
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
input:focus,
|
||||||
|
select:focus,
|
||||||
|
textarea:focus {
|
||||||
|
outline: 2px solid var(--accent);
|
||||||
|
outline-offset: 0;
|
||||||
|
border-color: var(--accent);
|
||||||
|
}
|
||||||
|
.field.has-err input,
|
||||||
|
.field.has-err select,
|
||||||
|
.field.has-err textarea {
|
||||||
|
border-color: var(--bad);
|
||||||
|
}
|
||||||
|
textarea {
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
textarea.mrz {
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 15px;
|
||||||
|
letter-spacing: 0.05em;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
.hint {
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--mute);
|
||||||
|
margin: 4px 0 0;
|
||||||
|
}
|
||||||
|
.lead {
|
||||||
|
margin: -4px 0 12px;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.err {
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--bad);
|
||||||
|
margin: 4px 0 0;
|
||||||
|
}
|
||||||
|
.req {
|
||||||
|
color: var(--bad);
|
||||||
|
}
|
||||||
|
.formactions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
.dangerzone {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-top: 22px;
|
||||||
|
padding-top: 14px;
|
||||||
|
border-top: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- a page outside the frame */
|
||||||
|
.solo {
|
||||||
|
max-width: 560px;
|
||||||
|
margin: 64px auto;
|
||||||
|
padding: 0 16px;
|
||||||
|
}
|
||||||
|
.solo .eyebrow {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--mute);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---- phones */
|
||||||
|
@media (max-width: 860px) {
|
||||||
|
.app {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
.side {
|
||||||
|
flex-direction: row;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 8px 12px;
|
||||||
|
border-right: 0;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.nav {
|
||||||
|
flex-direction: row;
|
||||||
|
}
|
||||||
|
.who {
|
||||||
|
margin: 0 0 0 auto;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.who .k,
|
||||||
|
.who b,
|
||||||
|
.who p {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
main {
|
||||||
|
padding: 16px 14px 32px;
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
padding: 14px;
|
||||||
|
}
|
||||||
|
.kv {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
.kv dt {
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
// Theme switch, the list filter and delete confirmations. Event delegation
|
||||||
|
// and no inline handlers: the Content Security Policy allows no inline script.
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
// ---- theme: <html data-theme="light|dark">, kept in localStorage
|
||||||
|
document.addEventListener("click", function (ev) {
|
||||||
|
var b = ev.target.closest && ev.target.closest("#themeBtn");
|
||||||
|
if (!b) return;
|
||||||
|
var root = document.documentElement;
|
||||||
|
var next = root.getAttribute("data-theme") === "light" ? "dark" : "light";
|
||||||
|
root.setAttribute("data-theme", next);
|
||||||
|
try {
|
||||||
|
localStorage.setItem("visa-theme", next);
|
||||||
|
} catch (e) {
|
||||||
|
/* storage blocked */
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- forms with data-confirm ask first (archive, delete)
|
||||||
|
document.addEventListener("submit", function (ev) {
|
||||||
|
var f = ev.target;
|
||||||
|
var msg = f && f.getAttribute && f.getAttribute("data-confirm");
|
||||||
|
if (msg && !window.confirm(msg)) ev.preventDefault();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- filter: rows carry data-q (lower case); "/" focuses the box
|
||||||
|
function applyFilter() {
|
||||||
|
var box = document.getElementById("q");
|
||||||
|
if (!box) return;
|
||||||
|
var q = box.value.trim().toLowerCase();
|
||||||
|
var rows = document.querySelectorAll("[data-q]");
|
||||||
|
var shown = 0;
|
||||||
|
rows.forEach(function (el) {
|
||||||
|
var hit = q === "" || el.getAttribute("data-q").indexOf(q) !== -1;
|
||||||
|
el.hidden = !hit;
|
||||||
|
if (hit) shown++;
|
||||||
|
});
|
||||||
|
document.querySelectorAll("[data-filter-empty]").forEach(function (el) {
|
||||||
|
el.hidden = q === "" || rows.length === 0 || shown > 0;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
document.addEventListener("input", function (ev) {
|
||||||
|
if (ev.target && ev.target.id === "q") applyFilter();
|
||||||
|
});
|
||||||
|
document.addEventListener("keydown", function (ev) {
|
||||||
|
var box = document.getElementById("q");
|
||||||
|
if (!box) return;
|
||||||
|
var tag = document.activeElement ? document.activeElement.tagName : "";
|
||||||
|
if (ev.key === "/" && !/^(INPUT|TEXTAREA|SELECT)$/.test(tag)) {
|
||||||
|
ev.preventDefault();
|
||||||
|
box.focus();
|
||||||
|
} else if (ev.key === "Escape" && document.activeElement === box) {
|
||||||
|
box.value = "";
|
||||||
|
applyFilter();
|
||||||
|
box.blur();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
document.addEventListener("DOMContentLoaded", applyFilter);
|
||||||
|
})();
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect x="1" y="1" width="62" height="62" rx="14" fill="#071323" stroke="#f5c000" stroke-opacity=".6" stroke-width="2"/><text x="32" y="41" text-anchor="middle" font-family="Montserrat, 'Arial Black', 'Segoe UI', sans-serif" font-weight="900" font-size="24" letter-spacing="1"><tspan fill="#ffffff">B4</tspan><tspan fill="#f5c000">L</tspan></text></svg>
|
||||||
|
After Width: | Height: | Size: 413 B |
@@ -0,0 +1,19 @@
|
|||||||
|
// Applies the theme before the first paint: <html data-theme="light|dark">.
|
||||||
|
// An external file because the CSP allows no inline scripts. The choice
|
||||||
|
// lives in localStorage; without one the device's setting decides.
|
||||||
|
(function () {
|
||||||
|
var t = null;
|
||||||
|
try {
|
||||||
|
t = localStorage.getItem("visa-theme");
|
||||||
|
} catch (e) {
|
||||||
|
/* storage blocked */
|
||||||
|
}
|
||||||
|
if (t !== "light" && t !== "dark") {
|
||||||
|
t =
|
||||||
|
window.matchMedia &&
|
||||||
|
window.matchMedia("(prefers-color-scheme: light)").matches
|
||||||
|
? "light"
|
||||||
|
: "dark";
|
||||||
|
}
|
||||||
|
document.documentElement.setAttribute("data-theme", t);
|
||||||
|
})();
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
{#- Form fields. Every field has a label, its error under it and the
|
||||||
|
error tied to the input for screen readers. -#}
|
||||||
|
|
||||||
|
{% macro text(name, label, value="", err="", hint="", req=false, type="text", list="", auto="off", cls="", ph="") -%}
|
||||||
|
<div class="field{% if err %} has-err{% endif %}{% if cls %} {{ cls }}{% endif %}">
|
||||||
|
<label for="f-{{ name }}">{{ label }}{% if req %} <span class="req" aria-hidden="true">*</span>{% endif %}</label>
|
||||||
|
<input id="f-{{ name }}" name="{{ name }}" type="{{ type }}" value="{{ value }}"{% if req %} required{% endif %}{% if list %} list="{{ list }}"{% endif %} autocomplete="{{ auto }}"{% if ph %} placeholder="{{ ph }}"{% endif %}{% if err %} aria-invalid="true" aria-describedby="e-{{ name }}"{% elif hint %} aria-describedby="h-{{ name }}"{% endif %}>
|
||||||
|
{%- if hint %}
|
||||||
|
<p class="hint" id="h-{{ name }}">{{ hint }}</p>
|
||||||
|
{%- endif %}
|
||||||
|
{%- if err %}
|
||||||
|
<p class="err" id="e-{{ name }}">{{ err }}</p>
|
||||||
|
{%- endif %}
|
||||||
|
</div>
|
||||||
|
{%- endmacro %}
|
||||||
|
|
||||||
|
{% macro select(name, label, value, options, err="", hint="", blank="Not recorded", cls="") -%}
|
||||||
|
<div class="field{% if err %} has-err{% endif %}{% if cls %} {{ cls }}{% endif %}">
|
||||||
|
<label for="f-{{ name }}">{{ label }}</label>
|
||||||
|
<select id="f-{{ name }}" name="{{ name }}"{% if err %} aria-invalid="true" aria-describedby="e-{{ name }}"{% endif %}>
|
||||||
|
<option value="">{{ blank }}</option>
|
||||||
|
{%- for o in options %}
|
||||||
|
<option value="{{ o[0] }}"{% if o[0] == value %} selected{% endif %}>{{ o[1] }}</option>
|
||||||
|
{%- endfor %}
|
||||||
|
</select>
|
||||||
|
{%- if hint %}
|
||||||
|
<p class="hint">{{ hint }}</p>
|
||||||
|
{%- endif %}
|
||||||
|
{%- if err %}
|
||||||
|
<p class="err" id="e-{{ name }}">{{ err }}</p>
|
||||||
|
{%- endif %}
|
||||||
|
</div>
|
||||||
|
{%- endmacro %}
|
||||||
|
|
||||||
|
{% macro area(name, label, value="", err="", hint="", rows=3, cls="", fcls="") -%}
|
||||||
|
<div class="field{% if err %} has-err{% endif %}{% if fcls %} {{ fcls }}{% endif %}">
|
||||||
|
<label for="f-{{ name }}">{{ label }}</label>
|
||||||
|
<textarea id="f-{{ name }}" name="{{ name }}" rows="{{ rows }}"{% if cls %} class="{{ cls }}"{% endif %} spellcheck="false"{% if err %} aria-invalid="true" aria-describedby="e-{{ name }}"{% endif %}>{{ value }}</textarea>
|
||||||
|
{%- if hint %}
|
||||||
|
<p class="hint">{{ hint }}</p>
|
||||||
|
{%- endif %}
|
||||||
|
{%- if err %}
|
||||||
|
<p class="err" id="e-{{ name }}">{{ err }}</p>
|
||||||
|
{%- endif %}
|
||||||
|
</div>
|
||||||
|
{%- endmacro %}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg class="mark" viewBox="0 0 64 64" aria-hidden="true"><rect x="1" y="1" width="62" height="62" rx="14" fill="#0d2240" stroke="#f5c000" stroke-opacity=".6" stroke-width="2"/><text x="32" y="41" text-anchor="middle" font-family="Montserrat, 'Arial Black', 'Segoe UI', sans-serif" font-weight="900" font-size="24" letter-spacing="1"><tspan fill="#ffffff">B4</tspan><tspan fill="#f5c000">L</tspan></text></svg>
|
||||||
|
After Width: | Height: | Size: 410 B |
@@ -0,0 +1,23 @@
|
|||||||
|
{#- The head of every page about one person: the same place on each. -#}
|
||||||
|
<div class="phead">
|
||||||
|
<div class="crumbs"><a href="/people">People</a></div>
|
||||||
|
<div class="pagehead">
|
||||||
|
<h1><a href="/people/{{ p.id }}">{{ p.name }}</a></h1>
|
||||||
|
<div class="actions">
|
||||||
|
{% if p.archived %}
|
||||||
|
<form method="post" action="/people/{{ p.id }}/restore" class="inline-form"><input type="hidden" name="csrf" value="{{ csrf }}"><button type="submit" class="btn sm">Restore</button></form>
|
||||||
|
{% else %}
|
||||||
|
<form method="post" action="/people/{{ p.id }}/archive" class="inline-form" data-confirm="Archive {{ p.name }}? The record stays and can be restored."><input type="hidden" name="csrf" value="{{ csrf }}"><button type="submit" class="btn sm ghost">Archive</button></form>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="meta">
|
||||||
|
{%- if p.nationality_name %}{{ p.nationality_name }}{% else %}Nationality not recorded{% endif %}
|
||||||
|
{%- if p.age is not none %}<span class="sep">·</span>{{ p.age }} years{% endif %}
|
||||||
|
{%- if p.current_passport %}<span class="sep">·</span>passport <span class="mono">{{ p.current_passport }}</span>{% endif %}
|
||||||
|
{%- if p.employer %}<span class="sep">·</span>{{ p.employer }}{% endif %}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{% if p.archived %}
|
||||||
|
<div class="notice warn">Archived on {{ p.archived_on }}. Archived people are left out of the list; Restore brings the record back.</div>
|
||||||
|
{% endif %}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block main %}
|
||||||
|
<div class="pagehead">
|
||||||
|
<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>
|
||||||
|
{% if items %}
|
||||||
|
<div class="card flush">
|
||||||
|
<div class="tblwrap">
|
||||||
|
<table class="tbl" id="activity">
|
||||||
|
<thead><tr><th>When</th><th>Who</th><th>Did</th><th>Record</th><th class="hs">Fields</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for e in items %}
|
||||||
|
<tr>
|
||||||
|
<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>{% else %}<span class="muted">{{ e.what }}</span>{% endif %}</td>
|
||||||
|
<td class="hs muted">{{ e.fields }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="card"><p class="empty-inline">Nothing has happened yet.</p></div>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% import "_fields.html" as fm %}
|
||||||
|
{% block main %}
|
||||||
|
{% include "_person_head.html" %}
|
||||||
|
<form method="post" action="{{ action }}" class="form" id="address-form">
|
||||||
|
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||||
|
<section class="card">
|
||||||
|
<header><h2>{{ heading }}</h2></header>
|
||||||
|
<p class="hint lead">In the order Thai forms use. Leave out what the address does not have.</p>
|
||||||
|
<div class="grid">
|
||||||
|
{{ fm.text("house_no", "House number", af.house_no, err=errors.house_no, ph="99/9") }}
|
||||||
|
{{ fm.text("moo", "Moo (village number)", af.moo, err=errors.moo) }}
|
||||||
|
{{ fm.text("building", "Village, building or condominium", af.building, err=errors.building, hint="With the room number, if any.", cls="wide") }}
|
||||||
|
{{ fm.text("soi", "Soi", af.soi, err=errors.soi) }}
|
||||||
|
{{ fm.text("road", "Road", af.road, err=errors.road) }}
|
||||||
|
{{ fm.text("subdistrict", "Subdistrict (tambon)", af.subdistrict, err=errors.subdistrict) }}
|
||||||
|
{{ fm.text("district", "District (amphoe)", af.district, err=errors.district, req=true) }}
|
||||||
|
{{ fm.text("province", "Province", af.province, err=errors.province, req=true, list="provinces") }}
|
||||||
|
{{ fm.text("postal_code", "Postal code", af.postal_code, err=errors.postal_code) }}
|
||||||
|
{{ fm.text("moved_in_on", "Moved in on", af.moved_in_on, err=errors.moved_in_on, type="date") }}
|
||||||
|
{{ fm.text("moved_out_on", "Moved out on", af.moved_out_on, err=errors.moved_out_on, type="date", hint="Empty while the person lives here.") }}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section class="card">
|
||||||
|
<header><h2>House master and TM.30</h2></header>
|
||||||
|
<p class="hint lead">The owner or landlord reports the person's address on form TM.30 within 24 hours of arrival, also after every trip abroad. Extensions of stay and 90-day reports ask for the receipt.</p>
|
||||||
|
<div class="grid">
|
||||||
|
{{ fm.text("house_master", "House master", af.house_master, err=errors.house_master, hint="The owner or landlord who files TM.30.") }}
|
||||||
|
{{ fm.text("house_master_phone", "House master's phone", af.house_master_phone, err=errors.house_master_phone, type="tel") }}
|
||||||
|
{{ fm.text("tm30_reported_on", "TM.30 reported on", af.tm30_reported_on, err=errors.tm30_reported_on, type="date") }}
|
||||||
|
{{ fm.text("tm30_receipt_no", "TM.30 receipt number", af.tm30_receipt_no, err=errors.tm30_receipt_no) }}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div class="formactions">
|
||||||
|
<button type="submit" class="btn pri" id="save">Save</button>
|
||||||
|
<a class="btn ghost" href="/people/{{ p.id }}#addresses">Cancel</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<datalist id="provinces">{% for pv in provinces %}<option value="{{ pv }}"></option>{% endfor %}</datalist>
|
||||||
|
{% if mode == "edit" %}
|
||||||
|
<form method="post" action="{{ action }}/delete" class="dangerzone" data-confirm="Delete this address from the record?">
|
||||||
|
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||||
|
<button type="submit" class="btn sm danger">Delete this address</button>
|
||||||
|
<span class="muted small">For an address entered by mistake. When the person moves, set the move-out date instead and add the new address.</span>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="robots" content="noindex,nofollow">
|
||||||
|
<title>{{ title }} · visa.buildfor.life</title>
|
||||||
|
<script src="/static/theme-init.js?v={{ v }}"></script>
|
||||||
|
<link rel="icon" href="/static/favicon.svg?v={{ v }}" type="image/svg+xml">
|
||||||
|
<link rel="stylesheet" href="/static/app.css?v={{ v }}">
|
||||||
|
<script src="/static/app.js?v={{ v }}" defer></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="top">
|
||||||
|
<a class="brand" href="/people" aria-label="visa.buildfor.life, the people">
|
||||||
|
{% include "_mark.html" %}
|
||||||
|
<span class="nm">Visa</span><span class="sub">buildfor.life</span>
|
||||||
|
</a>
|
||||||
|
<button type="button" class="ib" id="themeBtn" aria-label="Switch between light and dark" title="Switch between light and dark">◐</button>
|
||||||
|
</header>
|
||||||
|
<div class="app">
|
||||||
|
<aside class="side">
|
||||||
|
<nav class="nav" aria-label="Sections">
|
||||||
|
<a href="/people"{% if nav == "people" %} class="on" aria-current="page"{% endif %}>People</a>
|
||||||
|
<a href="/activity"{% if nav == "activity" %} class="on" aria-current="page"{% endif %}>Activity</a>
|
||||||
|
</nav>
|
||||||
|
<div class="who">
|
||||||
|
{% if user.local %}
|
||||||
|
<span class="k">Local development</span>
|
||||||
|
<b>No login</b>
|
||||||
|
<p>VISA_INSECURE_NO_LOGIN is set; this only runs on a loopback address.</p>
|
||||||
|
{% else %}
|
||||||
|
<span class="k">Signed in as</span>
|
||||||
|
<b>{{ user.name }}</b>
|
||||||
|
<p>{{ user.login }} at id.cnx.network</p>
|
||||||
|
<form method="post" action="/logout" class="inline-form"><input type="hidden" name="csrf" value="{{ csrf }}"><button type="submit" class="btn sm ghost">Sign out</button></form>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
<main id="main">
|
||||||
|
{% block main %}{% endblock %}
|
||||||
|
<footer class="ft">visa.buildfor.life {{ version }}. Every view and change of a person's record is written to the Activity log. Dates are in Chiang Mai time.</footer>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="robots" content="noindex,nofollow">
|
||||||
|
<title>{{ title }} · visa.buildfor.life</title>
|
||||||
|
<script src="/static/theme-init.js?v={{ v }}"></script>
|
||||||
|
<link rel="icon" href="/static/favicon.svg?v={{ v }}" type="image/svg+xml">
|
||||||
|
<link rel="stylesheet" href="/static/app.css?v={{ v }}">
|
||||||
|
<script src="/static/app.js?v={{ v }}" defer></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="top">
|
||||||
|
<a class="brand" href="/">{% include "_mark.html" %}<span class="nm">Visa</span><span class="sub">buildfor.life</span></a>
|
||||||
|
<button type="button" class="ib" id="themeBtn" aria-label="Switch between light and dark" title="Switch between light and dark">◐</button>
|
||||||
|
</header>
|
||||||
|
<main class="solo">
|
||||||
|
<div class="card">
|
||||||
|
<div class="eyebrow">visa.buildfor.life</div>
|
||||||
|
<h1>{{ title }}</h1>
|
||||||
|
<p>{{ text }}</p>
|
||||||
|
<p><a class="btn pri" href="{{ href }}">{{ link }}</a></p>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% import "_fields.html" as fm %}
|
||||||
|
{% block main %}
|
||||||
|
{% include "_person_head.html" %}
|
||||||
|
<form method="post" action="{{ action }}" class="form" id="passport-form">
|
||||||
|
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||||
|
<button type="submit" name="action" value="save" class="default-submit" tabindex="-1" aria-hidden="true">Save</button>
|
||||||
|
<section class="card" id="mrz-card">
|
||||||
|
<header><h2>{{ heading }}</h2></header>
|
||||||
|
<p class="hint lead">Type or paste the two lines at the bottom of the photo page and press Read to fill in the fields below.</p>
|
||||||
|
{{ fm.area("mrz", "Machine-readable zone, two lines of 44 characters", pf.mrz, err=errors.mrz, rows=2, cls="mrz") }}
|
||||||
|
<div class="formactions">
|
||||||
|
<button type="submit" name="action" value="read-mrz" class="btn" id="read-mrz" formnovalidate>Read</button>
|
||||||
|
{% if mrz_note %}<p class="okline" role="status">{{ mrz_note }}</p>{% endif %}
|
||||||
|
</div>
|
||||||
|
{% if name_hint %}<p class="hintline" role="status">{{ name_hint }}</p>{% endif %}
|
||||||
|
</section>
|
||||||
|
<section class="card">
|
||||||
|
<header><h2>Passport</h2></header>
|
||||||
|
<div class="grid">
|
||||||
|
{{ fm.text("number", "Passport number", pf.number, err=errors.number, req=true) }}
|
||||||
|
{{ fm.select("issuing_country", "Issued by", pf.issuing_country, countries, err=errors.issuing_country, blank="Choose a country") }}
|
||||||
|
{{ fm.text("issued_on", "Date of issue", pf.issued_on, err=errors.issued_on, type="date") }}
|
||||||
|
{{ fm.text("expires_on", "Date of expiry", pf.expires_on, err=errors.expires_on, type="date", req=true) }}
|
||||||
|
{{ fm.text("issued_at", "Authority or place of issue", pf.issued_at, err=errors.issued_at, hint="As printed in the passport.", cls="wide") }}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<div class="formactions">
|
||||||
|
<button type="submit" name="action" value="save" class="btn pri" id="save">Save</button>
|
||||||
|
<a class="btn ghost" href="/people/{{ p.id }}#passports">Cancel</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{% if mode == "edit" %}
|
||||||
|
<form method="post" action="{{ action }}/delete" class="dangerzone" data-confirm="Delete this passport from the record?">
|
||||||
|
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||||
|
<button type="submit" class="btn sm danger">Delete this passport</button>
|
||||||
|
<span class="muted small">For a passport entered by mistake. An expired passport stays on the record as a previous one.</span>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block main %}
|
||||||
|
<div class="pagehead">
|
||||||
|
<h1>{% if archived %}Archived people{% else %}People{% endif %}</h1>
|
||||||
|
<div class="actions"><a class="btn pri" href="/people/new" id="new-person">+ New person</a></div>
|
||||||
|
</div>
|
||||||
|
{% if people or n_archived %}
|
||||||
|
<div class="toolbar">
|
||||||
|
{% if people %}<input type="search" id="q" class="filter" placeholder="Filter by name, passport, nationality or employer ( / )" aria-label="Filter the list" autocomplete="off">{% endif %}
|
||||||
|
{% if archived %}<a href="/people">Back to the {{ n_active }} in the list</a>{% elif n_archived %}<a href="/people?archived=1">Archived ({{ n_archived }})</a>{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% if people %}
|
||||||
|
<div class="card flush">
|
||||||
|
<div class="tblwrap">
|
||||||
|
<table class="tbl" id="people">
|
||||||
|
<thead>
|
||||||
|
<tr><th>Name</th><th class="hs">Nationality</th><th>Passport</th><th>Valid until</th><th class="hs">Lives in</th><th class="hs">Employer</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in people %}
|
||||||
|
<tr data-q="{{ r.q }}">
|
||||||
|
<td><a class="strong" href="/people/{{ r.id }}">{{ r.name }}</a>{% if r.age is not none %}<div class="sub">{{ r.age }} years</div>{% endif %}</td>
|
||||||
|
<td class="hs">{{ r.nationality }}</td>
|
||||||
|
<td>{% if r.passport_number %}<span class="mono">{{ r.passport_number }}</span>{% else %}<span class="muted">none recorded</span>{% endif %}</td>
|
||||||
|
<td>{% if r.passport_status %}{{ r.passport_expires }}<div><span class="chip {{ r.passport_status.level }}">{{ r.passport_status.label }}</span></div>{% endif %}</td>
|
||||||
|
<td class="hs">{{ r.province }}</td>
|
||||||
|
<td class="hs">{{ r.employer }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<p class="filter-empty" data-filter-empty hidden>No one in the list matches the filter.</p>
|
||||||
|
</div>
|
||||||
|
{% elif archived %}
|
||||||
|
<div class="card"><p class="empty-inline">No one is archived.</p></div>
|
||||||
|
{% else %}
|
||||||
|
<div class="card">
|
||||||
|
<h2>No people yet</h2>
|
||||||
|
<p>Add the first person with <b>+ New person</b>. Paste the two lines at the bottom of the passport's photo page there, and the form fills in the name, nationality, date of birth and the passport itself.</p>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% block main %}
|
||||||
|
{% include "_person_head.html" %}
|
||||||
|
<div class="cols">
|
||||||
|
<section class="card" id="details">
|
||||||
|
<header><h2>Personal details</h2><a class="btn sm" href="/people/{{ p.id }}/edit">Edit</a></header>
|
||||||
|
<dl class="kv">
|
||||||
|
<dt>Surname</dt><dd>{{ p.surname }}</dd>
|
||||||
|
<dt>Given names</dt><dd>{{ p.given }}</dd>
|
||||||
|
{% if p.title %}<dt>Title</dt><dd>{{ p.title }}</dd>{% endif %}
|
||||||
|
<dt>Sex</dt><dd>{% if p.sex %}{{ p.sex }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||||
|
<dt>Date of birth</dt><dd>{% if p.dob %}{{ p.dob }} <span class="muted">({{ p.age }} years)</span>{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||||
|
<dt>Place of birth</dt><dd>{% if p.place_of_birth %}{{ p.place_of_birth }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||||
|
<dt>Nationality</dt><dd>{% if p.nationality %}{{ p.nationality_name }} <span class="muted mono">{{ p.nationality }}</span>{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||||
|
<dt>Occupation</dt><dd>{% if p.occupation %}{{ p.occupation }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||||
|
<dt>Employer</dt><dd>{% if p.employer %}{{ p.employer }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||||
|
<dt>Phone</dt><dd>{% if p.phone %}{{ p.phone }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||||
|
<dt>Email</dt><dd>{% if p.email %}{{ p.email }}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||||
|
{% if p.notes %}<dt>Notes</dt><dd class="pre">{{ p.notes }}</dd>{% endif %}
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card" id="passports">
|
||||||
|
<header><h2>Passport</h2><a class="btn sm" href="/people/{{ p.id }}/passports/new">+ New passport</a></header>
|
||||||
|
{% for pp in passports %}
|
||||||
|
<div class="item{% if not pp.current %} old{% endif %}">
|
||||||
|
<div class="row">
|
||||||
|
<span class="mono strong">{{ pp.number }}</span>
|
||||||
|
<span class="muted">{{ pp.country_name }}</span>
|
||||||
|
{% if pp.current %}<span class="tag">current</span>{% else %}<span class="tag plain">previous</span>{% endif %}
|
||||||
|
</div>
|
||||||
|
<dl class="kv">
|
||||||
|
<dt>Issued</dt><dd>{% if pp.issued_on %}{{ pp.issued_on }}{% else %}<span class="muted">date not recorded</span>{% endif %}{% if pp.issued_at %}, {{ pp.issued_at }}{% endif %}</dd>
|
||||||
|
<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>
|
||||||
|
{% 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>
|
||||||
|
{% endfor %}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card" id="addresses">
|
||||||
|
<header><h2>Address in Thailand</h2><a class="btn sm" href="/people/{{ p.id }}/addresses/new">+ New address</a></header>
|
||||||
|
{% for a in addresses %}
|
||||||
|
<div class="item{% if not a.current %} old{% endif %}">
|
||||||
|
<div class="row">
|
||||||
|
{% if a.current %}<span class="tag">current</span>{% else %}<span class="tag plain">earlier</span>{% endif %}
|
||||||
|
<span class="muted small">{% if a.moved_in_on %}since {{ a.moved_in_on }}{% endif %}{% if a.moved_out_on %} until {{ a.moved_out_on }}{% endif %}</span>
|
||||||
|
</div>
|
||||||
|
<p class="addr">{{ a.line }}</p>
|
||||||
|
<dl class="kv">
|
||||||
|
<dt>House master</dt><dd>{% if a.house_master %}{{ a.house_master }}{% if a.house_master_phone %}, {{ a.house_master_phone }}{% endif %}{% else %}<span class="muted">not recorded</span>{% endif %}</dd>
|
||||||
|
<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>
|
||||||
|
{% else %}
|
||||||
|
<p class="empty-inline">No address recorded yet. The TM.30 receipt of the current address goes with it.</p>
|
||||||
|
{% endfor %}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card" id="recent">
|
||||||
|
<header><h2>Recent activity</h2><a class="btn sm ghost" href="/activity?person={{ p.id }}">All of it</a></header>
|
||||||
|
<ul class="log">
|
||||||
|
{% for e in recent %}
|
||||||
|
<li><span class="when">{{ e.at }}</span><span><b>{{ e.actor }}</b> {{ e.action }} {{ e.what }}{% if e.fields %} <span class="muted">({{ e.fields }})</span>{% endif %}</span></li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
{% extends "base.html" %}
|
||||||
|
{% import "_fields.html" as fm %}
|
||||||
|
{% block main %}
|
||||||
|
{% if p %}
|
||||||
|
{% include "_person_head.html" %}
|
||||||
|
{% else %}
|
||||||
|
<div class="crumbs"><a href="/people">People</a></div>
|
||||||
|
<div class="pagehead"><h1>New person</h1></div>
|
||||||
|
{% endif %}
|
||||||
|
<form method="post" action="{{ action }}" class="form" id="person-form">
|
||||||
|
<input type="hidden" name="csrf" value="{{ csrf }}">
|
||||||
|
<button type="submit" name="action" value="save" class="default-submit" tabindex="-1" aria-hidden="true">Save</button>
|
||||||
|
{% if mode == "new" %}
|
||||||
|
<section class="card" id="mrz-card">
|
||||||
|
<header><h2>Read the passport</h2></header>
|
||||||
|
<p class="hint lead">Type or paste the two lines at the bottom of the photo page, then press Read. The form below fills itself in, and the check digits in the lines catch typing errors.</p>
|
||||||
|
{{ fm.area("mrz", "Machine-readable zone, two lines of 44 characters", pf.mrz, err=errors.mrz, rows=2, cls="mrz") }}
|
||||||
|
<div class="formactions">
|
||||||
|
<button type="submit" name="action" value="read-mrz" class="btn" id="read-mrz" formnovalidate>Read</button>
|
||||||
|
{% if mrz_note %}<p class="okline" role="status">{{ mrz_note }}</p>{% endif %}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
<section class="card">
|
||||||
|
<header><h2>{% if mode == "new" %}Person{% else %}Personal details{% endif %}</h2></header>
|
||||||
|
<div class="grid">
|
||||||
|
{{ fm.text("surname", "Surname", f.surname, err=errors.surname, req=true, hint="As printed in the passport.") }}
|
||||||
|
{{ fm.text("first_name", "First name", f.first_name, err=errors.first_name, req=true) }}
|
||||||
|
{{ fm.text("middle_name", "Middle names", f.middle_name, err=errors.middle_name) }}
|
||||||
|
{{ fm.select("title", "Title", f.title, titles, err=errors.title) }}
|
||||||
|
{{ fm.select("sex", "Sex", f.sex, sexes, err=errors.sex) }}
|
||||||
|
{{ fm.text("date_of_birth", "Date of birth", f.date_of_birth, err=errors.date_of_birth, type="date") }}
|
||||||
|
{{ fm.text("place_of_birth", "Place of birth", f.place_of_birth, err=errors.place_of_birth) }}
|
||||||
|
{{ fm.select("nationality", "Nationality", f.nationality, countries, err=errors.nationality) }}
|
||||||
|
{{ fm.text("occupation", "Occupation", f.occupation, err=errors.occupation) }}
|
||||||
|
{{ fm.text("employer", "Employer", f.employer, err=errors.employer, hint="The company named in the work permit.") }}
|
||||||
|
{{ fm.text("phone", "Phone", f.phone, err=errors.phone, type="tel") }}
|
||||||
|
{{ fm.text("email", "Email", f.email, err=errors.email, type="email") }}
|
||||||
|
{{ fm.area("notes", "Notes", f.notes, err=errors.notes, rows=3, fcls="wide") }}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% if mode == "new" %}
|
||||||
|
<section class="card">
|
||||||
|
<header><h2>Passport</h2><span class="muted small">Optional here; it can also be added later.</span></header>
|
||||||
|
<div class="grid">
|
||||||
|
{{ fm.text("number", "Passport number", pf.number, err=errors.number) }}
|
||||||
|
{{ fm.select("issuing_country", "Issued by", pf.issuing_country, countries, err=errors.issuing_country, blank="Choose a country") }}
|
||||||
|
{{ fm.text("issued_on", "Date of issue", pf.issued_on, err=errors.issued_on, type="date") }}
|
||||||
|
{{ fm.text("expires_on", "Date of expiry", pf.expires_on, err=errors.expires_on, type="date") }}
|
||||||
|
{{ fm.text("issued_at", "Authority or place of issue", pf.issued_at, err=errors.issued_at, hint="As printed in the passport.", cls="wide") }}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
<div class="formactions">
|
||||||
|
<button type="submit" name="action" value="save" class="btn pri" id="save">{% if mode == "new" %}Create the person{% else %}Save{% endif %}</button>
|
||||||
|
<a class="btn ghost" href="{% if p %}/people/{{ p.id }}{% else %}/people{% endif %}">Cancel</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
||||||
+337
@@ -0,0 +1,337 @@
|
|||||||
|
//! The login gate, and the whole login through a fake OpenID provider: a
|
||||||
|
//! member of `visa` gets a session, anyone else a refusal.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use axum::Json;
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use axum::routing::{get, post};
|
||||||
|
use base64::Engine as _;
|
||||||
|
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
|
||||||
|
use ring::signature::{ECDSA_P256_SHA256_FIXED_SIGNING, EcdsaKeyPair, KeyPair};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use visa::config::Auth;
|
||||||
|
use visa::oidc::Provider;
|
||||||
|
|
||||||
|
use crate::common::{App, oidc_config, with_auth};
|
||||||
|
|
||||||
|
fn app(pool: PgPool, issuer: &str) -> App {
|
||||||
|
with_auth(pool, Auth::Oidc(oidc_config(issuer)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn the_gate_sends_people_to_the_login(pool: PgPool) {
|
||||||
|
let app = app(pool, "https://id.test/oauth2/openid/visa-web");
|
||||||
|
let r = app.get("/people/3?x=1").await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||||
|
assert_eq!(r.location(), "/login?next=/people/3%3Fx%3D1");
|
||||||
|
// htmx gets a header instead of the provider's page
|
||||||
|
let r = app.get_with("/people", &[("hx-request", "true")]).await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK);
|
||||||
|
assert_eq!(r.headers["hx-redirect"], "/login?next=/people");
|
||||||
|
// open without a session
|
||||||
|
assert_eq!(app.get("/healthz").await.status, StatusCode::OK);
|
||||||
|
assert_eq!(app.get("/static/app.css").await.status, StatusCode::OK);
|
||||||
|
assert_eq!(app.get("/signed-out").await.status, StatusCode::OK);
|
||||||
|
// the provider has not answered yet
|
||||||
|
assert_eq!(
|
||||||
|
app.get("/login").await.status,
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE
|
||||||
|
);
|
||||||
|
// a login answer without this browser's flow cookie
|
||||||
|
let r = app.get("/auth/callback?code=c&state=s").await;
|
||||||
|
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||||
|
assert!(r.text().contains("started elsewhere"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn a_session_lets_in_and_sign_out_ends_it(pool: PgPool) {
|
||||||
|
let app = app(pool.clone(), "https://id.test/oauth2/openid/visa-web");
|
||||||
|
let id = visa::session::create(&pool, "grabowski", "Alexander Grabowski")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let cookie = format!("__Host-visa={id}");
|
||||||
|
let r = app.get_with("/people", &[("cookie", &cookie)]).await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||||
|
assert!(r.text().contains("Signed in as") && r.text().contains("Alexander Grabowski"));
|
||||||
|
|
||||||
|
// the session's token, as the page carries it
|
||||||
|
let csrf: String = sqlx::query_scalar("SELECT csrf FROM sessions")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert!(r.body.contains(&format!("value=\"{csrf}\"")));
|
||||||
|
|
||||||
|
// forms need the same site and the session's token
|
||||||
|
let new = [("surname", "Doe"), ("first_name", "Jane")];
|
||||||
|
let with = |site: &'static str| {
|
||||||
|
vec![
|
||||||
|
("cookie", cookie.clone()),
|
||||||
|
("sec-fetch-site", site.to_string()),
|
||||||
|
]
|
||||||
|
};
|
||||||
|
let send = |form: Vec<(&'static str, String)>, headers: Vec<(&'static str, String)>| {
|
||||||
|
let app = &app;
|
||||||
|
async move {
|
||||||
|
let f: Vec<(&str, &str)> = form.iter().map(|(k, v)| (*k, v.as_str())).collect();
|
||||||
|
let h: Vec<(&str, &str)> = headers.iter().map(|(k, v)| (*k, v.as_str())).collect();
|
||||||
|
app.post_raw("/people", &f, &h).await
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let form = |token: &str| {
|
||||||
|
let mut f: Vec<(&'static str, String)> =
|
||||||
|
new.iter().map(|(k, v)| (*k, v.to_string())).collect();
|
||||||
|
f.push(("csrf", token.to_string()));
|
||||||
|
f
|
||||||
|
};
|
||||||
|
let r = send(form(&csrf), with("cross-site")).await;
|
||||||
|
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||||
|
assert!(r.text().contains("another site"));
|
||||||
|
let r = send(form("forged"), with("same-origin")).await;
|
||||||
|
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||||
|
assert!(r.text().contains("The form has expired"));
|
||||||
|
let no_header = vec![("cookie", cookie.clone())];
|
||||||
|
assert_eq!(
|
||||||
|
send(form(&csrf), no_header).await.status,
|
||||||
|
StatusCode::FORBIDDEN
|
||||||
|
);
|
||||||
|
let r = send(form(&csrf), with("same-origin")).await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||||
|
let actor: String = sqlx::query_scalar("SELECT actor FROM audit_log WHERE action = 'create'")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(actor, "grabowski");
|
||||||
|
|
||||||
|
// sign out: the session row goes, the cookie is cleared
|
||||||
|
let r = app
|
||||||
|
.post_raw(
|
||||||
|
"/logout",
|
||||||
|
&[("csrf", &csrf)],
|
||||||
|
&[("cookie", &cookie), ("sec-fetch-site", "same-origin")],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||||
|
assert_eq!(r.location(), "/signed-out");
|
||||||
|
assert!(
|
||||||
|
r.headers["set-cookie"]
|
||||||
|
.to_str()
|
||||||
|
.unwrap()
|
||||||
|
.contains("Max-Age=0")
|
||||||
|
);
|
||||||
|
let n: i64 = sqlx::query_scalar("SELECT count(*) FROM sessions")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(n, 0);
|
||||||
|
assert_eq!(
|
||||||
|
app.get_with("/people", &[("cookie", &cookie)]).await.status,
|
||||||
|
StatusCode::SEE_OTHER
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------- a fake OpenID provider
|
||||||
|
|
||||||
|
struct Fake {
|
||||||
|
issuer: String,
|
||||||
|
key: EcdsaKeyPair,
|
||||||
|
x: String,
|
||||||
|
y: String,
|
||||||
|
/// What the next token says.
|
||||||
|
nonce: Mutex<String>,
|
||||||
|
groups: Mutex<Vec<String>>,
|
||||||
|
/// The token requests it got.
|
||||||
|
requests: Mutex<Vec<HashMap<String, String>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn jwks(State(f): State<Arc<Fake>>) -> Json<Value> {
|
||||||
|
Json(json!({"keys": [{"kty": "EC", "crv": "P-256", "kid": "k1", "x": f.x, "y": f.y}]}))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn token(
|
||||||
|
State(f): State<Arc<Fake>>,
|
||||||
|
headers: axum::http::HeaderMap,
|
||||||
|
axum::Form(form): axum::Form<HashMap<String, String>>,
|
||||||
|
) -> Json<Value> {
|
||||||
|
let auth = headers["authorization"].to_str().unwrap().to_string();
|
||||||
|
let mut seen = form.clone();
|
||||||
|
seen.insert("authorization".into(), auth);
|
||||||
|
f.requests.lock().unwrap().push(seen);
|
||||||
|
let now = std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_secs();
|
||||||
|
let claims = json!({
|
||||||
|
"iss": f.issuer,
|
||||||
|
"aud": "visa-web",
|
||||||
|
"sub": "uuid-of-alex",
|
||||||
|
"exp": now + 300,
|
||||||
|
"iat": now,
|
||||||
|
"nonce": *f.nonce.lock().unwrap(),
|
||||||
|
"preferred_username": "grabowski",
|
||||||
|
"name": "Alexander Grabowski",
|
||||||
|
"groups": *f.groups.lock().unwrap(),
|
||||||
|
});
|
||||||
|
let header = json!({"alg": "ES256", "typ": "JWT", "kid": "k1"});
|
||||||
|
let input = format!(
|
||||||
|
"{}.{}",
|
||||||
|
B64.encode(header.to_string()),
|
||||||
|
B64.encode(claims.to_string())
|
||||||
|
);
|
||||||
|
let rng = ring::rand::SystemRandom::new();
|
||||||
|
let sig = f.key.sign(&rng, input.as_bytes()).unwrap();
|
||||||
|
Json(json!({
|
||||||
|
"access_token": "at",
|
||||||
|
"token_type": "Bearer",
|
||||||
|
"id_token": format!("{input}.{}", B64.encode(sig.as_ref())),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts the provider on a free port; returns it and its issuer URL.
|
||||||
|
async fn fake_provider() -> Arc<Fake> {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let base = format!("http://{}", listener.local_addr().unwrap());
|
||||||
|
let rng = ring::rand::SystemRandom::new();
|
||||||
|
let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, &rng).unwrap();
|
||||||
|
let key =
|
||||||
|
EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, pkcs8.as_ref(), &rng).unwrap();
|
||||||
|
let public = key.public_key().as_ref().to_vec();
|
||||||
|
let fake = Arc::new(Fake {
|
||||||
|
issuer: format!("{base}/oauth2/openid/visa-web"),
|
||||||
|
x: B64.encode(&public[1..33]),
|
||||||
|
y: B64.encode(&public[33..65]),
|
||||||
|
key,
|
||||||
|
nonce: Mutex::new(String::new()),
|
||||||
|
groups: Mutex::new(vec![]),
|
||||||
|
requests: Mutex::new(vec![]),
|
||||||
|
});
|
||||||
|
let issuer = fake.issuer.clone();
|
||||||
|
let discovery = json!({
|
||||||
|
"issuer": issuer,
|
||||||
|
"authorization_endpoint": format!("{base}/ui/oauth2"),
|
||||||
|
"token_endpoint": format!("{base}/oauth2/token"),
|
||||||
|
"jwks_uri": format!("{base}/oauth2/openid/visa-web/public_key.jwk"),
|
||||||
|
});
|
||||||
|
let router = axum::Router::new()
|
||||||
|
.route(
|
||||||
|
"/oauth2/openid/visa-web/.well-known/openid-configuration",
|
||||||
|
get(move || async move { Json(discovery) }),
|
||||||
|
)
|
||||||
|
.route("/oauth2/openid/visa-web/public_key.jwk", get(jwks))
|
||||||
|
.route("/oauth2/token", post(token))
|
||||||
|
.with_state(fake.clone());
|
||||||
|
tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
|
||||||
|
fake
|
||||||
|
}
|
||||||
|
|
||||||
|
fn query(url: &str) -> HashMap<String, String> {
|
||||||
|
let q = url.split_once('?').map(|x| x.1).unwrap_or("");
|
||||||
|
form_urlencoded::parse(q.as_bytes()).into_owned().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cookie_of(set_cookie: &str) -> String {
|
||||||
|
set_cookie.split(';').next().unwrap().to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// /login, then the provider's answer at /auth/callback.
|
||||||
|
async fn sign_in(app: &App, fake: &Fake, groups: &[&str]) -> crate::common::Resp {
|
||||||
|
let r = app.get("/login?next=/people").await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||||
|
let to = r.location().to_string();
|
||||||
|
assert!(to.contains("/ui/oauth2?"), "{to}");
|
||||||
|
let q = query(&to);
|
||||||
|
assert_eq!(q["client_id"], "visa-web");
|
||||||
|
assert_eq!(q["redirect_uri"], "https://visa.test/auth/callback");
|
||||||
|
assert_eq!(q["code_challenge_method"], "S256");
|
||||||
|
assert_eq!(q["scope"], "openid profile email groups");
|
||||||
|
let flow = cookie_of(r.headers["set-cookie"].to_str().unwrap());
|
||||||
|
assert!(flow.starts_with("__Host-visa-login="));
|
||||||
|
|
||||||
|
*fake.nonce.lock().unwrap() = q["nonce"].clone();
|
||||||
|
*fake.groups.lock().unwrap() = groups.iter().map(|g| g.to_string()).collect();
|
||||||
|
app.get_with(
|
||||||
|
&format!("/auth/callback?code=the-code&state={}", q["state"]),
|
||||||
|
&[("cookie", &flow)],
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn a_member_signs_in_through_the_provider(pool: PgPool) {
|
||||||
|
let fake = fake_provider().await;
|
||||||
|
let app = app(pool.clone(), &fake.issuer);
|
||||||
|
let http = reqwest::Client::new();
|
||||||
|
app.st
|
||||||
|
.set_provider(Provider::discover(&http, &fake.issuer).await.unwrap());
|
||||||
|
|
||||||
|
let r = sign_in(&app, &fake, &["visa@id.test", "b4l@id.test"]).await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||||
|
assert_eq!(r.location(), "/people");
|
||||||
|
let cookies: Vec<String> = r
|
||||||
|
.headers
|
||||||
|
.get_all("set-cookie")
|
||||||
|
.iter()
|
||||||
|
.map(|v| v.to_str().unwrap().to_string())
|
||||||
|
.collect();
|
||||||
|
let session = cookies
|
||||||
|
.iter()
|
||||||
|
.find(|c| c.starts_with("__Host-visa="))
|
||||||
|
.expect("a session cookie");
|
||||||
|
assert!(
|
||||||
|
session.contains("Secure")
|
||||||
|
&& session.contains("HttpOnly")
|
||||||
|
&& session.contains("SameSite=Lax")
|
||||||
|
);
|
||||||
|
let page = app
|
||||||
|
.get_with("/people", &[("cookie", &cookie_of(session))])
|
||||||
|
.await;
|
||||||
|
assert_eq!(page.status, StatusCode::OK);
|
||||||
|
assert!(page.text().contains("Alexander Grabowski"));
|
||||||
|
|
||||||
|
// the token request carried the code, the PKCE verifier and the secret
|
||||||
|
let req = fake.requests.lock().unwrap()[0].clone();
|
||||||
|
assert_eq!(req["code"], "the-code");
|
||||||
|
assert_eq!(req["grant_type"], "authorization_code");
|
||||||
|
assert_eq!(req["code_verifier"].len(), 43);
|
||||||
|
assert!(req["authorization"].starts_with("Basic "));
|
||||||
|
|
||||||
|
let signed_in: i64 = sqlx::query_scalar(
|
||||||
|
"SELECT count(*) FROM audit_log WHERE action = 'sign-in' AND actor = 'grabowski'",
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(signed_in, 1);
|
||||||
|
// the cookie value is not stored, only its hash
|
||||||
|
let stored: Vec<u8> = sqlx::query_scalar("SELECT id_hash FROM sessions")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let value = cookie_of(session)
|
||||||
|
.trim_start_matches("__Host-visa=")
|
||||||
|
.to_string();
|
||||||
|
assert_ne!(stored, value.as_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn someone_outside_the_group_is_refused(pool: PgPool) {
|
||||||
|
let fake = fake_provider().await;
|
||||||
|
let app = app(pool.clone(), &fake.issuer);
|
||||||
|
let http = reqwest::Client::new();
|
||||||
|
app.st
|
||||||
|
.set_provider(Provider::discover(&http, &fake.issuer).await.unwrap());
|
||||||
|
|
||||||
|
// a group whose name only starts like "visa" does not count
|
||||||
|
let r = sign_in(&app, &fake, &["b4l@id.test", "visas@id.test"]).await;
|
||||||
|
assert_eq!(r.status, StatusCode::FORBIDDEN);
|
||||||
|
assert!(r.text().contains("not in the group visa"), "{}", r.text());
|
||||||
|
assert!(r.headers.get("set-cookie").is_none());
|
||||||
|
let n: i64 = sqlx::query_scalar("SELECT count(*) FROM sessions")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(n, 0);
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
#![allow(dead_code)]
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use axum::Router;
|
||||||
|
use axum::body::Body;
|
||||||
|
use axum::http::{HeaderMap, Request, StatusCode};
|
||||||
|
use chrono::NaiveDate;
|
||||||
|
use http_body_util::BodyExt;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use tower::ServiceExt;
|
||||||
|
use visa::config::{Auth, Config, OidcConfig};
|
||||||
|
use visa::web::{self, AppState};
|
||||||
|
|
||||||
|
pub fn config(auth: Auth) -> Config {
|
||||||
|
Config {
|
||||||
|
listen: "127.0.0.1:0".parse().unwrap(),
|
||||||
|
public_url: "https://visa.test".into(),
|
||||||
|
database_url: "postgres://unused".into(),
|
||||||
|
database_password: None,
|
||||||
|
auth,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn oidc_config(issuer: &str) -> OidcConfig {
|
||||||
|
OidcConfig {
|
||||||
|
issuer: issuer.into(),
|
||||||
|
client_id: "visa-web".into(),
|
||||||
|
client_secret: "test-secret".into(),
|
||||||
|
group: "visa".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct App {
|
||||||
|
pub st: Arc<AppState>,
|
||||||
|
pub router: Router,
|
||||||
|
pub pool: PgPool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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();
|
||||||
|
App {
|
||||||
|
router: web::router(st.clone()),
|
||||||
|
st,
|
||||||
|
pool,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Resp {
|
||||||
|
pub status: StatusCode,
|
||||||
|
pub headers: HeaderMap,
|
||||||
|
pub body: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Resp {
|
||||||
|
pub fn location(&self) -> &str {
|
||||||
|
self.headers
|
||||||
|
.get("location")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.unwrap_or("")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The decoded page text, for assertions on what people read.
|
||||||
|
pub fn text(&self) -> String {
|
||||||
|
self.body
|
||||||
|
.replace("'", "'")
|
||||||
|
.replace("'", "'")
|
||||||
|
.replace(""", "\"")
|
||||||
|
.replace("/", "/")
|
||||||
|
.replace("&", "&")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn form_body(pairs: &[(&str, &str)]) -> String {
|
||||||
|
form_urlencoded::Serializer::new(String::new())
|
||||||
|
.extend_pairs(pairs)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl App {
|
||||||
|
pub async fn call(&self, req: Request<Body>) -> Resp {
|
||||||
|
let resp = self.router.clone().oneshot(req).await.unwrap();
|
||||||
|
let status = resp.status();
|
||||||
|
let headers = resp.headers().clone();
|
||||||
|
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
|
||||||
|
Resp {
|
||||||
|
status,
|
||||||
|
headers,
|
||||||
|
body: String::from_utf8_lossy(&bytes).into_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get(&self, uri: &str) -> Resp {
|
||||||
|
self.get_with(uri, &[]).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_with(&self, uri: &str, headers: &[(&str, &str)]) -> Resp {
|
||||||
|
let mut req = Request::get(uri);
|
||||||
|
for (k, v) in headers {
|
||||||
|
req = req.header(*k, *v);
|
||||||
|
}
|
||||||
|
self.call(req.body(Body::empty()).unwrap()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A form as a browser on this site sends it, with the local token.
|
||||||
|
pub async fn post(&self, uri: &str, form: &[(&str, &str)]) -> Resp {
|
||||||
|
let csrf = self.st.local_csrf().to_string();
|
||||||
|
let mut pairs: Vec<(&str, &str)> = form.to_vec();
|
||||||
|
pairs.push(("csrf", &csrf));
|
||||||
|
self.post_raw(uri, &pairs, &[("sec-fetch-site", "same-origin")])
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn post_raw(
|
||||||
|
&self,
|
||||||
|
uri: &str,
|
||||||
|
form: &[(&str, &str)],
|
||||||
|
headers: &[(&str, &str)],
|
||||||
|
) -> Resp {
|
||||||
|
let mut req =
|
||||||
|
Request::post(uri).header("content-type", "application/x-www-form-urlencoded");
|
||||||
|
for (k, v) in headers {
|
||||||
|
req = req.header(*k, *v);
|
||||||
|
}
|
||||||
|
self.call(req.body(Body::from(form_body(form))).unwrap())
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn d(s: &str) -> NaiveDate {
|
||||||
|
NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The id at the end of a redirect to /people/<id>.
|
||||||
|
pub fn id_from(location: &str) -> i64 {
|
||||||
|
location
|
||||||
|
.trim_start_matches("/people/")
|
||||||
|
.split(['#', '/'])
|
||||||
|
.next()
|
||||||
|
.unwrap()
|
||||||
|
.parse()
|
||||||
|
.unwrap_or_else(|_| panic!("no person id in {location:?}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The two MRZ lines for an invented German passport.
|
||||||
|
pub fn erika_mrz() -> String {
|
||||||
|
visa::mrz::compose(&visa::mrz::Compose {
|
||||||
|
issuing_state: "D",
|
||||||
|
surname: "MUSTERMANN",
|
||||||
|
given_names: "ERIKA",
|
||||||
|
number: "C01X00T47",
|
||||||
|
nationality: "D",
|
||||||
|
date_of_birth: d("1984-08-12"),
|
||||||
|
sex: "F",
|
||||||
|
expiry_date: d("2031-08-01"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Duplicate element ids make `getElementById` pick the wrong element.
|
||||||
|
pub fn assert_unique_ids(html: &str, page: &str) {
|
||||||
|
let mut seen = std::collections::HashSet::new();
|
||||||
|
for part in html.split(" id=\"").skip(1) {
|
||||||
|
let id = part.split('"').next().unwrap();
|
||||||
|
assert!(
|
||||||
|
seen.insert(id.to_string()),
|
||||||
|
"{page}: id {id:?} occurs twice"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
//! Integration tests: one binary, every file a module (`autotests = false`).
|
||||||
|
//! The database tests need `DATABASE_URL` (a PostgreSQL role that may create
|
||||||
|
//! databases); each `#[sqlx::test]` gets its own database.
|
||||||
|
|
||||||
|
mod auth;
|
||||||
|
mod common;
|
||||||
|
mod pages;
|
||||||
|
mod people;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_test_file_is_a_module() {
|
||||||
|
let main = include_str!("main.rs");
|
||||||
|
for entry in std::fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/tests")).unwrap() {
|
||||||
|
let path = entry.unwrap().path();
|
||||||
|
let name = path.file_stem().unwrap().to_string_lossy().into_owned();
|
||||||
|
if name == "main" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
main.contains(&format!("mod {name};")),
|
||||||
|
"tests/{name} is not declared in tests/main.rs"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+138
@@ -0,0 +1,138 @@
|
|||||||
|
//! Every page renders with the demo data; headers and ids.
|
||||||
|
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
use crate::common::{assert_unique_ids, local};
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn every_page_renders_with_demo_data(pool: PgPool) {
|
||||||
|
assert!(visa::seed::demo(&pool, visa::dates::today()).await.unwrap());
|
||||||
|
assert!(
|
||||||
|
!visa::seed::demo(&pool, visa::dates::today()).await.unwrap(),
|
||||||
|
"seed runs once"
|
||||||
|
);
|
||||||
|
let app = local(pool.clone());
|
||||||
|
|
||||||
|
let erika: i64 = sqlx::query_scalar("SELECT id FROM people WHERE surname = 'Mustermann'")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let passport: i64 = sqlx::query_scalar("SELECT id FROM passports WHERE person_id = $1")
|
||||||
|
.bind(erika)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let address: i64 = sqlx::query_scalar(
|
||||||
|
"SELECT id FROM addresses WHERE person_id = $1 AND moved_out_on IS NULL",
|
||||||
|
)
|
||||||
|
.bind(erika)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let pages = [
|
||||||
|
("/people".to_string(), "MUSTERMANN, Erika"),
|
||||||
|
("/people?archived=1".to_string(), "SAMPLE, Oliver"),
|
||||||
|
("/people/new".to_string(), "Read the passport"),
|
||||||
|
(format!("/people/{erika}"), "Baan Suan Demo"),
|
||||||
|
(format!("/people/{erika}/edit"), "Personal details"),
|
||||||
|
(format!("/people/{erika}/passports/new"), "New passport"),
|
||||||
|
(
|
||||||
|
format!("/people/{erika}/passports/{passport}/edit"),
|
||||||
|
"C01X00T47",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
format!("/people/{erika}/addresses/new"),
|
||||||
|
"House master and TM.30",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
format!("/people/{erika}/addresses/{address}/edit"),
|
||||||
|
"TM30-DEMO-0012",
|
||||||
|
),
|
||||||
|
("/activity".to_string(), "seed"),
|
||||||
|
(format!("/activity?person={erika}"), "MUSTERMANN, Erika"),
|
||||||
|
];
|
||||||
|
for (path, expect) in &pages {
|
||||||
|
let r = app.get(path).await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK, "{path}: {}", r.body);
|
||||||
|
assert!(r.text().contains(expect), "{path} lacks {expect:?}");
|
||||||
|
assert_unique_ids(&r.body, path);
|
||||||
|
assert_eq!(r.headers["cache-control"], "no-store", "{path}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// warnings from the demo dates: Jane's passport runs out in 95 days, she
|
||||||
|
// has no TM.30 receipt, Tomas's passport has under a year
|
||||||
|
let list = app.get("/people").await.text();
|
||||||
|
assert!(list.contains("Under 6 months left"), "{list}");
|
||||||
|
assert!(list.contains("Under 12 months left"), "{list}");
|
||||||
|
let jane: i64 = sqlx::query_scalar("SELECT id FROM people WHERE surname = 'Doe'")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let page = app.get(&format!("/people/{jane}")).await.text();
|
||||||
|
assert!(page.contains("No TM.30 receipt recorded"), "{page}");
|
||||||
|
assert!(page.contains("previous"), "Jane's old passport is listed");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn empty_list_says_what_to_do(pool: PgPool) {
|
||||||
|
let app = local(pool);
|
||||||
|
let r = app.get("/people").await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK);
|
||||||
|
assert!(r.text().contains("No people yet"));
|
||||||
|
assert!(
|
||||||
|
app.get("/activity")
|
||||||
|
.await
|
||||||
|
.text()
|
||||||
|
.contains("Nothing has happened yet")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn open_paths_headers_and_not_found(pool: PgPool) {
|
||||||
|
let app = local(pool);
|
||||||
|
let r = app.get("/healthz").await;
|
||||||
|
assert_eq!((r.status, r.body.as_str()), (StatusCode::OK, "ok"));
|
||||||
|
let css = app.get("/static/app.css").await;
|
||||||
|
assert_eq!(css.status, StatusCode::OK);
|
||||||
|
assert_eq!(css.headers["content-type"], "text/css; charset=utf-8");
|
||||||
|
assert_eq!(
|
||||||
|
app.get("/static/nope.css").await.status,
|
||||||
|
StatusCode::NOT_FOUND
|
||||||
|
);
|
||||||
|
|
||||||
|
let r = app.get("/").await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||||
|
assert_eq!(r.location(), "/people");
|
||||||
|
|
||||||
|
let r = app.get("/people/999999").await;
|
||||||
|
assert_eq!(r.status, StatusCode::NOT_FOUND);
|
||||||
|
assert!(r.text().contains("no page or record"));
|
||||||
|
assert_eq!(app.get("/nowhere").await.status, StatusCode::NOT_FOUND);
|
||||||
|
|
||||||
|
let csp = r.headers["content-security-policy"].to_str().unwrap();
|
||||||
|
assert!(csp.contains("script-src 'self'") && csp.contains("frame-ancestors 'none'"));
|
||||||
|
assert_eq!(r.headers["x-frame-options"], "DENY");
|
||||||
|
assert_eq!(r.headers["x-robots-tag"], "noindex, nofollow");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn templates_have_no_inline_script_or_style() {
|
||||||
|
for (name, bytes) in visa::embedded::TEMPLATES {
|
||||||
|
let t = std::str::from_utf8(bytes).unwrap();
|
||||||
|
for bad in [
|
||||||
|
" style=\"",
|
||||||
|
" onclick=",
|
||||||
|
" onsubmit=",
|
||||||
|
" onchange=",
|
||||||
|
"<script>",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
!t.contains(bad),
|
||||||
|
"{name} contains {bad:?}; the CSP refuses it"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(visa::web::templates().is_ok());
|
||||||
|
}
|
||||||
+391
@@ -0,0 +1,391 @@
|
|||||||
|
//! People, passports and addresses through the forms, with the audit log.
|
||||||
|
|
||||||
|
use axum::http::StatusCode;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
|
||||||
|
use crate::common::{erika_mrz, id_from, local};
|
||||||
|
|
||||||
|
async fn audit_rows(pool: &PgPool, person: i64) -> Vec<(String, String, Vec<String>)> {
|
||||||
|
sqlx::query_as("SELECT action, entity, fields FROM audit_log WHERE person_id = $1 ORDER BY id")
|
||||||
|
.bind(person)
|
||||||
|
.fetch_all(pool)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn read_the_zone_then_create(pool: PgPool) {
|
||||||
|
let app = local(pool.clone());
|
||||||
|
let mrz = erika_mrz();
|
||||||
|
|
||||||
|
// Read fills the form and says the check digits match
|
||||||
|
let r = app
|
||||||
|
.post("/people", &[("action", "read-mrz"), ("mrz", &mrz)])
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
|
||||||
|
let page = r.text();
|
||||||
|
assert!(page.contains("every check digit matches"), "{page}");
|
||||||
|
for v in [
|
||||||
|
"MUSTERMANN",
|
||||||
|
"ERIKA",
|
||||||
|
"1984-08-12",
|
||||||
|
"C01X00T47",
|
||||||
|
"2031-08-01",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
page.contains(&format!("value=\"{v}\"")),
|
||||||
|
"{v} not filled in"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(page.contains("<option value=\"DEU\" selected>Germany</option>"));
|
||||||
|
assert!(page.contains("<option value=\"F\" selected>Female</option>"));
|
||||||
|
|
||||||
|
// Saving with only the zone fills the blanks and creates both records
|
||||||
|
let r = app
|
||||||
|
.post("/people", &[("action", "save"), ("mrz", &mrz)])
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||||
|
let id = id_from(r.location());
|
||||||
|
let (surname, nat): (String, String) =
|
||||||
|
sqlx::query_as("SELECT surname, nationality FROM people WHERE id = $1")
|
||||||
|
.bind(id)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!((surname.as_str(), nat.as_str()), ("MUSTERMANN", "DEU"));
|
||||||
|
let (number, stored): (String, String) =
|
||||||
|
sqlx::query_as("SELECT number, mrz FROM passports WHERE person_id = $1")
|
||||||
|
.bind(id)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(number, "C01X00T47");
|
||||||
|
assert_eq!(stored, mrz);
|
||||||
|
let log = audit_rows(&pool, id).await;
|
||||||
|
assert_eq!(log[0].0, "create");
|
||||||
|
assert_eq!(log[0].1, "person");
|
||||||
|
assert_eq!(log[1].1, "passport");
|
||||||
|
assert!(log.iter().all(|(_, _, f)| f.is_empty()));
|
||||||
|
|
||||||
|
// the same passport again is refused
|
||||||
|
let r = app
|
||||||
|
.post("/people", &[("action", "save"), ("mrz", &mrz)])
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
assert!(r.text().contains("already recorded"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn a_typo_in_the_zone_is_caught(pool: PgPool) {
|
||||||
|
let app = local(pool.clone());
|
||||||
|
// the birth date 840812 typed as 840813
|
||||||
|
let typo = erika_mrz().replacen("840812", "840813", 1);
|
||||||
|
assert_ne!(typo, erika_mrz(), "the fixture changed");
|
||||||
|
let r = app
|
||||||
|
.post("/people", &[("action", "read-mrz"), ("mrz", &typo)])
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
assert!(
|
||||||
|
r.text().contains("do not match for: date of birth"),
|
||||||
|
"{}",
|
||||||
|
r.text()
|
||||||
|
);
|
||||||
|
let r = app
|
||||||
|
.post("/people", &[("action", "save"), ("mrz", &typo)])
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
let n: i64 = sqlx::query_scalar("SELECT count(*) FROM people")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(n, 0);
|
||||||
|
// text that is no zone at all
|
||||||
|
let r = app
|
||||||
|
.post("/people", &[("action", "read-mrz"), ("mrz", "hello")])
|
||||||
|
.await;
|
||||||
|
assert!(r.text().contains("two lines of 44 characters"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn validation_and_edits_with_changed_fields(pool: PgPool) {
|
||||||
|
let app = local(pool.clone());
|
||||||
|
let r = app
|
||||||
|
.post("/people", &[("action", "save"), ("first_name", "Jane")])
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
assert!(r.text().contains("Enter the surname"));
|
||||||
|
assert!(r.body.contains("value=\"Jane\""), "typed values stay");
|
||||||
|
|
||||||
|
let r = app
|
||||||
|
.post(
|
||||||
|
"/people",
|
||||||
|
&[
|
||||||
|
("surname", "Doe"),
|
||||||
|
("first_name", "Jane"),
|
||||||
|
("nationality", "usa"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||||
|
let id = id_from(r.location());
|
||||||
|
|
||||||
|
let base = [
|
||||||
|
("surname", "Doe"),
|
||||||
|
("first_name", "Jane"),
|
||||||
|
("nationality", "USA"),
|
||||||
|
];
|
||||||
|
// no change: no audit row
|
||||||
|
let r = app.post(&format!("/people/{id}"), &base).await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||||
|
let mut changed = base.to_vec();
|
||||||
|
changed.push(("email", "jane@example.com"));
|
||||||
|
changed.push(("occupation", "Designer"));
|
||||||
|
let r = app.post(&format!("/people/{id}"), &changed).await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||||
|
let log = audit_rows(&pool, id).await;
|
||||||
|
assert_eq!(log.len(), 2, "{log:?}");
|
||||||
|
assert_eq!(log[1].0, "update");
|
||||||
|
assert_eq!(log[1].2, vec!["occupation", "email"]);
|
||||||
|
|
||||||
|
let bad = [
|
||||||
|
("surname", "Doe"),
|
||||||
|
("first_name", "Jane"),
|
||||||
|
("email", "nope"),
|
||||||
|
];
|
||||||
|
let r = app.post(&format!("/people/{id}"), &bad).await;
|
||||||
|
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
assert!(r.text().contains("does not look like an email"));
|
||||||
|
|
||||||
|
// viewing is logged too
|
||||||
|
assert_eq!(
|
||||||
|
app.get(&format!("/people/{id}")).await.status,
|
||||||
|
StatusCode::OK
|
||||||
|
);
|
||||||
|
assert_eq!(audit_rows(&pool, id).await.last().unwrap().0, "view");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn archive_and_restore(pool: PgPool) {
|
||||||
|
let app = local(pool.clone());
|
||||||
|
let r = app
|
||||||
|
.post("/people", &[("surname", "Novak"), ("first_name", "Tomas")])
|
||||||
|
.await;
|
||||||
|
let id = id_from(r.location());
|
||||||
|
let r = app.post(&format!("/people/{id}/archive"), &[]).await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||||
|
assert!(!app.get("/people").await.text().contains("NOVAK"));
|
||||||
|
assert!(
|
||||||
|
app.get("/people?archived=1")
|
||||||
|
.await
|
||||||
|
.text()
|
||||||
|
.contains("NOVAK, Tomas")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
app.get(&format!("/people/{id}"))
|
||||||
|
.await
|
||||||
|
.text()
|
||||||
|
.contains("Archived on")
|
||||||
|
);
|
||||||
|
app.post(&format!("/people/{id}/restore"), &[]).await;
|
||||||
|
assert!(app.get("/people").await.text().contains("NOVAK, Tomas"));
|
||||||
|
let actions: Vec<String> = audit_rows(&pool, id)
|
||||||
|
.await
|
||||||
|
.into_iter()
|
||||||
|
.map(|r| r.0)
|
||||||
|
.collect();
|
||||||
|
assert!(actions.contains(&"archive".to_string()) && actions.contains(&"restore".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn passports_add_edit_delete(pool: PgPool) {
|
||||||
|
let app = local(pool.clone());
|
||||||
|
let r = app
|
||||||
|
.post(
|
||||||
|
"/people",
|
||||||
|
&[("surname", "Mustermann"), ("first_name", "Erika")],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let id = id_from(r.location());
|
||||||
|
|
||||||
|
// Read on the passport form names a mismatch with the record's name
|
||||||
|
let other = visa::mrz::compose(&visa::mrz::Compose {
|
||||||
|
issuing_state: "D",
|
||||||
|
surname: "MUSTERFRAU",
|
||||||
|
given_names: "ERIKA",
|
||||||
|
number: "C01X00T47",
|
||||||
|
nationality: "D",
|
||||||
|
date_of_birth: crate::common::d("1984-08-12"),
|
||||||
|
sex: "F",
|
||||||
|
expiry_date: crate::common::d("2031-08-01"),
|
||||||
|
});
|
||||||
|
let r = app
|
||||||
|
.post(
|
||||||
|
&format!("/people/{id}/passports"),
|
||||||
|
&[("action", "read-mrz"), ("mrz", &other)],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::OK);
|
||||||
|
assert!(
|
||||||
|
r.text().contains("The zone names MUSTERFRAU, ERIKA"),
|
||||||
|
"{}",
|
||||||
|
r.text()
|
||||||
|
);
|
||||||
|
|
||||||
|
let r = app
|
||||||
|
.post(
|
||||||
|
&format!("/people/{id}/passports"),
|
||||||
|
&[
|
||||||
|
("number", "c01 x00t47"),
|
||||||
|
("issuing_country", "DEU"),
|
||||||
|
("issued_on", "2021-08-02"),
|
||||||
|
("expires_on", "2031-08-01"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||||
|
assert_eq!(r.location(), format!("/people/{id}#passports"));
|
||||||
|
let pid: i64 = sqlx::query_scalar("SELECT id FROM passports WHERE number = 'C01X00T47'")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// an expiry before the issue date is refused
|
||||||
|
let r = app
|
||||||
|
.post(
|
||||||
|
&format!("/people/{id}/passports/{pid}"),
|
||||||
|
&[
|
||||||
|
("number", "C01X00T47"),
|
||||||
|
("issuing_country", "DEU"),
|
||||||
|
("issued_on", "2032-01-01"),
|
||||||
|
("expires_on", "2031-08-01"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
let r = app
|
||||||
|
.post(
|
||||||
|
&format!("/people/{id}/passports/{pid}"),
|
||||||
|
&[
|
||||||
|
("number", "C01X00T47"),
|
||||||
|
("issuing_country", "DEU"),
|
||||||
|
("issued_on", "2021-08-02"),
|
||||||
|
("expires_on", "2031-08-01"),
|
||||||
|
("issued_at", "Stadt Koeln"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||||
|
let page = app.get(&format!("/people/{id}")).await.text();
|
||||||
|
assert!(page.contains("Stadt Koeln") && page.contains("current"));
|
||||||
|
|
||||||
|
// someone else's person id in the path finds nothing
|
||||||
|
assert_eq!(
|
||||||
|
app.get(&format!("/people/{}/passports/{pid}/edit", id + 1))
|
||||||
|
.await
|
||||||
|
.status,
|
||||||
|
StatusCode::NOT_FOUND
|
||||||
|
);
|
||||||
|
let r = app
|
||||||
|
.post(&format!("/people/{id}/passports/{pid}/delete"), &[])
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||||
|
let log = audit_rows(&pool, id).await;
|
||||||
|
let kinds: Vec<(&str, &str)> = log
|
||||||
|
.iter()
|
||||||
|
.map(|(a, e, _)| (a.as_str(), e.as_str()))
|
||||||
|
.collect();
|
||||||
|
assert!(kinds.contains(&("update", "passport")) && kinds.contains(&("delete", "passport")));
|
||||||
|
assert_eq!(
|
||||||
|
log.iter().find(|r| r.0 == "update").unwrap().2,
|
||||||
|
vec!["issued_at"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn addresses_add_edit_delete(pool: PgPool) {
|
||||||
|
let app = local(pool.clone());
|
||||||
|
let r = app
|
||||||
|
.post("/people", &[("surname", "Doe"), ("first_name", "Jane")])
|
||||||
|
.await;
|
||||||
|
let id = id_from(r.location());
|
||||||
|
let r = app
|
||||||
|
.post(
|
||||||
|
&format!("/people/{id}/addresses"),
|
||||||
|
&[("postal_code", "5030"), ("province", "Chiang Mai")],
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
let t = r.text();
|
||||||
|
assert!(
|
||||||
|
t.contains("five digits") && t.contains("Enter the district"),
|
||||||
|
"{t}"
|
||||||
|
);
|
||||||
|
|
||||||
|
let fields = [
|
||||||
|
("house_no", "1/23"),
|
||||||
|
("building", "Demo Condominium, room 512"),
|
||||||
|
("road", "Chotana Road"),
|
||||||
|
("subdistrict", "Chang Phueak"),
|
||||||
|
("district", "Mueang Chiang Mai"),
|
||||||
|
("province", "Chiang Mai"),
|
||||||
|
("postal_code", "50300"),
|
||||||
|
("moved_in_on", "2026-09-15"),
|
||||||
|
];
|
||||||
|
let r = app.post(&format!("/people/{id}/addresses"), &fields).await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
|
||||||
|
let page = app.get(&format!("/people/{id}")).await.text();
|
||||||
|
assert!(page.contains(
|
||||||
|
"1/23, Demo Condominium, room 512, Chotana Road, Chang Phueak, Mueang Chiang Mai, Chiang Mai 50300"
|
||||||
|
));
|
||||||
|
assert!(page.contains("No TM.30 receipt recorded"));
|
||||||
|
|
||||||
|
let aid: i64 = sqlx::query_scalar("SELECT id FROM addresses WHERE person_id = $1")
|
||||||
|
.bind(id)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let mut with_tm30 = fields.to_vec();
|
||||||
|
with_tm30.push(("tm30_reported_on", "2026-09-16"));
|
||||||
|
with_tm30.push(("tm30_receipt_no", "R-1"));
|
||||||
|
let r = app
|
||||||
|
.post(&format!("/people/{id}/addresses/{aid}"), &with_tm30)
|
||||||
|
.await;
|
||||||
|
assert_eq!(r.status, StatusCode::SEE_OTHER);
|
||||||
|
assert!(
|
||||||
|
app.get(&format!("/people/{id}"))
|
||||||
|
.await
|
||||||
|
.text()
|
||||||
|
.contains("TM.30 reported Sep 16, 2026")
|
||||||
|
);
|
||||||
|
let upd = audit_rows(&pool, id)
|
||||||
|
.await
|
||||||
|
.into_iter()
|
||||||
|
.find(|r| r.0 == "update")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(upd.2, vec!["tm30_reported_on", "tm30_receipt_no"]);
|
||||||
|
|
||||||
|
app.post(&format!("/people/{id}/addresses/{aid}/delete"), &[])
|
||||||
|
.await;
|
||||||
|
let n: i64 = sqlx::query_scalar("SELECT count(*) FROM addresses")
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(n, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "visa::db::MIGRATOR")]
|
||||||
|
async fn the_audit_log_cannot_be_changed(pool: PgPool) {
|
||||||
|
let app = local(pool.clone());
|
||||||
|
app.post("/people", &[("surname", "Doe"), ("first_name", "Jane")])
|
||||||
|
.await;
|
||||||
|
let e = sqlx::query("UPDATE audit_log SET actor = 'someone else'")
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(e.to_string().contains("append-only"), "{e}");
|
||||||
|
let e = sqlx::query("DELETE FROM audit_log")
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(e.to_string().contains("append-only"), "{e}");
|
||||||
|
}
|
||||||
Reference in new issue
Block a user