[control] Fix round 1: changes apply while Caddy serves (admin socket, watch through Caddy), revocations that fail are errors and catch up, proof only on the forward-auth UI host, root keys found by content, intermediates checked before install, stale SNI cleared before each handshake

This commit is contained in:
2026-11-08 10:49:31 +01:00
parent 0749119f19
commit e84eb1ba74
36 changed files with 934 additions and 131 deletions
Generated
+2
View File
@@ -1304,10 +1304,12 @@ dependencies = [
"ring",
"rpassword",
"rustls",
"rustls-pki-types",
"serde",
"serde_json",
"thiserror 2.0.21",
"tokio",
"tokio-rustls",
"toml",
"utoipa",
]
+3 -1
View File
@@ -23,6 +23,9 @@ test-hooks = []
[dependencies]
ianitor-core.workspace = true
rustls.workspace = true
rustls-pki-types.workspace = true
tokio-rustls.workspace = true
axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio", "matched-path"] }
utoipa = "5"
tokio.workspace = true
@@ -45,7 +48,6 @@ rpassword = "7"
ianitor-testkit.workspace = true
p12-keystore = "0.4"
ianitor-edge.workspace = true
rustls.workspace = true
[lints]
workspace = true
+3 -12
View File
@@ -233,18 +233,9 @@ pub async fn overview(
intermediate: super::pki::intermediate_view(c),
site,
paused_reason: c.effective_pause().map(|p| p.code),
paused: c.effective_pause().map(|p| {
if p.code == "engine.caddy" {
Blocked {
code: p.code,
message: p.message,
}
} else {
Blocked {
code: "control.paused".into(),
message: message("control.paused", &messages::params([("reason", p.message)])),
}
}
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
+23 -2
View File
@@ -252,6 +252,9 @@ pub struct CertsView {
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
@@ -288,6 +291,15 @@ pub async fn get_certs(State(st): Shared) -> Result<Response, ApiError> {
.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?;
@@ -480,7 +492,16 @@ pub async fn revoke_device(
})
.await?;
log::info!(target: "ianitor::pki", "device {} revoked by {}", d.id, actor.token_id);
st.ctl.devices_changed().await;
// 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())
}
@@ -648,7 +669,7 @@ pub struct EngineSwitchView {
pub fn engine_view(c: &Control) -> EngineSwitchView {
let e = c.engine_state();
let notes = if e.running == "caddy" {
["engine.caddy", "share.engine_caddy"]
["share.engine_caddy"]
.iter()
.map(|code| Blocked {
code: (*code).into(),
+1 -1
View File
@@ -531,7 +531,7 @@ pub struct Overview {
pub site: Option<SiteView>,
pub paused: Option<Blocked>,
/// Why changes are paused: the underlying code (`apply.needs_attention`, `control.files_unwritten`,
/// `repo.unreadable`, `engine.caddy`, …), so the UI can offer the right action.
/// `repo.unreadable`, …), so the UI can offer the right action.
pub paused_reason: Option<String>,
/// Set when control cannot read health from edge (`health.unavailable`).
pub health_error: Option<Blocked>,
+158
View File
@@ -0,0 +1,158 @@
// 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 Caddy fallback while it serves (Mark, 2026-11-08: changes keep
//! working under Caddy): loading a config through Caddy's admin API on its Unix socket
//! (`POST /load`, the whole JSON), and probing a host *through* Caddy for the health watch.
use std::net::SocketAddr;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
const TIMEOUT: Duration = Duration::from_secs(10);
/// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the
/// old one).
pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> {
#[cfg(unix)]
{
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let head = format!(
"POST /load HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n",
config.len()
);
let exchange = async {
let mut s = tokio::net::UnixStream::connect(socket).await?;
s.write_all(head.as_bytes()).await?;
s.write_all(config).await?;
let mut buf = Vec::new();
s.read_to_end(&mut buf).await?;
Ok::<_, std::io::Error>(buf)
};
let buf = tokio::time::timeout(TIMEOUT, exchange)
.await
.map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())?
.map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?;
let text = String::from_utf8_lossy(&buf);
let status: u16 = text
.split(' ')
.nth(1)
.and_then(|s| s.parse().ok())
.ok_or("no answer from Caddy's admin API")?;
if (200..300).contains(&status) {
Ok(())
} else {
let body = text.split("\r\n\r\n").nth(1).unwrap_or("").trim();
Err(format!(
"Caddy refused the config ({status}): {}",
body.chars().take(400).collect::<String>()
))
}
}
#[cfg(not(unix))]
{
let _ = (socket, config);
Err("Caddy's admin socket needs Unix".into())
}
}
/// One probe through Caddy: `GET path` on the HTTPS listener with this SNI and Host.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Probe {
/// The status Caddy answered with (its own 502/503 when the upstream is down).
Status(u16),
/// No answer at all (connection, TLS or timeout).
NoAnswer(String),
}
/// The probe does not check Caddy's certificate: it talks to this machine's own listener
/// on loopback to see whether the *upstream* answers through it, nothing else.
#[derive(Debug)]
struct AnyCert;
impl rustls::client::danger::ServerCertVerifier for AnyCert {
fn verify_server_cert(
&self,
_end_entity: &rustls_pki_types::CertificateDer<'_>,
_intermediates: &[rustls_pki_types::CertificateDer<'_>],
_server_name: &rustls_pki_types::ServerName<'_>,
_ocsp: &[u8],
_now: rustls_pki_types::UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
Ok(rustls::client::danger::ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &rustls_pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &rustls_pki_types::CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
rustls::crypto::ring::default_provider()
.signature_verification_algorithms
.supported_schemes()
}
}
pub async fn probe(addr: SocketAddr, host: &str, path: &str) -> Probe {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let started = Instant::now();
let run = async {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let cfg = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| e.to_string())?
.dangerous()
.with_custom_certificate_verifier(Arc::new(AnyCert))
.with_no_client_auth();
let name =
rustls_pki_types::ServerName::try_from(host.to_owned()).map_err(|e| e.to_string())?;
let tcp = tokio::net::TcpStream::connect(addr)
.await
.map_err(|e| e.to_string())?;
let mut tls = tokio_rustls::TlsConnector::from(Arc::new(cfg))
.connect(name, tcp)
.await
.map_err(|e| e.to_string())?;
let req = format!(
"GET {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: ianitor-watch\r\nConnection: close\r\n\r\n"
);
tls.write_all(req.as_bytes())
.await
.map_err(|e| e.to_string())?;
let mut head = [0u8; 64];
let mut n = 0;
while n < 13 {
let k = tls.read(&mut head[n..]).await.map_err(|e| e.to_string())?;
if k == 0 {
break;
}
n += k;
}
let line = String::from_utf8_lossy(&head[..n]);
line.split(' ')
.nth(1)
.and_then(|s| s.parse::<u16>().ok())
.ok_or_else(|| "no HTTP status".to_owned())
};
match tokio::time::timeout(Duration::from_secs(5), run).await {
Ok(Ok(s)) => Probe::Status(s),
Ok(Err(e)) => Probe::NoAnswer(e),
Err(_) => Probe::NoAnswer(format!(
"no answer within {} s",
started.elapsed().as_secs()
)),
}
}
+4
View File
@@ -110,6 +110,9 @@ pub struct Compile {
pub access_log: String,
pub caddy_credentials_dir: String,
pub caddy_admin: Option<SocketAddr>,
/// Caddy's admin API on a Unix socket: how control loads a change while Caddy serves.
#[serde(default)]
pub caddy_admin_socket: Option<String>,
}
impl Compile {
@@ -122,6 +125,7 @@ impl Compile {
access_log: self.access_log.clone(),
caddy_credentials_dir: self.caddy_credentials_dir.clone(),
caddy_admin: self.caddy_admin,
caddy_admin_socket: self.caddy_admin_socket.clone(),
}
}
}
+1
View File
@@ -148,6 +148,7 @@ pub async fn run(args: &[String]) -> Result<(), String> {
access_log: s("logs/access.log"),
caddy_credentials_dir: s("creds"),
caddy_admin: None,
caddy_admin_socket: None,
},
compile_caddy: None,
pki: Some(ianitor_control::config::PkiConfig {
+52 -4
View File
@@ -15,6 +15,8 @@
// A refusal is built once per failed request or apply; boxing it buys nothing.
#![allow(clippy::result_large_err)]
mod caddy_apply;
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -160,6 +162,10 @@ pub struct Control {
pause_saved: std::sync::atomic::AtomicBool,
/// Serialises applies with share-revocation writes and recovery.
pub(crate) apply_lock: tokio::sync::Mutex<()>,
/// Held while an engine is switched or told to reload its device or certificate files.
pub(crate) engine_lock: tokio::sync::Mutex<()>,
/// Why the device files are not (yet) in force, until a retry succeeds.
pub devices_problem: Mutex<Option<String>>,
}
const MAX_RECORDS: usize = 1000;
@@ -268,6 +274,8 @@ impl Control {
paused: Mutex::new(paused),
pause_saved: std::sync::atomic::AtomicBool::new(true),
apply_lock: tokio::sync::Mutex::new(()),
engine_lock: tokio::sync::Mutex::new(()),
devices_problem: Mutex::new(None),
cfg,
});
if let Ok((_, _, m)) = c.head_model()
@@ -437,9 +445,6 @@ impl Control {
/// `in_worker` is false when a request is first checked: a change that the worker may
/// still let through (after it retried the files) is queued rather than refused.
fn paused_for(&self, change: &Change, in_worker: bool) -> Option<Reason> {
if let Some(e) = self.engine_pause() {
return Some(e);
}
let p = self.paused()?;
if !in_worker && p.code == "control.files_unwritten" {
return None;
@@ -669,6 +674,31 @@ impl Control {
errors: fe,
}
})?;
// The UI proof belongs to the [ui] host only (core already demands forward-auth for it).
let ui_host = self.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref());
for h in model.hosts() {
let proof = h.request_headers.iter().any(|r| {
matches!(r, ianitor_core::HeaderRule::Set { value: ianitor_core::HeaderValue::Secret(s), .. } if s.as_str() == ianitor_core::UI_PROOF_SECRET)
});
if proof && ui_host != Some(h.hostname.as_str()) {
let p = messages::params([("hostname", h.hostname.to_string())]);
let fe = FieldError {
code: "host.header.proof_host".into(),
message: message("host.header.proof_host", &p),
field: Some("request_headers".into()),
params: p.clone(),
detail: None,
};
return Err(Fail {
status: 422,
reason: reason(
"apply.failed.validation",
messages::params([("first_error", fe.message.clone())]),
),
errors: vec![fe],
});
}
}
Ok(Plan {
kind,
verb: host_verb(kind),
@@ -1024,6 +1054,13 @@ impl Control {
r.step("reload", "running");
});
// Caddy serves: load the trial into Caddy and watch through it (Mark, 2026-11-08).
if self.engine_running() == "caddy" {
return self
.run_under_caddy(&id, j, &plan, &caddy_text, &job.change)
.await;
}
// Which hosts to judge: those this change adds or changes, not those it removes.
let watch_hosts: Vec<String> = plan
.hosts
@@ -1466,7 +1503,8 @@ impl Control {
/// The idempotent part of a revert. Returns the revert commit, if one was needed.
async fn finish_revert(&self, j: &Journal) -> Result<Option<String>, String> {
if self.edge.attached() {
let caddy = self.engine_running() == "caddy";
if self.edge.attached() && !caddy {
match self.edge.abort().await {
Ok(_) => {}
// Edge down: it starts from edge.json, which is still the last good config.
@@ -1502,6 +1540,11 @@ impl Control {
for p in [self.cfg.trial_path(), self.cfg.caddy_trial_path()] {
remove_if_exists(&p).map_err(|e| e.to_string())?;
}
if caddy {
// Caddy must run caddy.json again, the last good config.
self.caddy_reload().await?;
return Ok(rev);
}
// Edge must now run edge.json, the last good config. If it confirmed the trial after
// all (an answer lost on the way) it does not: reload it. If edge cannot be asked,
// this is not a finished revert (a restart asks again).
@@ -1660,6 +1703,11 @@ impl Control {
self.unpause();
self.sync_files().await;
}
if self.engine_running() == "caddy"
&& let Err(e) = self.caddy_reload().await
{
log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}");
}
if let Err(e) = self.shares.ensure_revocation_file() {
log::error!(target: "ianitor::share", "{e}");
}
+270
View File
@@ -0,0 +1,270 @@
// 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/.
//! Applies while Caddy serves (Mark, 2026-11-08: changes keep working under Caddy). The same
//! pipeline and journal as with edge; only the trial, the watch and the revert differ: the
//! trial is loaded into Caddy through its admin socket, the touched hosts are probed through
//! Caddy, and a revert loads caddy.json (the last good config) again.
use super::*;
use crate::caddy_link::{self, Probe};
impl Control {
/// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`).
pub fn caddy_socket(&self) -> Option<std::path::PathBuf> {
self.cfg
.caddy_compile()
.caddy_admin_socket
.as_ref()
.map(std::path::PathBuf::from)
}
/// Load caddy.json (the last good config) into the running Caddy.
pub async fn caddy_reload(&self) -> Result<(), String> {
let sock = self
.caddy_socket()
.ok_or("no caddy_admin_socket is configured, so Caddy cannot be told")?;
let text = std::fs::read(&self.cfg.caddy.config)
.map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?;
caddy_link::load(&sock, &text).await
}
pub(super) async fn run_under_caddy(
&self,
id: &str,
mut j: Journal,
plan: &Plan,
caddy_text: &str,
change: &Change,
) {
let fail = |code: &str, detail: String| {
let mut r = reason(code, messages::params([("engine", "Caddy".into())]));
r.detail = Some(detail);
r
};
let Some(sock) = self.caddy_socket() else {
let r = fail(
"apply.failed.reload",
"no caddy_admin_socket is configured".into(),
);
return self.revert(id, &j, r, "failed").await;
};
let watch_hosts: Vec<String> = plan
.hosts
.iter()
.filter(|h| plan.target.host(h).is_some())
.cloned()
.collect();
let addr = self.cfg.caddy_compile().https_listen;
let path_of = |h: &str| -> (String, bool) {
plan.model
.hosts()
.iter()
.find(|x| x.hostname.as_str() == h)
.and_then(|x| x.health_check.as_ref())
.map(|hc| (hc.path.clone(), true))
.unwrap_or_else(|| ("/".to_owned(), false))
};
let good = |p: &Probe, has_check: bool| match p {
Probe::Status(s) => {
if has_check {
(200..300).contains(s)
} else {
*s < 500
}
}
Probe::NoAnswer(_) => false,
};
// A host that already failed through Caddy before the change is no reason to revert.
let existed: BTreeSet<String> = self
.repo
.tree(&j.base)
.map(|t| {
watch_hosts
.iter()
.filter(|h| t.host(h).is_some())
.cloned()
.collect()
})
.unwrap_or_default();
let mut was_down = BTreeSet::new();
for h in &existed {
let (path, check) = path_of(h);
if !good(&caddy_link::probe(addr, h, &path).await, check) {
was_down.insert(h.clone());
}
}
if let Err(e) = caddy_link::load(&sock, caddy_text.as_bytes()).await {
return self
.revert(id, &j, fail("apply.failed.reload", e), "failed")
.await;
}
j.stage = "trial_loaded".into();
if let Err(e) = self.journal(&j) {
let mut r = reason("internal", Params::new());
r.detail = Some(e);
return self.revert(id, &j, r, "failed").await;
}
crash::point("trial_loaded");
self.update(id, |r| r.step("reload", "done"));
let judged: Vec<String> = watch_hosts
.iter()
.filter(|h| !was_down.contains(*h))
.cloned()
.collect();
let window = self.cfg.watch_secs;
let mut kept_reason = if watch_hosts.is_empty() {
reason(
"apply.kept.removed",
messages::params([("hostname", plan.hosts.join(", "))]),
)
} else {
reason(
"apply.kept",
messages::params([
("hostname", watch_hosts.join(", ")),
("seconds", window.to_string()),
]),
)
};
if judged.is_empty() {
self.update(id, |r| r.step("watch", "skipped"));
} else {
let ends = now() + window;
self.update(id, |r| {
r.state = "watching".into();
r.step("watch", "running");
r.watch = Some(Watch {
ends,
hosts: judged
.iter()
.map(|h| WatchHost {
hostname: h.clone(),
..Default::default()
})
.collect(),
});
});
// hostname -> (passed, failed, failed in a row, last probe)
let mut stats: BTreeMap<String, (u32, u32, u32, Option<Probe>)> = judged
.iter()
.map(|h| (h.clone(), (0, 0, 0, None)))
.collect();
let no_check: Vec<String> = judged.iter().filter(|h| !path_of(h).1).cloned().collect();
loop {
for h in &judged {
let (path, check) = path_of(h);
let p = caddy_link::probe(addr, h, &path).await;
let ok = good(&p, check);
if let Some(s) = stats.get_mut(h) {
if ok {
s.0 += 1;
s.2 = 0;
} else {
s.1 += 1;
s.2 += 1;
}
s.3 = Some(p);
}
}
self.update(id, |r| {
if let Some(w) = &mut r.watch {
for wh in &mut w.hosts {
if let Some(s) = stats.get(&wh.hostname) {
wh.passed = s.0;
wh.failed = s.1;
wh.total = s.0 + s.1;
}
}
}
});
let over = now() >= ends;
let failing = stats
.iter()
.find(|(_, s)| s.2 >= 3 || (over && s.2 > 0))
.map(|(h, s)| (h.clone(), s.clone()));
if let Some((h, s)) = failing {
let upstream = plan
.model
.hosts()
.iter()
.find(|x| x.hostname.as_str() == h)
.and_then(|x| x.upstreams.first())
.map(|u| u.to_string())
.unwrap_or_default();
let mut p = messages::params([
("hostname", h.clone()),
("verb", plan.verb.into()),
("upstream", upstream.clone()),
("count", s.1.to_string()),
("of", (s.0 + s.1).to_string()),
("seconds", window.to_string()),
]);
let (code, detail) = match &s.3 {
Some(Probe::Status(st)) => {
p.insert("status".into(), st.to_string());
(
"apply.reverted.server_error",
format!("through Caddy: HTTP {st}"),
)
}
Some(Probe::NoAnswer(e)) => {
("apply.reverted.no_answer", format!("through Caddy: {e}"))
}
None => ("apply.reverted.no_answer", String::new()),
};
let mut r = reason(code, p);
r.hostname = Some(h.clone());
r.upstream = Some(upstream);
r.field = Some("upstreams[0]".into());
r.detail = Some(detail);
return self.revert(id, &j, r, "reverted").await;
}
if over {
break;
}
tokio::time::sleep(Duration::from_secs(self.cfg.watch_every_secs)).await;
}
if !no_check.is_empty() && no_check.len() == judged.len() {
kept_reason = reason(
"apply.kept.no_watch",
messages::params([("hostname", no_check.join(", "))]),
);
}
self.update(id, |r| r.step("watch", "done"));
}
crash::point("watched");
j.stage = "confirmed".into();
if let Err(e) = self.journal(&j) {
let mut r = reason("internal", Params::new());
r.detail = Some(e);
return self.revert(id, &j, r, "failed").await;
}
crash::point("confirmed");
if let Err(e) = self.promote() {
log::error!(target: "ianitor::apply", "cannot write the config files: {e}");
let mut p = reason("control.files_unwritten", Params::new());
p.detail = Some(e.to_string());
p.params.insert("apply_id".into(), id.to_owned());
if let Err(pe) = self.pause(p) {
log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it");
}
let push_step = self.push_step();
self.update(id, |r| r.step("push", push_step));
self.finish(id, "kept", Some(kept_reason), Vec::new());
return;
}
crash::point("promoted");
let push_step = self.push_step();
self.update(id, |r| r.step("push", push_step));
self.finish(id, "kept", Some(kept_reason), Vec::new());
self.clear_journal();
if self.paused().is_some() && matches!(change, Change::Restore { .. }) {
self.unpause();
}
self.push_wake.notify_one();
}
}
+1
View File
@@ -7,6 +7,7 @@
//! edge keeps serving the last good config.
pub mod api;
pub mod caddy_link;
pub mod config;
pub mod crash;
pub mod edgelink;
+18 -1
View File
@@ -306,6 +306,24 @@ fn template(code: &str) -> &'static str {
"engine.switch_failed" => {
"{engine} did not start, so Ianitor went back to {previous}. Traffic is served as before."
}
"host.header.proof" => {
"Only a host behind sign-in can send the ui-proof secret. Choose Sign in first, or remove the rule."
}
"host.header.proof_host" => {
"Only the web UI's admin host can send the ui-proof secret, and {hostname} is not it ([ui] hostname in control.toml)."
}
"pki.manual.not_ca" => {
"This certificate cannot sign other certificates. Sign it again with the signing settings file (.ext)."
}
"pki.manual.eku" => {
"This certificate is limited to some uses, so it could not issue both host and device certificates. Sign it again with the signing settings file (.ext)."
}
"pki.manual.dates" => {
"This certificate is not valid yet, has already expired, or lasts longer than the Domi root. Check the offline computer's clock and use -days 365."
}
"pki.devices_unwritten" => {
"The device list could not be saved or handed to the proxy, so the change is not in force yet. Ianitor keeps trying; try again in a moment."
}
"engine.not_ready" => {
"Caddy is not ready: its settings could not be built from the current routes."
}
@@ -332,7 +350,6 @@ fn template(code: &str) -> &'static str {
"site.acme" => {
"The Let's Encrypt settings in ianitor.toml cannot be used. Show details to see why."
}
"engine.caddy" => "Caddy is serving. Changes wait until you switch back to Pingora.",
"share.engine_caddy" => {
"Share links are paused while Caddy serves. They work again after switching back."
}
+51 -18
View File
@@ -212,10 +212,32 @@ fn bundle_password() -> Result<String, PkiFail> {
Ok(s)
}
/// Is there anything that looks like a root CA key in `dir` (recursively, shallow)? Control
/// refuses to run with one in its state directory (ROADMAP §1.2: the root is never on the
/// server).
/// Private keys in `dir` that are not control's own: control refuses to run with one in its
/// state directory (ROADMAP §1.2: the root is never on the server). Found by content (any
/// `PRIVATE KEY` PEM block, plain or encrypted) and by name (`*root*key*`, `*root*.pem` with
/// a key); the only keys allowed are `pki/intermediate.key`, `pki/pending-*.key` and
/// `pki/devices/*.key`, which control writes encrypted itself.
pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
let allowed = |p: &Path| -> bool {
let Ok(rel) = p.strip_prefix(dir) else {
return false;
};
let parts: Vec<String> = rel
.components()
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
match parts
.iter()
.map(String::as_str)
.collect::<Vec<_>>()
.as_slice()
{
["pki", "intermediate.key"] => true,
["pki", f] => f.starts_with("pending-") && f.ends_with(".key"),
["pki", "devices", f] => f.ends_with(".key"),
_ => false,
}
};
let mut found = Vec::new();
let mut stack = vec![(dir.to_path_buf(), 0)];
while let Some((d, depth)) = stack.pop() {
@@ -224,12 +246,22 @@ pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
};
for e in rd.flatten() {
let p = e.path();
let name = e.file_name().to_string_lossy().to_ascii_lowercase();
if p.is_dir() {
if depth < 3 {
let Ok(meta) = e.metadata() else { continue };
if meta.is_dir() {
if depth < 8 {
stack.push((p, depth + 1));
}
} else if name.starts_with("root") && (name.ends_with(".key") || name.contains("key")) {
continue;
}
if !meta.is_file() || allowed(&p) {
continue;
}
let name = e.file_name().to_string_lossy().to_ascii_lowercase();
let by_name = name.contains("root") && name.contains("key");
let by_content = meta.len() <= 1 << 20
&& std::fs::read(&p)
.is_ok_and(|b| b.windows(KEY_MARK.len()).any(|w| w == KEY_MARK.as_bytes()));
if by_name || by_content {
found.push(p);
}
}
@@ -237,6 +269,9 @@ pub fn root_key_files(dir: &Path) -> Vec<PathBuf> {
found
}
// Split so that this file does not match the pre-commit hook itself.
const KEY_MARK: &str = concat!("PRIVATE ", "KEY-----");
impl Pki {
/// Open the CA state. The root certificate must be a CA and self-signed; the password
/// credential may be missing (then nothing can be issued, and the UI says why).
@@ -477,17 +512,15 @@ impl Pki {
}
let first = pki::first_pem(cert_pem).map_err(|_| PkiFail::Code("pki.bad_certificate"))?;
let info = pki::inspect(&first).map_err(|_| PkiFail::Code("pki.bad_certificate"))?;
if !pki::issued_by(&first, &self.root_pem).unwrap_or(false) {
return Err(PkiFail::Code("pki.not_our_root"));
}
if !info.is_ca
|| info.path_len != Some(0)
|| !info.subject_cn.starts_with(pki::INTERMEDIATE_CN)
{
return Err(PkiFail::Code("pki.bad_certificate"));
}
if info.not_before > now as i64 + 300 || info.not_after <= now as i64 {
return Err(PkiFail::Code("pki.bad_certificate"));
// Everything a hand-signed certificate can get wrong, before anything is reissued from it.
if let Some(problem) = pki::intermediate_problem(&first, &self.root_pem, now as i64) {
return Err(PkiFail::Code(match problem {
"not_root" => "pki.not_our_root",
"not_ca" => "pki.manual.not_ca",
"eku" => "pki.manual.eku",
"dates" => "pki.manual.dates",
_ => "pki.bad_certificate",
}));
}
let pending = self.dir.join(format!("pending-{request_id}.key"));
let key = self.open_key(&pending)?;
+49 -26
View File
@@ -30,7 +30,11 @@ pub fn status_of(code: &str) -> u16 {
| "pki.wrong_key"
| "pki.device_name"
| "pki.device_kind"
| "pki.wrong_code" => 422,
| "pki.wrong_code"
| "pki.manual.not_ca"
| "pki.manual.eku"
| "pki.manual.dates" => 422,
"pki.devices_unwritten" => 503,
"pki.too_many_requests" => 429,
_ => 409,
}
@@ -74,7 +78,6 @@ impl Control {
.filter(|h| h.tls == TlsMode::Domi)
.map(|h| h.hostname.to_string())
.collect();
let devices = model.hosts().iter().any(|h| h.device_certs);
let mut changed = false;
for dir in self.cert_dirs() {
let issued = p.ensure_host_certs(&domi, dir, t).map_err(|e| {
@@ -89,9 +92,8 @@ impl Control {
log::info!(target: "ianitor::pki", "issued server certificates for {}", issued.join(", "));
changed = true;
}
if devices || dir.join(ianitor_core::compile::DEVICE_CA_FILE).exists() {
changed |= p.write_device_files(dir, t).map_err(pki_fail)?;
}
// 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)
}
@@ -102,6 +104,9 @@ impl Control {
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();
@@ -126,8 +131,13 @@ impl Control {
last_renewal_check = t;
self.refresh_certificates(changes.intermediate).await;
}
if changes.devices {
self.devices_changed().await;
let retry = self
.devices_problem
.lock()
.map(|p| p.is_some())
.unwrap_or(false);
if changes.devices || retry {
let _ = self.devices_changed().await;
}
}
}
@@ -154,35 +164,48 @@ impl Control {
}
/// The device files changed (issue or revoke): rewrite them and tell the engine at once.
pub async fn devices_changed(&self) {
let Some(p) = &self.pki else { return };
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 changed = false;
let mut result = Ok(());
for dir in self.cert_dirs() {
match p.write_device_files(dir, t) {
Ok(c) => changed |= c,
Err(e) => log::error!(target: "ianitor::pki", "device files not written: {e}"),
if let Err(e) = p.write_device_files(dir, t) {
result = Err(format!(
"the device files in {} could not be written: {e}",
dir.display()
));
}
}
if !changed {
return;
// 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 self.engine_running() == "caddy" {
// Caddy reads the allow list when it starts: restart it so a revocation counts.
if let Err(e) = self.restart_caddy().await {
log::error!(target: "ianitor::pki", "caddy-fallback not restarted after a device change: {e}");
}
} else if self.edge.attached()
&& let Err(e) = self.edge.reload_devices().await
{
log::error!(target: "ianitor::pki", "edge did not re-read the device certificates: {e}");
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.restart_caddy().await {
log::error!(target: "ianitor::pki", "caddy-fallback not restarted: {e}");
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
+16 -33
View File
@@ -5,20 +5,18 @@
//! Switching the engine at runtime (ROADMAP §1.6 as corrected 2026-11-07, §3, §4).
//!
//! Exactly one of `ianitor-edge.service` and `caddy-fallback.service` runs. Control may start,
//! stop and restart only those two, through a polkit rule scoped to exactly them (NixOS
//! and stop only those two, through a polkit rule scoped to exactly them (NixOS
//! module). `/var/lib/ianitor/engine` names the one to run; the `ianitor-engine-select` unit
//! reads it at boot. A switch writes the file first (so a reboot mid-switch boots the
//! target), stops the old engine, starts the new one and waits until it serves; if the new
//! one does not come up, it goes back to the old one and says so.
//!
//! Decisions (phase 3):
//! - While Caddy serves, changes are paused (`engine.caddy`): Caddy is the emergency
//! fallback, and the apply pipeline's trial, watch and revert are built on edge's admin
//! socket. Changes made then would also have no differential check.
//! - While Caddy serves, changes keep working (Mark, 2026-11-08): an apply is loaded into Caddy
//! through its admin socket, watched through Caddy and kept or reverted (`engine/caddy_apply`).
//! - Share links are refused while Caddy serves (`share.engine_caddy`, see docs/api.md):
//! Caddy cannot check them, and control never serves visitors itself.
//! - Device revocations while Caddy serves restart caddy-fallback (Caddy reads the allow
//! list when it starts); this is why the polkit rule also allows `restart`.
//! - Device revocations while Caddy serves reload Caddy's config through its admin socket.
//!
//! The systemd calls go through [`Units`], so tests use a fake.
@@ -40,7 +38,6 @@ use crate::util::{now, write_atomic};
pub trait Units: Send + Sync {
fn start(&self, unit: &str) -> Result<(), String>;
fn stop(&self, unit: &str) -> Result<(), String>;
fn restart(&self, unit: &str) -> Result<(), String>;
fn is_active(&self, unit: &str) -> Result<bool, String>;
}
@@ -79,9 +76,6 @@ impl Units for Systemctl {
fn stop(&self, unit: &str) -> Result<(), String> {
self.verb("stop", unit)
}
fn restart(&self, unit: &str) -> Result<(), String> {
self.verb("restart", unit)
}
fn is_active(&self, unit: &str) -> Result<bool, String> {
Ok(self.run(&["is-active", "--quiet", unit])?.status.success())
}
@@ -117,12 +111,6 @@ impl Units for FakeUnits {
}
Ok(())
}
fn restart(&self, unit: &str) -> Result<(), String> {
if let Ok(mut c) = self.calls.lock() {
c.push(format!("restart {unit}"));
}
Ok(())
}
fn is_active(&self, unit: &str) -> Result<bool, String> {
Ok(self.active.lock().is_ok_and(|a| a.contains(unit)))
}
@@ -185,16 +173,6 @@ impl Control {
}
}
pub async fn restart_caddy(&self) -> Result<(), String> {
let (Some(cfg), Some(units)) = (self.engine_cfg(), self.units.clone()) else {
return Err("no engine settings".into());
};
let unit = cfg.caddy_unit.clone();
tokio::task::spawn_blocking(move || units.restart(&unit))
.await
.map_err(|e| e.to_string())?
}
/// Check a switch request and start it. Answers at once; the switch runs in the
/// background (`overview.engine.state` is `switching` until it ends).
pub fn request_switch(self: &Arc<Self>, target: &str) -> Result<EngineState, Fail> {
@@ -239,6 +217,7 @@ impl Control {
async fn switch(self: Arc<Self>, target: &str) {
// No apply runs during a switch, and none starts.
let _lock = self.apply_lock.lock().await;
let _engine = self.engine_lock.lock().await;
let from = self.engine_running();
let res = self.switch_inner(&from, target).await;
let t = now();
@@ -314,7 +293,16 @@ impl Control {
let u = units.clone();
let n = new.clone();
Self::blocking(move || u.start(&n)).await?;
self.wait_serving(target, &units, &new).await
self.wait_serving(target, &units, &new).await?;
// Edge reads edge.json when it starts; tell it again in case it kept running (changes
// kept under Caddy are in edge.json).
if target == "pingora"
&& self.edge.attached()
&& let Err(e) = self.edge.reload().await
{
log::warn!(target: "ianitor::engine", "edge did not reload edge.json after the switch: {e}");
}
Ok(())
}
async fn bring_back(&self, engine: &str) -> Result<(), String> {
@@ -397,12 +385,7 @@ impl Control {
/// Any reason changes wait now: Caddy serving, or a pause.
pub fn effective_pause(&self) -> Option<Reason> {
self.engine_pause().or_else(|| self.paused())
}
/// Changes wait while Caddy serves.
pub fn engine_pause(&self) -> Option<Reason> {
(self.engine_running() == "caddy").then(|| reason("engine.caddy", Params::new()))
self.paused()
}
}
+1
View File
@@ -114,6 +114,7 @@ impl Env {
access_log: dir.str("logs/access.log"),
caddy_credentials_dir: dir.str("creds"),
caddy_admin: None,
caddy_admin_socket: None,
};
// Edge starts from an empty config; control brings it in line on its first start.
let empty = load(
+34 -14
View File
@@ -661,7 +661,11 @@ mod unix {
std::fs::write(
&p,
// (Split so that this file does not match the pre-commit hook itself.)
concat!("-----BEGIN ", "PRIVATE KEY-----\nx\n-----END ", "PRIVATE KEY-----\n"),
concat!(
"-----BEGIN ",
"PRIVATE KEY-----\nx\n-----END ",
"PRIVATE KEY-----\n"
),
)
.unwrap();
if ianitor_control::pki::root_key_files(&d.join(".")).is_empty() {
@@ -680,8 +684,6 @@ mod unix {
async fn a_revocation_that_cannot_be_written_is_an_error_and_catches_up() {
let (mut env, off) = env_with_pki().await;
install_intermediate(&env, &off).await;
env.kill_control();
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "domi-devices.pem")]);
let r = env
.call(
"POST",
@@ -695,16 +697,23 @@ mod unix {
assert!(cli(&env, &["pki", "approve", &code]).status.success());
let done = wait_request(&env, &rid, "approved").await;
let did = done["device_id"].as_str().unwrap().to_owned();
// The allow list could not be written: the screen says so.
let allow_file = env.dir.join("certs/domi-devices.pem");
let on_list = || {
std::fs::read_to_string(&allow_file)
.unwrap_or_default()
.contains("BEGIN CERTIFICATE")
};
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let c = env.call("GET", "/api/v1/certs", None).await;
if !c.json["devices_problem"].is_null() {
break;
}
assert!(Instant::now() < deadline, "no problem shown: {}", c.text);
while !on_list() {
assert!(
Instant::now() < deadline,
"the device never reached the allow list"
);
tokio::time::sleep(Duration::from_millis(200)).await;
}
// From now on the allow list cannot be written.
env.kill_control();
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "domi-devices.pem")]);
let d = env
.call("DELETE", &format!("/api/v1/certs/devices/{did}"), None)
.await;
@@ -714,16 +723,27 @@ mod unix {
"{}",
d.text
);
// The disk works again.
// The certificates screen keeps saying so; the device is still on the list.
let c = env.call("GET", "/api/v1/certs", None).await;
assert_eq!(
c.json["devices_problem"]["code"], "pki.devices_unwritten",
"{}",
c.text
);
assert!(on_list());
// The disk works again: the list catches up by itself, without another Revoke.
env.kill_control();
env.start_control(None);
let deadline = Instant::now() + Duration::from_secs(10);
while on_list() {
assert!(Instant::now() < deadline, "the revocation never caught up");
tokio::time::sleep(Duration::from_millis(200)).await;
}
// A repeated Revoke is fine and nudges the engine again.
let d = env
.call("DELETE", &format!("/api/v1/certs/devices/{did}"), None)
.await;
assert_eq!(d.status, 204, "{}", d.text);
let allow =
std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap_or_default();
assert!(!allow.contains("BEGIN CERTIFICATE"), "{allow}");
let c = env.call("GET", "/api/v1/certs", None).await;
assert!(c.json["devices_problem"].is_null(), "{}", c.text);
}
+14 -6
View File
@@ -203,11 +203,19 @@ mod unix {
"tls": "domi", "auth": "none",
"request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}]
}});
let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await;
// Refused before it goes live: the proof belongs to the [ui] host behind forward-auth.
assert_eq!(rec["state"], "failed", "{rec}");
assert!(rec.to_string().contains("host.header.proof"), "{rec}");
if rec["state"] != "kept" {
let r = env.call("POST", "/api/v1/hosts", Some(host)).await;
// Refused at the door: the proof belongs to the [ui] host behind forward-auth.
assert_eq!(r.status, 422, "{}", r.text);
assert_eq!(
r.json["errors"][0]["code"], "host.header.proof",
"{}",
r.text
);
assert!(
env.call("GET", "/api/v1/hosts/a.test", None).await.status == 404,
"the host went live"
);
if r.status != 202 {
return;
}
let edge = env.edge.as_ref().unwrap();
@@ -265,7 +273,7 @@ mod unix {
assert_eq!(r.status, 200, "{}", r.text());
eprintln!(
"QC viewer: {}",
&r.text()[r.text().find("\"viewer\"").unwrap_or(0)..]
r.text()[r.text().find("\"viewer\"").unwrap_or(0)..]
.chars()
.take(80)
.collect::<String>()
+7 -3
View File
@@ -26,9 +26,13 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
root.insert(
"admin".into(),
match o.caddy_admin {
Some(addr) => json!({ "listen": addr.to_string() }),
None => json!({ "disabled": true }),
match (&o.caddy_admin_socket, o.caddy_admin) {
// Only the ianitor group (control) can reach it; no TCP port for local processes.
(Some(s), _) => {
json!({ "listen": format!("unix//{}|0660", s.trim_start_matches('/')) })
}
(None, Some(addr)) => json!({ "listen": addr.to_string() }),
(None, None) => json!({ "disabled": true }),
},
);
root.insert(
+9
View File
@@ -41,6 +41,9 @@ pub struct CompileOptions {
pub caddy_credentials_dir: String,
/// Caddy admin endpoint; `None` disables the admin API.
pub caddy_admin: Option<SocketAddr>,
/// Caddy admin endpoint on a Unix socket (mode 0660), which control uses to load a changed
/// config while Caddy serves. Takes precedence over `caddy_admin`.
pub caddy_admin_socket: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
@@ -73,6 +76,12 @@ pub fn caddy(model: &Model, options: &CompileOptions) -> Result<String, CompileE
}
fn check_options(o: &CompileOptions) -> Result<(), CompileError> {
if let Some(s) = &o.caddy_admin_socket {
check_path(s).map_err(|reason| CompileError::BadOption {
option: "caddy_admin_socket",
reason,
})?;
}
for (option, value) in [
("cert_dir", &o.cert_dir),
("state_dir", &o.state_dir),
+7
View File
@@ -170,6 +170,10 @@ pub enum ValidationError {
BadHealthCheck { file: String, reason: &'static str },
#[error("{file}: auth = \"forward-auth\" needs a [forward_auth] section in the site file")]
ForwardAuthNotConfigured { file: String },
#[error(
"{file}: only a host behind sign-in (auth = \"forward-auth\") may send the `ui-proof` secret; it is the web UI's admin host"
)]
ProofWithoutSignIn { file: String },
#[error("{file}: forward_auth is not usable: {reason}")]
BadForwardAuth { file: String, reason: &'static str },
#[error("{file}: acme is not usable: {reason}")]
@@ -211,6 +215,7 @@ impl ValidationError {
| E::BadHeaderRule { file, .. }
| E::BadHealthCheck { file, .. }
| E::ForwardAuthNotConfigured { file }
| E::ProofWithoutSignIn { file }
| E::BadForwardAuth { file, .. }
| E::BadAcme { file, .. } => file,
E::DuplicateHostname { second, .. } => second,
@@ -296,6 +301,7 @@ impl ValidationError {
}
E::BadHealthCheck { .. } => "host.health.path",
E::ForwardAuthNotConfigured { .. } => "host.auth.not_configured",
E::ProofWithoutSignIn { .. } => "host.header.proof",
E::BadForwardAuth { .. } => "site.forward_auth",
E::BadAcme { .. } => "site.acme",
}
@@ -331,6 +337,7 @@ impl ValidationError {
}
E::BadHealthCheck { .. } => Some("health_check.path".into()),
E::ForwardAuthNotConfigured { .. } => Some("auth".into()),
E::ProofWithoutSignIn { .. } => Some("auth".into()),
_ => None,
}
}
+2 -1
View File
@@ -22,6 +22,7 @@ pub use error::{ValidationError, ValidationErrors};
pub use model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, MAX_FILE_BYTES,
MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost,
MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream,
UpstreamHost,
};
pub use validate::{SourceFile, load};
+4
View File
@@ -219,6 +219,10 @@ impl Model {
}
}
/// The secret that carries the web UI's per-boot proof (docs/api.md, "Sign-in"). Only the admin
/// host, behind forward-auth, may send it.
pub const UI_PROOF_SECRET: &str = "ui-proof";
/// Let's Encrypt production directory, the default when `[acme] directory` is not set.
pub const LETSENCRYPT_PRODUCTION: &str = "https://acme-v02.api.letsencrypt.org/directory";
/// Let's Encrypt staging directory.
+73
View File
@@ -421,6 +421,24 @@ pub struct CertInfo {
pub dns_names: Vec<String>,
pub serial_hex: String,
pub sha256_hex: String,
/// keyUsage: `None` when the extension is absent.
pub key_usage: Option<KeyUsageInfo>,
/// extendedKeyUsage: `None` when the extension is absent (any use).
pub eku: Option<EkuInfo>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyUsageInfo {
pub key_cert_sign: bool,
pub crl_sign: bool,
pub digital_signature: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EkuInfo {
pub any: bool,
pub server_auth: bool,
pub client_auth: bool,
}
fn ders(pem: &str) -> Result<Vec<Vec<u8>>, PkiError> {
@@ -535,9 +553,64 @@ pub fn inspect_der(der: &[u8]) -> Result<CertInfo, PkiError> {
dns_names,
serial_hex: hex(c.raw_serial()),
sha256_hex: sha256_hex(der),
key_usage: c
.key_usage()
.map_err(|e| PkiError::BadCertificate(e.to_string()))?
.map(|k| KeyUsageInfo {
key_cert_sign: k.value.key_cert_sign(),
crl_sign: k.value.crl_sign(),
digital_signature: k.value.digital_signature(),
}),
eku: c
.extended_key_usage()
.map_err(|e| PkiError::BadCertificate(e.to_string()))?
.map(|e| EkuInfo {
any: e.value.any,
server_auth: e.value.server_auth,
client_auth: e.value.client_auth,
}),
})
}
/// Why a signed certificate cannot be the Domi intermediate, or `None` when it can. It must
/// be signed by the root, a CA with path length 0 that may sign certificates (keyCertSign),
/// allowed to issue both server and device certificates (no extendedKeyUsage, or one that
/// allows both), valid now, and no longer than the root.
pub fn intermediate_problem(cert_pem: &str, root_pem: &str, now: i64) -> Option<&'static str> {
let Ok(info) = inspect(cert_pem) else {
return Some("not_certificate");
};
let Ok(root) = inspect(root_pem) else {
return Some("not_root");
};
if !issued_by(cert_pem, root_pem).unwrap_or(false) {
return Some("not_root");
}
if !info.is_ca || info.path_len != Some(0) || !info.subject_cn.starts_with(INTERMEDIATE_CN) {
return Some("not_ca");
}
if !info
.key_usage
.is_some_and(|k| k.key_cert_sign && k.crl_sign)
{
return Some("not_ca");
}
if info
.eku
.is_some_and(|e| !e.any && !(e.server_auth && e.client_auth))
{
return Some("eku");
}
if info.not_before > now + 300
|| info.not_after <= now
|| info.not_after > root.not_after
|| info.not_before < root.not_before - 300
{
return Some("dates");
}
None
}
/// SubjectPublicKeyInfo DER of the first certificate.
pub fn public_key_der(pem: &str) -> Result<Vec<u8>, PkiError> {
let der = ders(pem)?
+10 -1
View File
@@ -15,7 +15,7 @@ use crate::error::{ValidationError as E, ValidationErrors, reason as r};
use crate::model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model,
Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost,
Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream, UpstreamHost,
};
/// One route file handed in by the caller (core does no I/O).
@@ -502,6 +502,15 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
}
});
// The web UI's per-boot proof (docs/api.md, "Sign-in") may only ride on a host whose
// visitors were checked by forward-auth: edge strips client `Remote-*` headers only there.
let sends_proof = request_headers.iter().any(|r| {
matches!(r, HeaderRule::Set { value: HeaderValue::Secret(s), .. } if s.as_str() == UI_PROOF_SECRET)
});
if sends_proof && auth != AuthMode::ForwardAuth {
errors.push(E::ProofWithoutSignIn { file: f() });
}
if errors.len() != before {
return None;
}
+1
View File
@@ -72,6 +72,7 @@ fn options() -> CompileOptions {
access_log: "/var/log/ianitor/access.log".into(),
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
caddy_admin: None,
caddy_admin_socket: None,
}
}
+4 -1
View File
@@ -335,7 +335,10 @@ impl BackgroundService for RevocationPoller {
loop {
tokio::select! {
_ = shutdown.changed() => return,
_ = tokio::time::sleep(Duration::from_secs(5)) => self.shared.poll_revocations(),
_ = tokio::time::sleep(Duration::from_secs(5)) => {
self.shared.poll_revocations();
self.shared.poll_device_trust();
}
}
}
}
+3
View File
@@ -130,6 +130,9 @@ pub fn server(shared: Arc<Shared>, opts: &Options) -> Result<Server, EdgeError>
tls.set_client_cert_verifier(shared.devices.clone());
tls.enable_h2();
https.add_tls_with_settings(&rt.cfg.https_listen, None, tls);
https
.endpoints()
.set_pre_tls_callback(Arc::new(tls::HandshakeStart));
let mut http = Service::new(
"ianitor http".to_owned(),
+10
View File
@@ -175,6 +175,16 @@ impl ProxyHttp for EdgeProxy {
}
}
if host.sends_proof {
// Control trusts Remote-* only next to its proof; a client never supplies either.
let req = session.req_header_mut();
for name in ianitor_core::AUTHELIA_COPY_HEADERS
.iter()
.chain(&["X-Ianitor-Proof"])
{
req.remove_header(*name);
}
}
if host.cfg.forward_auth {
let fa = rt.forward_auth.as_ref().ok_or_else(|| {
Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured")
+7
View File
@@ -97,6 +97,9 @@ pub struct HostRt {
pub response_ops: Vec<Op>,
/// Values of the secrets this host injects; a response header containing one is dropped.
pub secret_values: Vec<Vec<u8>>,
/// The host sends control's UI proof upstream: whatever the client says about who it is
/// (Remote-*) or about the proof is dropped first, with or without forward-auth.
pub sends_proof: bool,
}
pub struct ForwardAuthRt {
@@ -378,6 +381,9 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
let mut secret_values = Vec::new();
let request_ops = ops(&h.request_headers, &secrets, &mut secret_values)?;
let response_ops = ops(&h.response_headers, &secrets, &mut secret_values)?;
let sends_proof = h.request_headers.iter().any(|op| {
matches!(op, EdgeHeaderOp::Set { value: EdgeValue::Secret { name }, .. } if name == ianitor_core::UI_PROOF_SECRET)
});
let upstreams = h
.upstreams
.iter()
@@ -398,6 +404,7 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
request_ops,
response_ops,
secret_values,
sends_proof,
}),
);
}
+57 -5
View File
@@ -96,6 +96,10 @@ pub struct Shared {
pub certs: Arc<CertStore>,
/// The listener's device-certificate check; its trust follows the runtime.
pub devices: Arc<crate::tls::DeviceVerifier>,
/// Serialises building the device trust with installing a runtime.
trust_lock: Mutex<()>,
/// Size and mtime of the device files when they were last read.
device_stamp: Mutex<Option<DeviceStamp>>,
generation: AtomicU64,
changed: tokio::sync::watch::Sender<u64>,
trial: Mutex<Option<Trial>>,
@@ -142,6 +146,8 @@ impl Shared {
current: ArcSwap::from_pointee(rt),
certs,
devices,
trust_lock: Mutex::new(()),
device_stamp: Mutex::new(None),
generation: AtomicU64::new(1),
changed,
trial: Mutex::new(None),
@@ -196,8 +202,12 @@ impl Shared {
rt.device_trust.clone()
}
};
// Trust and runtime change together (reload_device_trust checks the runtime under the
// same lock).
let guard = self.trust_lock.lock();
self.devices.replace(trust);
self.current.store(rt);
drop(guard);
self.generation.fetch_add(1, Ordering::SeqCst);
self.notify();
self.acme_wake.notify_one();
@@ -530,11 +540,53 @@ 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<usize, String> {
// Built from the runtime that serves when it is installed: if a reload swapped the
// runtime meanwhile, build again from the new one (its host set may differ).
for _ in 0..5 {
let rt = self.current();
let t = fresh_trust(&rt)?;
let n = t.as_ref().map_or(0, |t| t.allowed());
let _g = self
.trust_lock
.lock()
.map_err(|_| "device lock".to_owned())?;
if Arc::ptr_eq(&rt, &self.current()) {
self.devices.replace(t);
log::info!(target: "ianitor::tls", "device certificates re-read: {n} allowed");
return Ok(n);
}
}
Err("the config changed while the device certificates were read; try again".into())
}
/// The backstop for revocations (every 5 s, like the share deny list): re-read the device
/// files when they changed on disk, so a revocation counts even if control's nudge is lost.
pub fn poll_device_trust(&self) {
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)
let Some(dc) = &rt.cfg.device_certs else {
return;
};
let stamp = |p: &str| {
std::fs::metadata(p)
.ok()
.map(|m| (m.len(), m.modified().ok()))
};
let now = (stamp(&dc.ca), stamp(&dc.allow));
let changed = match self.device_stamp.lock() {
Ok(mut s) => {
let c = s.as_ref() != Some(&now);
*s = Some(now);
c
}
Err(_) => true,
};
if changed && let Err(e) = self.reload_device_trust() {
// Fail closed: an unreadable list lets no device in until it is fixed.
log::error!(target: "ianitor::tls", "{e}; no device certificate is accepted until it is fixed");
self.devices.replace(None);
}
}
}
type FileStamp = Option<(u64, Option<std::time::SystemTime>)>;
type DeviceStamp = (FileStamp, FileStamp);
+26
View File
@@ -48,6 +48,8 @@ impl CertStore {
impl ResolvesServerCert for CertStore {
fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
// No SNI or an unknown name: no certificate, the handshake fails (as with Caddy).
// Whatever an earlier handshake on this thread left is not this one's.
let _ = take_hello_sni();
let name = hello.server_name()?.to_ascii_lowercase();
let found = match self.files.load().get(&name) {
Some(k) => Some(k.clone()),
@@ -102,6 +104,30 @@ fn take_hello_sni() -> Option<String> {
HELLO_SNI.with(|s| s.borrow_mut().take())
}
/// Call before each TLS handshake, on the thread that creates its `ServerConnection` (edge
/// does it in a pre-TLS hook): a handshake that ended after the certificate resolver but
/// before the certificate request (failed, or resumed) leaves its name behind, and rustls asks
/// the verifier once more when the next connection is created, before that connection's
/// hello is read. A stale name there would turn off the TLS 1.2 transcript a client
/// certificate needs.
pub fn begin_handshake() {
let _ = take_hello_sni();
}
/// The pre-TLS hook that calls [`begin_handshake`].
pub struct HandshakeStart;
#[async_trait::async_trait]
impl pingora::listeners::PreTlsProcess for HandshakeStart {
async fn process(
&self,
_stream: &mut pingora::protocols::l4::stream::Stream,
) -> pingora::Result<()> {
begin_handshake();
Ok(())
}
}
/// What one config says about device certificates.
pub struct DeviceTrust {
inner: Arc<dyn ClientCertVerifier>,
+1
View File
@@ -190,6 +190,7 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
access_log: dir.str("logs/access.log"),
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
caddy_admin: None,
caddy_admin_socket: None,
};
let config_text = compile_with(&dir, &ca, &opts, spec.site, &spec.hosts);
std::fs::write(dir.join("edge.json"), &config_text).unwrap();
+10 -2
View File
@@ -1,5 +1,12 @@
// QC (throw-away): the thread-local SNI that DeviceVerifier::offer_client_auth reads.
// In-memory rustls handshakes on ONE thread, with edge's own CertStore + DeviceVerifier.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! The per-SNI certificate request (QC, fix round 1): the thread-local name that
//! DeviceVerifier::offer_client_auth reads, with in-memory rustls handshakes on ONE thread and
//! edge's own CertStore and DeviceVerifier. Each connection starts with
//! `tls::begin_handshake()`, as edge's pre-TLS hook does before Pingora creates the
//! `ServerConnection`.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
@@ -97,6 +104,7 @@ fn client(w: &World, tls12_only: bool, cert: bool, alpn: &[&[u8]]) -> Arc<Client
/// Returns whether the server saw a client certificate.
fn handshake(sc: &Arc<ServerConfig>, cc: &Arc<ClientConfig>, name: &str) -> Result<bool, String> {
ianitor_edge::tls::begin_handshake();
let mut server = ServerConnection::new(sc.clone()).unwrap();
let mut client =
ClientConnection::new(cc.clone(), ServerName::try_from(name.to_owned()).unwrap()).unwrap();
+1
View File
@@ -179,6 +179,7 @@ impl Env {
access_log: self.dir.str(&format!("logs/{engine}-access.log")),
caddy_credentials_dir: self.dir.str("creds"),
caddy_admin: None,
caddy_admin_socket: None,
}
}
+1
View File
@@ -40,6 +40,7 @@ mod unix {
access_log: o.access_log.clone(),
caddy_credentials_dir: o.caddy_credentials_dir.clone(),
caddy_admin: o.caddy_admin,
caddy_admin_socket: o.caddy_admin_socket.clone(),
}
}