// SPDX-License-Identifier: CPAL-1.0 // Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution // License 1.0: see LICENSE (its Exhibit A is this file's notice). //! The handlers, each annotated for the OpenAPI document. // An error answer is built once per failed request; boxing it buys nothing. #![allow(clippy::result_large_err)] use std::sync::Arc; use axum::Extension; use axum::extract::{Path, Query, State}; use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; use axum::response::{IntoResponse, Response}; use serde::Deserialize; use utoipa::{IntoParams, Modify, OpenApi, ToSchema}; use super::views::*; use super::{Actor, ApiError, AppState, Body, Stored, fingerprint}; use crate::engine::Change; use crate::hostspec::{HeaderRuleSpec, HealthCheckSpec, HostSpec}; use crate::messages::{self, Params, message}; use crate::records::{FieldError, Reason, Step, WatchHost}; use crate::shares::MintError; use crate::util::{now, rfc3339, sha256_hex}; type Shared = State>; fn json(status: StatusCode, v: &T) -> Response { (status, axum::Json(v)).into_response() } fn check_hostname_param(h: &str) -> Result<(), ApiError> { if h.is_empty() || h.len() > 253 || !h .bytes() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'.' || c == b'-') { // Not a hostname: say so without repeating what was sent. let mut e = ApiError::new(StatusCode::NOT_FOUND, "host.not_found", Params::new()); e.body.message = "There is no such host.".into(); return Err(e); } Ok(()) } fn idem_key(headers: &HeaderMap) -> Result, ApiError> { match headers.get("idempotency-key") { None => Ok(None), Some(v) => { let s = v.to_str().unwrap_or(""); if s.is_empty() || s.len() > 128 || !s.bytes().all(|c| c.is_ascii_graphic()) { return Err(ApiError::new( StatusCode::BAD_REQUEST, "request.body", messages::params([( "problem", "the Idempotency-Key header must be 1 to 128 visible characters.".into(), )]), )); } Ok(Some(s.to_owned())) } } } /// Queue a change, answering 202 with the apply; a retried request with the same /// Idempotency-Key gets the same apply back instead of a second one. fn submit( st: &AppState, headers: &HeaderMap, fp: String, actor: &Actor, change: Change, base_rev: Option, ) -> Result { let key = idem_key(headers)?.map(|k| format!("{}:{k}", actor.token_id)); if let Some(k) = &key && let Some(stored) = st.idem_begin(k, &fp)? { return Ok(replay(st, stored)); } let rec = match st.ctl.submit(change, base_rev, &actor.name) { Ok(r) => r, Err(f) => { if let Some(k) = &key { st.idem_finish(k, &fp, None); } return Err(f.into()); } }; if let Some(k) = &key { st.idem_finish(k, &fp, Some(Stored::Apply(rec.id.clone()))); } Ok(json( StatusCode::ACCEPTED, &ApplyAccepted { apply: apply_view(&st.ctl, &rec), }, )) } fn replay(st: &AppState, s: Stored) -> Response { match s { Stored::Apply(id) => match st.ctl.record(&id) { Some(r) => json( StatusCode::ACCEPTED, &ApplyAccepted { apply: apply_view(&st.ctl, &r), }, ), None => ApiError::internal("the remembered apply is gone").into_response(), }, Stored::Json(status, v) => json(StatusCode::from_u16(status).unwrap_or(StatusCode::OK), &v), Stored::Pending => { ApiError::new(StatusCode::CONFLICT, "request.in_progress", Params::new()) .retry(1) .into_response() } } } // ---------------------------------------------------------------- overview and hosts /// What is known to differ on Caddy for these routes (decision Q3: switch allowed, the /// differences listed). Control cannot run the differential suite at runtime; these are the /// suite's known differences (tests/diff, KD-*) applied to the hosts that use the feature. /// Returns (hosts compared, hosts that behave the same, sentences). pub fn fallback_differences(m: &ianitor_core::Model) -> (u32, u32, Vec) { let mut out = Vec::new(); let mut matched = 0u32; for h in m.hosts() { let before = out.len(); if h.share_links { out.push(format!( "{}: share links do not work; visitors with a link get the normal sign-in.", h.hostname )); } if h.auth == ianitor_core::AuthMode::ForwardAuth { out.push(format!( "{}: if Authelia's answer is broken or cut off, Pingora refuses the visit; Caddy goes by its status alone.", h.hostname )); } if out.len() == before { matched += 1; } } if !m.hosts().is_empty() { out.push( "Every host: Caddy adds its own Server and Via headers to answers, and a Content-Type when your service sends none." .into(), ); } let n = u32::try_from(m.hosts().len()).unwrap_or(u32::MAX); (n, matched, out) } /// Everything the main screen shows, in one call. Answers 304 to a matching If-None-Match. #[utoipa::path(get, path = "/api/v1/overview", tag = "overview", responses((status = 200, body = Overview), (status = 304, description = "Unchanged since the ETag"), (status = 401, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn overview( State(st): Shared, Extension(actor): Extension, headers: HeaderMap, ) -> Result { let c = &st.ctl; let (status, error, since) = { let h = c .health .lock() .map_err(|_| ApiError::internal("health cache"))?; (h.status.clone(), h.error.clone(), h.since.clone()) }; let head = c .repo .head_required() .map_err(|e| ApiError::internal(e.to_string()))?; let tree = c.repo.tree(&head).ok(); let hosts = tree .as_ref() .map(|t| host_rows(c, t, status.as_ref(), &since)) .unwrap_or_default(); let mut counts = Counts { hosts: hosts.len(), ..Counts::default() }; for h in &hosts { match h.health.state.as_str() { "healthy" => counts.healthy += 1, "degraded" => counts.degraded += 1, "down" => counts.down += 1, _ => counts.unknown += 1, } } let recs = c.records(); let last_apply = recs.last().map(|r| apply_view(c, r)); let active = recs .iter() .rev() .find(|r| r.is_running()) .map(|r| ActiveApply { id: r.id.clone(), state: r.state.clone(), summary: r.summary.clone(), seconds_left: r.watch.as_ref().map(|w| w.ends.saturating_sub(now())), kind: r.kind.clone(), hosts: r.hosts.clone(), watch_ends_at: r.watch.as_ref().map(|w| rfc3339(w.ends)), queued: c.queued_count(), }); let site = tree .as_ref() .and_then(|t| t.model().ok()) .map(|m| SiteView { forward_auth_configured: m.site().forward_auth.is_some(), acme_configured: true, secrets: m.site().secrets.iter().map(|s| s.to_string()).collect(), watch_seconds: c.cfg.watch_secs, share_links_available: c.share_key.is_some() && c.engine_running() != "caddy", auth_logout_url: c.cfg.ui.as_ref().and_then(|u| u.logout_url.clone()), }); let es = super::pki::engine_view(c); let on_caddy = es.running == "caddy"; let caddy_built = std::fs::metadata(&c.cfg.caddy.config) .and_then(|m| m.modified()) .ok() .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) .map(|d| rfc3339(d.as_secs())); let caddy_current = tree .as_ref() .and_then(|t| t.model().ok()) .and_then(|m| ianitor_core::compile::caddy(&m, &c.cfg.caddy_compile().options()).ok()) .is_some_and(|text| { std::fs::read_to_string(&c.cfg.caddy.config).ok().as_deref() == Some(text.as_str()) }); let ov = Overview { counts, hosts, engine: EngineView { state: if es.state == "switching" { "switching".into() } else if on_caddy || (status.is_some() && error.is_none()) { "running".into() } else { "stopped".into() }, since: if on_caddy || es.state == "switching" { Some(es.since.clone()) } else { status.as_ref().map(|s| rfc3339(s.started_at)) }, running: es.running, target: es.target, switchable: es.switchable, fallback_ready: Some({ let (compared, matched, differences) = tree .as_ref() .and_then(|t| t.model().ok()) .map(|m| fallback_differences(&m)) .unwrap_or_default(); FallbackReady { built_at: caddy_built, current: caddy_current, compared, matched, differences, } }), last_error: es.last_error, notes: es.notes, }, last_apply, undo: undo_view(c), active_apply: active, repo: Some(repo_view(c, &head)), intermediate: super::pki::intermediate_view(c), site, paused_reason: c.effective_pause().map(|p| p.code), paused_detail: c.effective_pause().and_then(|p| p.detail), paused: c.effective_pause().map(|p| Blocked { code: "control.paused".into(), message: message("control.paused", &messages::params([("reason", p.message)])), }), // Under Caddy, health is not read (edge is stopped); the chip says Caddy serves. health_error: error .filter(|_| c.edge.attached() && !on_caddy) .map(|_| Blocked { code: "health.unavailable".into(), message: message( "health.unavailable", &messages::params([("engine", "Pingora".into())]), ), }), rev: Some(head), viewer: Some(Viewer { via: if actor.token_id.starts_with("user:") { "authelia".into() } else { "token".into() }, name: actor.name.clone(), }), }; let body = serde_json::to_vec(&ov).map_err(|e| ApiError::internal(e.to_string()))?; let etag = format!("\"{}\"", &sha256_hex(&body)[..32]); let mut resp = if headers .get(header::IF_NONE_MATCH) .is_some_and(|v| v.as_bytes() == etag.as_bytes()) { StatusCode::NOT_MODIFIED.into_response() } else { json(StatusCode::OK, &ov) }; if let Ok(v) = HeaderValue::from_str(&etag) { resp.headers_mut().insert(header::ETAG, v); } Ok(resp) } fn repo_view(c: &crate::engine::Control, head: &str) -> RepoView { let p = c.push_state(); RepoView { name: c.cfg.routes.remote_name.clone(), last_push_at: p.last_push_at.map(rfc3339), unpushed: if c.cfg.routes.remote.is_some() { c.repo.count_between(p.pushed.as_deref(), head).unwrap_or(0) } else { 0 }, push_error_code: p.error_code, remote_configured: c.cfg.routes.remote.is_some(), } } /// Every host with its health. #[utoipa::path(get, path = "/api/v1/hosts", tag = "hosts", responses((status = 200, body = HostList), (status = 401, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn list_hosts(State(st): Shared) -> Result { let c = &st.ctl; let head = c .repo .head_required() .map_err(|e| ApiError::internal(e.to_string()))?; let tree = c .repo .tree(&head) .map_err(|e| ApiError::internal(e.to_string()))?; let (status, since) = { let h = c .health .lock() .map_err(|_| ApiError::internal("health cache"))?; (h.status.clone(), h.since.clone()) }; Ok(json( StatusCode::OK, &HostList { hosts: host_rows(c, &tree, status.as_ref(), &since), rev: head, }, )) } /// One host: every field, its file, its health, and `rev` to send back as `base_rev`. #[utoipa::path(get, path = "/api/v1/hosts/{hostname}", tag = "hosts", params(("hostname" = String, Path)), responses((status = 200, body = HostDetail), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn get_host( State(st): Shared, Path(hostname): Path, ) -> Result { check_hostname_param(&hostname)?; let c = &st.ctl; let head = c .repo .head_required() .map_err(|e| ApiError::internal(e.to_string()))?; let tree = c .repo .tree(&head) .map_err(|e| ApiError::internal(e.to_string()))?; let Some(text) = tree.host(&hostname) else { return Err(ApiError::new( StatusCode::NOT_FOUND, "host.not_found", messages::params([("hostname", hostname)]), )); }; let spec = HostSpec::from_toml(text).map_err(|e| { let mut err = ApiError::new( StatusCode::CONFLICT, "repo.unreadable", messages::params([("file", ianitor_core::routes::host_path(&hostname))]), ); err.body.detail = Some(e); err })?; let (status, since) = { let h = c .health .lock() .map_err(|_| ApiError::internal("health cache"))?; (h.status.clone(), h.since.clone()) }; let hs = status .as_ref() .and_then(|s| s.hosts.iter().find(|x| x.hostname == hostname)); Ok(json( StatusCode::OK, &HostDetail { health: health_view(hs, Some(&spec), since.get(&hostname).copied()), certificate: cert_view(hs, Some(&spec)), host: spec, rev: head, toml: text.to_owned(), }, )) } #[derive(Debug, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct HostWrite { pub host: HostSpec, /// The routes commit the form was loaded from (`rev`). pub base_rev: Option, } #[derive(Debug, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct HostPatch { pub share_links: bool, pub base_rev: Option, } #[derive(Debug, Deserialize, IntoParams)] #[serde(deny_unknown_fields)] pub struct ValidateQuery { /// `create` (the hostname must be new) or `edit`. pub mode: Option, } #[derive(Debug, Deserialize, IntoParams)] #[serde(deny_unknown_fields)] pub struct BaseRevQuery { pub base_rev: Option, } /// Check a host body without applying it (field blur in the form). #[utoipa::path(post, path = "/api/v1/hosts/validate", tag = "hosts", params(ValidateQuery), request_body = HostSpec, responses((status = 200, body = Done), (status = 422, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn validate_host( State(st): Shared, Query(q): Query, body: Body, ) -> Result { let create = match q.mode.as_deref() { None | Some("create") => true, Some("edit") => false, Some(_) => { return Err(ApiError::new( StatusCode::BAD_REQUEST, "request.body", messages::params([("problem", "mode must be create or edit.".into())]), )); } }; st.ctl.validate(&body.value, create)?; Ok(json( StatusCode::OK, &Done { message: "This host can be applied.".into(), }, )) } /// Add a host. Answers 202 with the apply; poll `GET /applies/{id}`. #[utoipa::path(post, path = "/api/v1/hosts", tag = "hosts", request_body = HostWrite, params(("Idempotency-Key" = Option, Header, description = "One per click; a retry with the same key returns the same apply")), responses((status = 202, body = ApplyAccepted), (status = 409, body = ErrorEnvelope), (status = 422, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn create_host( State(st): Shared, Extension(actor): Extension, headers: HeaderMap, body: Body, ) -> Result { let fp = fingerprint("POST", "/api/v1/hosts", &body.raw); let b = body.value; submit( &st, &headers, fp, &actor, Change::Put { spec: b.host, create: true, }, b.base_rev, ) } /// Change a host (all fields). The hostname in the body must be the one in the path. #[utoipa::path(put, path = "/api/v1/hosts/{hostname}", tag = "hosts", request_body = HostWrite, params(("hostname" = String, Path), ("Idempotency-Key" = Option, Header)), responses((status = 202, body = ApplyAccepted), (status = 404, body = ErrorEnvelope), (status = 409, body = ErrorEnvelope), (status = 422, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn update_host( State(st): Shared, Extension(actor): Extension, Path(hostname): Path, headers: HeaderMap, body: Body, ) -> Result { check_hostname_param(&hostname)?; let fp = fingerprint("PUT", &format!("/api/v1/hosts/{hostname}"), &body.raw); let b = body.value; if b.host.hostname != hostname { let mut e = ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "host.hostname.mismatch", messages::params([ ("hostname", b.host.hostname.clone()), ("path_hostname", hostname), ]), ); e.body.field = Some("hostname".into()); return Err(e); } submit( &st, &headers, fp, &actor, Change::Put { spec: b.host, create: false, }, b.base_rev, ) } /// Turn share links on or off for a host (an apply like any other). #[utoipa::path(patch, path = "/api/v1/hosts/{hostname}", tag = "hosts", request_body = HostPatch, params(("hostname" = String, Path), ("Idempotency-Key" = Option, Header)), responses((status = 202, body = ApplyAccepted), (status = 404, body = ErrorEnvelope), (status = 409, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn patch_host( State(st): Shared, Extension(actor): Extension, Path(hostname): Path, headers: HeaderMap, body: Body, ) -> Result { check_hostname_param(&hostname)?; let fp = fingerprint("PATCH", &format!("/api/v1/hosts/{hostname}"), &body.raw); let b = body.value; submit( &st, &headers, fp, &actor, Change::ShareLinks { hostname, on: b.share_links, }, b.base_rev, ) } /// Remove a host. No confirmation: Undo brings it back in one click. #[utoipa::path(delete, path = "/api/v1/hosts/{hostname}", tag = "hosts", params(("hostname" = String, Path), BaseRevQuery, ("Idempotency-Key" = Option, Header)), responses((status = 202, body = ApplyAccepted), (status = 404, body = ErrorEnvelope), (status = 409, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn delete_host( State(st): Shared, Extension(actor): Extension, Path(hostname): Path, Query(q): Query, headers: HeaderMap, ) -> Result { check_hostname_param(&hostname)?; let fp = fingerprint( "DELETE", &format!("/api/v1/hosts/{hostname}"), q.base_rev.as_deref().unwrap_or("").as_bytes(), ); submit( &st, &headers, fp, &actor, Change::Delete { hostname }, q.base_rev, ) } /// Ask edge to try Let's Encrypt again now for this host. #[utoipa::path(post, path = "/api/v1/hosts/{hostname}/certificate/retry", tag = "hosts", params(("hostname" = String, Path)), responses((status = 200, body = Done), (status = 503, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn retry_certificate( State(st): Shared, Path(hostname): Path, ) -> Result { check_hostname_param(&hostname)?; st.ctl.edge.acme_retry().await.map_err(|e| { let mut err = ApiError::new( StatusCode::SERVICE_UNAVAILABLE, "apply.failed.edge_unreachable", Params::new(), ); err.body.detail = Some(e.to_string()); err })?; Ok(json( StatusCode::OK, &Done { message: "Trying again now.".into(), }, )) } // ---------------------------------------------------------------- applies, history, undo, restore #[derive(Debug, Deserialize, IntoParams)] #[serde(deny_unknown_fields)] pub struct ListQuery { pub limit: Option, /// A change id: entries older than it. pub before: Option, /// Only changes touching this host. pub host: Option, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct ApplyList { pub items: Vec, } /// Recent applies, newest first. #[utoipa::path(get, path = "/api/v1/applies", tag = "applies", params(ListQuery), responses((status = 200, body = ApplyList)), security(("bearer" = [])))] pub async fn list_applies( State(st): Shared, Query(q): Query, ) -> Result { let limit = q.limit.unwrap_or(20).clamp(1, 200); let items = st .ctl .records() .iter() .rev() .take(limit) .map(|r| apply_view(&st.ctl, r)) .collect(); Ok(json(StatusCode::OK, &ApplyList { items })) } /// One apply, with its steps and watch progress. Poll every second while it runs. #[utoipa::path(get, path = "/api/v1/applies/{id}", tag = "applies", params(("id" = String, Path)), responses((status = 200, body = ApplyView), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn get_apply(State(st): Shared, Path(id): Path) -> Result { let r = st .ctl .record(&id) .ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, "change.not_found", Params::new()))?; Ok(json(StatusCode::OK, &apply_view(&st.ctl, &r))) } /// Cancel an apply that is still queued. #[utoipa::path(delete, path = "/api/v1/applies/{id}", tag = "applies", params(("id" = String, Path)), responses((status = 204), (status = 409, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn cancel_apply(State(st): Shared, Path(id): Path) -> Result { if st.ctl.record(&id).is_none() { return Err(ApiError::new( StatusCode::NOT_FOUND, "change.not_found", Params::new(), )); } if st.ctl.cancel(&id) { Ok(StatusCode::NO_CONTENT.into_response()) } else { let mut e = ApiError::new(StatusCode::CONFLICT, "request.method", Params::new()); e.body.message = "This change is not waiting any more, so it cannot be cancelled.".into(); Err(e) } } /// One entry per user action, newest first. A reverted attempt is one entry. #[utoipa::path(get, path = "/api/v1/history", tag = "history", params(ListQuery), responses((status = 200, body = History)), security(("bearer" = [])))] pub async fn history(State(st): Shared, Query(q): Query) -> Result { let limit = q.limit.unwrap_or(50).clamp(1, 200); let recs = st.ctl.records(); let mut it: Box> = Box::new(recs.iter().rev()); if let Some(b) = &q.before { it = Box::new(it.skip_while(move |r| &r.id != b).skip(1)); } let filtered: Vec = it .filter(|r| q.host.as_ref().is_none_or(|h| r.hosts.contains(h))) .take(limit + 1) .map(history_row) .collect(); let next = (filtered.len() > limit).then(|| filtered[limit - 1].change_id.clone()); let entries = filtered.into_iter().take(limit).collect(); Ok(json( StatusCode::OK, &History { entries, next_before: next, }, )) } /// One change in full, including what was tried (`attempted_host`). #[utoipa::path(get, path = "/api/v1/history/{change_id}", tag = "history", params(("change_id" = String, Path)), responses((status = 200, body = ApplyView), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn history_entry( State(st): Shared, Path(change_id): Path, ) -> Result { get_apply(State(st), Path(change_id)).await } /// What restoring this change's version would change now. #[utoipa::path(get, path = "/api/v1/history/{change_id}/restore-preview", tag = "history", params(("change_id" = String, Path)), responses((status = 200, body = RestorePreview), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn restore_preview( State(st): Shared, Path(change_id): Path, ) -> Result { let c = &st.ctl; let r = c .record(&change_id) .ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, "change.not_found", Params::new()))?; let head = c .repo .head_required() .map_err(|e| ApiError::internal(e.to_string()))?; let current = c .repo .tree(&head) .map_err(|e| ApiError::internal(e.to_string()))?; let Some(commit) = r.commit.clone().filter(|_| r.state == "kept") else { return Ok(json( StatusCode::OK, &RestorePreview { restorable: false, same_as_current: false, changes: Vec::new(), blocked: Some(Blocked { code: "restore.not_kept".into(), message: message("restore.not_kept", &Params::new()), }), }, )); }; let then = c .repo .tree(&commit) .map_err(|e| ApiError::internal(e.to_string()))?; let mut names: std::collections::BTreeSet = current.hostnames().into_iter().collect(); names.extend(then.hostnames()); let mut changes = Vec::new(); for h in names { let (a, b) = (current.host(&h), then.host(&h)); if a == b { continue; } let pa = a.and_then(|t| HostSpec::from_toml(t).ok()); let pb = b.and_then(|t| HostSpec::from_toml(t).ok()); let (effect, fields) = match (&pa, &pb) { (None, Some(_)) => ("added", Vec::new()), (Some(_), None) => ("removed", Vec::new()), (Some(x), Some(y)) => ( "changed", x.diff(y) .into_iter() .map(|(field, from, to)| FieldChange { field, from, to }) .collect(), ), (None, None) => continue, }; changes.push(HostChange { hostname: h, effect: effect.into(), fields, }); } let same = *then == *current; Ok(json( StatusCode::OK, &RestorePreview { restorable: !same, same_as_current: same, changes, blocked: same.then(|| Blocked { code: "restore.same".into(), message: message("restore.same", &Params::new()), }), }, )) } /// What Undo would undo right now (also in the overview). #[utoipa::path(get, path = "/api/v1/undo", tag = "history", responses((status = 200, body = UndoView)), security(("bearer" = [])))] pub async fn get_undo(State(st): Shared) -> Result { Ok(json(StatusCode::OK, &undo_view(&st.ctl))) } #[derive(Debug, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct UndoBody { /// The change Undo named (`undo.target.change_id`); refused if it is no longer the latest kept change. pub target_change_id: String, } /// Undo the latest kept change, through the same apply path. Undo after an Undo is a redo. #[utoipa::path(post, path = "/api/v1/undo", tag = "history", request_body = UndoBody, params(("Idempotency-Key" = Option, Header)), responses((status = 202, body = ApplyAccepted), (status = 409, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn undo( State(st): Shared, Extension(actor): Extension, headers: HeaderMap, body: Body, ) -> Result { let fp = fingerprint("POST", "/api/v1/undo", &body.raw); submit( &st, &headers, fp, &actor, Change::Undo { target: body.value.target_change_id, }, None, ) } #[derive(Debug, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct RestoreBody { pub change_id: String, pub base_rev: Option, } /// Apply the routes as they were after a kept change, as a new change. #[utoipa::path(post, path = "/api/v1/restore", tag = "history", request_body = RestoreBody, params(("Idempotency-Key" = Option, Header)), responses((status = 202, body = ApplyAccepted), (status = 404, body = ErrorEnvelope), (status = 409, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn restore( State(st): Shared, Extension(actor): Extension, headers: HeaderMap, body: Body, ) -> Result { let fp = fingerprint("POST", "/api/v1/restore", &body.raw); let b = body.value; submit( &st, &headers, fp, &actor, Change::Restore { change_id: b.change_id, }, b.base_rev, ) } /// Push to the remote now instead of waiting for the next retry. #[utoipa::path(post, path = "/api/v1/repo/push", tag = "repo", responses((status = 200, body = RepoView), (status = 409, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn push_now(State(st): Shared) -> Result { let c = &st.ctl; let Some(remote) = c.cfg.routes.remote.clone() else { return Err(ApiError::new( StatusCode::CONFLICT, "repo.no_remote", Params::new(), )); }; c.push_once(&remote).await; let head = c .repo .head_required() .map_err(|e| ApiError::internal(e.to_string()))?; Ok(json(StatusCode::OK, &repo_view(c, &head))) } /// Settings the UI shows (read-only in v1). #[utoipa::path(get, path = "/api/v1/settings", tag = "settings", responses((status = 200, body = Settings)), security(("bearer" = [])))] pub async fn settings(State(st): Shared) -> Result { let head = st .ctl .repo .head_required() .map_err(|e| ApiError::internal(e.to_string()))?; Ok(json( StatusCode::OK, &Settings { repo: repo_view(&st.ctl, &head), watch_seconds: st.ctl.cfg.watch_secs, }, )) } // ---------------------------------------------------------------- tokens /// API tokens, without values or hashes. #[utoipa::path(get, path = "/api/v1/tokens", tag = "tokens", responses((status = 200, body = TokenList)), security(("bearer" = [])))] pub async fn list_tokens(State(st): Shared) -> Result { let items = st.ctl.tokens.list().map_err(ApiError::internal)?; Ok(json( StatusCode::OK, &TokenList { items: items.iter().map(TokenView::from).collect(), }, )) } #[derive(Debug, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct TokenCreate { pub name: Option, /// Days until it expires (default 365); `null` with `never: true` for no expiry. pub expires_in_days: Option, #[serde(default)] pub never_expires: bool, } /// Make a token. Its value is in this response only. #[utoipa::path(post, path = "/api/v1/tokens", tag = "tokens", request_body = TokenCreate, responses((status = 201, body = CreatedToken), (status = 422, body = ErrorEnvelope), (status = 429, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn create_token( State(st): Shared, Extension(actor): Extension, body: Body, ) -> Result { st.limit(&format!("token-create:{}", actor.token_id), 10, 3600) .map_err(|s| { ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s) })?; let b = body.value; let expires = if b.never_expires { None } else { let days = b.expires_in_days.unwrap_or(365); if !(1..=3650).contains(&days) { return Err(ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "token.expiry", Params::new(), )); } Some(now() + days * 86_400) }; let name = b .name .unwrap_or_else(|| format!("Token {}", ianitor_core::time::long_date(now()))); let (rec, value) = st.ctl.tokens.create(&name, expires).map_err(|e| { if e == "token.name" { let mut err = ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "token.name", Params::new(), ); err.body.field = Some("name".into()); err } else { ApiError::internal(e) } })?; log::info!(target: "ianitor::tokens", "token {} ({}) created by token {}", rec.id, rec.name, actor.token_id); Ok(json( StatusCode::CREATED, &CreatedToken { id: rec.id, name: rec.name, token: value, expires_at: rec.expires_at.map(rfc3339), }, )) } #[derive(Debug, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct TokenRename { pub name: String, } /// Rename a token. #[utoipa::path(patch, path = "/api/v1/tokens/{id}", tag = "tokens", request_body = TokenRename, params(("id" = String, Path)), responses((status = 200, body = TokenView), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn rename_token( State(st): Shared, Path(id): Path, body: Body, ) -> Result { match st.ctl.tokens.rename(&id, &body.value.name) { Ok(Some(r)) => Ok(json(StatusCode::OK, &TokenView::from(&r))), Ok(None) => Err(ApiError::new( StatusCode::NOT_FOUND, "token.not_found", Params::new(), )), Err(e) if e == "token.name" => Err(ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "token.name", Params::new(), )), Err(e) => Err(ApiError::internal(e)), } } /// Revoke a token. Anything using it stops working now. #[utoipa::path(delete, path = "/api/v1/tokens/{id}", tag = "tokens", params(("id" = String, Path)), responses((status = 204), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn revoke_token( State(st): Shared, Extension(actor): Extension, Path(id): Path, ) -> Result { match st.ctl.tokens.revoke(&id) { Ok(Some(r)) => { log::info!(target: "ianitor::tokens", "token {} revoked by token {}", r.id, actor.token_id); Ok(StatusCode::NO_CONTENT.into_response()) } Ok(None) => Err(ApiError::new( StatusCode::NOT_FOUND, "token.not_found", Params::new(), )), Err(e) => Err(ApiError::internal(e)), } } // ---------------------------------------------------------------- share links #[derive(Debug, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MintBody { #[serde(default = "root")] pub path_prefix: String, /// 1 hour to 90 days; default 7 days. #[serde(default = "week")] pub expires_in_s: u64, /// At least 8 characters; never returned. pub password: Option, /// A link of this host to stop at the same time. pub replaces: Option, } fn root() -> String { "/".into() } fn week() -> u64 { 7 * 86_400 } /// Make a share link for a host with share links on. The URL holds the token and is shown once. #[utoipa::path(post, path = "/api/v1/hosts/{hostname}/share-links", tag = "share-links", request_body = MintBody, params(("hostname" = String, Path), ("Idempotency-Key" = Option, Header)), responses((status = 201, body = MintedLink), (status = 409, body = ErrorEnvelope), (status = 422, body = ErrorEnvelope), (status = 503, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn mint_share_link( State(st): Shared, Extension(actor): Extension, Path(hostname): Path, headers: HeaderMap, body: Body, ) -> Result { check_hostname_param(&hostname)?; let fp = fingerprint( "POST", &format!("/api/v1/hosts/{hostname}/share-links"), &body.raw, ); let key = idem_key(&headers)?.map(|k| format!("{}:{k}", actor.token_id)); if let Some(k) = &key && let Some(s) = st.idem_begin(k, &fp)? { return Ok(replay(&st, s)); } // In its own task: a client that goes away mid-request neither cancels the mint nor // leaves its Idempotency-Key reserved. let task = tokio::spawn({ let (st, actor, key, fp) = (st.clone(), actor.clone(), key.clone(), fp.clone()); let value = body.value; async move { let out = mint_inner(&st, &actor, &hostname, value).await; if let Some(k) = &key { st.idem_finish( k, &fp, out.as_ref().ok().map(|v| Stored::Json(201, v.clone())), ); } out } }); let out = match task.await { Ok(out) => out, Err(e) => { if let Some(k) = &key { st.idem_finish(k, &fp, None); } Err(ApiError::internal(e.to_string())) } }; out.map(|v| json(StatusCode::CREATED, &v)) } async fn mint_inner( st: &AppState, actor: &Actor, hostname: &str, b: MintBody, ) -> Result { let hostname = hostname.to_owned(); st.limit(&format!("share-mint:{}", actor.token_id), 30, 60) .map_err(|s| { ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s) })?; let c = &st.ctl; if c.engine_running() == "caddy" { // G7: Caddy cannot check share links; control does not serve visitors itself. return Err(ApiError::new( StatusCode::CONFLICT, "share.engine_caddy", Params::new(), )); } let (_, _, model) = c.head_model()?; let Some(host) = model .hosts() .iter() .find(|h| h.hostname.as_str() == hostname) else { return Err(ApiError::new( StatusCode::NOT_FOUND, "host.not_found", messages::params([("hostname", hostname)]), )); }; if !host.share_links { return Err(ApiError::new( StatusCode::CONFLICT, "share.disabled", messages::params([("hostname", hostname)]), )); } let Some(share_key) = &c.share_key else { return Err(ApiError::new( StatusCode::SERVICE_UNAVAILABLE, "share.unavailable", Params::new(), )); }; let field_err = |code: &str, field: &str| { let mut e = ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, code, messages::params([("hostname", hostname.clone())]), ); e.body.field = Some(field.into()); e }; let minted = c .shares .mint( share_key, &hostname, &b.path_prefix, b.expires_in_s, b.password.as_deref(), b.replaces.as_deref(), &actor.name, ) .map_err(|e| match e { MintError::Prefix => field_err("share.prefix", "path_prefix"), MintError::Expiry => field_err("share.expiry", "expires_in_s"), MintError::PasswordShort => field_err("share.password_short", "password"), MintError::PasswordLong => field_err("share.password_long", "password"), MintError::Replaces => field_err("share.replaces", "replaces"), MintError::TooMany => { ApiError::new(StatusCode::CONFLICT, "share.too_many", Params::new()) } MintError::Store(s) => ApiError::internal(s), })?; if b.replaces.is_some() { c.revocations_changed().await; } let port = c.cfg.compile.https_listen.port(); let authority = if port == 443 { hostname.clone() } else { format!("{hostname}:{port}") }; let url = format!( "https://{authority}{}?{}={}", minted.record.path_prefix, ianitor_core::share::QUERY_PARAM, minted.token ); log::info!(target: "ianitor::share", "share link {} for {hostname} made by token {}", minted.record.id, actor.token_id); let out = MintedLink { id: minted.record.id, url, expires_at: rfc3339(minted.record.expires_at), path_prefix: minted.record.path_prefix, has_password: minted.record.has_password, warning: (host.auth == ianitor_core::AuthMode::None).then(|| Blocked { code: "host.share.no_signin".into(), message: message( "host.share.no_signin", &messages::params([("hostname", hostname.clone())]), ), }), }; serde_json::to_value(&out).map_err(|e| ApiError::internal(e.to_string())) } /// Every share link, newest first (without tokens). #[utoipa::path(get, path = "/api/v1/share-links", tag = "share-links", responses((status = 200, body = ShareLinkList)), security(("bearer" = [])))] pub async fn list_share_links(State(st): Shared) -> Result { let f = st.ctl.shares.load().map_err(ApiError::internal)?; let t = now(); let items = f .links .iter() .rev() // A device install link carries its one-time token in the path: never listed. It // expires within minutes, and "Stop all" stops it with the others. .filter(|l| !l.path_prefix.starts_with("/api/v1/device-bundles/")) .map(|l| ShareLinkView { id: l.id.clone(), hostname: l.hostname.clone(), path_prefix: l.path_prefix.clone(), created_at: rfc3339(l.created_at), expires_at: rfc3339(l.expires_at), has_password: l.has_password, state: l.state(f.epoch, t).into(), }) .collect(); Ok(json( StatusCode::OK, &ShareLinkList { items, epoch: f.epoch, }, )) } /// Stop one link. Edge refuses it within seconds. #[utoipa::path(delete, path = "/api/v1/share-links/{id}", tag = "share-links", params(("id" = String, Path)), responses((status = 204), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] pub async fn stop_share_link( State(st): Shared, Path(id): Path, ) -> Result { match st.ctl.shares.stop(&id).map_err(ApiError::internal)? { Some(_) => { st.ctl.revocations_changed().await; Ok(StatusCode::NO_CONTENT.into_response()) } None => Err(ApiError::new( StatusCode::NOT_FOUND, "share.not_found", Params::new(), )), } } /// Stop every share link made so far. New ones work as usual. #[utoipa::path(post, path = "/api/v1/share-links/stop-all", tag = "share-links", responses((status = 200, body = StoppedAll)), security(("bearer" = [])))] pub async fn stop_all_share_links(State(st): Shared) -> Result { let epoch = st.ctl.shares.stop_all().map_err(ApiError::internal)?; st.ctl.revocations_changed().await; Ok(json( StatusCode::OK, &StoppedAll { epoch, message: message("share.stopped_all", &Params::new()), }, )) } // ---------------------------------------------------------------- health, openapi /// Edge and control state, for scripts and checks. #[utoipa::path(get, path = "/api/v1/health", tag = "overview", responses((status = 200, body = HealthReport)), security(("bearer" = [])))] pub async fn health(State(st): Shared) -> Result { let c = &st.ctl; let (status, error, read_at, since) = { let h = c .health .lock() .map_err(|_| ApiError::internal("health cache"))?; ( h.status.clone(), h.error.clone(), h.read_at, h.since.clone(), ) }; let head = c .repo .head_required() .map_err(|e| ApiError::internal(e.to_string()))?; let tree = c .repo .tree(&head) .map_err(|e| ApiError::internal(e.to_string()))?; Ok(json( StatusCode::OK, &HealthReport { edge: EdgeHealth { attached: c.edge.attached(), reachable: status.is_some() && error.is_none(), config_sha256: status.as_ref().map(|s| s.config_sha256.clone()), trial_running: status.as_ref().is_some_and(|s| s.trial.is_some()), error, read_at: read_at.map(rfc3339), }, paused: c.paused().map(|p| Blocked { code: "control.paused".into(), message: p.message, }), queued: c.queued_count(), hosts: host_rows(c, &tree, status.as_ref(), &since), }, )) } /// This document. #[utoipa::path(get, path = "/api/v1/openapi.json", tag = "overview", responses((status = 200, description = "The OpenAPI document")), security(("bearer" = [])))] pub async fn openapi() -> Response { let mut r = super::openapi_json().into_response(); r.headers_mut().insert( header::CONTENT_TYPE, HeaderValue::from_static("application/json"), ); r } struct Bearer; impl Modify for Bearer { fn modify(&self, api: &mut utoipa::openapi::OpenApi) { use utoipa::openapi::security::{HttpAuthScheme, HttpBuilder, SecurityScheme}; let components = api.components.get_or_insert_with(Default::default); components.add_security_scheme( "bearer", SecurityScheme::Http(HttpBuilder::new().scheme(HttpAuthScheme::Bearer).build()), ); } } #[derive(OpenApi)] #[openapi( info( title = "Ianitor Domi control API", description = "REST + JSON on loopback. Every call needs `Authorization: Bearer `. \ Errors are `{error: {code, message, field, params, retry_after_s, detail}, errors: [...], request_id}`. \ Every JSON object answer carries `server_time`. See docs/api.md and docs/ui-api.md.", license(name = "CPAL-1.0", identifier = "CPAL-1.0") ), paths( overview, list_hosts, get_host, validate_host, create_host, update_host, patch_host, delete_host, retry_certificate, list_applies, get_apply, cancel_apply, history, history_entry, restore_preview, get_undo, undo, restore, push_now, settings, list_tokens, create_token, rename_token, revoke_token, mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi, super::pki::get_certs, super::pki::request_device, super::pki::get_request, super::pki::cancel_request, super::pki::get_csr, super::pki::get_ext, super::pki::put_certificate, super::pki::renew, super::pki::revoke_device, super::pki::make_bundle, super::pki::download_bundle, super::pki::get_engine, super::pki::switch_engine ), components(schemas( HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate, TokenRename, MintBody, ErrorEnvelope, ErrorBody, ApplyAccepted, ApplyView, ApplyList, Step, WatchHost, Reason, FieldError, Overview, HostList, HostDetail, History, RestorePreview, UndoView, TokenList, TokenView, CreatedToken, ShareLinkList, ShareLinkView, MintedLink, StoppedAll, Settings, RepoView, HealthReport, Done, super::pki::CertsView, super::pki::PkiRequestView, super::pki::IntermediateView, super::pki::RootView, super::pki::DeviceView, super::pki::DeviceRequestBody, super::pki::CertificateBody, super::pki::BundleBody, super::pki::BundleView, super::pki::EngineSwitchView, super::pki::EngineBody, FallbackReady )), modifiers(&Bearer), tags( (name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"), (name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links"), (name = "certs"), (name = "engine") ) )] pub struct ApiDoc;