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

+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>;