[control] QC minors: device install links open a page and download on POST (never listed), approve and install failures show on the request and the CLI waits, PBKDF2 floor, private pki dirs or an error, trusted_proxies for a proxy in front, a placeholder keeps the device allow list from being empty (Caddy refuses that)

This commit is contained in:
2026-11-08 11:02:50 +01:00
parent bc336d1188
commit 3bf5fa0e1a
27 changed files with 548 additions and 46 deletions
+10 -2
View File
@@ -79,13 +79,21 @@
const b = await post<Bundle>(`/certs/devices/${encodeURIComponent(d.id)}/bundle`, { format });
bundle = { device: d, b, format };
if (format === "p12") {
// The link's GET is only a page (so link previews cannot use it up); this browser is
// signed in on the same host, so it posts to the path and saves the file itself.
const res = await fetch(new URL(b.download_url, location.href).pathname, { method: "POST", credentials: "same-origin" });
if (!res.ok) {
problem = "The install file could not be downloaded. Choose Install again for a new link.";
return;
}
const href = URL.createObjectURL(await res.blob());
const a = document.createElement("a");
a.href = b.download_url;
a.href = href;
a.download = `${d.name}.p12`;
a.rel = "noreferrer";
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(href), 10_000);
}
} catch (e) {
problem = sentence(e);
+3
View File
@@ -1189,6 +1189,9 @@ pub async fn list_share_links(State(st): Shared) -> Result<Response, ApiError> {
.links
.iter()
.rev()
// A device install link carries its one-time token in the path: never listed. It
// expires within minutes, and "Stop all" stops it with the others.
.filter(|l| !l.path_prefix.starts_with("/api/v1/device-bundles/"))
.map(|l| ShareLinkView {
id: l.id.clone(),
hostname: l.hostname.clone(),
+80 -3
View File
@@ -616,9 +616,86 @@ async fn bundle_url(st: &AppState, token: &str) -> String {
format!("https://{authority}{path}")
}
/// The one-time download itself. The link is the secret: no token or sign-in is needed, and
/// it works once.
#[utoipa::path(get, path = "/api/v1/device-bundles/{token}", tag = "certs",
/// `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("&amp;"),
'<' => o.push_str("&lt;"),
'>' => o.push_str("&gt;"),
'"' => o.push_str("&quot;"),
'\'' => o.push_str("&#39;"),
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,
+10 -8
View File
@@ -28,18 +28,20 @@ pub async fn front(State(st): State<Arc<AppState>>, req: Request, next: Next) ->
return ApiError::new(StatusCode::FORBIDDEN, "request.host", Params::new())
.into_response();
}
if req.method() != axum::http::Method::GET {
return ApiError::new(
let token = token.to_owned();
// GET shows the page; only its button (POST) uses the link up.
return match req.method().as_str() {
"GET" | "HEAD" => super::pki::bundle_page(st, token).await,
"POST" => super::pki::download_bundle(State(st), AxPath(token))
.await
.unwrap_or_else(IntoResponse::into_response),
_ => ApiError::new(
StatusCode::METHOD_NOT_ALLOWED,
"request.method",
Params::new(),
)
.into_response();
}
let token = token.to_owned();
return super::pki::download_bundle(State(st), AxPath(token))
.await
.unwrap_or_else(IntoResponse::into_response);
.into_response(),
};
}
if path.starts_with("/api/") || path == "/api" {
return next.run(req).await;
+16
View File
@@ -113,6 +113,9 @@ pub struct Compile {
/// Caddy's admin API on a Unix socket: how control loads a change while Caddy serves.
#[serde(default)]
pub caddy_admin_socket: Option<String>,
/// Proxies in front whose X-Forwarded-For is believed (e.g. ["127.0.0.1"] beside Caddy).
#[serde(default)]
pub trusted_proxies: Vec<std::net::IpAddr>,
}
impl Compile {
@@ -126,6 +129,7 @@ impl Compile {
caddy_credentials_dir: self.caddy_credentials_dir.clone(),
caddy_admin: self.caddy_admin,
caddy_admin_socket: self.caddy_admin_socket.clone(),
trusted_proxies: self.trusted_proxies.clone(),
}
}
}
@@ -227,6 +231,15 @@ impl Config {
"routes.push_credential must be a plain credential name".into(),
));
}
// The keys at rest are only as strong as this; only test builds may lower it.
if let Some(p) = &self.pki
&& p.kdf_iterations < MIN_KDF_ITERATIONS
&& !cfg!(feature = "test-hooks")
{
return Err(ConfigError::Invalid(format!(
"pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}"
)));
}
if let Some(m) = empty_model() {
for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) {
ianitor_core::compile::edge(&m, &c.options())
@@ -295,6 +308,9 @@ fn empty_model() -> Option<ianitor_core::Model> {
.ok()
}
/// The PBKDF2 floor for keys at rest (OWASP 2023 for PBKDF2-HMAC-SHA256).
pub const MIN_KDF_ITERATIONS: u32 = 600_000;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PkiConfig {
+7 -1
View File
@@ -149,13 +149,19 @@ pub async fn run(args: &[String]) -> Result<(), String> {
caddy_credentials_dir: s("creds"),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
},
compile_caddy: None,
pki: Some(ianitor_control::config::PkiConfig {
root_cert: dir.join("offline-root/domi-root.crt"),
password_credential: "pki-password".into(),
approval: "manual".into(),
kdf_iterations: 10_000,
// Fast in test builds; the real floor in a release build.
kdf_iterations: if cfg!(feature = "test-hooks") {
10_000
} else {
ianitor_control::config::MIN_KDF_ITERATIONS
},
}),
ui: arg(args, "--ui-dir").map(|d| ianitor_control::config::UiConfig {
hostname: None,
+10 -4
View File
@@ -330,10 +330,13 @@ fn pki_cli(args: &[String]) -> Result<(), String> {
.collect::<Vec<_>>()
.join("");
let r = ianitor_control::pki::cli_approve(&dir, &code, verb == "deny", now)?;
let name = r.name.clone().unwrap_or_default();
eprintln!("Handed to control; waiting for it ...");
let state = ianitor_control::pki::cli_wait(&dir, &r.id, now)
.map_err(|e| format!("not done for \"{name}\" ({}): {e}", r.id))?;
eprintln!(
"{} the request for \"{}\" ({}). Control acts on it within a few seconds.",
if verb == "deny" { "Turned down" } else { "Approved" },
r.name.unwrap_or_default(),
"{} the request for \"{name}\" ({}).",
if state == "approved" { "Approved" } else { "Turned down" },
r.id
);
Ok(())
@@ -342,7 +345,10 @@ fn pki_cli(args: &[String]) -> Result<(), String> {
let f = args.get(1).filter(|a| !a.starts_with("--")).ok_or("pki install <intermediate.crt>")?;
let pem = std::fs::read_to_string(f).map_err(|e| format!("cannot read {f}: {e}"))?;
let r = ianitor_control::pki::cli_install(&dir, &pem, now)?;
eprintln!("Handed to renewal {}. Control installs it within a few seconds.", r.id);
eprintln!("Handed to renewal {}; waiting for control to install it ...", r.id);
ianitor_control::pki::cli_wait(&dir, &r.id, now)
.map_err(|e| format!("not installed: {e}"))?;
eprintln!("Installed. Server certificates are reissued from it now.");
Ok(())
}
Some("status") => {
+101 -3
View File
@@ -100,9 +100,13 @@ pub struct Request {
/// Renewals: when the new intermediate expires, once installed.
#[serde(default)]
pub not_after: Option<i64>,
/// Why it failed (plain English, no secrets).
/// Why it failed, or why the last approval or install for it was not used (plain
/// English, no secrets). A request that is still waiting can carry one.
#[serde(default)]
pub error: Option<String>,
/// When `error` was last set for a request that is still waiting (the CLI waits for it).
#[serde(default)]
pub problem_at: Option<u64>,
/// Who asked (token name or signed-in user).
#[serde(default)]
pub actor: String,
@@ -314,7 +318,8 @@ impl Pki {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700));
std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700))
.map_err(|e| format!("cannot make {} private: {e}", d.display()))?;
}
}
Ok(Pki {
@@ -485,6 +490,7 @@ impl Pki {
csr_pem: Some(csr),
not_after: None,
error: None,
problem_at: None,
actor: actor.to_owned(),
};
prune(&mut rs, now);
@@ -539,6 +545,8 @@ impl Pki {
remove_if_exists(&pending).map_err(io)?;
*self.current.lock().map_err(|_| io("pki"))? = Some(Arc::new(int));
r.state = "approved".into();
r.error = None;
r.problem_at = None;
r.approved_at = Some(now);
r.not_after = Some(info.not_after);
let out = r.clone();
@@ -605,12 +613,29 @@ impl Pki {
// while no intermediate exists, and the empty allow list still lets no one in.
ca.push_str(&self.root_pem);
}
let allow: String = self
let mut allow: String = self
.devices()?
.iter()
.filter(|d| d.state(now) == "valid")
.map(|d| d.cert_pem.as_str())
.collect();
if allow.is_empty() {
// Caddy refuses an empty leaf list (and the whole config with it): the list
// holds a certificate no one has the key to. Made once, so the file stays put.
let p = self.dir.join("no-device.crt");
allow = match std::fs::read_to_string(&p) {
Ok(pem) if pki::inspect(&pem).is_ok_and(|i| i.subject_cn == pki::NO_DEVICE_CN) => {
pem
}
_ => {
let pem = pki::no_device_placeholder(now as i64).map_err(|e| {
PkiFail::Internal(format!("cannot make the placeholder: {e}"))
})?;
write_atomic(&p, pem.as_bytes(), 0o644).map_err(io)?;
pem
}
};
}
let mut changed = false;
for (name, text) in [
(ianitor_core::compile::DEVICE_CA_FILE, ca),
@@ -686,6 +711,7 @@ impl Pki {
csr_pem: None,
not_after: None,
error: None,
problem_at: None,
actor: actor.to_owned(),
};
rs.push(r.clone());
@@ -749,6 +775,7 @@ impl Pki {
let _ = remove_if_exists(&path);
if let Err(e) = self.approve_device(&rid, code.trim(), now) {
log::warn!(target: "ianitor::pki", "approval for {rid} not used: {e}");
self.note_problem(&rid, &e, now);
} else {
changes.devices = true;
}
@@ -764,6 +791,7 @@ impl Pki {
Ok(_) => changes.intermediate = true,
Err(e) => {
log::warn!(target: "ianitor::pki", "intermediate for {rid} not installed: {e}");
self.note_problem(&rid, &e, now);
}
}
}
@@ -791,6 +819,26 @@ impl Pki {
Ok(changes)
}
/// An approval or install for a waiting request was not used: say why on the request
/// (the UI and the CLI show it), and keep it open for another try.
fn note_problem(&self, rid: &str, e: &PkiFail, now: u64) {
let text = match e {
PkiFail::Code(c) => crate::messages::message(c, &crate::messages::Params::new()),
PkiFail::Internal(_) => {
crate::messages::message("internal", &crate::messages::Params::new())
}
};
let Ok(_g) = self.guard() else { return };
let Ok(mut rs) = self.requests() else { return };
if let Some(r) = rs.iter_mut().find(|r| r.id == rid && r.state == "waiting") {
r.error = Some(text);
r.problem_at = Some(now);
if let Err(e) = self.save_requests(&rs) {
log::error!(target: "ianitor::pki", "cannot record the problem on {rid}: {e}");
}
}
}
fn close(&self, rid: &str, state: &str, error: Option<String>) -> Result<(), PkiFail> {
let _g = self.guard()?;
let mut rs = self.requests()?;
@@ -866,6 +914,8 @@ impl Pki {
}
self.save_devices(&ds)?;
r.state = "approved".into();
r.error = None;
r.problem_at = None;
r.approved_at = Some(now);
r.device_id = Some(did);
self.save_requests(&rs)?;
@@ -929,6 +979,24 @@ impl Pki {
/// Hand out an install file once: the PKCS#12 bytes and the device name. The token is
/// gone afterwards, whatever happens.
/// Whether a one-time link is still unused and in time (the device name, for its page),
/// without using it up.
pub fn peek_bundle(&self, token: &str, now: u64) -> Option<String> {
let device_id = {
let m = self.bundles.lock().ok()?;
let b = m.get(token)?;
if b.expires_at <= now {
return None;
}
b.device_id.clone()
};
self.devices()
.ok()?
.into_iter()
.find(|d| d.id == device_id && d.state(now) == "valid")
.map(|d| d.name)
}
pub fn take_bundle(&self, token: &str, now: u64) -> Result<(Vec<u8>, String), PkiFail> {
let b = {
let mut m = self.bundles.lock().map_err(|_| io("bundles"))?;
@@ -1084,3 +1152,33 @@ pub fn cli_install(state_dir: &Path, cert_pem: &str, now: u64) -> Result<Request
pub fn requests_path(state_dir: &Path) -> PathBuf {
state_dir.join("pki/requests.json")
}
/// After `pki approve` or `pki install`: wait (up to 20 s) for control to act on it. `Ok` with
/// the request's new state, or `Err` with why it was not used.
pub fn cli_wait(state_dir: &Path, rid: &str, since: u64) -> Result<String, String> {
let path = requests_path(state_dir);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
loop {
let rs: Vec<Request> = read_json(&path)?.unwrap_or_default();
match rs.iter().find(|r| r.id == rid) {
None => return Err("the request is gone (it may have expired)".into()),
Some(r) if r.state != "waiting" => {
return match (&r.error, r.state.as_str()) {
(Some(e), s) if s != "approved" => Err(e.clone()),
_ => Ok(r.state.clone()),
};
}
Some(r) if r.problem_at.is_some_and(|t| t >= since) => {
return Err(r.error.clone().unwrap_or_else(|| "it was not used".into()));
}
Some(_) => {}
}
if std::time::Instant::now() >= deadline {
return Err(
"control has not acted on it within 20 s; is ianitor-control running? It still will when it starts"
.into(),
);
}
std::thread::sleep(std::time::Duration::from_millis(250));
}
}
+1
View File
@@ -115,6 +115,7 @@ impl Env {
caddy_credentials_dir: dir.str("creds"),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
};
// Edge starts from an empty config; control brings it in line on its first start.
let empty = load(
+28 -9
View File
@@ -35,6 +35,15 @@ mod unix {
const PASSWORD: &str = "intermediate-test-password-123";
/// Whether an allow list names any device (the placeholder that keeps it from being
/// empty is not one).
fn lists_a_device(allow: &str) -> bool {
pki::chain_der(allow)
.unwrap_or_default()
.iter()
.any(|d| pki::inspect_der(d).is_ok_and(|i| i.subject_cn != pki::NO_DEVICE_CN))
}
fn now() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
@@ -341,7 +350,7 @@ mod unix {
// The allow list both engines read has it.
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
assert!(allow.contains("BEGIN CERTIFICATE"));
assert!(lists_a_device(&allow));
// One-time install file.
let b = env
@@ -359,8 +368,16 @@ mod unix {
.split_once("/api/v1/")
.map(|(_, p)| format!("/api/v1/{p}"))
.unwrap();
// Opening the link (GET, as a link preview or prefetcher would) shows a page and
// uses nothing up; its button posts.
for _ in 0..2 {
let g = env.call_with("GET", &path, &[], None).await;
assert_eq!(g.status, 200, "{}", g.text);
assert!(g.text.contains("<form method=\"post\">"), "{}", g.text);
assert!(g.text.contains("Mark&#39;s phone"), "{}", g.text);
}
// No token needed for the download itself (the link is the secret) ...
let d = env.call_with("GET", &path, &[], None).await;
let d = env.call_with("POST", &path, &[], None).await;
assert_eq!(d.status, 200, "{}", d.text);
assert_eq!(d.header("content-type"), Some("application/x-pkcs12"));
let ks = p12_keystore::KeyStore::from_pkcs12(
@@ -372,9 +389,11 @@ mod unix {
let (_, chain) = ks.private_key_chain().unwrap();
assert_eq!(chain.certs().len(), 3, "leaf, intermediate, root");
// ... and it works only once.
let d = env.call_with("GET", &path, &[], None).await;
let d = env.call_with("POST", &path, &[], None).await;
assert_eq!(d.status, 410, "{}", d.text);
assert_eq!(d.json["error"]["code"], "pki.bundle_used");
let g = env.call_with("GET", &path, &[], None).await;
assert_eq!(g.status, 410, "{}", g.text);
// Revoke: off the allow list, no new install file.
let r = env
@@ -382,7 +401,11 @@ mod unix {
.await;
assert_eq!(r.status, 204, "{}", r.text);
let allow = std::fs::read_to_string(env.dir.join("certs/domi-devices.pem")).unwrap();
assert!(!allow.contains("BEGIN CERTIFICATE"), "{allow}");
assert!(!lists_a_device(&allow), "{allow}");
assert!(
allow.contains("BEGIN CERTIFICATE"),
"never empty (Caddy refuses that)"
);
let b = env
.call(
"POST",
@@ -698,11 +721,7 @@ mod unix {
let done = wait_request(&env, &rid, "approved").await;
let did = done["device_id"].as_str().unwrap().to_owned();
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 on_list = || lists_a_device(&std::fs::read_to_string(&allow_file).unwrap_or_default());
let deadline = Instant::now() + Duration::from_secs(10);
while !on_list() {
assert!(
+12
View File
@@ -89,6 +89,18 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
}),
);
https.insert("protocols".into(), json!(["h1", "h2"]));
if !o.trusted_proxies.is_empty() {
// Like edge: X-Forwarded-For from these peers names the client (logs, `client_ip`).
https.insert(
"trusted_proxies".into(),
json!({
"source": "static",
"ranges": o.trusted_proxies.iter().map(ToString::to_string).collect::<Vec<_>>()
}),
);
https.insert("client_ip_headers".into(), json!(["X-Forwarded-For"]));
https.insert("trusted_proxies_strict".into(), json!(1));
}
if !logged.is_empty() {
let names: Map<String, Value> = logged
.iter()
+1
View File
@@ -34,6 +34,7 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig {
ca: join(&o.cert_dir, DEVICE_CA_FILE),
allow: join(&o.cert_dir, DEVICE_ALLOW_FILE),
}),
trusted_proxies: o.trusted_proxies.iter().map(ToString::to_string).collect(),
forward_auth: site.forward_auth.as_ref().map(|fa| EdgeForwardAuth {
upstream: upstream(&fa.upstream),
path_and_query: fa.path_and_query.clone(),
+4
View File
@@ -44,6 +44,10 @@ pub struct CompileOptions {
/// 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>,
/// Peers whose `X-Forwarded-For` is believed (a proxy in front, such as Caddy beside
/// Ianitor on loopback): the share-link throttle and the access log then see the real
/// client. Empty (the default): only the connection's own address counts.
pub trusted_proxies: Vec<std::net::IpAddr>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+3
View File
@@ -31,6 +31,9 @@ pub struct EdgeConfig {
pub forward_auth: Option<EdgeForwardAuth>,
/// Device certificates (mTLS); present when any host has `device_certs`.
pub device_certs: Option<EdgeDeviceCerts>,
/// Peers whose `X-Forwarded-For` is believed (IP addresses); empty: none.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub trusted_proxies: Vec<String>,
/// Sorted by hostname.
pub hosts: Vec<EdgeHost>,
}
+21
View File
@@ -193,6 +193,27 @@ pub fn create_root(now: i64) -> Result<(String, KeyPair), PkiError> {
Ok((cert.pem(), key))
}
/// Common name of [`no_device_placeholder`].
pub const NO_DEVICE_CN: &str = "Ianitor placeholder: no device is allowed";
/// The allow list's only entry while no device is enrolled. Caddy refuses to load an empty
/// leaf list (and with it the whole config), so the list is never empty: this self-signed
/// certificate's key is dropped right here, so no client can ever present it, and it is not
/// issued by the Domi intermediate, so edge refuses it too.
pub fn no_device_placeholder(now: i64) -> Result<String, PkiError> {
let key = generate_key()?;
let mut p = CertificateParams::default();
p.distinguished_name = dn(NO_DEVICE_CN);
p.is_ca = IsCa::ExplicitNoCa;
p.key_usages = vec![KeyUsagePurpose::DigitalSignature];
p.not_before = time(now - BACKDATE_SECS)?;
p.not_after = time(now + 100 * 365 * DAY)?;
p.serial_number = Some(serial()?);
let cert = p.self_signed(&key.0).map_err(build)?;
drop(key);
Ok(cert.pem())
}
/// A CSR for a new intermediate key (made by control on the server).
pub fn intermediate_csr(key: &KeyPair, cn: &str) -> Result<String, PkiError> {
let mut p = CertificateParams::default();
+24
View File
@@ -73,6 +73,7 @@ fn options() -> CompileOptions {
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
}
}
@@ -150,6 +151,29 @@ fn caddy_output_is_valid_json_with_servers() {
assert_eq!(v["admin"]["disabled"], serde_json::json!(true));
}
#[test]
fn trusted_proxies_reach_both_engines_only_when_set() {
let edge = compile::edge(&model(false), &options()).unwrap();
let caddy = compile::caddy(&model(false), &options()).unwrap();
assert!(!edge.contains("trusted_proxies") && !caddy.contains("trusted_proxies"));
let mut o = options();
o.trusted_proxies = vec!["127.0.0.1".parse().unwrap()];
let cfg: EdgeConfig = serde_json::from_str(&compile::edge(&model(false), &o).unwrap()).unwrap();
assert_eq!(cfg.trusted_proxies, vec!["127.0.0.1".to_owned()]);
let v: serde_json::Value =
serde_json::from_str(&compile::caddy(&model(false), &o).unwrap()).unwrap();
let servers = v["apps"]["http"]["servers"].as_object().unwrap();
let https = servers
.values()
.find(|s| s["listen"][0] == "0.0.0.0:443")
.unwrap();
assert_eq!(
https["trusted_proxies"],
serde_json::json!({"source": "static", "ranges": ["127.0.0.1"]})
);
assert_eq!(https["trusted_proxies_strict"], serde_json::json!(1));
}
#[test]
fn outputs_reference_secrets_by_name_only() {
let edge = compile::edge(&model(false), &options()).unwrap();
+42 -7
View File
@@ -75,11 +75,35 @@ pub fn hostname(host_header: &str) -> String {
name.to_ascii_lowercase()
}
pub fn client_ip(session: &Session) -> Option<IpAddr> {
session
/// The client's address: the peer, or, when the peer is a trusted proxy, the rightmost
/// `X-Forwarded-For` entry that is not itself trusted (the same right-to-left rule as Caddy's
/// `trusted_proxies_strict`). Anything a client could forge to the left is ignored.
pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option<IpAddr> {
let peer = session
.client_addr()
.and_then(|a| a.as_inet())
.map(|a| a.ip())
.map(|a| a.ip())?;
if !trusted.contains(&peer) {
return Some(peer);
}
let mut last = peer;
for v in session
.req_header()
.headers
.get_all("x-forwarded-for")
.iter()
.rev()
{
let Ok(s) = v.to_str() else { return Some(last) };
for part in s.rsplit(',') {
match part.trim().parse::<IpAddr>() {
Ok(ip) if trusted.contains(&ip) => last = ip,
Ok(ip) => return Some(ip),
Err(_) => return Some(last),
}
}
}
Some(last)
}
/// A response with an empty body, like Caddy's `static_response` and error responses.
@@ -157,7 +181,7 @@ impl ProxyHttp for EdgeProxy {
if !host.cfg.share_links {
share::strip_any_token(session)?;
} else {
let ip = client_ip(session);
let ip = client_ip(session, &rt.trusted_proxies);
let revs = self.shared.revocations();
match share::handle(
session,
@@ -198,7 +222,7 @@ impl ProxyHttp for EdgeProxy {
// A valid share link stands in for the sign-in on its prefix.
return self.after_auth(session, &host).await;
}
let ip = client_ip(session).map(|i| i.to_string());
let ip = client_ip(session, &rt.trusted_proxies).map(|i| i.to_string());
let outcome = match forward_auth::check(
&self.connector,
fa,
@@ -322,7 +346,12 @@ impl ProxyHttp for EdgeProxy {
}
req.insert_header(header::HOST, ctx.host_header.as_str())?;
// Forwarding headers are always edge's own; client-supplied values are replaced.
match client_ip(session) {
let trusted = ctx
.rt
.as_ref()
.map(|r| r.trusted_proxies.as_slice())
.unwrap_or(&[]);
match client_ip(session, trusted) {
Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?,
None => {
req.remove_header("X-Forwarded-For");
@@ -415,7 +444,13 @@ impl ProxyHttp for EdgeProxy {
method: req.method.as_str(),
path: req.uri.path(),
status: session.response_written().map_or(0, |r| r.status.as_u16()),
remote_ip: client_ip(session).map(|i| truncate_ip(i).to_string()),
remote_ip: client_ip(
session,
ctx.rt
.as_ref()
.map_or(&[], |r| r.trusted_proxies.as_slice()),
)
.map(|i| truncate_ip(i).to_string()),
duration_ms: u64::try_from(ctx.start.elapsed().as_millis()).unwrap_or(u64::MAX),
});
}
+13
View File
@@ -123,6 +123,8 @@ pub struct Runtime {
pub share_key: Option<Arc<ShareKey>>,
/// Loaded when any host has `device_certs`.
pub device_trust: Option<Arc<crate::tls::DeviceTrust>>,
/// Peers whose X-Forwarded-For names the client.
pub trusted_proxies: Vec<std::net::IpAddr>,
/// SHA-256 (hex) of the config file bytes this runtime was built from; empty when it was
/// built from a parsed config.
pub sha256: String,
@@ -470,9 +472,20 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
} else {
None
};
let trusted_proxies = cfg
.trusted_proxies
.iter()
.map(|s| {
s.parse().map_err(|_| EdgeError::Config {
path: PathBuf::from("<config>"),
message: format!("trusted_proxies: {s:?} is not an IP address"),
})
})
.collect::<Result<Vec<std::net::IpAddr>, _>>()?;
Ok(Runtime {
cfg,
trusted_proxies,
hosts,
forward_auth,
access_log,
+4
View File
@@ -110,6 +110,8 @@ pub struct EdgeSpec<'a> {
pub http_port: Option<u16>,
/// Extra files written into the edge directory before it starts (path relative to it).
pub files: Vec<(String, Vec<u8>)>,
/// Peers whose X-Forwarded-For edge believes.
pub trusted_proxies: Vec<std::net::IpAddr>,
}
impl Default for EdgeSpec<'_> {
@@ -122,6 +124,7 @@ impl Default for EdgeSpec<'_> {
extra_args: Vec::new(),
http_port: None,
files: Vec::new(),
trusted_proxies: Vec::new(),
}
}
}
@@ -191,6 +194,7 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: spec.trusted_proxies.clone(),
};
let config_text = compile_with(&dir, &ca, &opts, spec.site, &spec.hosts);
std::fs::write(dir.join("edge.json"), &config_text).unwrap();
+84
View File
@@ -0,0 +1,84 @@
// 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/.
//! `trusted_proxies` (off by default): behind a proxy on loopback (Caddy beside Ianitor), the
//! client named in X-Forwarded-For is the one edge forwards and logs; without the option a
//! client-sent X-Forwarded-For is ignored.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#[cfg(unix)]
mod common;
#[cfg(not(unix))]
#[test]
fn skipped_on_windows() {
eprintln!(
"SKIPPED on Windows: {} needs Linux (Pingora runner); run it in WSL2, see CLAUDE.md",
file!()
);
}
#[cfg(unix)]
mod unix {
use crate::common::{EdgeSpec, host_file, start};
use ianitor_testkit::client::{self, Req};
use ianitor_testkit::upstream::Echo;
async fn forwarded_for(trusted: Vec<std::net::IpAddr>, xff: &str) -> (String, String) {
let echo = Echo::start("app").await;
let edge = start(EdgeSpec {
hosts: vec![host_file(
"app.test",
&format!(
"upstreams = [\"{}\"]\naccess_log = \"truncated\"\n",
echo.url()
),
)],
trusted_proxies: trusted,
..Default::default()
});
let r = client::https(
edge.https,
"app.test",
edge.roots(),
&Req::get("app.test", "/").header("x-forwarded-for", xff),
)
.await
.unwrap();
assert_eq!(r.status, 200);
let seen = echo.proxied();
let got = String::from_utf8(seen[0].header("x-forwarded-for").unwrap().to_vec()).unwrap();
// The access line is written after the response; give it a moment.
let mut log = String::new();
for _ in 0..50 {
log = edge.access_log();
if log.contains("app.test") {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
(got, log)
}
#[tokio::test(flavor = "multi_thread")]
async fn without_the_option_a_client_sent_forwarded_for_is_ignored() {
let (xff, log) = forwarded_for(Vec::new(), "203.0.113.7").await;
assert_eq!(xff, "127.0.0.1");
assert!(!log.contains("203.0.113"), "{log}");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_trusted_proxy_names_the_client_rightmost_first() {
// The leftmost entry is what a client could forge; the rightmost untrusted one counts.
let (xff, log) = forwarded_for(
vec!["127.0.0.1".parse().unwrap()],
"198.51.100.9, 203.0.113.7, 127.0.0.1",
)
.await;
assert_eq!(xff, "203.0.113.7");
assert!(log.contains("203.0.113.0"), "the real /24 is logged: {log}");
assert!(!log.contains("198.51.100"), "{log}");
}
}
+7
View File
@@ -41,6 +41,7 @@ let
state_dir = "${stateRoot}/edge-state";
access_log = "/var/log/ianitor/access.log";
caddy_credentials_dir = "/run/credentials/caddy-fallback.service";
trusted_proxies = cfg.edge.trustedProxies;
};
controlToml = toml.generate "control.toml" (
@@ -146,6 +147,12 @@ in
default = false;
description = "Open edge's two ports in the firewall.";
};
trustedProxies = mkOption {
type = types.listOf types.str;
default = [ ];
example = [ "127.0.0.1" ];
description = "Proxies in front of edge whose X-Forwarded-For names the client (beside Caddy: 127.0.0.1), for the share-link throttle and the access log. Off by default.";
};
};
control.listen = mkOption {
+4 -3
View File
@@ -15,7 +15,7 @@ Everything below was run end to end on loopback against `--dev` with a real edge
Without either: `401` with `token.missing`, `token.unknown`, `token.expired` or
`token.revoked`; a `Remote-*` header without edge's proof is `401 ui.no_proof`, whatever
else the request carries. 120 calls a minute per token or user. The one exception is the
one-time device download (`GET /device-bundles/{token}`), where the link is the secret.
one-time device download (`/device-bundles/{token}`), where the link is the secret.
- **Host header.** Only `127.0.0.1:<port>`, `localhost:<port>`, `[::1]:<port>` and the
configured `allowed_hosts` are answered (DNS rebinding). A browser write (`Origin` or
`Sec-Fetch-Site` present) also needs `X-Ianitor-UI: 1` (CSRF).
@@ -287,7 +287,7 @@ curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/certs/devices"
# on the server: sudo -u ianitor-control ianitor-control pki approve 47 19 83 --config /etc/ianitor/control.toml
curl -s -H "$H" -H 'Content-Type: application/json' -X POST "$API/certs/devices/$DEV/bundle" \
-d '{"format": "p12"}' | jq '{download_url, one_time_password}'
curl -s -o phone.p12 "$DOWNLOAD_URL" # once; a second try is 410 pki.bundle_used
curl -s -X POST -o phone.p12 "$DOWNLOAD_URL" # once; a second try is 410 pki.bundle_used (GET is only its page)
curl -s -H "$H" -X DELETE "$API/certs/devices/$DEV" # 204, off the allow list at once
```
@@ -350,6 +350,7 @@ safe and nudges the engine again. Edge also re-reads the device files by itself
| `GET /health` | edge reachability, config hash, trial, paused state, hosts |
| `GET /certs`, `POST /certs/devices`, `DELETE /certs/devices/{id}`, `POST /certs/devices/{id}/bundle` | the Domi CA screen, device requests, revocation, one-time install files |
| `POST /certs/intermediate/renewal`, `GET/DELETE /pki-requests/{id}`, `GET /pki-requests/{id}/csr`, `GET /pki-requests/{id}/ext`, `PUT /pki-requests/{id}/certificate` | renewals and approvals |
| `GET /device-bundles/{token}` | the one-time PKCS#12 download (no token; the link is the secret) |
| `GET /device-bundles/{token}` | the link's page with a Download button (uses nothing up: link previews only GET) |
| `POST /device-bundles/{token}` | the one-time PKCS#12 download (no token; the link is the secret) |
| `GET /engine`, `POST /engine` | which engine serves; switch |
| `GET /openapi.json` | the OpenAPI document |
+3 -1
View File
@@ -67,7 +67,7 @@ new file mode 100644
index 0000000..cd23016
--- /dev/null
+++ b/hyperv-infra/modules/ianitor.nix
@@ -0,0 +1,49 @@
@@ -0,0 +1,51 @@
+{ config, lib, inputs, ... }:
+
+# Ianitor beside Caddy (Ianitor ROADMAP §1.12, Phase 3): two low-risk hosts, flowers and esp32,
@@ -100,6 +100,8 @@ index 0000000..cd23016
+ httpListen = "127.0.0.1:18080";
+ httpsListen = "127.0.0.1:18443";
+ openFirewall = false;
+ # Caddy in front, on loopback: its X-Forwarded-For names the visitor (throttle, logs).
+ trustedProxies = [ "127.0.0.1" ];
+ };
+ control.listen = "127.0.0.1:7878";
+ shareLinkKeyFile = config.sops.secrets."ianitor/share-link-key".path;
+4 -3
View File
@@ -522,9 +522,10 @@ Recorded by the Phase 3 implementation (branch `phase-3`); docs/api.md has the c
- **G14**: edge's per-boot proof header on the admin host; control trusts `Remote-User` (actor)
and `Remote-Name` (shown) only with it; a forged `Remote-User` is `401 ui.no_proof`.
`overview.viewer {name, via}` and `overview.site.auth_logout_url` are new.
- **G15**: `POST /certs/devices/{id}/bundle` → one-time `GET /device-bundles/{token}` (10 min,
one use, PKCS#12 with a one-time password, `qr_svg` for `format = "qr"`); through edge on the
admin host, as a share link when that host has share links on.
- **G15**: `POST /certs/devices/{id}/bundle` → one-time `/device-bundles/{token}` (GET shows a
page, its button POSTs the download, so link previews cannot use it up; 10 min, one use,
PKCS#12 with a one-time password, `qr_svg` for `format = "qr"`); through edge on the admin
host, as a share link when that host has share links on (never listed in `GET /share-links`).
- **G18**: `GET/POST /engine` (shape in docs/api.md). Differences from §1.9: no `fallback_ready
{compared, matched}` (control cannot run the differential suite at runtime; it reports
`{built_at, current}`). Changes keep working while Caddy serves (Mark 2026-11-08): they are
+1
View File
@@ -180,6 +180,7 @@ impl Env {
caddy_credentials_dir: self.dir.str("creds"),
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
}
}
+1
View File
@@ -41,6 +41,7 @@ mod unix {
caddy_credentials_dir: o.caddy_credentials_dir.clone(),
caddy_admin: o.caddy_admin,
caddy_admin_socket: o.caddy_admin_socket.clone(),
trusted_proxies: o.trusted_proxies.clone(),
}
}
+54 -2
View File
@@ -19,8 +19,8 @@ fn skipped_on_windows() {
#[cfg(unix)]
mod unix {
use ianitor_diff::{
Env, break_caddy, break_edge, compile_pair, corpus, run_corpus, settle, start_caddy,
start_edge,
Action, Env, break_caddy, break_edge, compile_pair, corpus, run_cases, run_corpus, settle,
start_caddy, start_edge,
};
use ianitor_testkit::proc::require_binary;
@@ -61,6 +61,58 @@ mod unix {
}
}
/// No device enrolled yet (or every one revoked). Caddy refuses a leaf list with no
/// certificate in it (QC, fix round 1: the whole config fails to load), so control writes
/// a placeholder no one holds the key to. Both engines start, serve the other hosts, and
/// let no device in.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn with_no_device_enrolled_both_engines_start_and_let_no_device_in() {
let Some(caddy_bin) = require_binary("caddy") else {
return;
};
let env = Env::start().await;
std::fs::write(
env.dir.join(&format!(
"certs/{}",
ianitor_core::compile::DEVICE_ALLOW_FILE
)),
ianitor_core::pki::no_device_placeholder(0).unwrap(),
)
.unwrap();
let (edge_cfg, caddy_cfg) = compile_pair(&env);
let ianitor = start_edge(&env, "ianitor", &edge_cfg);
let caddy = start_caddy(&env, "caddy", &caddy_bin, &caddy_cfg);
settle().await;
let report = run_cases(&ianitor, &caddy, env.roots(), |c| {
matches!(c.action, Action::HttpsDevice { .. }) || c.name == "plain GET"
})
.await;
println!("{}", report.render("Ianitor vs Caddy, empty allow list"));
assert!(
report.mismatches().is_empty(),
"{}",
report.render("Ianitor vs Caddy, empty allow list")
);
let get = |name: &str| {
report
.outcomes
.iter()
.find(|o| o.name == name)
.unwrap_or_else(|| panic!("no case {name}"))
};
assert_eq!(
get("plain GET").caddy.status,
200,
"Caddy serves the others"
);
let listed = get("Domi device certificate on the allow list");
assert!(
!(200..300).contains(&listed.ianitor.status),
"a device got in with an empty allow list: {}",
listed.ianitor.status
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_deliberately_broken_compiler_is_caught() {
let Some(caddy_bin) = require_binary("caddy") else {