Phase 1: app, Kanidm login, people, passports, addresses, audit log
CI / secret scan (push) Successful in 4s
CI / fmt, clippy, tests (push) Successful in 42s

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:
grabowski committed 2026-11-17 16:58:48 +07:00
commit 2e009700a9
56 files changed
+11193

No files matched your search

+164
View File
@@ -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
View File
@@ -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();
}
}
+132
View File
@@ -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");
}
}
+252
View File
@@ -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
View File
@@ -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");
}
}
+32
View File
@@ -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")
}
+41
View File
@@ -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);
}
}
+45
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
File diff suppressed because it is too large. Load diff
+344
View File
@@ -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
View File
@@ -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);
}
}
+43
View File
@@ -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
View File
@@ -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
View File
@@ -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>;
+970
View File
@@ -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())
}