[edge] Proxy: Pingora data plane with SNI certs, forward-auth, header rules, health checks, ACME

This commit is contained in:
2026-11-07 14:57:36 +01:00
parent 4fe041082d
commit 17e1df8320
24 changed files with 2316 additions and 123 deletions
+36 -10
View File
@@ -41,18 +41,25 @@ pub struct MockAuthelia {
impl MockAuthelia {
pub async fn start() -> MockAuthelia {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let m = MockAuthelia { addr: listener.local_addr().unwrap(), requests: Arc::default() };
let m = MockAuthelia {
addr: listener.local_addr().unwrap(),
requests: Arc::default(),
};
let mm = m.clone();
tokio::spawn(async move {
loop {
let Ok((stream, _)) = listener.accept().await else { continue };
let Ok((stream, _)) = listener.accept().await else {
continue;
};
let mm = mm.clone();
tokio::spawn(async move {
let svc = service_fn(move |req| {
let mm = mm.clone();
async move { Ok::<_, Infallible>(mm.handle(req).await) }
});
let _ = http1::Builder::new().serve_connection(TokioIo::new(stream), svc).await;
let _ = http1::Builder::new()
.serve_connection(TokioIo::new(stream), svc)
.await;
});
}
});
@@ -70,14 +77,28 @@ impl MockAuthelia {
async fn handle(&self, req: Request<Incoming>) -> Response<Full<Bytes>> {
let (parts, body) = req.into_parts();
let body = body.collect().await.map(|b| b.to_bytes()).unwrap_or_default();
let body = body
.collect()
.await
.map(|b| b.to_bytes())
.unwrap_or_default();
self.requests.lock().unwrap().push(Recorded {
method: parts.method.to_string(),
path: parts.uri.path().to_owned(),
headers: parts.headers.iter().map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec())).collect(),
headers: parts
.headers
.iter()
.map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec()))
.collect(),
body: body.to_vec(),
});
let h = |name: &str| parts.headers.get(name).and_then(|v| v.to_str().ok()).map(str::to_owned);
let h = |name: &str| {
parts
.headers
.get(name)
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
};
let text = |status: u16, body: &str| {
Response::builder()
.status(status)
@@ -89,9 +110,12 @@ impl MockAuthelia {
if parts.method != hyper::Method::GET || parts.uri.path() != PATH {
return text(404, "404 page not found");
}
let (Some(method), Some(proto), Some(host), Some(uri)) =
(h("x-forwarded-method"), h("x-forwarded-proto"), h("x-forwarded-host"), h("x-forwarded-uri"))
else {
let (Some(method), Some(proto), Some(host), Some(uri)) = (
h("x-forwarded-method"),
h("x-forwarded-proto"),
h("x-forwarded-host"),
h("x-forwarded-uri"),
) else {
return text(400, "missing X-Forwarded headers");
};
@@ -136,7 +160,9 @@ impl MockAuthelia {
.header("location", location.clone())
.header("set-cookie", "authelia_flow=1; Path=/; HttpOnly")
.header("content-type", "text/html; charset=utf-8")
.body(Full::new(Bytes::from(format!("<a href=\"{location}\">302 Found</a>"))))
.body(Full::new(Bytes::from(format!(
"<a href=\"{location}\">302 Found</a>"
))))
.unwrap()
}
_ => text(401, "401 Unauthorized"),
+72 -16
View File
@@ -37,7 +37,12 @@ impl Req {
}
pub fn new(method: &str, host: &str, path: &str) -> Req {
Req { method: method.into(), path: path.into(), headers: vec![("host".into(), host.into())], body: Vec::new() }
Req {
method: method.into(),
path: path.into(),
headers: vec![("host".into(), host.into())],
body: Vec::new(),
}
}
pub fn header(mut self, name: &str, value: &str) -> Req {
@@ -61,11 +66,18 @@ pub struct Resp {
impl Resp {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
self.headers
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
pub fn header_all(&self, name: &str) -> Vec<&str> {
self.headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()).collect()
self.headers
.iter()
.filter(|(n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
.collect()
}
pub fn text(&self) -> String {
@@ -81,7 +93,9 @@ fn other(e: impl std::fmt::Display) -> io::Error {
pub fn tls_connector(roots: Arc<RootCertStore>) -> TlsConnector {
crate::tls::install_crypto();
let mut cfg = rustls::ClientConfig::builder().with_root_certificates(roots).with_no_client_auth();
let mut cfg = rustls::ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
TlsConnector::from(Arc::new(cfg))
}
@@ -96,29 +110,58 @@ async fn tls_stream(
tls_connector(roots).connect(name, tcp).await
}
async fn send<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(io: S, req: &Req) -> io::Result<Resp> {
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(io)).await.map_err(other)?;
async fn send<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
io: S,
req: &Req,
) -> io::Result<Resp> {
let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(io))
.await
.map_err(other)?;
tokio::spawn(async move {
let _ = conn.await;
});
let mut b = hyper::Request::builder().method(req.method.as_str()).uri(req.path.as_str());
let mut b = hyper::Request::builder()
.method(req.method.as_str())
.uri(req.path.as_str());
for (n, v) in &req.headers {
b = b.header(n.as_str(), v.as_str());
}
let request = b.body(Full::new(Bytes::from(req.body.clone()))).map_err(other)?;
let request = b
.body(Full::new(Bytes::from(req.body.clone())))
.map_err(other)?;
let resp = sender.send_request(request).await.map_err(other)?;
let status = resp.status().as_u16();
let headers = resp
.headers()
.iter()
.map(|(n, v)| (n.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned()))
.map(|(n, v)| {
(
n.as_str().to_owned(),
String::from_utf8_lossy(v.as_bytes()).into_owned(),
)
})
.collect();
let body = resp.into_body().collect().await.map_err(other)?.to_bytes().to_vec();
Ok(Resp { status, headers, body })
let body = resp
.into_body()
.collect()
.await
.map_err(other)?
.to_bytes()
.to_vec();
Ok(Resp {
status,
headers,
body,
})
}
/// One request over a fresh TLS connection to `addr` with the given SNI.
pub async fn https(addr: SocketAddr, sni: &str, roots: Arc<RootCertStore>, req: &Req) -> io::Result<Resp> {
pub async fn https(
addr: SocketAddr,
sni: &str,
roots: Arc<RootCertStore>,
req: &Req,
) -> io::Result<Resp> {
tokio::time::timeout(TIMEOUT, async {
let s = tls_stream(addr, sni, roots).await?;
send(s, req).await
@@ -157,7 +200,9 @@ pub async fn websocket(
) -> io::Result<WsOutcome> {
tokio::time::timeout(TIMEOUT, async {
let s = tls_stream(addr, sni, roots).await?;
let mut request = format!("wss://{host}{path}").into_client_request().map_err(other)?;
let mut request = format!("wss://{host}{path}")
.into_client_request()
.map_err(other)?;
for (n, v) in extra {
request.headers_mut().insert(
http::HeaderName::from_bytes(n.as_bytes()).map_err(other)?,
@@ -167,7 +212,9 @@ pub async fn websocket(
match tokio_tungstenite::client_async(request, s).await {
Ok((mut ws, resp)) => {
let status = resp.status().as_u16();
ws.send(tungstenite::Message::text(message)).await.map_err(other)?;
ws.send(tungstenite::Message::text(message))
.await
.map_err(other)?;
let echo = match ws.next().await {
Some(Ok(m)) => m.into_text().map_err(other)?.to_string(),
other_msg => return Err(other(format!("no echo: {other_msg:?}"))),
@@ -180,10 +227,19 @@ pub async fn websocket(
let headers = resp
.headers()
.iter()
.map(|(n, v)| (n.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned()))
.map(|(n, v)| {
(
n.as_str().to_owned(),
String::from_utf8_lossy(v.as_bytes()).into_owned(),
)
})
.collect();
let body = resp.body().clone().unwrap_or_default();
Ok(WsOutcome::Refused(Resp { status, headers, body }))
Ok(WsOutcome::Refused(Resp {
status,
headers,
body,
}))
}
Err(e) => Err(other(e)),
}
+19 -8
View File
@@ -12,7 +12,11 @@ use std::time::{Duration, Instant};
/// A port on 127.0.0.1 that was free a moment ago.
pub fn free_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port()
}
pub fn local(port: u16) -> SocketAddr {
@@ -70,12 +74,17 @@ impl Drop for TempDir {
/// Locate an external tool: `$IANITOR_<NAME>_BIN`, then `$PATH`.
pub fn find_binary(name: &str) -> Option<PathBuf> {
let var = format!("IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_"));
let var = format!(
"IANITOR_{}_BIN",
name.to_ascii_uppercase().replace('-', "_")
);
if let Some(p) = std::env::var_os(&var) {
return Some(PathBuf::from(p));
}
let path = std::env::var_os("PATH")?;
std::env::split_paths(&path).map(|d| d.join(name)).find(|p| p.is_file())
std::env::split_paths(&path)
.map(|d| d.join(name))
.find(|p| p.is_file())
}
/// Like [`find_binary`], but a missing tool fails the test, unless `IANITOR_ALLOW_SKIP=1`,
@@ -87,11 +96,13 @@ pub fn require_binary(name: &str) -> Option<PathBuf> {
eprintln!("SKIPPED: `{name}` not found (IANITOR_ALLOW_SKIP=1)");
None
}
None => panic!(
"`{name}` is needed for this test but was not found on PATH (or ${}). \
In WSL: nix profile add nixpkgs#{name}. Set IANITOR_ALLOW_SKIP=1 to skip instead.",
format!("IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_"))
),
None => {
let var = format!("IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_"));
panic!(
"`{name}` is needed for this test but was not found on PATH (or ${var}). \
In WSL: nix profile add nixpkgs#{name}. Set IANITOR_ALLOW_SKIP=1 to skip instead."
)
}
}
}
+16 -4
View File
@@ -32,15 +32,24 @@ impl TestCa {
dn.push(DnType::CommonName, common_name);
params.distinguished_name = dn;
params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign, KeyUsagePurpose::DigitalSignature];
params.key_usages = vec![
KeyUsagePurpose::KeyCertSign,
KeyUsagePurpose::CrlSign,
KeyUsagePurpose::DigitalSignature,
];
let cert = params.self_signed(&key).unwrap();
TestCa { cert_pem: cert.pem(), issuer: Issuer::new(params, key) }
TestCa {
cert_pem: cert.pem(),
issuer: Issuer::new(params, key),
}
}
/// A server certificate for the given DNS names (or IP literals).
pub fn issue(&self, names: &[&str]) -> Leaf {
let key = KeyPair::generate().unwrap();
let mut params = CertificateParams::new(names.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>()).unwrap();
let mut params =
CertificateParams::new(names.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>())
.unwrap();
let mut dn = DistinguishedName::new();
dn.push(DnType::CommonName, names.first().copied().unwrap_or("test"));
params.distinguished_name = dn;
@@ -48,7 +57,10 @@ impl TestCa {
params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
params.key_usages = vec![KeyUsagePurpose::DigitalSignature];
let cert = params.signed_by(&key, &self.issuer).unwrap();
Leaf { cert_pem: cert.pem(), key_pem: key.serialize_pem() }
Leaf {
cert_pem: cert.pem(),
key_pem: key.serialize_pem(),
}
}
pub fn roots(&self) -> Arc<RootCertStore> {
+63 -16
View File
@@ -49,7 +49,10 @@ pub struct Recorded {
impl Recorded {
pub fn header(&self, name: &str) -> Option<&[u8]> {
self.headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_slice())
self.headers
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_slice())
}
}
@@ -80,14 +83,18 @@ impl Echo {
let e = echo.clone();
tokio::spawn(async move {
loop {
let Ok((stream, _)) = listener.accept().await else { continue };
let Ok((stream, _)) = listener.accept().await else {
continue;
};
let e = e.clone();
tokio::spawn(async move {
let svc = service_fn(move |req| {
let e = e.clone();
async move { Ok::<_, Infallible>(e.handle(req).await) }
});
let _ = http1::Builder::new().serve_connection(TokioIo::new(stream), svc).await;
let _ = http1::Builder::new()
.serve_connection(TokioIo::new(stream), svc)
.await;
});
}
});
@@ -104,7 +111,10 @@ impl Echo {
/// Requests other than health checks.
pub fn proxied(&self) -> Vec<Recorded> {
self.requests().into_iter().filter(|r| r.path != "/healthz").collect()
self.requests()
.into_iter()
.filter(|r| r.path != "/healthz")
.collect()
}
pub fn clear(&self) {
@@ -113,13 +123,21 @@ impl Echo {
async fn handle(&self, req: Request<Incoming>) -> Response<Body> {
let (parts, body) = req.into_parts();
let body = body.collect().await.map(|b| b.to_bytes()).unwrap_or_default();
let body = body
.collect()
.await
.map(|b| b.to_bytes())
.unwrap_or_default();
let path = parts.uri.path().to_owned();
let query = parts.uri.query().unwrap_or("").to_owned();
self.requests.lock().unwrap().push(Recorded {
method: parts.method.to_string(),
path: path.clone(),
headers: parts.headers.iter().map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec())).collect(),
headers: parts
.headers
.iter()
.map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec()))
.collect(),
body: body.to_vec(),
});
let base = |status: u16| {
@@ -133,19 +151,35 @@ impl Echo {
let s = self.health.load(Ordering::SeqCst);
return base(s).body(full(format!("health {s}"))).unwrap();
}
if let Some(code) = path.strip_prefix("/status/").and_then(|c| c.parse::<u16>().ok()) {
return base(code).header("content-type", "text/plain").body(full(format!("status {code}"))).unwrap();
if let Some(code) = path
.strip_prefix("/status/")
.and_then(|c| c.parse::<u16>().ok())
{
return base(code)
.header("content-type", "text/plain")
.body(full(format!("status {code}")))
.unwrap();
}
if path == "/big" {
let n: usize = query.strip_prefix("n=").and_then(|n| n.parse().ok()).unwrap_or(1024).min(10 << 20);
return base(200).header("content-type", "application/octet-stream").body(full(vec![b'x'; n])).unwrap();
let n: usize = query
.strip_prefix("n=")
.and_then(|n| n.parse().ok())
.unwrap_or(1024)
.min(10 << 20);
return base(200)
.header("content-type", "application/octet-stream")
.body(full(vec![b'x'; n]))
.unwrap();
}
if path == "/chunked" {
let chunks = ["first,", "second,", "third"]
.into_iter()
.map(|c| Ok::<_, Infallible>(Frame::data(Bytes::from_static(c.as_bytes()))));
let stream = futures_util::stream::iter(chunks);
return base(200).header("content-type", "text/plain").body(BodyExt::boxed(StreamBody::new(stream))).unwrap();
return base(200)
.header("content-type", "text/plain")
.body(BodyExt::boxed(StreamBody::new(stream)))
.unwrap();
}
if path == "/set-cookie" {
return base(200)
@@ -167,7 +201,10 @@ impl Echo {
let mut headers = serde_json::Map::new();
for h in ECHO_HEADERS {
if let Some(v) = parts.headers.get(h) {
headers.insert(h.to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned().into());
headers.insert(
h.to_owned(),
String::from_utf8_lossy(v.as_bytes()).into_owned().into(),
);
}
}
for h in HASHED_HEADERS {
@@ -184,7 +221,10 @@ impl Echo {
"body_fnv": fnv64(&body),
"headers": headers,
});
base(200).header("content-type", "application/json").body(full(json.to_string())).unwrap()
base(200)
.header("content-type", "application/json")
.body(full(json.to_string()))
.unwrap()
}
}
@@ -198,14 +238,21 @@ pub struct WsEcho {
impl WsEcho {
pub async fn start() -> WsEcho {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let ws = WsEcho { addr: listener.local_addr().unwrap(), connections: Arc::default() };
let ws = WsEcho {
addr: listener.local_addr().unwrap(),
connections: Arc::default(),
};
let conns = ws.connections.clone();
tokio::spawn(async move {
loop {
let Ok((stream, _)) = listener.accept().await else { continue };
let Ok((stream, _)) = listener.accept().await else {
continue;
};
let conns = conns.clone();
tokio::spawn(async move {
let Ok(mut ws) = tokio_tungstenite::accept_async(stream).await else { return };
let Ok(mut ws) = tokio_tungstenite::accept_async(stream).await else {
return;
};
conns.fetch_add(1, Ordering::SeqCst);
while let Some(Ok(msg)) = ws.next().await {
if msg.is_text() || msg.is_binary() {