//! The web side: state, routes, the login gate, form checks, rendering. pub mod activity; pub mod auth; pub mod companies; pub mod dashboard; pub mod people; pub mod records; use std::sync::{Arc, RwLock}; use std::time::Duration; 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 axum::{Extension, Form, Router}; use minijinja::{Environment, Value, context}; use sqlx::PgPool; use tracing::{error, info, warn}; use crate::config::{Auth, Config}; use crate::forms::Fields; 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>>, /// The form token of local development, which has no sessions. local_csrf: String, } impl AppState { pub fn new(cfg: Config, db: PgPool) -> anyhow::Result> { 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> { 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> { 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 { v.as_deref() .and_then(dates::parse_date) .map(dates::fmt_date) .unwrap_or_default() }); env.add_filter("country", |v: Option| -> 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) { 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) -> Router { use companies as c; use people as p; let mut r = Router::new() .route("/", get(dashboard::page_handler)) .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( "/people/{id}/stay", get( |State(st): State>, Extension(user): Extension, Path(id): Path| records::stay(st, user, id), ), ) .route( "/people/{id}/activity", get( |State(st): State>, Extension(user): Extension, Path(id): Path| records::person_activity(st, user, id), ), ) .route("/companies", get(c::list).post(c::create)) .route("/companies/new", get(c::new_form)) .route("/companies/{id}", get(c::show).post(c::update)) .route("/companies/{id}/edit", get(c::edit_form)) .route("/companies/{id}/archive", post(c::archive)) .route("/companies/{id}/restore", post(c::restore)) .route("/companies/{id}/employees", post(c::hire)) .route("/companies/{id}/employees/{pid}/remove", post(c::release)); // Every kind of stay record: /people/{id}/, .../new, // .../{rid}, .../{rid}/edit and .../{rid}/delete. for kind in crate::records::STAY { let base = format!("/people/{{id}}/{}", kind.slug); r = r .route( &base, post( move |State(st): State>, Extension(user): Extension, Path(id): Path, Form(f): Form| { records::create(kind, st, user, id, f) }, ), ) .route( &format!("{base}/new"), get( move |State(st): State>, Extension(user): Extension, Path(id): Path| { records::new_form(kind, st, user, id) }, ), ) .route( &format!("{base}/{{rid}}"), post( move |State(st): State>, Extension(user): Extension, Path((id, rid)): Path<(i64, i64)>, Form(f): Form| { records::update(kind, st, user, id, rid, f) }, ), ) .route( &format!("{base}/{{rid}}/edit"), get( move |State(st): State>, Extension(user): Extension, Path((id, rid)): Path<(i64, i64)>| { records::edit_form(kind, st, user, id, rid) }, ), ) .route( &format!("{base}/{{rid}}/delete"), post( move |State(st): State>, Extension(user): Extension, Path((id, rid)): Path<(i64, i64)>| { records::delete(kind, st, user, id, rid) }, ), ); } r.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>, 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>, 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::().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>) -> Response { not_found_page(&st) } async fn healthz(State(st): State>) -> 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) -> 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> From 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;