Every day from 07:00 Chiang Mai time the app mails the journal's last entry number and its hash to the addresses set on the Notifications page (src/anchor.rs, migration 0012: settings, journal_anchors), when anything was added since the last anchor that went out. A day without news is noted without a mail; a failed send is tried again after an hour; a transaction-level advisory lock keeps two runs from both sending. "Send the anchor now" sends at once. Each mail says whether the chain checked whole (in capitals when it did not) and links to /journal/anchor, which compares a kept entry number and hash with the journal now: the same hash, another one, or no such entry. Changing the recipients is itself a journal entry. Every anchor mail is in the notifications log. Tests: the daily rule (before seven, once a day, an hour after a failure), recipients checked and journaled, one mail per recipient with the head hash, unchanged days, by hand, the check page's three answers, and a chain broken around the app said in the mail. 126 unit, 67 integration.
884 lines
31 KiB
Rust
884 lines
31 KiB
Rust
//! 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 legal;
|
|
pub mod links;
|
|
pub mod notifications;
|
|
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<Option<Arc<oidc::Provider>>>,
|
|
/// 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<Store>,
|
|
}
|
|
|
|
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()?;
|
|
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<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 companies as c;
|
|
use people as p;
|
|
let mut r = Router::new()
|
|
.route("/", get(landing))
|
|
.route(HOME, 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<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path(id): Path<i64>| records::stay(st, user, id),
|
|
),
|
|
)
|
|
.route(
|
|
"/people/{id}/activity",
|
|
get(
|
|
|State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path(id): Path<i64>| 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}/<slug>, .../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<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path(id): Path<i64>,
|
|
Form(f): Form<Fields>| {
|
|
records::create(kind, st, user, id, f)
|
|
},
|
|
),
|
|
)
|
|
.route(
|
|
&format!("{base}/new"),
|
|
get(
|
|
move |State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path(id): Path<i64>| {
|
|
records::new_form(kind, st, user, id)
|
|
},
|
|
),
|
|
)
|
|
.route(
|
|
&format!("{base}/{{rid}}"),
|
|
post(
|
|
move |State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path((id, rid)): Path<(i64, i64)>,
|
|
Form(f): Form<Fields>| {
|
|
records::update(kind, st, user, id, rid, f)
|
|
},
|
|
),
|
|
)
|
|
.route(
|
|
&format!("{base}/{{rid}}/edit"),
|
|
get(
|
|
move |State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path((id, rid)): Path<(i64, i64)>| {
|
|
records::edit_form(kind, st, user, id, rid)
|
|
},
|
|
),
|
|
)
|
|
.route(
|
|
&format!("{base}/{{rid}}/delete"),
|
|
post(
|
|
move |State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
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<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path(id): Path<i64>,
|
|
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<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path((id, did)): Path<(i64, i64)>,
|
|
Query(q): Query<documents::FileQuery>| {
|
|
documents::file(st, user, owner(id), did, q)
|
|
},
|
|
),
|
|
)
|
|
.route(
|
|
&format!("{base}/{{did}}/sides.pdf"),
|
|
get(
|
|
move |State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path((id, did)): Path<(i64, i64)>| {
|
|
documents::sides(st, user, owner(id), did)
|
|
},
|
|
),
|
|
)
|
|
.route(
|
|
&format!("{base}/{{did}}/edit"),
|
|
get(
|
|
move |State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path((id, did)): Path<(i64, i64)>| {
|
|
documents::edit_form(st, user, owner(id), did)
|
|
},
|
|
),
|
|
)
|
|
.route(
|
|
&format!("{base}/{{did}}"),
|
|
post(
|
|
move |State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path((id, did)): Path<(i64, i64)>,
|
|
Form(f): Form<Fields>| {
|
|
documents::update(st, user, owner(id), did, f)
|
|
},
|
|
),
|
|
)
|
|
.route(
|
|
&format!("{base}/{{did}}/delete"),
|
|
post(
|
|
move |State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
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),
|
|
);
|
|
// The legal practice (phase 9): lawyers, clients and contracts are
|
|
// records with a form each; a contract's versions, its paper copies and
|
|
// the journal have their own pages.
|
|
{
|
|
use crate::legal::{CLIENTS, CONTRACTS, LAWYERS};
|
|
use legal as l;
|
|
macro_rules! record_routes {
|
|
($r:ident, $kind:expr, $base:literal, $list:expr, $show:expr) => {
|
|
$r = $r
|
|
.route(
|
|
$base,
|
|
get($list).post(
|
|
|State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Form(f): Form<Fields>| l::create(&$kind, st, user, f),
|
|
),
|
|
)
|
|
.route(
|
|
concat!($base, "/new"),
|
|
get(
|
|
|State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Query(q): Query<l::NewQuery>| {
|
|
l::new_form(&$kind, st, user, q)
|
|
},
|
|
),
|
|
)
|
|
.route(
|
|
concat!($base, "/{id}"),
|
|
get($show).post(
|
|
|State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path(id): Path<i64>,
|
|
Form(f): Form<Fields>| {
|
|
l::update(&$kind, st, user, id, f)
|
|
},
|
|
),
|
|
)
|
|
.route(
|
|
concat!($base, "/{id}/edit"),
|
|
get(
|
|
|State(st): State<Arc<AppState>>,
|
|
Extension(user): Extension<User>,
|
|
Path(id): Path<i64>| {
|
|
l::edit_form(&$kind, st, user, id)
|
|
},
|
|
),
|
|
);
|
|
};
|
|
}
|
|
record_routes!(r, LAWYERS, "/lawyers", l::lawyers, l::lawyer);
|
|
record_routes!(r, CLIENTS, "/clients", l::clients, l::client_page);
|
|
record_routes!(r, CONTRACTS, "/contracts", l::contracts, l::contract_page);
|
|
r = r
|
|
.route(
|
|
"/contracts/{id}/versions",
|
|
post(l::add_version).layer(DefaultBodyLimit::max(documents::UPLOAD_LIMIT)),
|
|
)
|
|
.route("/contracts/{id}/versions/{n}/file", get(l::version_file))
|
|
.route("/contracts/{id}/papers", post(l::add_paper))
|
|
.route("/contracts/{id}/parties", post(l::add_party))
|
|
.route(
|
|
"/contracts/{id}/parties/{pid}/remove",
|
|
post(l::remove_party),
|
|
)
|
|
.route("/conflicts", get(l::conflicts_page))
|
|
.route("/papers", get(l::find_paper))
|
|
.route("/papers/{code}", get(l::paper_by_code))
|
|
.route("/papers/{pid}/move", post(l::move_paper))
|
|
.route("/papers/{pid}/label", get(l::paper_label))
|
|
.route("/journal", get(l::journal_page))
|
|
.route("/journal.csv", get(l::journal_csv))
|
|
.route("/journal/anchor", get(l::anchor_check));
|
|
}
|
|
r.route("/activity", get(activity::page))
|
|
.route("/notifications", get(notifications::notifications))
|
|
.route("/notifications/test-email", post(notifications::test_email))
|
|
.route("/notifications/anchor-to", post(notifications::anchor_to))
|
|
.route("/notifications/anchor-now", post(notifications::anchor_now))
|
|
.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: `/`, which leads to the back office, and the
|
|
/// client's pages (`/c/<token>`, 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<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(|| HOME.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<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 lannadesk.com and try again there.",
|
|
(HOME, "Open the app"),
|
|
);
|
|
}
|
|
let Some(user) = req.extensions().get::<User>().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`,
|
|
/// `/companies/{id}/documents` and a contract's `/contracts/{id}/versions`.
|
|
fn is_upload(path: &str) -> bool {
|
|
let parts: Vec<&str> = path.split('/').collect();
|
|
matches!(
|
|
parts.as_slice(),
|
|
["", "people" | "companies", id, "documents"] | ["", "contracts", id, "versions"]
|
|
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.",
|
|
(HOME, "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()
|
|
}
|
|
_ => HOME.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,
|
|
)
|
|
}
|
|
|
|
/// The back office's first page, the deadlines; `/` is the public page.
|
|
pub const HOME: &str = "/desk";
|
|
|
|
/// `/` leads to the back office. Lanna Desk's public website is
|
|
/// lannadesk.com (B4L/lannadesk-web); this app is app.lannadesk.com.
|
|
async fn landing() -> Response {
|
|
Redirect::to(HOME).into_response()
|
|
}
|
|
|
|
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()
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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<String>) -> 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<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>;
|