[core] Unix upstreams: unix:/path parses strictly into a socket upstream; edge proxies and health-checks it in plain HTTP over the socket, Caddy dials unix/<path>
This commit is contained in:
@@ -281,7 +281,11 @@ fn host_route(h: &Host, fa: Option<&ForwardAuth>, o: &CompileOptions) -> Value {
|
|||||||
fn upstreams(list: &[&Upstream]) -> Value {
|
fn upstreams(list: &[&Upstream]) -> Value {
|
||||||
Value::Array(
|
Value::Array(
|
||||||
list.iter()
|
list.iter()
|
||||||
.map(|u| json!({ "dial": u.authority() }))
|
.map(|u| match u.unix_path() {
|
||||||
|
// Caddy's network address: `unix/` then the absolute path.
|
||||||
|
Some(p) => json!({ "dial": format!("unix/{p}") }),
|
||||||
|
None => json!({ "dial": u.authority() }),
|
||||||
|
})
|
||||||
.collect(),
|
.collect(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ pub(crate) mod reason {
|
|||||||
pub const URL_CREDENTIALS: &str = "credentials in the URL are not allowed";
|
pub const URL_CREDENTIALS: &str = "credentials in the URL are not allowed";
|
||||||
pub const URL_FRAGMENT: &str = "a #fragment is not allowed";
|
pub const URL_FRAGMENT: &str = "a #fragment is not allowed";
|
||||||
pub const URL_NO_HOST: &str = "it has no host";
|
pub const URL_NO_HOST: &str = "it has no host";
|
||||||
|
pub const URL_UNIX_PATH: &str = "a socket upstream is unix:/absolute/path: letters, digits, '.', '_', '-' and single '/' only, no '.' or '..' parts, at most 100 characters";
|
||||||
pub const URL_HOST_NAME: &str = "the host name is not valid";
|
pub const URL_HOST_NAME: &str = "the host name is not valid";
|
||||||
pub const URL_NO_PORT: &str = "it has no port";
|
pub const URL_NO_PORT: &str = "it has no port";
|
||||||
pub const URL_PORT_ZERO: &str = "port 0 is not usable";
|
pub const URL_PORT_ZERO: &str = "port 0 is not usable";
|
||||||
@@ -275,6 +276,7 @@ impl ValidationError {
|
|||||||
x if x == r::URL_PATH => "host.upstream.path",
|
x if x == r::URL_PATH => "host.upstream.path",
|
||||||
x if x == r::URL_QUERY => "host.upstream.query",
|
x if x == r::URL_QUERY => "host.upstream.query",
|
||||||
x if x == r::URL_MIXED => "host.upstream.mixed_schemes",
|
x if x == r::URL_MIXED => "host.upstream.mixed_schemes",
|
||||||
|
x if x == r::URL_UNIX_PATH => "host.upstream.unix_path",
|
||||||
_ => "host.upstream.not_url",
|
_ => "host.upstream.not_url",
|
||||||
},
|
},
|
||||||
E::DuplicateUpstream { .. } => "host.upstream.duplicate",
|
E::DuplicateUpstream { .. } => "host.upstream.duplicate",
|
||||||
|
|||||||
@@ -401,7 +401,11 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
|||||||
let mut upstreams: Vec<Upstream> = Vec::new();
|
let mut upstreams: Vec<Upstream> = Vec::new();
|
||||||
let mut seen_upstreams = BTreeSet::new();
|
let mut seen_upstreams = BTreeSet::new();
|
||||||
for (index, u) in raw.upstreams.iter().take(MAX_UPSTREAMS).enumerate() {
|
for (index, u) in raw.upstreams.iter().take(MAX_UPSTREAMS).enumerate() {
|
||||||
match parse_url(u, false) {
|
let parsed = match u.strip_prefix("unix:") {
|
||||||
|
Some(path) => parse_unix(path).map(|up| (up, String::new())),
|
||||||
|
None => parse_url(u, false),
|
||||||
|
};
|
||||||
|
match parsed {
|
||||||
Ok((up, _)) => {
|
Ok((up, _)) => {
|
||||||
if seen_upstreams.insert(up.clone()) {
|
if seen_upstreams.insert(up.clone()) {
|
||||||
upstreams.push(up);
|
upstreams.push(up);
|
||||||
@@ -786,6 +790,31 @@ fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static
|
|||||||
Ok((Upstream { scheme, host, port }, path))
|
Ok((Upstream { scheme, host, port }, path))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The path of a `unix:` upstream. It ends up in JSON strings and in Caddy's dial address
|
||||||
|
/// (where `{...}` would be a placeholder), so it is plain: absolute, `[A-Za-z0-9._-]` parts
|
||||||
|
/// joined by single `/`, no `.` or `..` part, at most 100 bytes (sun_path is 108 on Linux).
|
||||||
|
fn parse_unix(path: &str) -> Result<Upstream, &'static str> {
|
||||||
|
let ok = path.len() <= 100
|
||||||
|
&& path.len() > 1
|
||||||
|
&& path.starts_with('/')
|
||||||
|
&& path[1..].split('/').all(|part| {
|
||||||
|
!part.is_empty()
|
||||||
|
&& part != "."
|
||||||
|
&& part != ".."
|
||||||
|
&& part
|
||||||
|
.bytes()
|
||||||
|
.all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-'))
|
||||||
|
});
|
||||||
|
if !ok {
|
||||||
|
return Err(r::URL_UNIX_PATH);
|
||||||
|
}
|
||||||
|
Ok(Upstream {
|
||||||
|
scheme: Scheme::Http,
|
||||||
|
host: UpstreamHost::Unix(path.to_owned()),
|
||||||
|
port: 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// A URL as an error may show it: everything before the last `@` (after the scheme) is
|
/// A URL as an error may show it: everything before the last `@` (after the scheme) is
|
||||||
/// replaced by `…`, so a user name or password, even one containing `/`, `?` or `#`, never
|
/// replaced by `…`, so a user name or password, even one containing `/`, `?` or `#`, never
|
||||||
/// reaches a message, a log or the API. A URL with no `@` is shown as it is.
|
/// reaches a message, a log or the API. A URL with no `@` is shown as it is.
|
||||||
|
|||||||
@@ -39,6 +39,36 @@ pub fn peer(addr: SocketAddr, u: &UpstreamRt) -> HttpPeer {
|
|||||||
p
|
p
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The peer of a `unix:` upstream (plain HTTP over the socket).
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub fn unix_peer(path: &str) -> Result<HttpPeer> {
|
||||||
|
let mut p = HttpPeer::new_uds(path, false, String::new())?;
|
||||||
|
p.options.connection_timeout = Some(DIAL_TIMEOUT);
|
||||||
|
Ok(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
pub fn unix_peer(path: &str) -> Result<HttpPeer> {
|
||||||
|
Error::e_explain(
|
||||||
|
ErrorType::SocketError,
|
||||||
|
format!("{path}: Unix sockets need a Unix system"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every peer to try for `u`, in order: its socket, or each address its name resolves to.
|
||||||
|
pub async fn peers(u: &UpstreamRt) -> Result<Vec<HttpPeer>> {
|
||||||
|
if let Some(path) = &u.unix {
|
||||||
|
return Ok(vec![unix_peer(path)?]);
|
||||||
|
}
|
||||||
|
let addrs = u.resolve().await.map_err(|e| {
|
||||||
|
Error::explain(
|
||||||
|
ErrorType::ConnectNoRoute,
|
||||||
|
format!("cannot resolve {}: {e}", u.authority),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
Ok(addrs.into_iter().map(|a| peer(a, u)).collect())
|
||||||
|
}
|
||||||
|
|
||||||
/// Send `req` without a body; read the whole response, at most `max_body` bytes of body,
|
/// Send `req` without a body; read the whole response, at most `max_body` bytes of body,
|
||||||
/// all within `timeout`.
|
/// all within `timeout`.
|
||||||
pub async fn fetch(
|
pub async fn fetch(
|
||||||
@@ -64,16 +94,9 @@ async fn exchange(
|
|||||||
max_body: usize,
|
max_body: usize,
|
||||||
timeout: Duration,
|
timeout: Duration,
|
||||||
) -> Result<Fetched> {
|
) -> Result<Fetched> {
|
||||||
let addrs = u.resolve().await.map_err(|e| {
|
|
||||||
Error::explain(
|
|
||||||
ErrorType::ConnectNoRoute,
|
|
||||||
format!("cannot resolve {}: {e}", u.authority),
|
|
||||||
)
|
|
||||||
})?;
|
|
||||||
let mut last = None;
|
let mut last = None;
|
||||||
let mut session = None;
|
let mut session = None;
|
||||||
for addr in addrs {
|
for mut p in peers(u).await? {
|
||||||
let mut p = peer(addr, u);
|
|
||||||
p.options.total_connection_timeout = Some(timeout);
|
p.options.total_connection_timeout = Some(timeout);
|
||||||
match connector.get_http_session(&p).await {
|
match connector.get_http_session(&p).await {
|
||||||
Ok((s, _reused)) => {
|
Ok((s, _reused)) => {
|
||||||
|
|||||||
@@ -122,6 +122,9 @@ async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>, watch
|
|||||||
let (h, p, c) = (host.clone(), path.to_owned(), connector.clone());
|
let (h, p, c) = (host.clone(), path.to_owned(), connector.clone());
|
||||||
let probe_host = if watch {
|
let probe_host = if watch {
|
||||||
host.cfg.hostname.clone()
|
host.cfg.hostname.clone()
|
||||||
|
} else if host.upstreams[i].unix.is_some() {
|
||||||
|
// A socket has no authority to name; the probe asks as a local client would.
|
||||||
|
"localhost".to_owned()
|
||||||
} else {
|
} else {
|
||||||
host.upstreams[i].authority.clone()
|
host.upstreams[i].authority.clone()
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -306,6 +306,11 @@ impl ProxyHttp for EdgeProxy {
|
|||||||
Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream")
|
Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream")
|
||||||
})?;
|
})?;
|
||||||
let up = &host.upstreams[i];
|
let up = &host.upstreams[i];
|
||||||
|
if let Some(path) = &up.unix {
|
||||||
|
// A socket: one peer, nothing to resolve and no other address to try.
|
||||||
|
log::debug!(target: "ianitor::proxy", "{}: upstream {}", host.cfg.hostname, up.authority);
|
||||||
|
return Ok(Box::new(fetch::unix_peer(path)?));
|
||||||
|
}
|
||||||
ctx.addrs = match up.resolve().await {
|
ctx.addrs = match up.resolve().await {
|
||||||
Ok(a) => a,
|
Ok(a) => a,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
|||||||
@@ -85,6 +85,8 @@ pub struct UpstreamRt {
|
|||||||
pub authority: String,
|
pub authority: String,
|
||||||
pub tls: bool,
|
pub tls: bool,
|
||||||
pub sni: String,
|
pub sni: String,
|
||||||
|
/// A `unix:` upstream's socket path (plain HTTP); `host` and `port` are then unused.
|
||||||
|
pub unix: Option<String>,
|
||||||
pub healthy: AtomicBool,
|
pub healthy: AtomicBool,
|
||||||
pub health: HealthRecord,
|
pub health: HealthRecord,
|
||||||
}
|
}
|
||||||
@@ -205,6 +207,21 @@ fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
|
|||||||
address: u.address.clone(),
|
address: u.address.clone(),
|
||||||
reason: reason.to_owned(),
|
reason: reason.to_owned(),
|
||||||
};
|
};
|
||||||
|
if let Some(path) = u.address.strip_prefix("unix:") {
|
||||||
|
if !path.starts_with('/') || u.tls {
|
||||||
|
return Err(err("expected unix:/absolute/path, plain HTTP"));
|
||||||
|
}
|
||||||
|
return Ok(UpstreamRt {
|
||||||
|
host: String::new(),
|
||||||
|
port: 0,
|
||||||
|
authority: u.address.clone(),
|
||||||
|
tls: false,
|
||||||
|
sni: String::new(),
|
||||||
|
unix: Some(path.to_owned()),
|
||||||
|
healthy: AtomicBool::new(true),
|
||||||
|
health: HealthRecord::default(),
|
||||||
|
});
|
||||||
|
}
|
||||||
let (host, port) = u
|
let (host, port) = u
|
||||||
.address
|
.address
|
||||||
.rsplit_once(':')
|
.rsplit_once(':')
|
||||||
@@ -223,6 +240,7 @@ fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
|
|||||||
authority: u.address.clone(),
|
authority: u.address.clone(),
|
||||||
tls: u.tls,
|
tls: u.tls,
|
||||||
sni: u.sni.clone(),
|
sni: u.sni.clone(),
|
||||||
|
unix: None,
|
||||||
healthy: AtomicBool::new(true),
|
healthy: AtomicBool::new(true),
|
||||||
health: HealthRecord::default(),
|
health: HealthRecord::default(),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -240,4 +240,93 @@ mod unix {
|
|||||||
assert_eq!(r.status, 403, "{}", edge.stderr());
|
assert_eq!(r.status, 403, "{}", edge.stderr());
|
||||||
assert!(echo.proxied().is_empty());
|
assert!(echo.proxied().is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A `unix:` upstream (G14 option b: the admin host reaches control on its socket):
|
||||||
|
/// requests and health checks go over the socket, in plain HTTP.
|
||||||
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
|
async fn a_unix_socket_upstream_is_proxied_and_health_checked() {
|
||||||
|
use http_body_util::Full;
|
||||||
|
use hyper::server::conn::http1;
|
||||||
|
use hyper::service::service_fn;
|
||||||
|
use hyper_util::rt::TokioIo;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
let dir = ianitor_testkit::proc::TempDir::new("unix-upstream");
|
||||||
|
let sock = dir.join("app.sock");
|
||||||
|
let listener = tokio::net::UnixListener::bind(&sock).unwrap();
|
||||||
|
let seen: Arc<Mutex<Vec<(String, String)>>> = Arc::default();
|
||||||
|
let s = seen.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
let Ok((stream, _)) = listener.accept().await else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let s = s.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let svc = service_fn(move |req: hyper::Request<hyper::body::Incoming>| {
|
||||||
|
let host = req
|
||||||
|
.headers()
|
||||||
|
.get("host")
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned();
|
||||||
|
s.lock().unwrap().push((req.uri().path().to_owned(), host));
|
||||||
|
async move {
|
||||||
|
Ok::<_, std::convert::Infallible>(hyper::Response::new(Full::new(
|
||||||
|
bytes::Bytes::from_static(b"via the socket"),
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let _ = http1::Builder::new()
|
||||||
|
.serve_connection(TokioIo::new(stream), svc)
|
||||||
|
.await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let edge = start(EdgeSpec {
|
||||||
|
hosts: vec![host_file(
|
||||||
|
"ui.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"unix:{}\"]
|
||||||
|
[health_check]
|
||||||
|
path = \"/healthz\"
|
||||||
|
interval_secs = 1
|
||||||
|
",
|
||||||
|
sock.display()
|
||||||
|
),
|
||||||
|
)],
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"ui.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("ui.test", "/x"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(r.status, r.text().as_str()),
|
||||||
|
(200, "via the socket"),
|
||||||
|
"{}",
|
||||||
|
edge.stderr()
|
||||||
|
);
|
||||||
|
for _ in 0..50 {
|
||||||
|
if seen.lock().unwrap().iter().any(|(p, _)| p == "/healthz") {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||||
|
}
|
||||||
|
let seen = seen.lock().unwrap().clone();
|
||||||
|
assert!(
|
||||||
|
seen.contains(&("/x".to_owned(), "ui.test".to_owned())),
|
||||||
|
"{seen:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
seen.iter()
|
||||||
|
.any(|(p, h)| p == "/healthz" && h == "localhost"),
|
||||||
|
"{seen:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user