[edge] Fixes: skip 1xx, enforce auth timeout, resolve upstreams per connect, all Upgrade tokens, strip Remote-*
This commit is contained in:
+88
-23
@@ -30,18 +30,27 @@ pub struct EdgeProxy {
|
||||
|
||||
pub struct Ctx {
|
||||
host: Option<Arc<HostRt>>,
|
||||
/// Chosen upstream and its resolved addresses; connect failures move to the next address.
|
||||
upstream: Option<usize>,
|
||||
addrs: Vec<std::net::SocketAddr>,
|
||||
addr_idx: usize,
|
||||
/// 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).
|
||||
/// The request's host: the authority of an absolute-form target (or HTTP/2 :authority) wins
|
||||
/// over the Host header, as RFC 9112 §3.2.2 requires and Go/Caddy do.
|
||||
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()))
|
||||
req.uri
|
||||
.authority()
|
||||
.map(|a| a.as_str().to_owned())
|
||||
.or_else(|| {
|
||||
req.headers
|
||||
.get(header::HOST)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_owned)
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -89,11 +98,13 @@ fn apply(
|
||||
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"))
|
||||
/// Any `Upgrade` field, any comma-separated token, equal to `websocket` (case-insensitive).
|
||||
pub fn is_websocket_upgrade(req: &RequestHeader) -> bool {
|
||||
req.headers.get_all(header::UPGRADE).iter().any(|v| {
|
||||
String::from_utf8_lossy(v.as_bytes())
|
||||
.split(',')
|
||||
.any(|t| t.trim().eq_ignore_ascii_case("websocket"))
|
||||
})
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
@@ -103,6 +114,9 @@ impl ProxyHttp for EdgeProxy {
|
||||
fn new_ctx(&self) -> Ctx {
|
||||
Ctx {
|
||||
host: None,
|
||||
upstream: None,
|
||||
addrs: Vec::new(),
|
||||
addr_idx: 0,
|
||||
host_header: String::new(),
|
||||
start: Instant::now(),
|
||||
}
|
||||
@@ -120,6 +134,11 @@ impl ProxyHttp for EdgeProxy {
|
||||
let fa = self.rt.forward_auth.as_ref().ok_or_else(|| {
|
||||
Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured")
|
||||
})?;
|
||||
// Client-sent identity headers never survive, whatever copy_headers says.
|
||||
let req = session.req_header_mut();
|
||||
for name in &fa.strip_headers {
|
||||
req.remove_header(name);
|
||||
}
|
||||
let ip = client_ip(session).map(|i| i.to_string());
|
||||
let outcome = match forward_auth::check(
|
||||
&self.connector,
|
||||
@@ -171,27 +190,60 @@ impl ProxyHttp for EdgeProxy {
|
||||
async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result<Box<HttpPeer>> {
|
||||
let host = ctx
|
||||
.host
|
||||
.as_ref()
|
||||
.clone()
|
||||
.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)))
|
||||
let idx = match ctx.upstream {
|
||||
// A retry after a failed connect: same upstream, next address.
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let n = host.upstreams.len();
|
||||
let first = host.next.fetch_add(1, Ordering::Relaxed);
|
||||
let i = (0..n)
|
||||
.map(|k| (first + k) % n)
|
||||
.find(|&k| host.upstreams[k].healthy.load(Ordering::Relaxed))
|
||||
.ok_or_else(|| {
|
||||
Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream")
|
||||
})?;
|
||||
let up = &host.upstreams[i];
|
||||
ctx.addrs = match up.resolve().await {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
log::warn!(target: "ianitor::proxy", "{}: cannot resolve upstream {}: {e}", host.cfg.hostname, up.authority);
|
||||
return Err(Error::explain(
|
||||
ErrorType::HTTPStatus(502),
|
||||
"upstream does not resolve",
|
||||
));
|
||||
}
|
||||
};
|
||||
ctx.upstream = Some(i);
|
||||
ctx.addr_idx = 0;
|
||||
i
|
||||
}
|
||||
};
|
||||
let up = &host.upstreams[idx];
|
||||
let addr = *ctx
|
||||
.addrs
|
||||
.get(ctx.addr_idx)
|
||||
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(502), "no address left"))?;
|
||||
log::debug!(target: "ianitor::proxy", "{}: upstream {} at {addr}", host.cfg.hostname, up.authority);
|
||||
Ok(Box::new(fetch::peer(addr, up)))
|
||||
}
|
||||
|
||||
fn fail_to_connect(
|
||||
&self,
|
||||
_s: &mut Session,
|
||||
_p: &HttpPeer,
|
||||
_c: &mut Ctx,
|
||||
ctx: &mut Ctx,
|
||||
mut e: Box<Error>,
|
||||
) -> Box<Error> {
|
||||
// Like Caddy's default (no lb_try_duration): one attempt, then 502.
|
||||
e.set_retry(false);
|
||||
// Like Caddy's dialer: try every address of the chosen upstream, then 502. Other
|
||||
// upstreams are not tried (Caddy's default has no lb_try_duration).
|
||||
if ctx.addr_idx + 1 < ctx.addrs.len() {
|
||||
ctx.addr_idx += 1;
|
||||
e.set_retry(true);
|
||||
} else {
|
||||
e.set_retry(false);
|
||||
}
|
||||
e
|
||||
}
|
||||
|
||||
@@ -201,6 +253,19 @@ impl ProxyHttp for EdgeProxy {
|
||||
req: &mut RequestHeader,
|
||||
ctx: &mut Ctx,
|
||||
) -> Result<()> {
|
||||
// Origin-form target and the routed host, also for absolute-form requests.
|
||||
if req.uri.authority().is_some() {
|
||||
let pq = req
|
||||
.uri
|
||||
.path_and_query()
|
||||
.map_or("/", |p| p.as_str())
|
||||
.to_owned();
|
||||
let uri = pq
|
||||
.parse::<http::Uri>()
|
||||
.map_err(|_| Error::explain(ErrorType::HTTPStatus(400), "bad request target"))?;
|
||||
req.set_uri(uri);
|
||||
}
|
||||
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) {
|
||||
Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?,
|
||||
|
||||
Reference in New Issue
Block a user