//! The web side: state, routes, the login gate, form checks, rendering. pub mod activity; pub mod agreements; pub mod auth; pub mod client; pub mod companies; pub mod dashboard; pub mod documents; pub mod links; pub mod pack; pub mod papers; pub mod people; pub mod records; use std::sync::{Arc, RwLock}; use std::time::Duration; use axum::body::Body; use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, Request, State}; use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header}; use axum::middleware::{self, Next}; use axum::response::{Html, IntoResponse, Redirect, Response}; 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::documents::Owner; use crate::files::Store; use crate::forms::Fields; use crate::session::{self, Flows, SESSION_COOKIE, User}; use crate::{VERSION, countries, dates, embedded, oidc}; 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, /// The documents' files; none in local development without a place /// and a key for them. pub files: Option, } 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()?; let files = cfg.files.as_ref().map(Store::open).transpose()?; Ok(Arc::new(AppState { templates: templates()?, files, 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/new-client", get(links::new_client_form).post(links::new_client), ) .route("/people/{id}/links", post(links::create)) .route("/people/{id}/links/{lid}/close", post(links::close)) .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) }, ), ); } // Documents of people and of companies: the upload, a file, the page // about one document, its change and its deletion. A person's documents // have their own tab; a company's are on its page. r = r.route("/people/{id}/documents", get(documents::person_tab)); // The filled-in forms: the tab, and a form's PDF (or the extension's). r = r .route("/people/{id}/forms", get(papers::tab)) .route("/people/{id}/forms/{file}", get(papers::pdf)); // The extension pack: its checklist, and all of it as one PDF. r = r .route("/people/{id}/pack", get(pack::tab)) .route("/people/{id}/pack.pdf", get(pack::pdf)); type OwnerOf = fn(i64) -> Owner; let owners: [(&str, OwnerOf); 2] = [("people", Owner::Person), ("companies", Owner::Company)]; for (prefix, owner) in owners { let base = format!("/{prefix}/{{id}}/documents"); r = r .route( &base, post( move |State(st): State>, Extension(user): Extension, Path(id): Path, mp: Multipart| { documents::upload(st, user, owner(id), mp) }, ) .layer(DefaultBodyLimit::max(documents::UPLOAD_LIMIT)), ) .route( &format!("{base}/{{did}}/file"), get( move |State(st): State>, Extension(user): Extension, Path((id, did)): Path<(i64, i64)>, Query(q): Query| { documents::file(st, user, owner(id), did, q) }, ), ) .route( &format!("{base}/{{did}}/sides.pdf"), get( move |State(st): State>, Extension(user): Extension, Path((id, did)): Path<(i64, i64)>| { documents::sides(st, user, owner(id), did) }, ), ) .route( &format!("{base}/{{did}}/edit"), get( move |State(st): State>, Extension(user): Extension, Path((id, did)): Path<(i64, i64)>| { documents::edit_form(st, user, owner(id), did) }, ), ) .route( &format!("{base}/{{did}}"), post( move |State(st): State>, Extension(user): Extension, Path((id, did)): Path<(i64, i64)>, Form(f): Form| { documents::update(st, user, owner(id), did, f) }, ), ) .route( &format!("{base}/{{did}}/delete"), post( move |State(st): State>, Extension(user): Extension, Path((id, did)): Path<(i64, i64)>| { documents::delete(st, user, owner(id), did) }, ), ); } // The client's pages: open without a login, each checks its link. r = r .route("/c/{token}", get(client::overview)) .route( "/c/{token}/about", get(client::about).post(client::about_save), ) .route( "/c/{token}/contact", get(client::contact).post(client::contact_save), ) .route( "/c/{token}/passport", get(client::passport).post(client::passport_save), ) .route( "/c/{token}/address", get(client::address).post(client::address_save), ) .route( "/c/{token}/documents", get(client::documents_get) .post(client::documents_upload) .layer(DefaultBodyLimit::max(documents::UPLOAD_LIMIT)), ) .route("/c/{token}/send", post(client::send)); r = r .route( "/agreements", get(agreements::list).post(agreements::create), ) .route("/agreements/new", get(agreements::new_form)) .route("/agreements/{id}", get(agreements::show)) .route("/agreements/{id}/versions", post(agreements::publish)) .route( "/agreements/{id}/versions/{n}", get(agreements::show_version), ) .route("/agreements/{id}/active", post(agreements::set_active)) .route( "/c/{token}/agree/{id}", get(client::agreement).post(client::sign), ); 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("/version", get(version)) .route("/static/{*path}", get(static_file)) // asked for by pages without their own icon: an image or a PDF .route( "/favicon.ico", get(|| static_file(Path("favicon.svg".to_string()))), ) .fallback(not_found) .layer(middleware::from_fn_with_state(st.clone(), forms_guard)) .layer(middleware::from_fn_with_state(st.clone(), gate)) .layer(middleware::from_fn(security_headers)) .with_state(st) } /// Paths open without a session: the client's pages (`/c/`, which /// check their link themselves) among them. fn is_public(path: &str) -> bool { matches!( path, "/healthz" | "/version" | "/login" | "/auth/callback" | "/signed-out" | "/favicon.ico" ) || path.starts_with("/static/") || path.starts_with("/c/") } /// 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. An /// agreement's text in Thai takes nine bytes a character once encoded. const FORM_LIMIT: usize = 1024 * 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 but the client's, which check the // link's own token (`web::client`) return next.run(req).await; }; let multipart = req .headers() .get(header::CONTENT_TYPE) .and_then(|v| v.to_str().ok()) .is_some_and(|ct| ct.to_ascii_lowercase().starts_with("multipart/form-data")); if multipart { // An upload checks its token itself, as the form's first field, so // that its files are not held here. if is_upload(req.uri().path()) { return next.run(req).await; } return ( StatusCode::UNSUPPORTED_MEDIA_TYPE, "This address takes no uploads.", ) .into_response(); } let (parts, body) = req.into_parts(); let bytes = match axum::body::to_bytes(body, FORM_LIMIT).await { Ok(b) => b, 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 expired(&st); } next.run(Request::from_parts(parts, Body::from(bytes))) .await } /// The addresses that take uploads: `/people/{id}/documents` and /// `/companies/{id}/documents`. fn is_upload(path: &str) -> bool { let parts: Vec<&str> = path.split('/').collect(); matches!( parts.as_slice(), ["", "people" | "companies", id, "documents"] if !id.is_empty() && id.bytes().all(|b| b.is_ascii_digit()) ) } /// A form without the session's token. pub fn expired(st: &AppState) -> Response { message( st, StatusCode::FORBIDDEN, "The form has expired", "The page was older than your current session. Go back, reload the page and send the \ form again.", ("/", "Open the app"), ) } pub fn same_site(st: &AppState, headers: &HeaderMap) -> bool { match headers.get("sec-fetch-site").and_then(|v| v.to_str().ok()) { Some(v) => v == "same-origin", None => { headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) == Some(st.cfg.public_url.as_str()) } } } /// Every page's policy: nothing but the app's own files, no inline script. pub const PAGE_CSP: &str = "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'"; /// The policy of the pages that read a passport from a photo, and of the /// reader's own files: WebAssembly may run (a worker takes the policy of /// its script, in some browsers the page's), and a picture may be shown /// from a `blob:` address. pub const READER_CSP: &str = "default-src 'self'; img-src 'self' data: blob:; style-src 'self'; \ script-src 'self' 'wasm-unsafe-eval'; worker-src 'self'; connect-src 'self'; \ frame-ancestors 'none'; base-uri 'none'; form-action 'self'"; /// A page with the passport photo reader, or one of its files: its policy, /// and the camera allowed to this site for the camera view. pub fn with_reader(mut resp: Response) -> Response { let h = resp.headers_mut(); h.insert( header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(READER_CSP), ); h.insert( HeaderName::from_static("permissions-policy"), HeaderValue::from_static("camera=(self), microphone=(), geolocation=()"), ); resp } async fn security_headers(req: Request, next: Next) -> Response { let mut resp = next.run(req).await; let h = resp.headers_mut(); // a document's file brings its own, stricter policy if !h.contains_key(header::CONTENT_SECURITY_POLICY) { h.insert( header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(PAGE_CSP), ); } 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"), ); // the photo reader's pages allow the camera (`with_reader`) let policy = HeaderName::from_static("permissions-policy"); if !h.contains_key(&policy) { h.insert( 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, commit => embedded::short(embedded::COMMIT), commit_url => embedded::url(embedded::COMMIT), ..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() } } } /// The commit that runs, in full, for scripts and the fleet's checks; open /// without a session, like the health check. async fn version() -> Response { let commit = match embedded::COMMIT { "" => "unknown", c => c, }; ( [ (header::CONTENT_TYPE, "text/plain; charset=utf-8"), (header::CACHE_CONTROL, "no-store"), ], format!("{commit}\n"), ) .into_response() } async fn static_file(Path(path): Path) -> Response { match embedded::static_file(&path) { Some(bytes) => { let resp = ( [ (header::CONTENT_TYPE, embedded::content_type(&path)), (header::CACHE_CONTROL, "public, max-age=86400"), ], bytes, ) .into_response(); // the photo reader's worker compiles WebAssembly if path.starts_with("vendor/tesseract/") { with_reader(resp) } else { resp } } 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;