diff --git a/crates/control/src/api/handlers.rs b/crates/control/src/api/handlers.rs index a6d12fe..a1f69dc 100644 --- a/crates/control/src/api/handlers.rs +++ b/crates/control/src/api/handlers.rs @@ -179,39 +179,77 @@ pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result ApiError { // ---------------------------------------------------------------- middleware -fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool { +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; }; @@ -328,7 +330,14 @@ fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool { format!("127.0.0.1:{port}"), format!("[::1]:{port}"), ]; - ok.iter().any(|o| o.eq_ignore_ascii_case(host)) + // 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 @@ -336,6 +345,45 @@ fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool { .any(|a| a.eq_ignore_ascii_case(host)) } +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, + User(String), +} + +fn ui_identity(ctl: &Control, headers: &HeaderMap) -> 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, + }; + if !ok { + 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':') => + { + UiIdentity::User(u.to_owned()) + } + _ => 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(); @@ -367,6 +415,46 @@ async fn guard(State(st): State>, mut req: Request, next: Next) -> 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. + match ui_identity(&st.ctl, req.headers()) { + 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) => { + // 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: user, + }); + return Ok(next.run(req).await); + } + } let auth = req .headers() .get(header::AUTHORIZATION) @@ -429,7 +517,7 @@ async fn finish(req: Request, next: Next) -> Response { 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.contains_key("error") { + 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()) @@ -503,14 +591,35 @@ pub fn router(st: Arc) -> Router { 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}/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); - api.layer(middleware::from_fn(finish)) + .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. diff --git a/crates/control/src/api/pki.rs b/crates/control/src/api/pki.rs new file mode 100644 index 0000000..c9297d4 --- /dev/null +++ b/crates/control/src/api/pki.rs @@ -0,0 +1,687 @@ +// 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/. + +//! Certificates (docs/ui-api.md §1.7, §1.8, §3.6) and the engine switch (§1.9). + +// 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, State}; +use axum::http::{HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +use super::views::Blocked; +use super::{Actor, ApiError, AppState, Body}; +use crate::engine::Control; +use crate::messages::{self, Params, message}; +use crate::pki::{Device, PkiFail, Request}; +use crate::pki_ctl::pki_fail; +use crate::switch::engine_name; +use crate::util::{now, rfc3339}; + +type Shared = State>; + +fn json(status: StatusCode, v: &T) -> Response { + (status, axum::Json(v)).into_response() +} + +fn plain_id(s: &str) -> bool { + !s.is_empty() && s.len() <= 64 && s.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') +} + +fn not_found(code: &str) -> ApiError { + ApiError::new(StatusCode::NOT_FOUND, code, Params::new()) +} + +/// Run blocking PKI work (key unlock, file writes) off the async threads. +async fn blocking( + st: &Arc, + f: impl FnOnce(&Control) -> Result + Send + 'static, +) -> Result { + let c = st.ctl.clone(); + if c.pki.is_none() { + return Err(ApiError::new( + StatusCode::CONFLICT, + "pki.not_configured", + Params::new(), + )); + } + tokio::task::spawn_blocking(move || f(&c)) + .await + .map_err(|e| ApiError::internal(e.to_string()))? + .map_err(|e| ApiError::from(pki_fail(e))) +} + +fn pki(c: &Control) -> Result<&crate::pki::Pki, PkiFail> { + c.pki.as_ref().ok_or(PkiFail::Code("pki.not_configured")) +} + +// ---------------------------------------------------------------- views + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct PkiRequestView { + pub request_id: String, + /// `device` or `intermediate`. + pub kind: String, + /// `waiting`, `approved`, `denied`, `expired`, `cancelled` or `failed`. + pub state: String, + pub match_code: String, + pub created_at: String, + pub expires_at: String, + pub approved_at: Option, + pub device_id: Option, + pub name: Option, + /// Renewals: the request to sign offline (also `GET /pki-requests/{id}/csr`). + pub csr_pem: Option, + /// Renewals, once installed: the new intermediate's expiry. + pub not_after: Option, + /// What to tell the user now (`pki.waiting.manual`, `pki.renew.manual`, `pki.denied`, …). + pub message_code: String, + pub message: String, + /// The command that approves it on the server (manual approval). + pub approve_command: Option, + /// Why it failed, when it did. + pub problem: Option, +} + +pub fn request_view(c: &Control, r: &Request) -> PkiRequestView { + let (message_code, message_text) = match r.state.as_str() { + "waiting" => c.waiting_message(&r.kind, &r.match_code), + "approved" if r.kind == "intermediate" => { + let date = r + .not_after + .map(|t| ianitor_core::time::long_date(t.max(0) as u64)) + .unwrap_or_default(); + ( + "pki.renewed".to_owned(), + message("pki.renewed", &messages::params([("date", date)])), + ) + } + "approved" => ( + "pki.issued".to_owned(), + message( + "pki.issued", + &messages::params([("name", r.name.clone().unwrap_or_default())]), + ), + ), + "denied" => ( + "pki.denied".to_owned(), + message("pki.denied", &Params::new()), + ), + "expired" => ( + "pki.expired".to_owned(), + message("pki.expired", &Params::new()), + ), + "cancelled" => ( + "pki.cancelled".to_owned(), + "Cancelled. Nothing was issued.".to_owned(), + ), + _ => ("internal".to_owned(), message("internal", &Params::new())), + }; + let manual = c.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual"); + PkiRequestView { + request_id: r.id.clone(), + kind: r.kind.clone(), + state: r.state.clone(), + match_code: r.match_code.clone(), + created_at: rfc3339(r.created_at), + expires_at: rfc3339(r.expires_at), + approved_at: r.approved_at.map(rfc3339), + device_id: r.device_id.clone(), + name: r.name.clone(), + csr_pem: r.csr_pem.clone(), + not_after: r.not_after.map(|t| rfc3339(t.max(0) as u64)), + message_code, + message: message_text, + approve_command: (r.state == "waiting" && manual).then(|| { + if r.kind == "intermediate" { + "ianitor-control ca sign --root --csr request.csr --out intermediate.crt; then ianitor-control pki install intermediate.crt".to_owned() + } else { + format!("ianitor-control pki approve {}", r.match_code) + } + }), + problem: r.error.clone(), + } +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct IntermediateView { + /// `ok`, `due` (≤ 30 days), `urgent` (≤ 7 days), `expired` or `missing`. + pub state: String, + pub subject: Option, + pub not_after: Option, + pub days_left: Option, + pub renewal: Option, + /// The banner text for `due`, `urgent`, `expired` and `missing`; `null` when `ok`. + pub banner: Option, +} + +pub fn intermediate_view(c: &Control) -> Option { + let p = c.pki.as_ref()?; + let s = p.status(now()); + let date = s + .not_after + .map(|t| ianitor_core::time::long_date(t.max(0) as u64)) + .unwrap_or_default(); + let days = s.days_left.unwrap_or(0).to_string(); + let banner = match s.state { + "due" => Some("pki.renew_due"), + "urgent" => Some("pki.renew_urgent"), + "expired" => Some("pki.intermediate_expired"), + "missing" => Some("pki.no_intermediate"), + _ => None, + } + .map(|code| Blocked { + code: code.into(), + message: message( + code, + &messages::params([("days", days.clone()), ("date", date.clone())]), + ), + }); + Some(IntermediateView { + state: s.state.into(), + subject: s.subject, + not_after: s.not_after.map(|t| rfc3339(t.max(0) as u64)), + days_left: s.days_left, + renewal: s.renewal.as_ref().map(|r| request_view(c, r)), + banner, + }) +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct RootView { + /// The root key is never on this server. + pub offline: bool, + pub subject: String, + pub not_after: String, + pub sha256: String, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct DeviceView { + pub id: String, + pub name: String, + /// `phone`, `computer` or `app`. + pub kind: String, + pub created_at: String, + pub not_after: String, + /// `valid`, `revoked` or `expired`. + pub state: String, + pub revoked_at: Option, + pub serial: String, +} + +fn device_view(d: &Device, t: u64) -> DeviceView { + DeviceView { + id: d.id.clone(), + name: d.name.clone(), + kind: d.kind.clone(), + created_at: rfc3339(d.created_at), + not_after: rfc3339(d.not_after.max(0) as u64), + state: d.state(t).into(), + revoked_at: d.revoked_at.map(rfc3339), + serial: d.serial.clone(), + } +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct CertsView { + pub intermediate: Option, + pub root: RootView, + pub devices: Vec, + pub device_lifetime_days: u32, + pub server_lifetime_days: u32, + /// `manual` (on the server, until Custos can) or `custos`. + pub approval: String, + /// Open device requests. + pub requests: Vec, +} + +// ---------------------------------------------------------------- handlers + +/// The certificates screen. +#[utoipa::path(get, path = "/api/v1/certs", tag = "certs", + responses((status = 200, body = CertsView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn get_certs(State(st): Shared) -> Result { + let view = blocking(&st, |c| { + let p = pki(c)?; + let t = now(); + let root = ianitor_core::pki::inspect(p.root_pem())?; + let requests = p_requests(c, t)?; + Ok(CertsView { + intermediate: intermediate_view(c), + root: RootView { + offline: true, + subject: root.subject_cn, + not_after: rfc3339(root.not_after.max(0) as u64), + sha256: root.sha256_hex, + }, + devices: p + .devices()? + .iter() + .rev() + .map(|d| device_view(d, t)) + .collect(), + device_lifetime_days: ianitor_core::pki::DEVICE_DAYS, + server_lifetime_days: ianitor_core::pki::SERVER_DAYS, + approval: c + .cfg + .pki + .as_ref() + .map(|p| p.approval.clone()) + .unwrap_or_default(), + requests, + }) + }) + .await?; + Ok(json(StatusCode::OK, &view)) +} + +fn p_requests(c: &Control, t: u64) -> Result, PkiFail> { + let path = crate::pki::requests_path(&c.cfg.state_dir); + let rs: Vec = crate::util::read_json(&path) + .map_err(PkiFail::Internal)? + .unwrap_or_default(); + Ok(rs + .iter() + .filter(|r| r.kind == "device" && r.state == "waiting" && r.expires_at > t) + .map(|r| request_view(c, r)) + .collect()) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct DeviceRequestBody { + pub name: String, + /// `phone`, `computer` or `app`. + pub kind: String, +} + +/// Ask for a device certificate; it is issued once the request is approved with its code. +#[utoipa::path(post, path = "/api/v1/certs/devices", tag = "certs", request_body = DeviceRequestBody, + responses((status = 202, body = PkiRequestView), (status = 409, body = super::views::ErrorEnvelope), (status = 422, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn request_device( + State(st): Shared, + Extension(actor): Extension, + body: Body, +) -> Result { + st.limit(&format!("pki:{}", actor.token_id), 20, 3600) + .map_err(|s| { + ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s) + })?; + let b = body.value; + let name_for_err = b.name.clone(); + let r = blocking(&st, move |c| { + let r = pki(c)?.request_device(&b.name, &b.kind, now(), &actor.name)?; + Ok(request_view(c, &r)) + }) + .await + .map_err(|mut e| { + if e.body.code == "pki.device_name_taken" || e.body.code == "pki.device_name" { + e.body.field = Some("name".into()); + e.body + .params + .insert("name".into(), name_for_err.chars().take(64).collect()); + } else if e.body.code == "pki.device_kind" { + e.body.field = Some("kind".into()); + } + e + })?; + log::info!(target: "ianitor::pki", "device certificate requested ({})", r.request_id); + Ok(json(StatusCode::ACCEPTED, &r)) +} + +/// One approval request. +#[utoipa::path(get, path = "/api/v1/pki-requests/{id}", tag = "certs", + responses((status = 200, body = PkiRequestView), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn get_request(State(st): Shared, Path(id): Path) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.request_not_found")); + } + let v = blocking(&st, move |c| { + let r = pki(c)? + .request(&id, now())? + .ok_or(PkiFail::Code("pki.request_not_found"))?; + Ok(request_view(c, &r)) + }) + .await?; + Ok(json(StatusCode::OK, &v)) +} + +/// Cancel a request that waits. +#[utoipa::path(delete, path = "/api/v1/pki-requests/{id}", tag = "certs", + responses((status = 204), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn cancel_request( + State(st): Shared, + Path(id): Path, +) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.request_not_found")); + } + blocking(&st, move |c| { + pki(c)? + .cancel(&id)? + .map(|_| ()) + .ok_or(PkiFail::Code("pki.request_not_found")) + }) + .await?; + Ok(StatusCode::NO_CONTENT.into_response()) +} + +/// A renewal's CSR, as a file to carry to the offline machine. +#[utoipa::path(get, path = "/api/v1/pki-requests/{id}/csr", tag = "certs", + responses((status = 200, description = "PEM PKCS#10"), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn get_csr(State(st): Shared, Path(id): Path) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.request_not_found")); + } + let csr = blocking(&st, move |c| { + pki(c)? + .request(&id, now())? + .and_then(|r| r.csr_pem) + .ok_or(PkiFail::Code("pki.request_not_found")) + }) + .await?; + let mut r = csr.into_response(); + r.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/pkcs10"), + ); + r.headers_mut().insert( + header::CONTENT_DISPOSITION, + HeaderValue::from_static("attachment; filename=\"ianitor-intermediate.csr\""), + ); + Ok(r) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct CertificateBody { + /// The intermediate certificate signed by the Domi root (PEM). + pub certificate_pem: String, +} + +/// Install the signed intermediate for an open renewal. +#[utoipa::path(put, path = "/api/v1/pki-requests/{id}/certificate", tag = "certs", request_body = CertificateBody, + responses((status = 200, body = PkiRequestView), (status = 422, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn put_certificate( + State(st): Shared, + Path(id): Path, + body: Body, +) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.request_not_found")); + } + let pem = body.value.certificate_pem; + if pem.len() > 16 * 1024 { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "pki.bad_certificate", + Params::new(), + )); + } + let v = blocking(&st, move |c| { + let r = pki(c)?.install_intermediate(&id, &pem, now())?; + Ok(request_view(c, &r)) + }) + .await?; + let c = st.ctl.clone(); + tokio::spawn(async move { c.refresh_certificates(true).await }); + Ok(json(StatusCode::OK, &v)) +} + +/// Start the renewal of the intermediate (or set up the first one). +#[utoipa::path(post, path = "/api/v1/certs/intermediate/renewal", tag = "certs", + responses((status = 202, body = PkiRequestView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn renew( + State(st): Shared, + Extension(actor): Extension, +) -> Result { + let v = blocking(&st, move |c| { + let r = pki(c)?.request_renewal(now(), &actor.name)?; + Ok(request_view(c, &r)) + }) + .await?; + Ok(json(StatusCode::ACCEPTED, &v)) +} + +/// Revoke a device: it is off the allow list at once. +#[utoipa::path(delete, path = "/api/v1/certs/devices/{id}", tag = "certs", + responses((status = 204), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn revoke_device( + State(st): Shared, + Extension(actor): Extension, + Path(id): Path, +) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.device_not_found")); + } + let d = blocking(&st, move |c| { + pki(c)? + .revoke(&id, now())? + .ok_or(PkiFail::Code("pki.device_not_found")) + }) + .await?; + log::info!(target: "ianitor::pki", "device {} revoked by {}", d.id, actor.token_id); + st.ctl.devices_changed().await; + Ok(StatusCode::NO_CONTENT.into_response()) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct BundleBody { + /// `p12` (a file to download) or `qr` (the same link as a QR code). + #[serde(default = "p12")] + pub format: String, +} + +fn p12() -> String { + "p12".into() +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct BundleView { + /// Works once, for 10 minutes. + pub download_url: String, + /// Asked for when the file is installed. Shown once. + pub one_time_password: String, + pub expires_at: String, + pub filename: String, + /// `format = "qr"`: the link as an SVG QR code. + pub qr_svg: Option, +} + +/// A one-time install file for a device (G15): PKCS#12, behind a link that works once. +#[utoipa::path(post, path = "/api/v1/certs/devices/{id}/bundle", tag = "certs", request_body = BundleBody, + responses((status = 200, body = BundleView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn make_bundle( + State(st): Shared, + Path(id): Path, + body: Body, +) -> Result { + if !plain_id(&id) { + return Err(not_found("pki.device_not_found")); + } + let format = body.value.format; + if format != "p12" && format != "qr" { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "request.body", + messages::params([("problem", "format must be \"p12\" or \"qr\".".into())]), + )); + } + let (token, password, expires) = + blocking(&st, move |c| pki(c)?.make_bundle(&id, now())).await?; + let url = bundle_url(&st, &token).await; + let qr_svg = if format == "qr" { + Some(crate::pki::qr_svg(&url).map_err(|e| ApiError::from(pki_fail(e)))?) + } else { + None + }; + Ok(json( + StatusCode::OK, + &BundleView { + download_url: url, + one_time_password: password, + expires_at: rfc3339(expires), + filename: "domi-device.p12".into(), + qr_svg, + }, + )) +} + +/// Where a device downloads its file: through edge on the admin host when there is one +/// (as a share link when that host has share links on, so a device without a sign-in can +/// reach it; the link covers only this one-time path), else control's own address. +async fn bundle_url(st: &AppState, token: &str) -> String { + let c = &st.ctl; + let path = format!("/api/v1/device-bundles/{token}"); + let Some(ui) = c.cfg.ui.as_ref().and_then(|u| u.hostname.clone()) else { + return format!("http://{}{path}", c.cfg.listen); + }; + let port = c.cfg.compile.https_listen.port(); + let authority = if port == 443 { + ui.clone() + } else { + format!("{ui}:{port}") + }; + let shares_on = c + .head_model() + .ok() + .and_then(|(_, _, m)| { + m.hosts() + .iter() + .find(|h| h.hostname.as_str() == ui) + .map(|h| h.share_links) + }) + .unwrap_or(false); + if shares_on + && c.engine_running() != "caddy" + && let Some(key) = &c.share_key + && let Ok(m) = c.shares.mint( + key, + &ui, + &path, + crate::shares::MIN_EXPIRY, + None, + None, + "device install", + ) + { + return format!( + "https://{authority}{}?{}={}", + m.record.path_prefix, + ianitor_core::share::QUERY_PARAM, + m.token + ); + } + format!("https://{authority}{path}") +} + +/// The one-time download itself. The link is the secret: no token or sign-in is needed, and +/// it works once. +#[utoipa::path(get, path = "/api/v1/device-bundles/{token}", tag = "certs", + responses((status = 200, description = "application/x-pkcs12"), (status = 410, body = super::views::ErrorEnvelope)))] +pub async fn download_bundle( + State(st): Shared, + Path(token): Path, +) -> Result { + if token.len() != 64 || !token.bytes().all(|c| c.is_ascii_hexdigit()) { + return Err(ApiError::new( + StatusCode::GONE, + "pki.bundle_used", + Params::new(), + )); + } + let (bytes, _name) = blocking(&st, move |c| pki(c)?.take_bundle(&token, now())).await?; + log::info!(target: "ianitor::pki", "a device install file was downloaded"); + let mut r = bytes.into_response(); + let h = r.headers_mut(); + h.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/x-pkcs12"), + ); + h.insert( + header::CONTENT_DISPOSITION, + HeaderValue::from_static("attachment; filename=\"domi-device.p12\""), + ); + h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); + h.insert("referrer-policy", HeaderValue::from_static("no-referrer")); + Ok(r) +} + +// ---------------------------------------------------------------- engine + +#[derive(Debug, Serialize, ToSchema)] +pub struct EngineSwitchView { + /// `pingora` or `caddy`. + pub running: String, + /// `running`, `switching` or `stopped`. + pub state: String, + pub target: Option, + pub since: String, + /// Whether this server lets control switch (an `[engine]` section and its units). + pub switchable: bool, + /// Why the last switch did not happen. + pub last_error: Option, + /// What changes while Caddy serves. + pub notes: Vec, +} + +pub fn engine_view(c: &Control) -> EngineSwitchView { + let e = c.engine_state(); + let notes = if e.running == "caddy" { + ["engine.caddy", "share.engine_caddy"] + .iter() + .map(|code| Blocked { + code: (*code).into(), + message: message(code, &Params::new()), + }) + .collect() + } else { + Vec::new() + }; + EngineSwitchView { + running: e.running, + state: e.state, + target: e.target, + since: rfc3339(e.since), + switchable: c.engine_cfg().is_some() && c.units.is_some(), + last_error: e.last_error, + notes, + } +} + +/// Which engine serves. +#[utoipa::path(get, path = "/api/v1/engine", tag = "engine", + responses((status = 200, body = EngineSwitchView)), security(("bearer" = [])))] +pub async fn get_engine(State(st): Shared) -> Response { + json(StatusCode::OK, &engine_view(&st.ctl)) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct EngineBody { + /// `pingora` or `caddy`. + pub target: String, +} + +/// Switch the engine. Answers at once; poll `GET /engine` until `state` is `running`. +#[utoipa::path(post, path = "/api/v1/engine", tag = "engine", request_body = EngineBody, + responses((status = 202, body = EngineSwitchView), (status = 409, body = super::views::ErrorEnvelope)), security(("bearer" = [])))] +pub async fn switch_engine( + State(st): Shared, + Extension(actor): Extension, + body: Body, +) -> Result { + let target = body.value.target; + st.ctl.request_switch(&target).map_err(ApiError::from)?; + log::info!(target: "ianitor::engine", "switch to {} asked by {}", engine_name(&target), actor.token_id); + Ok(json(StatusCode::ACCEPTED, &engine_view(&st.ctl))) +} diff --git a/crates/control/src/api/ui.rs b/crates/control/src/api/ui.rs new file mode 100644 index 0000000..e57a9dc --- /dev/null +++ b/crates/control/src/api/ui.rs @@ -0,0 +1,122 @@ +// 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/. + +//! In front of the API guard: the built web UI (`[ui] static_dir`) and the one-time device +//! downloads. The UI's files hold no data (it reads everything from the API, which the guard +//! protects), so they need no token; the Host check still applies against DNS rebinding. + +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; + +use axum::body::Body as AxumBody; +use axum::extract::{Path as AxPath, Request, State}; +use axum::http::{HeaderValue, StatusCode, header}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; + +use super::{ApiError, AppState, host_allowed}; +use crate::messages::Params; + +const CSP: &str = "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; \ + script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"; + +pub async fn front(State(st): State>, req: Request, next: Next) -> Response { + let path = req.uri().path().to_owned(); + if let Some(token) = path.strip_prefix("/api/v1/device-bundles/") { + if !host_allowed(&st.ctl, req.headers()) { + return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new()) + .into_response(); + } + if req.method() != axum::http::Method::GET { + return ApiError::new( + StatusCode::METHOD_NOT_ALLOWED, + "request.method", + Params::new(), + ) + .into_response(); + } + let token = token.to_owned(); + return super::pki::download_bundle(State(st), AxPath(token)) + .await + .unwrap_or_else(IntoResponse::into_response); + } + if path.starts_with("/api/") || path == "/api" { + return next.run(req).await; + } + if !host_allowed(&st.ctl, req.headers()) { + return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new()).into_response(); + } + let Some(dir) = st.ctl.cfg.ui.as_ref().and_then(|u| u.static_dir.clone()) else { + return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new()) + .into_response(); + }; + if !matches!(req.method().as_str(), "GET" | "HEAD") { + return ApiError::new( + StatusCode::METHOD_NOT_ALLOWED, + "request.method", + Params::new(), + ) + .into_response(); + } + serve_static(&dir, &path).await +} + +/// A file from the UI build. Paths with `..`, odd characters or hidden names are refused; +/// a path without a file extension is the single-page app (`index.html`). +async fn serve_static(dir: &Path, url_path: &str) -> Response { + let rel = url_path.trim_start_matches('/'); + let clean = !rel.contains('\\') + && rel + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"-_./".contains(&c)) + && Path::new(rel) + .components() + .all(|c| matches!(c, Component::Normal(n) if !n.to_string_lossy().starts_with('.'))); + if !clean { + return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new()) + .into_response(); + } + let has_ext = Path::new(rel).extension().is_some(); + let file: PathBuf = if rel.is_empty() || !has_ext { + dir.join("index.html") + } else { + dir.join(rel) + }; + let Ok(bytes) = tokio::fs::read(&file).await else { + return ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new()) + .into_response(); + }; + let ctype = match file.extension().and_then(|e| e.to_str()).unwrap_or("") { + "html" => "text/html; charset=utf-8", + "js" | "mjs" => "text/javascript; charset=utf-8", + "css" => "text/css; charset=utf-8", + "svg" => "image/svg+xml", + "png" => "image/png", + "ico" => "image/x-icon", + "woff2" => "font/woff2", + "json" | "webmanifest" => "application/json", + "txt" => "text/plain; charset=utf-8", + _ => "application/octet-stream", + }; + let immutable = rel.starts_with("assets/") || rel.starts_with("_app/immutable/"); + let mut r = Response::new(AxumBody::from(bytes)); + let h = r.headers_mut(); + h.insert(header::CONTENT_TYPE, HeaderValue::from_static(ctype)); + h.insert( + header::CACHE_CONTROL, + HeaderValue::from_static(if immutable { + "public, max-age=31536000, immutable" + } else { + "no-cache" + }), + ); + h.insert("content-security-policy", HeaderValue::from_static(CSP)); + h.insert( + "x-content-type-options", + HeaderValue::from_static("nosniff"), + ); + h.insert("referrer-policy", HeaderValue::from_static("no-referrer")); + h.insert("x-frame-options", HeaderValue::from_static("DENY")); + r +} diff --git a/crates/control/src/api/views.rs b/crates/control/src/api/views.rs index dfd5fc9..9e8db7e 100644 --- a/crates/control/src/api/views.rs +++ b/crates/control/src/api/views.rs @@ -406,6 +406,8 @@ pub struct HostRow { pub auth: String, pub websockets: bool, pub share_links: bool, + /// Visitors need a Domi device certificate. + pub device_certs: bool, pub added_at: Option, pub health: HealthView, pub certificate: CertView, @@ -439,13 +441,28 @@ pub struct Counts { #[derive(Debug, Clone, Serialize, ToSchema)] pub struct EngineView { - /// `pingora` (the Caddy switch waits on Mark, ROADMAP §10 (b)). + /// `pingora` or `caddy`. pub running: String, - /// `running` or `stopped` (control cannot reach it). + /// `running`, `switching` or `stopped` (control cannot reach it). pub state: String, pub since: Option, - #[schema(value_type = Option)] - pub fallback_ready: Option, + /// The engine a running switch goes to. + pub target: Option, + /// Whether control can switch on this server (`[engine]` in control.toml). + pub switchable: bool, + /// The fallback's config: when it was written and whether it is the current tree's. + pub fallback_ready: Option, + /// Why the last switch did not happen. + pub last_error: Option, + /// What is different while Caddy serves (`engine.caddy`, `share.engine_caddy`). + pub notes: Vec, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct FallbackReady { + pub built_at: Option, + /// caddy.json is the compiled current tree. + pub current: bool, } #[derive(Debug, Clone, Serialize, ToSchema)] @@ -507,9 +524,8 @@ pub struct Overview { pub undo: UndoView, pub active_apply: Option, pub repo: Option, - /// The Domi intermediate; arrives in phase 3. - #[schema(value_type = Option)] - pub intermediate: Option, + /// The Domi intermediate; `null` when the Domi CA is not set up (`[pki]`). + pub intermediate: Option, pub site: Option, pub paused: Option, /// Set when control cannot read health from edge (`health.unavailable`). @@ -526,7 +542,7 @@ pub fn added_at(c: &Control, hostname: &str) -> Option { } pub fn undo_view(c: &Control) -> UndoView { - let blocked = if let Some(p) = c.paused() { + let blocked = if let Some(p) = c.effective_pause() { Some(Blocked { code: "undo.paused".into(), message: message("undo.paused", &messages::Params::new()) + " " + &p.message, @@ -621,6 +637,7 @@ pub fn host_rows( auth: spec.as_ref().map(|s| s.auth.clone()).unwrap_or_default(), websockets: spec.as_ref().is_none_or(|s| s.websockets), share_links: spec.as_ref().is_some_and(|s| s.share_links), + device_certs: spec.as_ref().is_some_and(|s| s.device_certs), added_at: added_at(c, &h), health: health_view(st, spec.as_ref(), since.get(&h).copied()), certificate: cert_view(st, spec.as_ref()), diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs index 573484d..fdf4b11 100644 --- a/crates/control/src/engine.rs +++ b/crates/control/src/engine.rs @@ -143,6 +143,8 @@ pub struct Control { pub share_key: Option, /// The Domi CA, when `[pki]` is configured. pub pki: Option, + /// The per-boot secret edge adds on the admin host (`X-Ianitor-Proof`), from `[ui]`. + pub ui_proof: Option>, /// Which engine serves (see `switch`). pub engine: Mutex, /// How control starts and stops the engines; `None` without `[engine]`. @@ -238,6 +240,12 @@ impl Control { repo, edge, share_key, + ui_proof: cfg + .ui + .as_ref() + .and_then(|u| u.proof_credential.as_deref()) + .and_then(|n| cfg.credential(n)) + .filter(|p| p.len() >= 32), pki, engine: Mutex::new(crate::switch::EngineState { running: cfg diff --git a/crates/control/src/hostspec.rs b/crates/control/src/hostspec.rs index 538a72c..2b7e8ec 100644 --- a/crates/control/src/hostspec.rs +++ b/crates/control/src/hostspec.rs @@ -26,6 +26,9 @@ pub struct HostSpec { pub websockets: bool, #[serde(default)] pub share_links: bool, + /// Visitors need a Domi device certificate (mTLS). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub device_certs: bool, /// `off` or `truncated`. #[serde(default = "off")] pub access_log: String, @@ -115,6 +118,11 @@ impl HostSpec { to.share_links.to_string(), ); push("access_log", self.access_log.clone(), to.access_log.clone()); + push( + "device_certs", + self.device_certs.to_string(), + to.device_certs.to_string(), + ); let hc = |h: &Option| h.as_ref().map(|h| (h.path.clone(), h.interval_secs)); let (a, b) = (hc(&self.health_check), hc(&to.health_check)); @@ -157,6 +165,7 @@ mod tests { auth: "none".into(), websockets: false, share_links: true, + device_certs: true, access_log: "truncated".into(), health_check: Some(HealthCheckSpec { path: "/health".into(), diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index 3740c9c..578d27d 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -39,6 +39,7 @@ pub async fn serve( tokio::spawn(ctl.clone().worker()); tokio::spawn(ctl.clone().health_poller()); tokio::spawn(ctl.clone().pusher()); + tokio::spawn(ctl.clone().pki_poller()); let app = api::router(api::AppState::new(ctl.clone())); if !listen.ip().is_loopback() { return Err("ianitor-control only listens on loopback".into()); diff --git a/crates/control/src/main.rs b/crates/control/src/main.rs index 063e2b3..c2a6375 100644 --- a/crates/control/src/main.rs +++ b/crates/control/src/main.rs @@ -9,6 +9,11 @@ //! ianitor-control token list (--config | --state-dir ) //! ianitor-control token revoke (--config | --state-dir ) //! ianitor-control openapi print the OpenAPI document +//! ianitor-control pki approve|deny (--config | --state-dir ) approve a device request +//! ianitor-control pki install (--config ) install a signed intermediate +//! ianitor-control pki status (--config ) open requests +//! ianitor-control ca init --out [--passphrase-file ] the offline root (never on the server) +//! ianitor-control ca sign --root --csr --out [--yes] sign an intermediate offline //! ianitor-control check --config check the config and exit //! ``` //! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`), @@ -197,6 +202,168 @@ fn token(args: &[String]) -> Result<(), String> { } } +fn arg_after(args: &[String], name: &str) -> Option { + let mut it = args.iter(); + while let Some(a) = it.next() { + if a == name { + return it.next().cloned(); + } + } + None +} + +/// A passphrase from `--passphrase-file`, or asked on the terminal without echo. +fn passphrase(args: &[String], confirm: bool) -> Result { + if let Some(f) = arg_after(args, "--passphrase-file") { + let v = std::fs::read_to_string(&f).map_err(|e| format!("cannot read {f}: {e}"))?; + let v = v.trim_end_matches(['\r', '\n']).to_owned(); + if v.chars().count() < 12 { + return Err("the passphrase must have at least 12 characters".into()); + } + return Ok(v); + } + let p = rpassword::prompt_password("Root key passphrase: ").map_err(|e| e.to_string())?; + if p.chars().count() < 12 { + return Err("the passphrase must have at least 12 characters".into()); + } + if confirm { + let again = rpassword::prompt_password("Again: ").map_err(|e| e.to_string())?; + if again != p { + return Err("the two passphrases differ".into()); + } + } + Ok(p) +} + +/// `ca init` and `ca sign`: the offline root (ROADMAP §1.2; docs/pki.md). Never run on the +/// server. +fn ca(args: &[String]) -> Result<(), String> { + use ianitor_core::pki; + let now = ianitor_control::util::now() as i64; + match args.first().map(String::as_str) { + Some("init") => { + let out = PathBuf::from(arg_after(args, "--out").ok_or("ca init --out ")?); + let crt = out.join("domi-root.crt"); + let key = out.join("domi-root.key"); + if crt.exists() || key.exists() { + return Err(format!( + "{} already has a root; refusing to replace it", + out.display() + )); + } + std::fs::create_dir_all(&out).map_err(|e| e.to_string())?; + let pass = passphrase(args, true)?; + let (cert, k) = pki::create_root(now).map_err(|e| e.to_string())?; + let sealed = pki::encrypt_key(&k, pass.as_bytes()).map_err(|e| e.to_string())?; + ianitor_control::util::write_atomic(&key, sealed.as_bytes(), 0o600) + .map_err(|e| e.to_string())?; + ianitor_control::util::write_atomic(&crt, cert.as_bytes(), 0o644) + .map_err(|e| e.to_string())?; + let info = pki::inspect(&cert).map_err(|e| e.to_string())?; + eprintln!( + "Domi root created in {}: {} (valid until {}).\nSHA-256 {}\n\ + Copy domi-root.crt to the server's configuration (services.ianitor.pki.rootCertificate).\n\ + Keep domi-root.key and its passphrase offline (Custos, once it can hold it).", + out.display(), + info.subject_cn, + ianitor_core::time::long_date(info.not_after.max(0) as u64), + info.sha256_hex + ); + Ok(()) + } + Some("sign") => { + let root = PathBuf::from( + arg_after(args, "--root") + .ok_or("ca sign --root --csr --out ")?, + ); + let csr_path = arg_after(args, "--csr").ok_or("--csr is required")?; + let out = PathBuf::from(arg_after(args, "--out").ok_or("--out is required")?); + let csr = std::fs::read_to_string(&csr_path) + .map_err(|e| format!("cannot read {csr_path}: {e}"))?; + let code = pki::match_code(&pki::csr_der(&csr).map_err(|e| e.to_string())?); + eprintln!("This request's code is {code}. It must be the code Ianitor shows."); + if !args.iter().any(|a| a == "--yes") { + let typed = rpassword::prompt_password("Type the code to sign (no echo): ") + .map_err(|e| e.to_string())?; + if ianitor_control::pki::normalise_code(&typed) + != ianitor_control::pki::normalise_code(&code) + { + return Err("the code does not match; nothing was signed".into()); + } + } + let cert = + std::fs::read_to_string(root.join("domi-root.crt")).map_err(|e| e.to_string())?; + let sealed = + std::fs::read_to_string(root.join("domi-root.key")).map_err(|e| e.to_string())?; + let pass = passphrase(args, false)?; + let key = pki::decrypt_key(&sealed, pass.as_bytes()).map_err(|e| e.to_string())?; + let signed = + pki::sign_intermediate(&cert, &key, &csr, now).map_err(|e| e.to_string())?; + ianitor_control::util::write_atomic(&out, signed.as_bytes(), 0o644) + .map_err(|e| e.to_string())?; + let info = pki::inspect(&signed).map_err(|e| e.to_string())?; + eprintln!( + "Signed {} until {}. Install it on the server: ianitor-control pki install {}", + info.subject_cn, + ianitor_core::time::long_date(info.not_after.max(0) as u64), + out.display() + ); + Ok(()) + } + _ => Err("ca init --out | ca sign --root --csr --out ".into()), + } +} + +/// `pki approve|deny|install|status` on the server, as the user control runs as. +fn pki_cli(args: &[String]) -> Result<(), String> { + let dir = state_dir(args)?; + same_owner(&dir)?; + let now = ianitor_control::util::now(); + match args.first().map(String::as_str) { + Some(verb @ ("approve" | "deny")) => { + // The code may be given as one word or three (47 19 83). + let code: String = args + .iter() + .skip(1) + .take_while(|a| !a.starts_with("--")) + .cloned() + .collect::>() + .join(""); + let r = ianitor_control::pki::cli_approve(&dir, &code, verb == "deny", now)?; + eprintln!( + "{} the request for \"{}\" ({}). Control acts on it within a few seconds.", + if verb == "deny" { "Turned down" } else { "Approved" }, + r.name.unwrap_or_default(), + r.id + ); + Ok(()) + } + Some("install") => { + let f = args.get(1).filter(|a| !a.starts_with("--")).ok_or("pki install ")?; + let pem = std::fs::read_to_string(f).map_err(|e| format!("cannot read {f}: {e}"))?; + let r = ianitor_control::pki::cli_install(&dir, &pem, now)?; + eprintln!("Handed to renewal {}. Control installs it within a few seconds.", r.id); + Ok(()) + } + Some("status") => { + let rs: Vec = + ianitor_control::util::read_json(&ianitor_control::pki::requests_path(&dir))?.unwrap_or_default(); + for r in rs.iter().filter(|r| r.state == "waiting" && r.expires_at > now) { + println!( + "{} {} {} code {} until {}", + r.id, + r.kind, + r.name.clone().unwrap_or_default(), + r.match_code, + ianitor_control::util::rfc3339(r.expires_at) + ); + } + Ok(()) + } + _ => Err("pki approve | pki deny | pki install | pki status (--config | --state-dir )".into()), + } +} + fn main() -> ExitCode { if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") { return askpass(); @@ -215,6 +382,8 @@ fn main() -> ExitCode { }; let result = match args.first().map(String::as_str) { Some("token") => token(&args[1..]), + Some("pki") => pki_cli(&args[1..]), + Some("ca") => ca(&args[1..]), Some("openapi") => { println!("{}", ianitor_control::api::openapi_json()); Ok(()) diff --git a/crates/control/src/pki.rs b/crates/control/src/pki.rs index d68c990..f5b4fec 100644 --- a/crates/control/src/pki.rs +++ b/crates/control/src/pki.rs @@ -279,12 +279,7 @@ impl Pki { #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; - let mode = if d.ends_with("approvals") { - 0o700 - } else { - 0o700 - }; - let _ = std::fs::set_permissions(&d, std::fs::Permissions::from_mode(mode)); + let _ = std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700)); } } Ok(Pki { diff --git a/crates/control/src/switch.rs b/crates/control/src/switch.rs index 5bd6e15..b7311f6 100644 --- a/crates/control/src/switch.rs +++ b/crates/control/src/switch.rs @@ -22,6 +22,9 @@ //! //! The systemd calls go through [`Units`], so tests use a fake. +// A refusal is built once per request; boxing it buys nothing. +#![allow(clippy::result_large_err)] + use std::collections::HashSet; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; @@ -382,6 +385,11 @@ impl Control { Ok(()) } + /// Any reason changes wait now: Caddy serving, or a pause. + pub fn effective_pause(&self) -> Option { + self.engine_pause().or_else(|| self.paused()) + } + /// Changes wait while Caddy serves. pub fn engine_pause(&self) -> Option { (self.engine_running() == "caddy").then(|| reason("engine.caddy", Params::new())) diff --git a/crates/control/tests/api.rs b/crates/control/tests/api.rs index 2d45a8c..c41f05c 100644 --- a/crates/control/tests/api.rs +++ b/crates/control/tests/api.rs @@ -34,6 +34,11 @@ mod unix { fn routes(doc: &Value) -> Vec<(String, String)> { let mut out = Vec::new(); for (path, item) in doc["paths"].as_object().unwrap() { + // The one-time device download is the one call without a token: the link is + // the secret (G15). Every other call needs one. + if path.starts_with("/api/v1/device-bundles/") { + continue; + } for method in ["get", "post", "put", "patch", "delete"] { if item.get(method).is_some() { let p = path @@ -118,14 +123,14 @@ mod unix { vec![("Authorization".into(), "Bearer ".into())], "token.unknown", ), - // Identity headers do not authenticate (docs/ui-api.md G14). + // Identity headers without edge's proof are refused (docs/ui-api.md G14). ( "remote-user".into(), vec![ ("Remote-User".into(), "mark".into()), ("Remote-Groups".into(), "admins".into()), ], - "token.missing", + "ui.no_proof", ), ]; for (what, headers, code) in &cases { @@ -147,7 +152,8 @@ mod unix { env.call_with("GET", "/api/v1/nope", &[], None).await.status, 401 ); - assert_eq!(env.call_with("GET", "/", &[], None).await.status, 401); + // Outside /api/ only the built UI is served (no data, no token); none is set up here. + assert_eq!(env.call_with("GET", "/", &[], None).await.status, 404); // A wrong Host header (DNS rebinding) is refused even with a good token. let auth = format!("Bearer {}", env.token); diff --git a/crates/control/tests/pki.rs b/crates/control/tests/pki.rs index 9e14f54..b54d2d4 100644 --- a/crates/control/tests/pki.rs +++ b/crates/control/tests/pki.rs @@ -116,7 +116,16 @@ mod unix { let r2 = env .call("GET", &format!("/api/v1/pki-requests/{rid}/csr"), None) .await; - assert_eq!(r2.status, 200); + assert_eq!( + r2.status, + 200, + "{} +{} +{}", + r.text, + r2.text, + env.control_log() + ); assert_eq!(r2.text, csr); let signed = pki::sign_intermediate(&off.root_pem, &off.root_key, &csr, now()).unwrap(); let f = env.dir.join("signed.crt"); @@ -170,7 +179,8 @@ mod unix { i64::from(pki::SERVER_DAYS) - 1 ); - // No root key anywhere control writes. + // No root key anywhere control writes. (The start of a P-256 PKCS#8 body is the same + // for every key, so the unique end is compared.) let key_pem = off.root_key.serialize_pem(); let body: String = key_pem .lines() @@ -181,7 +191,7 @@ mod unix { let bytes = std::fs::read(&f).unwrap(); let text = String::from_utf8_lossy(&bytes); assert!( - !text.contains(&body[..40]), + !text.contains(&body[body.len() - 40..]), "root key material in {}", f.display() ); @@ -407,7 +417,7 @@ mod unix { let p = e.path(); if p.is_dir() { stack.push(p); - } else { + } else if p.is_file() { out.push(p); } } diff --git a/crates/edge/src/admin.rs b/crates/edge/src/admin.rs index 9ffd085..505142b 100644 --- a/crates/edge/src/admin.rs +++ b/crates/edge/src/admin.rs @@ -235,6 +235,10 @@ async fn handle(shared: Arc, req: Request) -> Resp { } } ("POST", "/v1/abort") => reply(StatusCode::OK, json!({ "reverted": shared.abort() })), + ("POST", "/v1/device-certs/reload") => match shared.reload_device_trust() { + Ok(n) => reply(StatusCode::OK, json!({ "reloaded": true, "allowed": n })), + Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e), + }, ("POST", "/v1/share-revocations/reload") => match shared.reload_revocations() { Ok(()) => { let r = shared.revocations(); diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index a69f400..134f9ea 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -131,7 +131,9 @@ impl ProxyHttp for EdgeProxy { let rt = self.shared.current(); ctx.rt = Some(rt.clone()); ctx.host_header = host_header(session.req_header()); - if rt.device_trust.is_some() && sni_mismatch(session, &hostname(&ctx.host_header)) { + if self.shared.devices.current().is_some() + && sni_mismatch(session, &hostname(&ctx.host_header)) + { // Like Caddy once client certificates are configured: a request for another host // than the one the TLS connection was opened for is refused, so a connection // that was never asked for a certificate cannot reach a device host. @@ -144,7 +146,7 @@ impl ProxyHttp for EdgeProxy { }; ctx.host = Some(host.clone()); - if host.cfg.device_certs && !has_allowed_device_cert(session, &rt) { + if host.cfg.device_certs && !has_allowed_device_cert(session, &self.shared) { // No certificate on this connection (one that is presented but not allowed never // gets here: the handshake fails). Same as Caddy's route: 403, nothing upstream. respond_empty(session, 403).await?; @@ -441,8 +443,8 @@ fn sni_mismatch(session: &Session, host: &str) -> bool { /// Did this connection present a device certificate that the current config allows? The /// handshake already checked the chain and the list; this checks again against the runtime /// serving the request, so a revocation also ends requests on connections made before it. -fn has_allowed_device_cert(session: &Session, rt: &crate::runtime::Runtime) -> bool { - let Some(trust) = rt.device_trust.as_ref() else { +fn has_allowed_device_cert(session: &Session, shared: &crate::shared::Shared) -> bool { + let Some(trust) = shared.devices.current() else { return false; }; session diff --git a/crates/edge/src/shared.rs b/crates/edge/src/shared.rs index a6e2fac..0493b20 100644 --- a/crates/edge/src/shared.rs +++ b/crates/edge/src/shared.rs @@ -187,7 +187,16 @@ impl Shared { fn install(&self, rt: Arc) { self.certs.replace_files(rt.file_certs.clone()); - self.devices.replace(rt.device_trust.clone()); + // Read the device files again: the runtime may be older than the latest allow list + // (a revert after a revocation must not let a revoked device back in). + let trust = match fresh_trust(&rt) { + Ok(t) => t, + Err(e) => { + log::error!(target: "ianitor::tls", "{e}; keeping the device check this config was built with"); + rt.device_trust.clone() + } + }; + self.devices.replace(trust); self.current.store(rt); self.generation.fetch_add(1, Ordering::SeqCst); self.notify(); @@ -496,3 +505,36 @@ fn poisoned() -> AdminError { fn short(sha: &str) -> &str { sha.get(..12).unwrap_or(sha) } + +/// The device check for a runtime, built from the files as they are now. +fn fresh_trust(rt: &Runtime) -> Result>, String> { + let Some(dc) = &rt.cfg.device_certs else { + return Ok(None); + }; + let hosts: std::collections::HashSet = rt + .cfg + .hosts + .iter() + .filter(|h| h.device_certs) + .map(|h| h.hostname.clone()) + .collect(); + if hosts.is_empty() { + return Ok(None); + } + let ca = std::fs::read(&dc.ca).map_err(|e| format!("cannot read {}: {e}", dc.ca))?; + let allow = std::fs::read(&dc.allow).map_err(|e| format!("cannot read {}: {e}", dc.allow))?; + crate::tls::DeviceTrust::new(&ca, &allow, hosts).map(|t| Some(Arc::new(t))) +} + +impl Shared { + /// Re-read the device CA bundle and allow list now (control calls this after an issue + /// or a revocation; allowed during a trial). Returns how many devices are allowed. + pub fn reload_device_trust(&self) -> Result { + let rt = self.current(); + let t = fresh_trust(&rt)?; + let n = t.as_ref().map_or(0, |t| t.allowed()); + self.devices.replace(t); + log::info!(target: "ianitor::tls", "device certificates re-read: {n} allowed"); + Ok(n) + } +} diff --git a/crates/edge/src/tls.rs b/crates/edge/src/tls.rs index 51e345c..347acef 100644 --- a/crates/edge/src/tls.rs +++ b/crates/edge/src/tls.rs @@ -159,6 +159,10 @@ impl DeviceTrust { }) } + pub fn allowed(&self) -> usize { + self.allow.len() + } + pub fn allows(&self, cert_sha256: &[u8]) -> bool { <[u8; 32]>::try_from(cert_sha256).is_ok_and(|d| self.allow.contains(&d)) }