[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:
@@ -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()
|
||||
)),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user