840 lines
30 KiB
Rust
840 lines
30 KiB
Rust
// 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<Arc<AppState>>;
|
|
|
|
fn json<T: serde::Serialize>(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<T: Send + 'static>(
|
|
st: &Arc<AppState>,
|
|
f: impl FnOnce(&Control) -> Result<T, PkiFail> + Send + 'static,
|
|
) -> Result<T, ApiError> {
|
|
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<String>,
|
|
pub device_id: Option<String>,
|
|
pub name: Option<String>,
|
|
/// Renewals: the request to sign offline (also `GET /pki-requests/{id}/csr`).
|
|
pub csr_pem: Option<String>,
|
|
/// Renewals: SHA-256 of the request (DER, lowercase hex), what
|
|
/// `openssl req -in X.csr -outform DER | openssl dgst -sha256` prints on the offline computer.
|
|
pub csr_sha256: Option<String>,
|
|
/// Renewals, once installed: the new intermediate's expiry.
|
|
pub not_after: Option<String>,
|
|
/// 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<String>,
|
|
/// Renewals: the base name of the files (`<base>.csr`, `<base>.ext`, `<base>.crt`).
|
|
pub file_base: Option<String>,
|
|
/// Why it failed, when it did.
|
|
pub problem: Option<String>,
|
|
}
|
|
|
|
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(),
|
|
csr_sha256: r
|
|
.csr_pem
|
|
.as_deref()
|
|
.and_then(|c| ianitor_core::pki::csr_der(c).ok())
|
|
.map(|d| ianitor_core::pki::sha256_hex(&d)),
|
|
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_core::pki::openssl_sign_command(&file_base(r))
|
|
} else {
|
|
format!("ianitor-control pki approve {}", r.match_code)
|
|
}
|
|
}),
|
|
file_base: (r.kind == "intermediate").then(|| file_base(r)),
|
|
problem: r.error.clone(),
|
|
}
|
|
}
|
|
|
|
/// `domi-intermediate-2026-11-07`, from the day the request was made.
|
|
pub fn file_base(r: &Request) -> String {
|
|
format!(
|
|
"domi-intermediate-{}",
|
|
rfc3339(r.created_at).get(..10).unwrap_or("request")
|
|
)
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
|
pub struct IntermediateView {
|
|
/// `ok`, `due` (≤ 30 days), `urgent` (≤ 7 days), `expired` or `missing`.
|
|
pub state: String,
|
|
pub subject: Option<String>,
|
|
pub not_after: Option<String>,
|
|
pub days_left: Option<i64>,
|
|
pub renewal: Option<PkiRequestView>,
|
|
/// The banner text for `due`, `urgent`, `expired` and `missing`; `null` when `ok`.
|
|
pub banner: Option<Blocked>,
|
|
}
|
|
|
|
pub fn intermediate_view(c: &Control) -> Option<IntermediateView> {
|
|
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<String>,
|
|
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<IntermediateView>,
|
|
pub root: RootView,
|
|
pub devices: Vec<DeviceView>,
|
|
pub device_lifetime_days: u32,
|
|
/// When a device certificate issued now would end: a year, but never past the
|
|
/// intermediate's end (decision Q7). None without an intermediate.
|
|
pub device_valid_until: Option<String>,
|
|
pub server_lifetime_days: u32,
|
|
/// `manual` (on the server, until Custos can) or `custos`.
|
|
pub approval: String,
|
|
/// Open device requests.
|
|
pub requests: Vec<PkiRequestView>,
|
|
/// Set while the device list is not in force (could not be written or handed to the
|
|
/// proxy); Ianitor retries every few seconds.
|
|
pub devices_problem: Option<Blocked>,
|
|
}
|
|
|
|
// ---------------------------------------------------------------- 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<Response, ApiError> {
|
|
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,
|
|
device_valid_until: p.intermediate_info().map(|i| {
|
|
let end = (t as i64 + i64::from(ianitor_core::pki::DEVICE_DAYS) * 86_400)
|
|
.min(i.not_after);
|
|
rfc3339(end.max(0) as u64)
|
|
}),
|
|
server_lifetime_days: ianitor_core::pki::SERVER_DAYS,
|
|
approval: c
|
|
.cfg
|
|
.pki
|
|
.as_ref()
|
|
.map(|p| p.approval.clone())
|
|
.unwrap_or_default(),
|
|
requests,
|
|
devices_problem: c
|
|
.devices_problem
|
|
.lock()
|
|
.ok()
|
|
.and_then(|p| p.clone())
|
|
.map(|_| Blocked {
|
|
code: "pki.devices_unwritten".into(),
|
|
message: message("pki.devices_unwritten", &Params::new()),
|
|
}),
|
|
})
|
|
})
|
|
.await?;
|
|
Ok(json(StatusCode::OK, &view))
|
|
}
|
|
|
|
fn p_requests(c: &Control, t: u64) -> Result<Vec<PkiRequestView>, PkiFail> {
|
|
let path = crate::pki::requests_path(&c.cfg.state_dir);
|
|
let rs: Vec<Request> = 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<Actor>,
|
|
body: Body<DeviceRequestBody>,
|
|
) -> Result<Response, ApiError> {
|
|
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<String>) -> Result<Response, ApiError> {
|
|
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<String>,
|
|
) -> Result<Response, ApiError> {
|
|
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<String>) -> Result<Response, ApiError> {
|
|
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.clone().map(|c| (c, file_base(&r))))
|
|
.ok_or(PkiFail::Code("pki.request_not_found"))
|
|
})
|
|
.await?;
|
|
let (csr, base) = csr;
|
|
let mut r = csr.into_response();
|
|
r.headers_mut().insert(
|
|
header::CONTENT_TYPE,
|
|
HeaderValue::from_static("application/pkcs10"),
|
|
);
|
|
if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{base}.csr\"")) {
|
|
r.headers_mut().insert(header::CONTENT_DISPOSITION, v);
|
|
}
|
|
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<String>,
|
|
body: Body<CertificateBody>,
|
|
) -> Result<Response, ApiError> {
|
|
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<Actor>,
|
|
) -> Result<Response, ApiError> {
|
|
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<Actor>,
|
|
Path(id): Path<String>,
|
|
) -> Result<Response, ApiError> {
|
|
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);
|
|
// The revocation is recorded; it is in force only once the engines have the new list.
|
|
if let Err(e) = st.ctl.devices_changed().await {
|
|
let mut err = ApiError::new(
|
|
StatusCode::SERVICE_UNAVAILABLE,
|
|
"pki.devices_unwritten",
|
|
Params::new(),
|
|
);
|
|
err.body.detail = Some(e);
|
|
return Err(err);
|
|
}
|
|
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<String>,
|
|
}
|
|
|
|
/// 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<String>,
|
|
body: Body<BundleBody>,
|
|
) -> Result<Response, ApiError> {
|
|
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}")
|
|
}
|
|
|
|
/// `GET` on a one-time link: a small page with a Download button that posts back. Link
|
|
/// previews and prefetchers only ever GET, so they cannot use up the download.
|
|
pub async fn bundle_page(st: Arc<AppState>, token: String) -> Response {
|
|
let valid = token.len() == 64 && token.bytes().all(|c| c.is_ascii_hexdigit());
|
|
let name = if valid {
|
|
let ctl = st.ctl.clone();
|
|
tokio::task::spawn_blocking(move || {
|
|
ctl.pki.as_ref().and_then(|p| p.peek_bundle(&token, now()))
|
|
})
|
|
.await
|
|
.ok()
|
|
.flatten()
|
|
} else {
|
|
None
|
|
};
|
|
let (status, body) = match name {
|
|
Some(n) => (
|
|
StatusCode::OK,
|
|
format!(
|
|
"<h1>Install the certificate for {}</h1>\
|
|
<p>This link works once. After the download, open the file and enter the \
|
|
one-time password shown in Ianitor.</p>\
|
|
<form method=\"post\"><button type=\"submit\">Download domi-device.p12</button></form>",
|
|
html_escape(&n)
|
|
),
|
|
),
|
|
None => (
|
|
StatusCode::GONE,
|
|
format!(
|
|
"<h1>This link has been used</h1><p>{}</p>",
|
|
html_escape(&message("pki.bundle_used", &Params::new()))
|
|
),
|
|
),
|
|
};
|
|
let page = format!(
|
|
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
|
|
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
|
|
<meta name=\"robots\" content=\"noindex\"><title>Ianitor: device certificate</title>\
|
|
<style>body{{margin:0;padding:24px 16px;background:#0f1115;color:#e6e8ee;\
|
|
font:16px/1.5 system-ui,sans-serif}}main{{max-width:32rem;margin:0 auto}}\
|
|
h1{{font-size:1.25rem}}button{{font:inherit;padding:10px 16px;border-radius:8px;\
|
|
border:0;background:#7aa2ff;color:#0f1115;cursor:pointer}}\
|
|
button:focus-visible{{outline:2px solid #e6e8ee;outline-offset:2px}}</style>\
|
|
</head><body><main>{body}</main></body></html>"
|
|
);
|
|
let mut r = (status, page).into_response();
|
|
let h = r.headers_mut();
|
|
h.insert(
|
|
header::CONTENT_TYPE,
|
|
HeaderValue::from_static("text/html; charset=utf-8"),
|
|
);
|
|
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
|
h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));
|
|
h.insert(
|
|
"content-security-policy",
|
|
HeaderValue::from_static(
|
|
"default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
|
|
),
|
|
);
|
|
r
|
|
}
|
|
|
|
fn html_escape(s: &str) -> String {
|
|
let mut o = String::with_capacity(s.len());
|
|
for c in s.chars() {
|
|
match c {
|
|
'&' => o.push_str("&"),
|
|
'<' => o.push_str("<"),
|
|
'>' => o.push_str(">"),
|
|
'"' => o.push_str("""),
|
|
'\'' => o.push_str("'"),
|
|
c => o.push(c),
|
|
}
|
|
}
|
|
o
|
|
}
|
|
|
|
/// The one-time download itself (`POST`, from the link's page). The link is the secret: no
|
|
/// token or sign-in is needed, and it works once.
|
|
#[utoipa::path(post, 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<String>,
|
|
) -> Result<Response, ApiError> {
|
|
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<String>,
|
|
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<crate::records::Reason>,
|
|
/// What changes while Caddy serves.
|
|
pub notes: Vec<Blocked>,
|
|
}
|
|
|
|
pub fn engine_view(c: &Control) -> EngineSwitchView {
|
|
let e = c.engine_state();
|
|
let notes = if e.running == "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<Actor>,
|
|
body: Body<EngineBody>,
|
|
) -> Result<Response, ApiError> {
|
|
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)))
|
|
}
|
|
|
|
/// The openssl extensions file for signing a renewal by hand (the same profile Custos will
|
|
/// use; docs/pki.md).
|
|
#[utoipa::path(get, path = "/api/v1/pki-requests/{id}/ext", tag = "certs",
|
|
responses((status = 200, description = "openssl -extfile"), (status = 404, body = super::views::ErrorEnvelope)), security(("bearer" = [])))]
|
|
pub async fn get_ext(State(st): Shared, Path(id): Path<String>) -> Result<Response, ApiError> {
|
|
if !plain_id(&id) {
|
|
return Err(not_found("pki.request_not_found"));
|
|
}
|
|
let r = blocking(&st, move |c| {
|
|
pki(c)?
|
|
.request(&id, now())?
|
|
.filter(|r| r.kind == "intermediate")
|
|
.ok_or(PkiFail::Code("pki.request_not_found"))
|
|
})
|
|
.await?;
|
|
let mut resp = ianitor_core::pki::INTERMEDIATE_OPENSSL_EXT.into_response();
|
|
resp.headers_mut().insert(
|
|
header::CONTENT_TYPE,
|
|
HeaderValue::from_static("text/plain; charset=utf-8"),
|
|
);
|
|
if let Ok(v) = HeaderValue::from_str(&format!("attachment; filename=\"{}.ext\"", file_base(&r)))
|
|
{
|
|
resp.headers_mut().insert(header::CONTENT_DISPOSITION, v);
|
|
}
|
|
Ok(resp)
|
|
}
|