// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! The REST + JSON API on loopback (`/api/v1`), with its OpenAPI document generated from the //! handlers (utoipa). //! //! Every request: the `Host` header must name this server (against DNS rebinding); a browser //! write without `X-Ianitor-UI: 1` is refused (CSRF); a valid `Authorization: Bearer` API //! token is required (nothing else identifies the caller: control trusts no `Remote-*` //! header); 120 requests a minute per token. Bodies are at most 64 KiB, JSON, with no //! unknown fields. Errors are one typed envelope with a plain-English message. Logs show //! method, route template, status and time only. // An error answer is built once per failed request; boxing it buys nothing. #![allow(clippy::result_large_err)] pub mod handlers; pub mod pki; pub mod ui; pub mod views; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::Instant; use axum::Router; use axum::body::{Body as AxumBody, Bytes}; use axum::extract::{DefaultBodyLimit, FromRequest, MatchedPath, Request, State}; use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; use axum::middleware::{self, Next}; use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, post}; use serde::de::DeserializeOwned; use utoipa::OpenApi; pub use views::health_state; use crate::engine::{Control, Fail}; use crate::messages::{self, Params, message}; use crate::tokens::Refusal; use crate::util::{hex, now, random, rfc3339, sha256_hex}; use views::{ErrorBody, ErrorEnvelope}; pub const MAX_BODY: usize = 64 * 1024; const RATE_PER_MINUTE: u32 = 120; /// Who is calling: the API token's id and name. #[derive(Debug, Clone)] pub struct Actor { pub token_id: String, pub name: String, } pub enum Stored { /// The first request with this key is still being handled. Pending, Apply(String), Json(u16, serde_json::Value), } /// Most Idempotency-Keys held at once (each for 24 h). const MAX_IDEM_KEYS: usize = 2000; pub struct AppState { pub ctl: Arc, idem: Mutex>, rate: Mutex>, } impl AppState { pub fn new(ctl: Arc) -> Arc { Arc::new(AppState { ctl, idem: Mutex::new(HashMap::new()), rate: Mutex::new(HashMap::new()), }) } /// Count one request against `bucket`; `Err(seconds to wait)` over the limit. pub fn limit(&self, bucket: &str, per_window: u32, window: u64) -> Result<(), u64> { let Ok(mut m) = self.rate.lock() else { return Ok(()); }; let t = now(); let slot = t / window; if m.len() > 10_000 { m.retain(|_, (s, _)| *s + 1 >= slot); } let e = m.entry(bucket.to_owned()).or_insert((slot, 0)); if e.0 != slot { *e = (slot, 0); } if e.1 >= per_window { return Err((slot + 1) * window - t); } e.1 += 1; Ok(()) } /// Start a request with an Idempotency-Key, atomically: `Ok(Some)` replays an earlier /// answer, `Ok(None)` reserves the key (finish with [`AppState::idem_finish`]), `Err` when /// the key was used for another request, is still in progress, or no key can be held. pub fn idem_begin(&self, key: &str, fingerprint: &str) -> Result, ApiError> { let mut m = self .idem .lock() .map_err(|_| ApiError::internal("idempotency store"))?; let t = now(); match m.get(key) { Some((fp, _, at)) if t.saturating_sub(*at) < 86_400 && fp != fingerprint => { return Err(ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "request.idempotency", Params::new(), )); } Some((_, Stored::Pending, at)) if t.saturating_sub(*at) < 86_400 => { return Err(ApiError::new( StatusCode::CONFLICT, "request.in_progress", Params::new(), ) .retry(1)); } Some((_, Stored::Apply(id), at)) if t.saturating_sub(*at) < 86_400 => { return Ok(Some(Stored::Apply(id.clone()))); } Some((_, Stored::Json(s, v), at)) if t.saturating_sub(*at) < 86_400 => { return Ok(Some(Stored::Json(*s, v.clone()))); } _ => {} } if m.len() >= MAX_IDEM_KEYS { m.retain(|_, (_, _, at)| t.saturating_sub(*at) < 86_400); } if m.len() >= MAX_IDEM_KEYS { return Err(ApiError::new( StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new(), ) .retry(60)); } m.insert(key.to_owned(), (fingerprint.to_owned(), Stored::Pending, t)); Ok(None) } /// Finish a reserved key: remember the answer, or (on `None`, a refusal) free the key. pub fn idem_finish(&self, key: &str, fingerprint: &str, s: Option) { if let Ok(mut m) = self.idem.lock() { match s { Some(s) => { m.insert(key.to_owned(), (fingerprint.to_owned(), s, now())); } None => { m.remove(key); } } } } } // ---------------------------------------------------------------- errors #[derive(Debug)] pub struct ApiError { pub status: StatusCode, pub body: ErrorBody, pub errors: Vec, } impl ApiError { pub fn new(status: StatusCode, code: &str, params: Params) -> ApiError { ApiError { status, body: ErrorBody { code: code.into(), message: message(code, ¶ms), field: params.get("field").cloned(), params, retry_after_s: None, detail: None, }, errors: Vec::new(), } } pub fn internal(detail: impl Into) -> ApiError { let mut e = ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", Params::new()); e.body.detail = Some(detail.into()); e } pub fn retry(mut self, secs: u64) -> ApiError { self.body.retry_after_s = Some(secs); self.body.params.insert("seconds".into(), secs.to_string()); self.body.message = message(&self.body.code, &self.body.params); self } } impl From for ApiError { fn from(f: Fail) -> ApiError { ApiError { status: StatusCode::from_u16(f.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), body: ErrorBody::from(&f.reason), errors: f.errors.iter().map(ErrorBody::from).collect(), } } } impl IntoResponse for ApiError { fn into_response(self) -> Response { let retry = self.body.retry_after_s; let env = ErrorEnvelope { error: self.body, errors: self.errors, request_id: String::new(), }; let mut r = (self.status, axum::Json(env)).into_response(); if let Some(s) = retry && let Ok(v) = HeaderValue::from_str(&s.to_string()) { r.headers_mut().insert(header::RETRY_AFTER, v); } r } } // ---------------------------------------------------------------- JSON bodies /// A JSON request body: at most 64 KiB, no unknown fields, errors that never echo values. pub struct Body { pub value: T, pub raw: Bytes, } impl FromRequest for Body { type Rejection = ApiError; async fn from_request(req: Request, state: &S) -> Result { let json_type = req .headers() .get(header::CONTENT_TYPE) .and_then(|v| v.to_str().ok()) .is_some_and(|v| v.starts_with("application/json")); let raw = Bytes::from_request(req, state).await.map_err(|_| { ApiError::new( StatusCode::PAYLOAD_TOO_LARGE, "request.too_large", Params::new(), ) })?; let text: &[u8] = if raw.is_empty() { b"{}" } else { &raw }; if !raw.is_empty() && !json_type { return Err(ApiError::new( StatusCode::UNSUPPORTED_MEDIA_TYPE, "request.body", messages::params([("problem", "send it as application/json.".into())]), )); } match serde_json::from_slice::(text) { Ok(value) => Ok(Body { value, raw }), Err(e) => Err(body_error(&e)), } } } fn body_error(e: &serde_json::Error) -> ApiError { let m = e.to_string(); let quoted = |prefix: &str| -> Option { let rest = m.split(prefix).nth(1)?; Some(rest.split('`').next()?.to_owned()) }; if let Some(f) = quoted("unknown field `") { // The name is the sender's: repeat it only if it is a plain field name. let plain = !f.is_empty() && f.len() <= 64 && f.bytes() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_'); let shown = if plain { f } else { "(a field name)".to_owned() }; let mut err = ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "request.body_unknown_field", messages::params([("field", shown.clone())]), ); err.body.field = plain.then_some(shown); return err; } if let Some(f) = quoted("missing field `") { return ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "request.body", messages::params([ ("problem", format!("the field \"{f}\" is missing.")), ("field", f), ]), ); } // Other serde messages can quote the value sent; say only where the problem is. let what = match e.classify() { serde_json::error::Category::Syntax | serde_json::error::Category::Eof => "it is not JSON", _ => "a value has the wrong type or form", }; ApiError::new( StatusCode::BAD_REQUEST, "request.body", messages::params([( "problem", format!("{what} (line {}, column {}).", e.line(), e.column()), )]), ) } // ---------------------------------------------------------------- middleware pub(crate) fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool { let Some(host) = headers.get(header::HOST).and_then(|h| h.to_str().ok()) else { return false; }; let port = ctl.cfg.listen.port(); let ok = [ ctl.cfg.listen.to_string(), format!("localhost:{port}"), format!("127.0.0.1:{port}"), format!("[::1]:{port}"), ]; // The admin host edge forwards the UI on, with or without edge's HTTPS port. let ui = ctl.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref()); let ui_ok = ui.is_some_and(|u| { let edge_port = ctl.cfg.compile.https_listen.port(); host.eq_ignore_ascii_case(u) || host.eq_ignore_ascii_case(&format!("{u}:{edge_port}")) }); ui_ok || ok.iter().any(|o| o.eq_ignore_ascii_case(host)) || ctl .cfg .allowed_hosts .iter() .any(|a| a.eq_ignore_ascii_case(host)) } /// Marks a request that came in on control's UI socket (`[ui] socket`). #[derive(Debug, Clone, Copy)] pub struct ViaUiSocket; enum UiIdentity { /// No sign-in headers: an API-token request. None, /// `Remote-*` or a proof header without the right proof. Forged, /// The right proof but no usable `Remote-User`. NoUser, /// The Authelia user name, and the name to show (`Remote-Name` when it is usable). User(String, String), } fn ui_identity(ctl: &Control, headers: &HeaderMap, via_socket: bool) -> UiIdentity { let names_user = headers.keys().any(|k| k.as_str().starts_with("remote-")); let proof = headers.get("x-ianitor-proof"); if !names_user && proof.is_none() { return UiIdentity::None; } let ok = match (proof, &ctl.ui_proof) { (Some(p), Some(want)) => crate::util::ct_eq(p.as_bytes(), want), _ => false, }; // With a UI socket (G14 option b) the proof counts only there: the loopback port is open // to every local process, and one that learned the proof (say, by taking control's port // while it restarted and reading what edge sent) must not be able to use it. let socket_only = ctl.cfg.ui.as_ref().is_some_and(|u| u.socket.is_some()); if !ok || (socket_only && !via_socket) { return UiIdentity::Forged; } let users: Vec<&HeaderValue> = headers.get_all("remote-user").iter().collect(); match users.as_slice() { [one] => match one.to_str() { Ok(u) if !u.is_empty() && u.len() <= 64 && u.bytes().all(|c| c.is_ascii_graphic() && c != b':') => { let display = headers .get("remote-name") .and_then(|v| v.to_str().ok()) .map(str::trim) .filter(|n| { !n.is_empty() && n.chars().count() <= 64 && !n.chars().any(char::is_control) }) .unwrap_or(u) .to_owned(); UiIdentity::User(u.to_owned(), display) } _ => UiIdentity::NoUser, }, _ => UiIdentity::NoUser, } } /// Host check, CSRF check, token, rate limit; logs method, route template, status, time. async fn guard(State(st): State>, mut req: Request, next: Next) -> Response { let started = Instant::now(); let method = req.method().clone(); let route = req .extensions() .get::() .map(|p| p.as_str().to_owned()) .unwrap_or_else(|| "(no route)".into()); let resp = async { if !host_allowed(&st.ctl, req.headers()) { return Err(ApiError::new( StatusCode::FORBIDDEN, "request.host", Params::new(), )); } let browser = req.headers().contains_key(header::ORIGIN) || req.headers().contains_key("sec-fetch-site"); let write = !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS"); let ui = req .headers() .get("x-ianitor-ui") .is_some_and(|v| v.as_bytes() == b"1"); if browser && write && !ui { return Err(ApiError::new( StatusCode::FORBIDDEN, "request.csrf", Params::new(), )); } // The web UI, through edge on the admin host (docs/api.md, "Sign-in"): only a request // with the per-boot proof edge adds is identified by its Remote-User. Any other // request that names a user is refused, so a local process cannot claim to be one. let via_socket = req.extensions().get::().is_some(); match ui_identity(&st.ctl, req.headers(), via_socket) { UiIdentity::None => {} UiIdentity::Forged => { return Err(ApiError::new( StatusCode::UNAUTHORIZED, "ui.no_proof", Params::new(), )); } UiIdentity::NoUser => { return Err(ApiError::new( StatusCode::UNAUTHORIZED, "ui.no_user", Params::new(), )); } UiIdentity::User(user, display) => { // Cookie-based sign-in: every write carries the UI header, browser or not. if write && !ui { return Err(ApiError::new( StatusCode::FORBIDDEN, "request.csrf", Params::new(), )); } st.limit(&format!("user:{user}"), RATE_PER_MINUTE, 60) .map_err(|s| { ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()) .retry(s) })?; req.extensions_mut().insert(Actor { token_id: format!("user:{user}"), name: display, }); return Ok(next.run(req).await); } } let auth = req .headers() .get(header::AUTHORIZATION) .and_then(|v| v.to_str().ok()) .map(str::to_owned); // The token store takes a file lock: off the async threads. let ctl = st.ctl.clone(); let checked = tokio::task::spawn_blocking(move || ctl.tokens.check(auth.as_deref())) .await .unwrap_or(Err(Refusal::Unknown)); let tok = checked.map_err(|r| { let (code, params) = match r { Refusal::Missing => ("token.missing", Params::new()), Refusal::Unknown => ("token.unknown", Params::new()), Refusal::Expired(t) => ( "token.expired", messages::params([("date", ianitor_core::time::long_date(t))]), ), Refusal::Revoked(t) => ( "token.revoked", messages::params([("date", ianitor_core::time::long_date(t))]), ), }; ApiError::new(StatusCode::UNAUTHORIZED, code, params) })?; st.limit(&format!("token:{}", tok.id), RATE_PER_MINUTE, 60) .map_err(|s| { ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s) })?; req.extensions_mut().insert(Actor { token_id: tok.id, name: tok.name, }); Ok(next.run(req).await) } .await; let resp = resp.unwrap_or_else(IntoResponse::into_response); log::info!(target: "ianitor::api", "{method} {route} {} {} ms", resp.status().as_u16(), started.elapsed().as_millis()); resp } /// Adds `server_time` to every JSON object answer and `request_id` to error envelopes. async fn finish(req: Request, next: Next) -> Response { let request_id = random::<8>().map(|b| hex(&b)).unwrap_or_default(); let resp = next.run(req).await; let json = resp .headers() .get(header::CONTENT_TYPE) .is_some_and(|v| v.as_bytes().starts_with(b"application/json")); let (mut parts, body) = resp.into_parts(); if let Ok(v) = HeaderValue::from_str(&request_id) { parts.headers.insert("x-request-id", v); } if !json { return Response::from_parts(parts, body); } let Ok(bytes) = axum::body::to_bytes(body, 16 << 20).await else { return Response::from_parts(parts, AxumBody::empty()); }; let out = match serde_json::from_slice::(&bytes) { Ok(serde_json::Value::Object(mut m)) => { m.insert("server_time".into(), rfc3339(now()).into()); if m.get("error").is_some_and(serde_json::Value::is_object) { m.insert("request_id".into(), request_id.into()); } serde_json::to_vec(&m).unwrap_or_else(|_| bytes.to_vec()) } _ => bytes.to_vec(), }; parts.headers.remove(header::CONTENT_LENGTH); Response::from_parts(parts, AxumBody::from(out)) } async fn not_found() -> ApiError { ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new()) } async fn method_not_allowed() -> ApiError { ApiError::new( StatusCode::METHOD_NOT_ALLOWED, "request.method", Params::new(), ) } pub fn fingerprint(method: &str, path: &str, raw: &[u8]) -> String { sha256_hex(format!("{method} {path} {}", sha256_hex(raw)).as_bytes()) } pub fn router(st: Arc) -> Router { use handlers as h; let api = Router::new() .route("/api/v1/overview", get(h::overview)) .route("/api/v1/hosts", get(h::list_hosts).post(h::create_host)) .route("/api/v1/hosts/validate", post(h::validate_host)) .route( "/api/v1/hosts/{hostname}", get(h::get_host) .put(h::update_host) .patch(h::patch_host) .delete(h::delete_host), ) .route( "/api/v1/hosts/{hostname}/share-links", post(h::mint_share_link), ) .route( "/api/v1/hosts/{hostname}/certificate/retry", post(h::retry_certificate), ) .route("/api/v1/applies", get(h::list_applies)) .route( "/api/v1/applies/{id}", get(h::get_apply).delete(h::cancel_apply), ) .route("/api/v1/history", get(h::history)) .route("/api/v1/history/{change_id}", get(h::history_entry)) .route( "/api/v1/history/{change_id}/restore-preview", get(h::restore_preview), ) .route("/api/v1/undo", get(h::get_undo).post(h::undo)) .route("/api/v1/restore", post(h::restore)) .route("/api/v1/repo/push", post(h::push_now)) .route("/api/v1/settings", get(h::settings)) .route("/api/v1/tokens", get(h::list_tokens).post(h::create_token)) .route( "/api/v1/tokens/{id}", delete(h::revoke_token).patch(h::rename_token), ) .route("/api/v1/share-links", get(h::list_share_links)) .route( "/api/v1/share-links/stop-all", post(h::stop_all_share_links), ) .route("/api/v1/share-links/{id}", delete(h::stop_share_link)) .route("/api/v1/certs", get(pki::get_certs)) .route("/api/v1/certs/devices", post(pki::request_device)) .route("/api/v1/certs/devices/{id}", delete(pki::revoke_device)) .route("/api/v1/certs/devices/{id}/bundle", post(pki::make_bundle)) .route("/api/v1/certs/intermediate/renewal", post(pki::renew)) .route( "/api/v1/pki-requests/{id}", get(pki::get_request).delete(pki::cancel_request), ) .route("/api/v1/pki-requests/{id}/csr", get(pki::get_csr)) .route("/api/v1/pki-requests/{id}/ext", get(pki::get_ext)) .route( "/api/v1/pki-requests/{id}/certificate", axum::routing::put(pki::put_certificate), ) .route( "/api/v1/engine", get(pki::get_engine).post(pki::switch_engine), ) .route("/api/v1/health", get(h::health)) .route("/api/v1/openapi.json", get(h::openapi)) .method_not_allowed_fallback(method_not_allowed) .fallback(not_found) .layer(middleware::from_fn_with_state(st.clone(), guard)) .layer(DefaultBodyLimit::max(MAX_BODY)) .with_state(st.clone()); // In front of the guard: the built UI (static files, no token: they hold no data) and // the one-time device downloads (the link is the secret). Both still check the Host. api.layer(middleware::from_fn_with_state(st, ui::front)) .layer(middleware::from_fn(finish)) } /// The OpenAPI document. pub fn openapi_json() -> String { handlers::ApiDoc::openapi() .to_pretty_json() .unwrap_or_else(|_| "{}".into()) }