231 lines
8.4 KiB
Rust
231 lines
8.4 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/.
|
|
|
|
//! Control's side of the Domi CA: certificates for the hosts of every tree that is applied,
|
|
//! the device files both engines read, and what happens after an approval, a renewal or a
|
|
//! revocation.
|
|
|
|
// A refusal is built once per failed request; boxing it buys nothing.
|
|
#![allow(clippy::result_large_err)]
|
|
|
|
use std::path::Path;
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use ianitor_core::TlsMode;
|
|
|
|
use crate::engine::{Control, Fail};
|
|
use crate::messages::{self, Params};
|
|
use crate::pki::PkiFail;
|
|
use crate::util::now;
|
|
|
|
/// The HTTP status for a PKI refusal.
|
|
pub fn status_of(code: &str) -> u16 {
|
|
match code {
|
|
"pki.request_not_found" | "pki.device_not_found" => 404,
|
|
"pki.bundle_used" => 410,
|
|
"pki.bad_certificate"
|
|
| "pki.not_our_root"
|
|
| "pki.wrong_key"
|
|
| "pki.device_name"
|
|
| "pki.device_kind"
|
|
| "pki.wrong_code"
|
|
| "pki.manual.not_ca"
|
|
| "pki.manual.eku"
|
|
| "pki.manual.dates" => 422,
|
|
"pki.devices_unwritten" => 503,
|
|
"pki.too_many_requests" => 429,
|
|
_ => 409,
|
|
}
|
|
}
|
|
|
|
pub fn pki_fail(e: PkiFail) -> Fail {
|
|
match e {
|
|
PkiFail::Code(c) => Fail::new(status_of(c), c, Params::new()),
|
|
PkiFail::Internal(d) => Fail::new(500, "internal", Params::new()).detail(d),
|
|
}
|
|
}
|
|
|
|
impl Control {
|
|
pub fn pki_or_fail(&self) -> Result<&crate::pki::Pki, Fail> {
|
|
self.pki
|
|
.as_ref()
|
|
.ok_or_else(|| Fail::new(409, "pki.not_configured", Params::new()))
|
|
}
|
|
|
|
/// Every certificate directory a compiler output points at.
|
|
fn cert_dirs(&self) -> Vec<&Path> {
|
|
let mut v = vec![Path::new(&self.cfg.compile.cert_dir)];
|
|
let c = Path::new(&self.cfg.caddy_compile().cert_dir);
|
|
if c != v[0] {
|
|
v.push(c);
|
|
}
|
|
v
|
|
}
|
|
|
|
/// Before a tree goes live: server certificates for its `tls = "domi"` hosts and the
|
|
/// device files when a host needs them. Without `[pki]` nothing is issued (the files are
|
|
/// expected to be there, as in phase 2). Returns whether a file changed.
|
|
pub fn pki_prepare(&self, model: &ianitor_core::Model) -> Result<bool, Fail> {
|
|
let Some(p) = &self.pki else {
|
|
return Ok(false);
|
|
};
|
|
let t = now();
|
|
let domi: Vec<String> = model
|
|
.hosts()
|
|
.iter()
|
|
.filter(|h| h.tls == TlsMode::Domi)
|
|
.map(|h| h.hostname.to_string())
|
|
.collect();
|
|
let mut changed = false;
|
|
for dir in self.cert_dirs() {
|
|
let issued = p.ensure_host_certs(&domi, dir, t).map_err(|e| {
|
|
let mut f = pki_fail(e);
|
|
// The apply's reason names a host so the UI can point at it.
|
|
if let Some(h) = domi.first() {
|
|
f.reason.hostname = Some(h.clone());
|
|
}
|
|
f
|
|
})?;
|
|
if !issued.is_empty() {
|
|
log::info!(target: "ianitor::pki", "issued server certificates for {}", issued.join(", "));
|
|
changed = true;
|
|
}
|
|
// Always: the files are tiny, and a list that failed to be written catches up here.
|
|
changed |= p.write_device_files(dir, t).map_err(pki_fail)?;
|
|
}
|
|
Ok(changed)
|
|
}
|
|
|
|
/// Every couple of seconds: act on approvals; once an hour: renew server certificates.
|
|
pub async fn pki_poller(self: Arc<Self>) {
|
|
if self.pki.is_none() {
|
|
return;
|
|
}
|
|
let mut last_renewal_check = now();
|
|
// At start: bring the device files in line (a revocation that could not be written
|
|
// before a restart is in force now).
|
|
let _ = self.devices_changed().await;
|
|
loop {
|
|
tokio::time::sleep(Duration::from_secs(2)).await;
|
|
let me = self.clone();
|
|
let polled = tokio::task::spawn_blocking(move || match &me.pki {
|
|
Some(p) => p.poll(now()),
|
|
None => Ok(Default::default()),
|
|
})
|
|
.await;
|
|
let changes = match polled {
|
|
Ok(Ok(c)) => c,
|
|
Ok(Err(e)) => {
|
|
log::error!(target: "ianitor::pki", "{e}");
|
|
continue;
|
|
}
|
|
Err(e) => {
|
|
log::error!(target: "ianitor::pki", "pki poll crashed: {e}");
|
|
continue;
|
|
}
|
|
};
|
|
let t = now();
|
|
if changes.intermediate || t.saturating_sub(last_renewal_check) >= 3600 {
|
|
last_renewal_check = t;
|
|
self.refresh_certificates(changes.intermediate).await;
|
|
}
|
|
let retry = self
|
|
.devices_problem
|
|
.lock()
|
|
.map(|p| p.is_some())
|
|
.unwrap_or(false);
|
|
if changes.devices || retry {
|
|
let _ = self.devices_changed().await;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Issue what the current tree needs (after a new intermediate: everything) and reload
|
|
/// the engine that serves, under the apply lock so no trial is running.
|
|
pub async fn refresh_certificates(&self, new_intermediate: bool) {
|
|
let _lock = self.apply_lock.lock().await;
|
|
let Ok((_, _, model)) = self.head_model() else {
|
|
return;
|
|
};
|
|
match self.pki_prepare(&model) {
|
|
Ok(changed) if changed || new_intermediate => {
|
|
if new_intermediate {
|
|
log::info!(target: "ianitor::pki", "new Domi intermediate installed; certificates reissued");
|
|
}
|
|
self.reload_serving_engine().await;
|
|
}
|
|
Ok(_) => {}
|
|
Err(f) => {
|
|
log::error!(target: "ianitor::pki", "certificates not renewed: {}", f.reason.message);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The device files changed (issue or revoke): rewrite them and tell the engine at once.
|
|
pub async fn devices_changed(&self) -> Result<(), String> {
|
|
let Some(p) = &self.pki else { return Ok(()) };
|
|
let _engine = self.engine_lock.lock().await;
|
|
let t = now();
|
|
let mut result = Ok(());
|
|
for dir in self.cert_dirs() {
|
|
if let Err(e) = p.write_device_files(dir, t) {
|
|
result = Err(format!(
|
|
"the device files in {} could not be written: {e}",
|
|
dir.display()
|
|
));
|
|
}
|
|
}
|
|
// Tell the serving engine every time, changed or not: a repeated Revoke nudges again.
|
|
if result.is_ok() {
|
|
result = if self.engine_running() == "caddy" {
|
|
self.caddy_reload()
|
|
.await
|
|
.map_err(|e| format!("Caddy did not reload the device list: {e}"))
|
|
} else if self.edge.attached() {
|
|
self.edge
|
|
.reload_devices()
|
|
.await
|
|
.map_err(|e| format!("edge did not re-read the device list: {e}"))
|
|
} else {
|
|
Ok(())
|
|
};
|
|
}
|
|
if let Ok(mut pr) = self.devices_problem.lock() {
|
|
*pr = result.as_ref().err().cloned();
|
|
}
|
|
if let Err(e) = &result {
|
|
log::error!(target: "ianitor::pki", "{e}; retrying");
|
|
}
|
|
result
|
|
}
|
|
|
|
async fn reload_serving_engine(&self) {
|
|
let _engine = self.engine_lock.lock().await;
|
|
if self.engine_running() == "caddy" {
|
|
if let Err(e) = self.caddy_reload().await {
|
|
log::error!(target: "ianitor::pki", "Caddy did not reload the new certificates: {e}");
|
|
}
|
|
} else if self.edge.attached()
|
|
&& let Err(e) = self.edge.reload().await
|
|
{
|
|
log::error!(target: "ianitor::pki", "edge did not reload the new certificates: {e}");
|
|
}
|
|
}
|
|
|
|
/// The code and message for a PKI request that waits for its approval.
|
|
pub fn waiting_message(&self, kind: &str, code: &str) -> (String, String) {
|
|
let manual = self.cfg.pki.as_ref().is_none_or(|p| p.approval == "manual");
|
|
let c = match (kind, manual) {
|
|
("intermediate", _) => "pki.renew.manual",
|
|
(_, true) => "pki.waiting.manual",
|
|
(_, false) => "pki.waiting",
|
|
};
|
|
(
|
|
c.to_owned(),
|
|
messages::message(c, &messages::params([("code", code.to_owned())])),
|
|
)
|
|
}
|
|
}
|