[core] Proxy socket: compile option proxy_socket gives both engines a 0660 Unix socket for the front proxy (edge in its config, Caddy a third server with trusted_proxies_unix); listeners change only with a restart

This commit is contained in:
2026-11-10 20:59:57 +01:00
parent 4150848842
commit ffffa62999
15 changed files with 117 additions and 20 deletions
+5
View File
@@ -116,6 +116,10 @@ pub struct Compile {
/// 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>,
/// The front proxy's Unix socket (beside Caddy): both engines serve the HTTPS hosts on it
/// and believe its X-Forwarded-For.
#[serde(default)]
pub proxy_socket: Option<String>,
}
impl Compile {
@@ -130,6 +134,7 @@ impl Compile {
caddy_admin: self.caddy_admin,
caddy_admin_socket: self.caddy_admin_socket.clone(),
trusted_proxies: self.trusted_proxies.clone(),
proxy_socket: self.proxy_socket.clone(),
}
}
}
+1
View File
@@ -150,6 +150,7 @@ pub async fn run(args: &[String]) -> Result<(), String> {
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
proxy_socket: None,
},
compile_caddy: None,
pki: Some(ianitor_control::config::PkiConfig {
+1
View File
@@ -116,6 +116,7 @@ impl Env {
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
proxy_socket: None,
};
// Edge starts from an empty config; control brings it in line on its first start.
let empty = load(
+26 -4
View File
@@ -19,6 +19,7 @@ use crate::{
const ACCESS_LOGGER: &str = "ianitor_access";
const HTTPS_SERVER: &str = "ianitor_https";
const HTTP_SERVER: &str = "ianitor_http";
const PROXY_SERVER: &str = "ianitor_proxy";
pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
let hosts = model.hosts();
@@ -77,6 +78,23 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
.collect();
policies.push(json!({}));
// ---- The front proxy's socket: the same routes in plain HTTP, its peer trusted (edge:
// `client_ip` on the socket). No TLS here, so no certificates are managed for it.
let mut proxy = o.proxy_socket.as_ref().map(|sock| {
let mut p = Map::new();
p.insert(
"listen".into(),
json!([format!("unix//{}|0660", sock.trim_start_matches('/'))]),
);
p.insert("routes".into(), Value::Array(routes.clone()));
p.insert("automatic_https".into(), json!({ "disable": true }));
p.insert("protocols".into(), json!(["h1"]));
p.insert("trusted_proxies_unix".into(), json!(true));
p.insert("client_ip_headers".into(), json!(["X-Forwarded-For"]));
p.insert("trusted_proxies_strict".into(), json!(1));
p
});
let mut https = Map::new();
https.insert("listen".into(), json!([o.https_listen.to_string()]));
https.insert("routes".into(), Value::Array(routes));
@@ -106,10 +124,11 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
.iter()
.map(|h| (h.hostname.to_string(), json!([ACCESS_LOGGER])))
.collect();
https.insert(
"logs".into(),
json!({ "logger_names": names, "skip_unmapped_hosts": true }),
);
let logs = json!({ "logger_names": names, "skip_unmapped_hosts": true });
if let Some(p) = proxy.as_mut() {
p.insert("logs".into(), logs.clone());
}
https.insert("logs".into(), logs);
}
// ---- HTTP server: redirect known hosts to HTTPS (ACME HTTP-01 is answered by Caddy itself).
@@ -142,6 +161,9 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
let mut servers = Map::new();
servers.insert(HTTPS_SERVER.into(), Value::Object(https));
servers.insert(HTTP_SERVER.into(), http);
if let Some(p) = proxy {
servers.insert(PROXY_SERVER.into(), Value::Object(p));
}
let mut tls = Map::new();
if !domi.is_empty() {
+1
View File
@@ -35,6 +35,7 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig {
allow: join(&o.cert_dir, DEVICE_ALLOW_FILE),
}),
trusted_proxies: o.trusted_proxies.iter().map(ToString::to_string).collect(),
proxy_socket: o.proxy_socket.clone(),
forward_auth: site.forward_auth.as_ref().map(|fa| EdgeForwardAuth {
upstream: upstream(&fa.upstream),
path_and_query: fa.path_and_query.clone(),
+17
View File
@@ -48,6 +48,10 @@ pub struct CompileOptions {
/// 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>,
/// A Unix socket (mode 0660) on which the engine also serves the HTTPS hosts, in plain HTTP,
/// to a front proxy that terminated TLS (Caddy beside Ianitor). Only the socket's owner and
/// group can connect, so its peer is trusted and its `X-Forwarded-For` names the client.
pub proxy_socket: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
@@ -80,6 +84,19 @@ pub fn caddy(model: &Model, options: &CompileOptions) -> Result<String, CompileE
}
fn check_options(o: &CompileOptions) -> Result<(), CompileError> {
if let Some(s) = &o.proxy_socket {
check_path(s).map_err(|reason| CompileError::BadOption {
option: "proxy_socket",
reason,
})?;
// sun_path holds 108 bytes on Linux, the terminating NUL included.
if s.len() > 100 {
return Err(CompileError::BadOption {
option: "proxy_socket",
reason: "a socket path is at most 100 characters",
});
}
}
if let Some(s) = &o.caddy_admin_socket {
check_path(s).map_err(|reason| CompileError::BadOption {
option: "caddy_admin_socket",
+4
View File
@@ -34,6 +34,10 @@ pub struct EdgeConfig {
/// Peers whose `X-Forwarded-For` is believed (IP addresses); empty: none.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub trusted_proxies: Vec<String>,
/// A Unix socket (mode 0660) serving the HTTPS hosts in plain HTTP to a front proxy that
/// terminated TLS; its peer is trusted (`X-Forwarded-For` names the client).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub proxy_socket: Option<String>,
/// Sorted by hostname.
pub hosts: Vec<EdgeHost>,
}
+39
View File
@@ -74,6 +74,7 @@ fn options() -> CompileOptions {
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
proxy_socket: None,
}
}
@@ -174,6 +175,44 @@ fn trusted_proxies_reach_both_engines_only_when_set() {
assert_eq!(https["trusted_proxies_strict"], serde_json::json!(1));
}
#[test]
fn the_proxy_socket_reaches_both_engines_only_when_set() {
let edge = compile::edge(&model(false), &options()).unwrap();
let caddy = compile::caddy(&model(false), &options()).unwrap();
assert!(!edge.contains("proxy_socket") && !caddy.contains("ianitor_proxy"));
let mut o = options();
o.proxy_socket = Some("/run/ianitor-proxy/edge.sock".into());
let cfg: EdgeConfig = serde_json::from_str(&compile::edge(&model(false), &o).unwrap()).unwrap();
assert_eq!(
cfg.proxy_socket.as_deref(),
Some("/run/ianitor-proxy/edge.sock")
);
let v: serde_json::Value =
serde_json::from_str(&compile::caddy(&model(false), &o).unwrap()).unwrap();
let servers = &v["apps"]["http"]["servers"];
let proxy = &servers["ianitor_proxy"];
assert_eq!(
proxy["listen"],
serde_json::json!(["unix//run/ianitor-proxy/edge.sock|0660"])
);
// The same routes as the HTTPS server, no TLS, the socket's peer trusted.
assert_eq!(proxy["routes"], servers["ianitor_https"]["routes"]);
assert_eq!(
proxy["automatic_https"],
serde_json::json!({"disable": true})
);
assert_eq!(proxy["trusted_proxies_unix"], serde_json::json!(true));
assert!(proxy.get("tls_connection_policies").is_none());
let long = format!("/{}", "a".repeat(120));
for bad in ["relative.sock", "/run/{env.HOME}.sock", long.as_str()] {
let mut o = options();
o.proxy_socket = Some(bad.to_owned());
assert!(compile::edge(&model(false), &o).is_err(), "{bad}");
assert!(compile::caddy(&model(false), &o).is_err(), "{bad}");
}
}
#[test]
fn outputs_reference_secrets_by_name_only() {
let edge = compile::edge(&model(false), &options()).unwrap();
+2 -6
View File
@@ -60,10 +60,6 @@ pub struct Options {
pub credentials_dir: Option<PathBuf>,
/// The overall deadline for a request header; default [`deadline::HEADER_TIMEOUT`].
pub header_timeout: Option<std::time::Duration>,
/// A Unix socket (mode 0660) on which edge serves the HTTPS hosts in plain HTTP to a front
/// proxy that terminated TLS (Caddy beside Ianitor). Only the socket's owner and group can
/// connect, so its `X-Forwarded-For` is believed (Unix only).
pub proxy_socket: Option<PathBuf>,
}
impl Options {
@@ -148,8 +144,8 @@ pub fn server(shared: Arc<Shared>, opts: &Options) -> Result<Server, EdgeError>
https
.endpoints()
.set_pre_tls_callback(Arc::new(tls::HandshakeStart));
if let Some(path) = &opts.proxy_socket {
add_proxy_socket(&mut https, path)?;
if let Some(path) = &rt.cfg.proxy_socket {
add_proxy_socket(&mut https, Path::new(path))?;
}
let mut http = Service::new(
+2 -4
View File
@@ -3,8 +3,7 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! `ianitor-edge --config <edge.json> [--check] [--admin-socket <path>] [--trial-config <path>]
//! [--share-revocations <path>] [--acme-root <ca.pem>] [--header-timeout <secs>]
//! [--proxy-socket <path>]`
//! [--share-revocations <path>] [--acme-root <ca.pem>] [--header-timeout <secs>]`
//!
//! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG`
//! (error, warn, info, debug, trace; libraries are capped at info).
@@ -24,7 +23,6 @@ fn parse_args() -> Result<(Options, bool), EdgeError> {
Some("--config") => config = args.next().map(PathBuf::from),
Some("--acme-root") => opts.acme_root = args.next().map(PathBuf::from),
Some("--admin-socket") => opts.admin_socket = args.next().map(PathBuf::from),
Some("--proxy-socket") => opts.proxy_socket = args.next().map(PathBuf::from),
Some("--trial-config") => opts.trial_config = args.next().map(PathBuf::from),
Some("--share-revocations") => opts.share_revocations = args.next().map(PathBuf::from),
Some("--header-timeout") => {
@@ -42,7 +40,7 @@ fn parse_args() -> Result<(Options, bool), EdgeError> {
println!(
"usage: ianitor-edge --config <edge.json> [--check] [--admin-socket <path>] \
[--trial-config <path>] [--share-revocations <path>] [--acme-root <ca.pem>] \
[--header-timeout <secs>] [--proxy-socket <path>]"
[--header-timeout <secs>]"
);
std::process::exit(0);
}
+4 -1
View File
@@ -119,7 +119,10 @@ pub struct Shared {
}
fn same_listeners(a: &Runtime, b: &Runtime) -> Result<(), EdgeError> {
if a.cfg.http_listen != b.cfg.http_listen || a.cfg.https_listen != b.cfg.https_listen {
if a.cfg.http_listen != b.cfg.http_listen
|| a.cfg.https_listen != b.cfg.https_listen
|| a.cfg.proxy_socket != b.cfg.proxy_socket
{
return Err(EdgeError::Config {
path: PathBuf::from("<new config>"),
message: "the listen addresses can only change with a restart".into(),
+4
View File
@@ -112,6 +112,8 @@ pub struct EdgeSpec<'a> {
pub files: Vec<(String, Vec<u8>)>,
/// Peers whose X-Forwarded-For edge believes.
pub trusted_proxies: Vec<std::net::IpAddr>,
/// The front proxy's Unix socket.
pub proxy_socket: Option<String>,
}
impl Default for EdgeSpec<'_> {
@@ -125,6 +127,7 @@ impl Default for EdgeSpec<'_> {
http_port: None,
files: Vec::new(),
trusted_proxies: Vec::new(),
proxy_socket: None,
}
}
}
@@ -195,6 +198,7 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge {
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: spec.trusted_proxies.clone(),
proxy_socket: spec.proxy_socket.clone(),
};
let config_text = compile_with(&dir, &ca, &opts, spec.site, &spec.hosts);
std::fs::write(dir.join("edge.json"), &config_text).unwrap();
+9 -5
View File
@@ -147,10 +147,14 @@ mod unix {
let echo = Echo::start("app").await;
let dir = ianitor_testkit::proc::TempDir::new("proxy-sock");
let sock = dir.join("proxy.sock");
let edge = app_edge(
&echo,
vec!["--proxy-socket".into(), sock.to_string_lossy().into()],
);
let edge = start(EdgeSpec {
hosts: vec![host_file(
"app.test",
&format!("upstreams = [\"{}\"]\n", echo.url()),
)],
proxy_socket: Some(sock.to_string_lossy().into()),
..Default::default()
});
for _ in 0..100 {
if sock.exists() {
break;
@@ -221,7 +225,7 @@ mod unix {
devices_ca.issue(&["a-device"]).cert_pem.into_bytes(),
),
],
extra_args: vec!["--proxy-socket".into(), sock.to_string_lossy().into()],
proxy_socket: Some(sock.to_string_lossy().into()),
..Default::default()
});
for _ in 0..100 {
+1
View File
@@ -181,6 +181,7 @@ impl Env {
caddy_admin: None,
caddy_admin_socket: None,
trusted_proxies: Vec::new(),
proxy_socket: None,
}
}
+1
View File
@@ -40,6 +40,7 @@ mod unix {
caddy_admin: o.caddy_admin,
caddy_admin_socket: o.caddy_admin_socket.clone(),
trusted_proxies: o.trusted_proxies.clone(),
proxy_socket: o.proxy_socket.clone(),
}
}