[edge] Proxy: Pingora data plane with SNI certs, forward-auth, header rules, health checks, ACME
This commit is contained in:
@@ -0,0 +1,332 @@
|
||||
// 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/.
|
||||
|
||||
//! The HTTPS reverse proxy. Order per request (same as the Caddy compiler emits):
|
||||
//! host lookup (unknown → 404) → forward-auth → websocket refusal → upstream with header rules.
|
||||
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Instant;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use http::header;
|
||||
use pingora::connectors::http::Connector;
|
||||
use pingora::http::{RequestHeader, ResponseHeader};
|
||||
use pingora::proxy::{FailToProxy, ProxyHttp, Session};
|
||||
use pingora::upstreams::peer::HttpPeer;
|
||||
use pingora::{Error, ErrorSource, ErrorType, Result};
|
||||
|
||||
use crate::fetch;
|
||||
use crate::forward_auth::{self, Outcome};
|
||||
use crate::logging::{AccessRecord, now_secs, truncate_ip};
|
||||
use crate::runtime::{HostRt, Op, Runtime};
|
||||
|
||||
pub struct EdgeProxy {
|
||||
pub rt: Arc<Runtime>,
|
||||
pub connector: Connector,
|
||||
}
|
||||
|
||||
pub struct Ctx {
|
||||
host: Option<Arc<HostRt>>,
|
||||
/// The Host header as the client sent it (with port, if any).
|
||||
host_header: String,
|
||||
start: Instant,
|
||||
}
|
||||
|
||||
/// Host header (HTTP/1) or :authority (HTTP/2).
|
||||
pub fn host_header(req: &RequestHeader) -> String {
|
||||
req.headers
|
||||
.get(header::HOST)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| req.uri.authority().map(|a| a.as_str().to_owned()))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Host without port, lowercase. `[v6]:port` keeps the brackets off.
|
||||
pub fn hostname(host_header: &str) -> String {
|
||||
let h = host_header.trim();
|
||||
let name = if let Some(rest) = h.strip_prefix('[') {
|
||||
rest.split(']').next().unwrap_or("")
|
||||
} else {
|
||||
h.rsplit_once(':').map_or(h, |(n, port)| {
|
||||
if port.bytes().all(|c| c.is_ascii_digit()) {
|
||||
n
|
||||
} else {
|
||||
h
|
||||
}
|
||||
})
|
||||
};
|
||||
name.to_ascii_lowercase()
|
||||
}
|
||||
|
||||
pub fn client_ip(session: &Session) -> Option<IpAddr> {
|
||||
session
|
||||
.client_addr()
|
||||
.and_then(|a| a.as_inet())
|
||||
.map(|a| a.ip())
|
||||
}
|
||||
|
||||
/// A response with an empty body, like Caddy's `static_response` and error responses.
|
||||
pub async fn respond_empty(session: &mut Session, code: u16) -> Result<()> {
|
||||
let mut resp = ResponseHeader::build(code, Some(1))?;
|
||||
resp.insert_header(header::CONTENT_LENGTH, "0")?;
|
||||
session.write_response_header(Box::new(resp), true).await
|
||||
}
|
||||
|
||||
fn apply(
|
||||
ops: &[Op],
|
||||
mut set: impl FnMut(&http::HeaderName, Option<&http::HeaderValue>) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
for op in ops {
|
||||
match op {
|
||||
Op::Set(n, v) => set(n, Some(v))?,
|
||||
Op::Remove(n) => set(n, None)?,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_websocket_upgrade(req: &RequestHeader) -> bool {
|
||||
req.headers
|
||||
.get(header::UPGRADE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.is_some_and(|v| v.trim().eq_ignore_ascii_case("websocket"))
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ProxyHttp for EdgeProxy {
|
||||
type CTX = Ctx;
|
||||
|
||||
fn new_ctx(&self) -> Ctx {
|
||||
Ctx {
|
||||
host: None,
|
||||
host_header: String::new(),
|
||||
start: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn request_filter(&self, session: &mut Session, ctx: &mut Ctx) -> Result<bool> {
|
||||
ctx.host_header = host_header(session.req_header());
|
||||
let Some(host) = self.rt.host(&hostname(&ctx.host_header)).cloned() else {
|
||||
respond_empty(session, 404).await?;
|
||||
return Ok(true);
|
||||
};
|
||||
ctx.host = Some(host.clone());
|
||||
|
||||
if host.cfg.forward_auth {
|
||||
let fa = self.rt.forward_auth.as_ref().ok_or_else(|| {
|
||||
Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured")
|
||||
})?;
|
||||
let ip = client_ip(session).map(|i| i.to_string());
|
||||
let outcome = match forward_auth::check(
|
||||
&self.connector,
|
||||
fa,
|
||||
session,
|
||||
&ctx.host_header,
|
||||
ip,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
log::error!(target: "ianitor::auth", "forward-auth for {} failed, denying: {e}", host.cfg.hostname);
|
||||
return Err(Error::explain(
|
||||
ErrorType::HTTPStatus(502),
|
||||
"forward-auth unreachable",
|
||||
));
|
||||
}
|
||||
};
|
||||
match outcome {
|
||||
Outcome::Deny(resp, body) => {
|
||||
let head = session.req_header().method == http::Method::HEAD;
|
||||
let end = head || body.is_empty();
|
||||
session.write_response_header(resp, end).await?;
|
||||
if !end {
|
||||
session.write_response_body(Some(body), true).await?;
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
Outcome::Allow(copy) => {
|
||||
let req = session.req_header_mut();
|
||||
for (name, value) in copy {
|
||||
req.remove_header(&name);
|
||||
if let Some(v) = value {
|
||||
req.insert_header(name, v)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !host.cfg.websockets && is_websocket_upgrade(session.req_header()) {
|
||||
respond_empty(session, 403).await?;
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result<Box<HttpPeer>> {
|
||||
let host = ctx
|
||||
.host
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(500), "no host"))?;
|
||||
let n = host.upstreams.len();
|
||||
let first = host.next.fetch_add(1, Ordering::Relaxed);
|
||||
let chosen = (0..n)
|
||||
.map(|i| &host.upstreams[(first + i) % n])
|
||||
.find(|u| u.healthy.load(Ordering::Relaxed))
|
||||
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream"))?;
|
||||
log::debug!(target: "ianitor::proxy", "{}: upstream {}", host.cfg.hostname, chosen.authority);
|
||||
Ok(Box::new(fetch::peer(chosen)))
|
||||
}
|
||||
|
||||
fn fail_to_connect(
|
||||
&self,
|
||||
_s: &mut Session,
|
||||
_p: &HttpPeer,
|
||||
_c: &mut Ctx,
|
||||
mut e: Box<Error>,
|
||||
) -> Box<Error> {
|
||||
// Like Caddy's default (no lb_try_duration): one attempt, then 502.
|
||||
e.set_retry(false);
|
||||
e
|
||||
}
|
||||
|
||||
async fn upstream_request_filter(
|
||||
&self,
|
||||
session: &mut Session,
|
||||
req: &mut RequestHeader,
|
||||
ctx: &mut Ctx,
|
||||
) -> Result<()> {
|
||||
// Forwarding headers are always edge's own; client-supplied values are replaced.
|
||||
match client_ip(session) {
|
||||
Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?,
|
||||
None => {
|
||||
req.remove_header("X-Forwarded-For");
|
||||
}
|
||||
}
|
||||
req.insert_header("X-Forwarded-Proto", "https")?;
|
||||
req.insert_header("X-Forwarded-Host", ctx.host_header.as_str())?;
|
||||
if let Some(host) = &ctx.host {
|
||||
apply(&host.request_ops, |n, v| {
|
||||
match v {
|
||||
Some(v) => req.insert_header(n.clone(), v.clone())?,
|
||||
None => {
|
||||
req.remove_header(n);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn upstream_response_filter(
|
||||
&self,
|
||||
_s: &mut Session,
|
||||
resp: &mut ResponseHeader,
|
||||
ctx: &mut Ctx,
|
||||
) -> Result<()> {
|
||||
let Some(host) = &ctx.host else { return Ok(()) };
|
||||
apply(&host.response_ops, |n, v| {
|
||||
match v {
|
||||
Some(v) => resp.insert_header(n.clone(), v.clone())?,
|
||||
None => {
|
||||
resp.remove_header(n);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
// Defence in depth: never hand a secret back to a client, even if the upstream echoes it.
|
||||
if !host.secret_values.is_empty() {
|
||||
let leaking: Vec<http::HeaderName> = resp
|
||||
.headers
|
||||
.iter()
|
||||
.filter(|(_, v)| host.secret_values.iter().any(|s| contains(v.as_bytes(), s)))
|
||||
.map(|(n, _)| n.clone())
|
||||
.collect();
|
||||
for n in leaking {
|
||||
log::warn!(target: "ianitor::secrets", "{}: dropped response header `{n}` because it contained a secret", host.cfg.hostname);
|
||||
resp.remove_header(&n);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn fail_to_proxy(&self, session: &mut Session, e: &Error, _ctx: &mut Ctx) -> FailToProxy {
|
||||
let code = match e.etype() {
|
||||
ErrorType::HTTPStatus(c) => *c,
|
||||
_ => match e.esource() {
|
||||
ErrorSource::Upstream => 502,
|
||||
ErrorSource::Downstream => match e.etype() {
|
||||
ErrorType::WriteError | ErrorType::ReadError | ErrorType::ConnectionClosed => 0,
|
||||
_ => 400,
|
||||
},
|
||||
ErrorSource::Internal | ErrorSource::Unset => 500,
|
||||
},
|
||||
};
|
||||
if code > 0
|
||||
&& session.response_written().is_none()
|
||||
&& let Err(err) = respond_empty(session, code).await
|
||||
{
|
||||
log::debug!(target: "ianitor::proxy", "could not send the error response: {err}");
|
||||
}
|
||||
FailToProxy {
|
||||
error_code: code,
|
||||
can_reuse_downstream: false,
|
||||
}
|
||||
}
|
||||
|
||||
async fn logging(&self, session: &mut Session, _e: Option<&Error>, ctx: &mut Ctx) {
|
||||
let Some(host) = &ctx.host else { return };
|
||||
if !host.cfg.access_log {
|
||||
return;
|
||||
}
|
||||
let Some(log) = &self.rt.access_log else {
|
||||
return;
|
||||
};
|
||||
let req = session.req_header();
|
||||
log.write(&AccessRecord {
|
||||
ts: now_secs(),
|
||||
host: &host.cfg.hostname,
|
||||
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()),
|
||||
duration_ms: u64::try_from(ctx.start.elapsed().as_millis()).unwrap_or(u64::MAX),
|
||||
});
|
||||
}
|
||||
|
||||
fn request_summary(&self, session: &Session, ctx: &Ctx) -> String {
|
||||
// Method, host and path only: no query string, no headers.
|
||||
let req = session.req_header();
|
||||
format!("{} {}{}", req.method, ctx.host_header, req.uri.path())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contains(hay: &[u8], needle: &[u8]) -> bool {
|
||||
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hostname_strips_port_and_case() {
|
||||
assert_eq!(hostname("App.Test:8443"), "app.test");
|
||||
assert_eq!(hostname("app.test"), "app.test");
|
||||
assert_eq!(hostname("[::1]:443"), "::1");
|
||||
assert_eq!(hostname(""), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contains_finds_substrings() {
|
||||
assert!(contains(b"abc-secret-def", b"secret"));
|
||||
assert!(!contains(b"abc", b""));
|
||||
assert!(!contains(b"sec", b"secret"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user