[core] Phase 1: core, edge and differential tests #2
+81
-13
@@ -3,7 +3,14 @@
|
|||||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
//! Small HTTP client on Pingora's connector, for forward-auth subrequests and health checks.
|
//! Small HTTP client on Pingora's connector, for forward-auth subrequests and health checks.
|
||||||
|
//!
|
||||||
|
//! - The whole exchange is bounded by one deadline (Pingora's connector ignores the peer's
|
||||||
|
//! read timeout, so the deadline is enforced here with `tokio::time::timeout`).
|
||||||
|
//! - Informational answers (100, 102, 103) are skipped; `101` is returned as the final head
|
||||||
|
//! without a body, for the caller to reject.
|
||||||
|
//! - Every resolved address is tried in order until one accepts the connection.
|
||||||
|
|
||||||
|
use std::net::SocketAddr;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use bytes::{Bytes, BytesMut};
|
use bytes::{Bytes, BytesMut};
|
||||||
@@ -21,14 +28,17 @@ pub struct Fetched {
|
|||||||
|
|
||||||
/// Dial timeout, matching Caddy's reverse_proxy default.
|
/// Dial timeout, matching Caddy's reverse_proxy default.
|
||||||
pub const DIAL_TIMEOUT: Duration = Duration::from_secs(3);
|
pub const DIAL_TIMEOUT: Duration = Duration::from_secs(3);
|
||||||
|
/// More 1xx heads than this before a final answer is treated as a broken server.
|
||||||
|
const MAX_INFORMATIONAL: usize = 8;
|
||||||
|
|
||||||
pub fn peer(u: &UpstreamRt) -> HttpPeer {
|
pub fn peer(addr: SocketAddr, u: &UpstreamRt) -> HttpPeer {
|
||||||
let mut p = HttpPeer::new(u.addr, u.tls, u.sni.clone());
|
let mut p = HttpPeer::new(addr, u.tls, u.sni.clone());
|
||||||
p.options.connection_timeout = Some(DIAL_TIMEOUT);
|
p.options.connection_timeout = Some(DIAL_TIMEOUT);
|
||||||
p
|
p
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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`.
|
||||||
pub async fn fetch(
|
pub async fn fetch(
|
||||||
connector: &Connector,
|
connector: &Connector,
|
||||||
u: &UpstreamRt,
|
u: &UpstreamRt,
|
||||||
@@ -36,18 +46,76 @@ pub async fn fetch(
|
|||||||
max_body: usize,
|
max_body: usize,
|
||||||
timeout: Duration,
|
timeout: Duration,
|
||||||
) -> Result<Fetched> {
|
) -> Result<Fetched> {
|
||||||
let mut p = peer(u);
|
match tokio::time::timeout(timeout, exchange(connector, u, req, max_body, timeout)).await {
|
||||||
p.options.read_timeout = Some(timeout);
|
Ok(r) => r,
|
||||||
p.options.write_timeout = Some(timeout);
|
Err(_) => Error::e_explain(
|
||||||
p.options.total_connection_timeout = Some(timeout);
|
ErrorType::ReadTimedout,
|
||||||
let (mut http, _reused) = connector.get_http_session(&p).await?;
|
format!("no complete answer within {timeout:?}"),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn exchange(
|
||||||
|
connector: &Connector,
|
||||||
|
u: &UpstreamRt,
|
||||||
|
req: RequestHeader,
|
||||||
|
max_body: usize,
|
||||||
|
timeout: Duration,
|
||||||
|
) -> 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 session = None;
|
||||||
|
for addr in addrs {
|
||||||
|
let mut p = peer(addr, u);
|
||||||
|
p.options.total_connection_timeout = Some(timeout);
|
||||||
|
match connector.get_http_session(&p).await {
|
||||||
|
Ok((s, _reused)) => {
|
||||||
|
session = Some(s);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(e) => last = Some(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let Some(mut http) = session else {
|
||||||
|
return Err(last.unwrap_or_else(|| {
|
||||||
|
Error::explain(ErrorType::ConnectError, "no address to connect to")
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
http.set_read_timeout(Some(timeout));
|
||||||
|
http.set_write_timeout(Some(timeout));
|
||||||
http.write_request_header(Box::new(req)).await?;
|
http.write_request_header(Box::new(req)).await?;
|
||||||
http.finish_request_body().await?;
|
http.finish_request_body().await?;
|
||||||
http.read_response_header().await?;
|
|
||||||
let header = http
|
let mut header = None;
|
||||||
.response_header()
|
for _ in 0..=MAX_INFORMATIONAL {
|
||||||
.cloned()
|
http.read_response_header().await?;
|
||||||
.ok_or_else(|| Error::explain(ErrorType::InvalidHTTPHeader, "no response header"))?;
|
let h = http
|
||||||
|
.response_header()
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| Error::explain(ErrorType::InvalidHTTPHeader, "no response header"))?;
|
||||||
|
let s = h.status.as_u16();
|
||||||
|
if (100..200).contains(&s) && s != 101 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
header = Some(h);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let header = header.ok_or_else(|| {
|
||||||
|
Error::explain(ErrorType::InvalidHTTPHeader, "only informational answers")
|
||||||
|
})?;
|
||||||
|
if header.status.as_u16() == 101 {
|
||||||
|
// Switching protocols: there is no HTTP body to read.
|
||||||
|
return Ok(Fetched {
|
||||||
|
header,
|
||||||
|
body: Bytes::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
let mut body = BytesMut::new();
|
let mut body = BytesMut::new();
|
||||||
while let Some(chunk) = http.read_response_body().await? {
|
while let Some(chunk) = http.read_response_body().await? {
|
||||||
if body.len() + chunk.len() > max_body {
|
if body.len() + chunk.len() > max_body {
|
||||||
|
|||||||
@@ -19,10 +19,10 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use http::header::{self, HeaderName, HeaderValue};
|
use http::header::{self, HeaderName, HeaderValue};
|
||||||
use pingora::Result;
|
|
||||||
use pingora::connectors::http::Connector;
|
use pingora::connectors::http::Connector;
|
||||||
use pingora::http::{RequestHeader, ResponseHeader};
|
use pingora::http::{RequestHeader, ResponseHeader};
|
||||||
use pingora::proxy::Session;
|
use pingora::proxy::Session;
|
||||||
|
use pingora::{Error, ErrorType, Result};
|
||||||
|
|
||||||
use crate::fetch::fetch;
|
use crate::fetch::fetch;
|
||||||
use crate::runtime::ForwardAuthRt;
|
use crate::runtime::ForwardAuthRt;
|
||||||
@@ -82,6 +82,13 @@ pub async fn check(
|
|||||||
|
|
||||||
let got = fetch(connector, &fa.upstream, sub, MAX_AUTH_BODY, AUTH_TIMEOUT).await?;
|
let got = fetch(connector, &fa.upstream, sub, MAX_AUTH_BODY, AUTH_TIMEOUT).await?;
|
||||||
let status = got.header.status.as_u16();
|
let status = got.header.status.as_u16();
|
||||||
|
if status < 200 {
|
||||||
|
// 101 (or any 1xx left over) is not an answer we can pass on or treat as an allow.
|
||||||
|
return Error::e_explain(
|
||||||
|
ErrorType::InvalidHTTPHeader,
|
||||||
|
format!("auth server answered {status}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
if (200..300).contains(&status) {
|
if (200..300).contains(&status) {
|
||||||
let copy = fa
|
let copy = fa
|
||||||
.copy_headers
|
.copy_headers
|
||||||
|
|||||||
+61
-23
@@ -35,25 +35,40 @@ async fn probe(connector: &Connector, u: &UpstreamRt, path: &str) -> bool {
|
|||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
match tokio::time::timeout(TIMEOUT, fetch(connector, u, req, 64 * 1024, TIMEOUT)).await {
|
match fetch(connector, u, req, 64 * 1024, TIMEOUT).await {
|
||||||
Ok(Ok(f)) => f.header.status.is_success(),
|
Ok(f) => f.header.status.is_success(),
|
||||||
_ => false,
|
Err(_) => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One round over a host's upstreams. Each probe runs in its own task, so a panic inside a
|
||||||
|
/// probe (e.g. a library bug on an odd answer) marks that upstream unhealthy instead of
|
||||||
|
/// ending health checks.
|
||||||
|
async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>) {
|
||||||
|
for i in 0..host.upstreams.len() {
|
||||||
|
let (h, p, c) = (host.clone(), path.to_owned(), connector.clone());
|
||||||
|
let ok = match tokio::spawn(async move { probe(&c, &h.upstreams[i], &p).await }).await {
|
||||||
|
Ok(ok) => ok,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(target: "ianitor::health", "{}: health check of {} crashed ({e}); counting it as failed", host.cfg.hostname, host.upstreams[i].authority);
|
||||||
|
false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let u = &host.upstreams[i];
|
||||||
|
if u.healthy.swap(ok, Ordering::Relaxed) != ok {
|
||||||
|
if ok {
|
||||||
|
log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority);
|
||||||
|
} else {
|
||||||
|
log::warn!(target: "ianitor::health", "{}: upstream {} failed its health check", host.cfg.hostname, u.authority);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn watch(host: Arc<HostRt>, path: String, every: Duration) {
|
async fn watch(host: Arc<HostRt>, path: String, every: Duration) {
|
||||||
let connector = Connector::new(None);
|
let connector = Arc::new(Connector::new(None));
|
||||||
loop {
|
loop {
|
||||||
for u in &host.upstreams {
|
round(&host, &path, &connector).await;
|
||||||
let ok = probe(&connector, u, &path).await;
|
|
||||||
if u.healthy.swap(ok, Ordering::Relaxed) != ok {
|
|
||||||
if ok {
|
|
||||||
log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority);
|
|
||||||
} else {
|
|
||||||
log::warn!(target: "ianitor::health", "{}: upstream {} failed its health check", host.cfg.hostname, u.authority);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
tokio::time::sleep(every).await;
|
tokio::time::sleep(every).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -61,16 +76,39 @@ async fn watch(host: Arc<HostRt>, path: String, every: Duration) {
|
|||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl BackgroundService for HealthChecks {
|
impl BackgroundService for HealthChecks {
|
||||||
async fn start(&self, mut shutdown: ShutdownWatch) {
|
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||||
let mut tasks = Vec::new();
|
let checked: Vec<(Arc<HostRt>, String, Duration)> = self
|
||||||
for host in self.rt.hosts.values() {
|
.rt
|
||||||
if let Some(hc) = &host.cfg.health_check {
|
.hosts
|
||||||
let every = Duration::from_secs(u64::from(hc.interval_secs.max(1)));
|
.values()
|
||||||
tasks.push(tokio::spawn(watch(host.clone(), hc.path.clone(), every)));
|
.filter_map(|h| {
|
||||||
|
h.cfg.health_check.as_ref().map(|hc| {
|
||||||
|
(
|
||||||
|
h.clone(),
|
||||||
|
hc.path.clone(),
|
||||||
|
Duration::from_secs(u64::from(hc.interval_secs.max(1))),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let mut tasks = tokio::task::JoinSet::new();
|
||||||
|
let mut which = std::collections::HashMap::new();
|
||||||
|
for (i, (h, p, every)) in checked.iter().enumerate() {
|
||||||
|
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i);
|
||||||
|
}
|
||||||
|
// A watcher never returns; if one ends anyway, say so and start it again.
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
_ = shutdown.changed() => break,
|
||||||
|
Some(done) = tasks.join_next_with_id() => {
|
||||||
|
let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() };
|
||||||
|
if let Some(i) = which.remove(&id) {
|
||||||
|
let (h, p, every) = &checked[i];
|
||||||
|
log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", h.cfg.hostname);
|
||||||
|
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let _ = shutdown.changed().await;
|
tasks.abort_all();
|
||||||
for t in tasks {
|
|
||||||
t.abort();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,8 +10,11 @@ use std::time::Instant;
|
|||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use http::{Response, StatusCode, header};
|
use http::{Response, StatusCode, header};
|
||||||
use pingora::apps::http_app::ServeHttp;
|
use pingora::ErrorType;
|
||||||
|
use pingora::apps::{HttpPersistentSettings, HttpServerApp, ReusedHttpStream};
|
||||||
|
use pingora::http::ResponseHeader;
|
||||||
use pingora::protocols::http::ServerSession;
|
use pingora::protocols::http::ServerSession;
|
||||||
|
use pingora::server::ShutdownWatch;
|
||||||
|
|
||||||
use crate::acme::Challenges;
|
use crate::acme::Challenges;
|
||||||
use crate::logging::{AccessRecord, now_secs, truncate_ip};
|
use crate::logging::{AccessRecord, now_secs, truncate_ip};
|
||||||
@@ -32,7 +35,44 @@ fn empty(status: StatusCode) -> Response<Vec<u8>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl ServeHttp for HttpApp {
|
impl HttpServerApp for HttpApp {
|
||||||
|
/// Like Pingora's `ServeHttp` driver, but a request Pingora refuses to parse (for example
|
||||||
|
/// an absolute-form target whose authority differs from Host) gets a 400 instead of a
|
||||||
|
/// silently closed connection, as on the HTTPS listener.
|
||||||
|
async fn process_new_http(
|
||||||
|
self: &Arc<Self>,
|
||||||
|
mut http: ServerSession,
|
||||||
|
shutdown: &ShutdownWatch,
|
||||||
|
) -> Option<ReusedHttpStream> {
|
||||||
|
match http.read_request().await {
|
||||||
|
Ok(true) => {}
|
||||||
|
Ok(false) => return None,
|
||||||
|
Err(e) => {
|
||||||
|
if matches!(e.etype(), ErrorType::InvalidHTTPHeader) {
|
||||||
|
log::debug!(target: "ianitor::http", "bad request: {e}");
|
||||||
|
let _ = http.respond_error(400).await;
|
||||||
|
}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
http.set_keepalive(if *shutdown.borrow() { None } else { Some(60) });
|
||||||
|
let (parts, body) = self.response(&mut http).await.into_parts();
|
||||||
|
let header: ResponseHeader = parts.into();
|
||||||
|
if http.write_response_header(Box::new(header)).await.is_err() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if !body.is_empty() && http.write_response_body(body.into(), true).await.is_err() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let settings = HttpPersistentSettings::for_session(&http);
|
||||||
|
match http.finish().await {
|
||||||
|
Ok(c) => c.map(|s| ReusedHttpStream::from_reusable_stream(s, settings)),
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HttpApp {
|
||||||
async fn response(&self, session: &mut ServerSession) -> Response<Vec<u8>> {
|
async fn response(&self, session: &mut ServerSession) -> Response<Vec<u8>> {
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
let req = session.req_header();
|
let req = session.req_header();
|
||||||
|
|||||||
+88
-23
@@ -30,18 +30,27 @@ pub struct EdgeProxy {
|
|||||||
|
|
||||||
pub struct Ctx {
|
pub struct Ctx {
|
||||||
host: Option<Arc<HostRt>>,
|
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).
|
/// The Host header as the client sent it (with port, if any).
|
||||||
host_header: String,
|
host_header: String,
|
||||||
start: Instant,
|
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 {
|
pub fn host_header(req: &RequestHeader) -> String {
|
||||||
req.headers
|
req.uri
|
||||||
.get(header::HOST)
|
.authority()
|
||||||
.and_then(|v| v.to_str().ok())
|
.map(|a| a.as_str().to_owned())
|
||||||
.map(str::to_owned)
|
.or_else(|| {
|
||||||
.or_else(|| req.uri.authority().map(|a| a.as_str().to_owned()))
|
req.headers
|
||||||
|
.get(header::HOST)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(str::to_owned)
|
||||||
|
})
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,11 +98,13 @@ fn apply(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_websocket_upgrade(req: &RequestHeader) -> bool {
|
/// Any `Upgrade` field, any comma-separated token, equal to `websocket` (case-insensitive).
|
||||||
req.headers
|
pub fn is_websocket_upgrade(req: &RequestHeader) -> bool {
|
||||||
.get(header::UPGRADE)
|
req.headers.get_all(header::UPGRADE).iter().any(|v| {
|
||||||
.and_then(|v| v.to_str().ok())
|
String::from_utf8_lossy(v.as_bytes())
|
||||||
.is_some_and(|v| v.trim().eq_ignore_ascii_case("websocket"))
|
.split(',')
|
||||||
|
.any(|t| t.trim().eq_ignore_ascii_case("websocket"))
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
@@ -103,6 +114,9 @@ impl ProxyHttp for EdgeProxy {
|
|||||||
fn new_ctx(&self) -> Ctx {
|
fn new_ctx(&self) -> Ctx {
|
||||||
Ctx {
|
Ctx {
|
||||||
host: None,
|
host: None,
|
||||||
|
upstream: None,
|
||||||
|
addrs: Vec::new(),
|
||||||
|
addr_idx: 0,
|
||||||
host_header: String::new(),
|
host_header: String::new(),
|
||||||
start: Instant::now(),
|
start: Instant::now(),
|
||||||
}
|
}
|
||||||
@@ -120,6 +134,11 @@ impl ProxyHttp for EdgeProxy {
|
|||||||
let fa = self.rt.forward_auth.as_ref().ok_or_else(|| {
|
let fa = self.rt.forward_auth.as_ref().ok_or_else(|| {
|
||||||
Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured")
|
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 ip = client_ip(session).map(|i| i.to_string());
|
||||||
let outcome = match forward_auth::check(
|
let outcome = match forward_auth::check(
|
||||||
&self.connector,
|
&self.connector,
|
||||||
@@ -171,27 +190,60 @@ impl ProxyHttp for EdgeProxy {
|
|||||||
async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result<Box<HttpPeer>> {
|
async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result<Box<HttpPeer>> {
|
||||||
let host = ctx
|
let host = ctx
|
||||||
.host
|
.host
|
||||||
.as_ref()
|
.clone()
|
||||||
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(500), "no host"))?;
|
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(500), "no host"))?;
|
||||||
let n = host.upstreams.len();
|
let idx = match ctx.upstream {
|
||||||
let first = host.next.fetch_add(1, Ordering::Relaxed);
|
// A retry after a failed connect: same upstream, next address.
|
||||||
let chosen = (0..n)
|
Some(i) => i,
|
||||||
.map(|i| &host.upstreams[(first + i) % n])
|
None => {
|
||||||
.find(|u| u.healthy.load(Ordering::Relaxed))
|
let n = host.upstreams.len();
|
||||||
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream"))?;
|
let first = host.next.fetch_add(1, Ordering::Relaxed);
|
||||||
log::debug!(target: "ianitor::proxy", "{}: upstream {}", host.cfg.hostname, chosen.authority);
|
let i = (0..n)
|
||||||
Ok(Box::new(fetch::peer(chosen)))
|
.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(
|
fn fail_to_connect(
|
||||||
&self,
|
&self,
|
||||||
_s: &mut Session,
|
_s: &mut Session,
|
||||||
_p: &HttpPeer,
|
_p: &HttpPeer,
|
||||||
_c: &mut Ctx,
|
ctx: &mut Ctx,
|
||||||
mut e: Box<Error>,
|
mut e: Box<Error>,
|
||||||
) -> Box<Error> {
|
) -> Box<Error> {
|
||||||
// Like Caddy's default (no lb_try_duration): one attempt, then 502.
|
// Like Caddy's dialer: try every address of the chosen upstream, then 502. Other
|
||||||
e.set_retry(false);
|
// 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
|
e
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,6 +253,19 @@ impl ProxyHttp for EdgeProxy {
|
|||||||
req: &mut RequestHeader,
|
req: &mut RequestHeader,
|
||||||
ctx: &mut Ctx,
|
ctx: &mut Ctx,
|
||||||
) -> Result<()> {
|
) -> 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.
|
// Forwarding headers are always edge's own; client-supplied values are replaced.
|
||||||
match client_ip(session) {
|
match client_ip(session) {
|
||||||
Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?,
|
Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?,
|
||||||
|
|||||||
+46
-11
@@ -6,7 +6,7 @@
|
|||||||
//! parsed header names, secrets loaded, certificates loaded. Built once at startup.
|
//! parsed header names, secrets loaded, certificates loaded. Built once at startup.
|
||||||
|
|
||||||
use std::collections::{BTreeSet, HashMap};
|
use std::collections::{BTreeSet, HashMap};
|
||||||
use std::net::{SocketAddr, ToSocketAddrs};
|
use std::net::SocketAddr;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::atomic::{AtomicBool, AtomicUsize};
|
use std::sync::atomic::{AtomicBool, AtomicUsize};
|
||||||
@@ -27,7 +27,9 @@ pub enum Op {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct UpstreamRt {
|
pub struct UpstreamRt {
|
||||||
pub addr: SocketAddr,
|
/// Host name or IP literal (IPv6 without brackets).
|
||||||
|
pub host: String,
|
||||||
|
pub port: u16,
|
||||||
/// `host:port` as configured; the Host header of health checks.
|
/// `host:port` as configured; the Host header of health checks.
|
||||||
pub authority: String,
|
pub authority: String,
|
||||||
pub tls: bool,
|
pub tls: bool,
|
||||||
@@ -49,6 +51,8 @@ pub struct ForwardAuthRt {
|
|||||||
pub upstream: UpstreamRt,
|
pub upstream: UpstreamRt,
|
||||||
pub path_and_query: String,
|
pub path_and_query: String,
|
||||||
pub copy_headers: Vec<HeaderName>,
|
pub copy_headers: Vec<HeaderName>,
|
||||||
|
/// Removed from every client request on a forward-auth host before anything else.
|
||||||
|
pub strip_headers: Vec<HeaderName>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Runtime {
|
pub struct Runtime {
|
||||||
@@ -97,19 +101,25 @@ pub fn read_config(path: &Path) -> Result<EdgeConfig, EdgeError> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
|
fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
|
||||||
let err = |reason: String| EdgeError::Upstream {
|
let err = |reason: &str| EdgeError::Upstream {
|
||||||
address: u.address.clone(),
|
address: u.address.clone(),
|
||||||
reason,
|
reason: reason.to_owned(),
|
||||||
};
|
};
|
||||||
// Resolved once at startup; Pingora peers need a socket address.
|
let (host, port) = u
|
||||||
let addr = u
|
|
||||||
.address
|
.address
|
||||||
.to_socket_addrs()
|
.rsplit_once(':')
|
||||||
.map_err(|e| err(format!("cannot resolve: {e}")))?
|
.ok_or_else(|| err("expected host:port"))?;
|
||||||
.next()
|
let port: u16 = port.parse().map_err(|_| err("bad port"))?;
|
||||||
.ok_or_else(|| err("resolves to no address".into()))?;
|
let host = host
|
||||||
|
.strip_prefix('[')
|
||||||
|
.and_then(|h| h.strip_suffix(']'))
|
||||||
|
.unwrap_or(host);
|
||||||
|
if host.is_empty() {
|
||||||
|
return Err(err("empty host"));
|
||||||
|
}
|
||||||
Ok(UpstreamRt {
|
Ok(UpstreamRt {
|
||||||
addr,
|
host: host.to_owned(),
|
||||||
|
port,
|
||||||
authority: u.address.clone(),
|
authority: u.address.clone(),
|
||||||
tls: u.tls,
|
tls: u.tls,
|
||||||
sni: u.sni.clone(),
|
sni: u.sni.clone(),
|
||||||
@@ -117,6 +127,26 @@ fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl UpstreamRt {
|
||||||
|
/// Addresses to try, in resolver order. Names are resolved at connect time (like Caddy's
|
||||||
|
/// dialer), so DNS changes and unresolvable names only affect requests, not startup.
|
||||||
|
pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> {
|
||||||
|
if let Ok(ip) = self.host.parse::<std::net::IpAddr>() {
|
||||||
|
return Ok(vec![SocketAddr::new(ip, self.port)]);
|
||||||
|
}
|
||||||
|
let addrs: Vec<SocketAddr> = tokio::net::lookup_host((self.host.as_str(), self.port))
|
||||||
|
.await?
|
||||||
|
.collect();
|
||||||
|
if addrs.is_empty() {
|
||||||
|
return Err(std::io::Error::new(
|
||||||
|
std::io::ErrorKind::NotFound,
|
||||||
|
"name resolves to no address",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(addrs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn header_name(name: &str) -> Result<HeaderName, EdgeError> {
|
fn header_name(name: &str) -> Result<HeaderName, EdgeError> {
|
||||||
HeaderName::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header {
|
HeaderName::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header {
|
||||||
name: name.to_owned(),
|
name: name.to_owned(),
|
||||||
@@ -225,6 +255,11 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
|
|||||||
.iter()
|
.iter()
|
||||||
.map(|h| header_name(h))
|
.map(|h| header_name(h))
|
||||||
.collect::<Result<_, _>>()?,
|
.collect::<Result<_, _>>()?,
|
||||||
|
strip_headers: fa
|
||||||
|
.strip_headers
|
||||||
|
.iter()
|
||||||
|
.map(|h| header_name(h))
|
||||||
|
.collect::<Result<_, _>>()?,
|
||||||
}),
|
}),
|
||||||
None => None,
|
None => None,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -266,7 +266,10 @@ async fn misbehaving_auth_answers_fail_closed() {
|
|||||||
site: &site,
|
site: &site,
|
||||||
hosts: vec![host_file(
|
hosts: vec![host_file(
|
||||||
"auth.test",
|
"auth.test",
|
||||||
&format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url()),
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\n",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
)],
|
)],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
});
|
});
|
||||||
@@ -275,15 +278,26 @@ async fn misbehaving_auth_answers_fail_closed() {
|
|||||||
let addr = edge.https;
|
let addr = edge.https;
|
||||||
async move {
|
async move {
|
||||||
let cookie = format!("authelia_session={session}");
|
let cookie = format!("authelia_session={session}");
|
||||||
client::https(addr, "auth.test", roots, &Req::get("auth.test", "/").header("cookie", &cookie)).await
|
client::https(
|
||||||
|
addr,
|
||||||
|
"auth.test",
|
||||||
|
roots,
|
||||||
|
&Req::get("auth.test", "/").header("cookie", &cookie),
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 100 Continue before the real answer is skipped, like any HTTP client does.
|
// 100 Continue before the real answer is skipped, like any HTTP client does.
|
||||||
let r = go("continue-ok").await.expect("edge answers after a 1xx from the auth server");
|
let r = go("continue-ok")
|
||||||
|
.await
|
||||||
|
.expect("edge answers after a 1xx from the auth server");
|
||||||
assert_eq!(r.status, 200);
|
assert_eq!(r.status, 200);
|
||||||
assert_eq!(echo.proxied().len(), 1);
|
assert_eq!(echo.proxied().len(), 1);
|
||||||
assert_eq!(echo.proxied()[0].header("remote-user"), Some(b"alice".as_slice()));
|
assert_eq!(
|
||||||
|
echo.proxied()[0].header("remote-user"),
|
||||||
|
Some(b"alice".as_slice())
|
||||||
|
);
|
||||||
echo.clear();
|
echo.clear();
|
||||||
|
|
||||||
// 101 is a final answer but not an allow: denied with 502.
|
// 101 is a final answer but not an allow: denied with 502.
|
||||||
@@ -296,9 +310,15 @@ async fn misbehaving_auth_answers_fail_closed() {
|
|||||||
|
|
||||||
// An auth server that never answers: 502 once the 10 s auth timeout passes.
|
// An auth server that never answers: 502 once the 10 s auth timeout passes.
|
||||||
let t = std::time::Instant::now();
|
let t = std::time::Instant::now();
|
||||||
let r = go("hang").await.expect("edge answers a hanging auth server");
|
let r = go("hang")
|
||||||
|
.await
|
||||||
|
.expect("edge answers a hanging auth server");
|
||||||
assert_eq!(r.status, 502);
|
assert_eq!(r.status, 502);
|
||||||
assert!(t.elapsed() < std::time::Duration::from_secs(14), "took {:?}", t.elapsed());
|
assert!(
|
||||||
|
t.elapsed() < std::time::Duration::from_secs(14),
|
||||||
|
"took {:?}",
|
||||||
|
t.elapsed()
|
||||||
|
);
|
||||||
assert!(echo.proxied().is_empty());
|
assert!(echo.proxied().is_empty());
|
||||||
|
|
||||||
// Still serving afterwards.
|
// Still serving afterwards.
|
||||||
@@ -313,12 +333,18 @@ async fn remote_headers_are_stripped_even_with_a_custom_copy_list() {
|
|||||||
let echo = Echo::start("app").await;
|
let echo = Echo::start("app").await;
|
||||||
for copy in ["[]", "[\"Remote-User\"]"] {
|
for copy in ["[]", "[\"Remote-User\"]"] {
|
||||||
echo.clear();
|
echo.clear();
|
||||||
let site = format!("[forward_auth]\nurl = \"{}\"\ncopy_headers = {copy}\n", authelia.url());
|
let site = format!(
|
||||||
|
"[forward_auth]\nurl = \"{}\"\ncopy_headers = {copy}\n",
|
||||||
|
authelia.url()
|
||||||
|
);
|
||||||
let edge = start(EdgeSpec {
|
let edge = start(EdgeSpec {
|
||||||
site: &site,
|
site: &site,
|
||||||
hosts: vec![host_file(
|
hosts: vec![host_file(
|
||||||
"auth.test",
|
"auth.test",
|
||||||
&format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url()),
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\nauth = \"forward-auth\"\n",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
)],
|
)],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
});
|
});
|
||||||
|
|||||||
+107
-22
@@ -23,15 +23,35 @@ async fn upstream_names_are_resolved_at_connect_time_trying_every_address() {
|
|||||||
let echo = Echo::start("app").await;
|
let echo = Echo::start("app").await;
|
||||||
let edge = start(EdgeSpec {
|
let edge = start(EdgeSpec {
|
||||||
hosts: vec![
|
hosts: vec![
|
||||||
host_file("local.test", &format!("upstreams = [\"http://localhost:{}\"]\n", echo.addr.port())),
|
host_file(
|
||||||
host_file("gone.test", "upstreams = [\"http://no-such-host.invalid:8080\"]\n"),
|
"local.test",
|
||||||
|
&format!("upstreams = [\"http://localhost:{}\"]\n", echo.addr.port()),
|
||||||
|
),
|
||||||
|
host_file(
|
||||||
|
"gone.test",
|
||||||
|
"upstreams = [\"http://no-such-host.invalid:8080\"]\n",
|
||||||
|
),
|
||||||
],
|
],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
});
|
});
|
||||||
let r = client::https(edge.https, "local.test", edge.roots(), &Req::get("local.test", "/")).await.unwrap();
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"local.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("local.test", "/"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
assert_eq!(r.status, 200, "{}", edge.stderr());
|
assert_eq!(r.status, 200, "{}", edge.stderr());
|
||||||
// An upstream that does not resolve is a 502 for that host, not a startup failure.
|
// An upstream that does not resolve is a 502 for that host, not a startup failure.
|
||||||
let r = client::https(edge.https, "gone.test", edge.roots(), &Req::get("gone.test", "/")).await.unwrap();
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"gone.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("gone.test", "/"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
assert_eq!(r.status, 502);
|
assert_eq!(r.status, 502);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,14 +72,35 @@ async fn health_checks_survive_informational_answers() {
|
|||||||
let edge = start(EdgeSpec {
|
let edge = start(EdgeSpec {
|
||||||
hosts: vec![host_file(
|
hosts: vec![host_file(
|
||||||
"hc.test",
|
"hc.test",
|
||||||
&format!("upstreams = [\"{}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n", up.url()),
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]\n[health_check]\npath = \"/healthz\"\ninterval_secs = 1\n",
|
||||||
|
up.url()
|
||||||
|
),
|
||||||
)],
|
)],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
});
|
});
|
||||||
tokio::time::sleep(Duration::from_millis(5500)).await;
|
tokio::time::sleep(Duration::from_millis(5500)).await;
|
||||||
let r = client::https(edge.https, "hc.test", edge.roots(), &Req::get("hc.test", "/")).await.unwrap();
|
let r = client::https(
|
||||||
assert_eq!(r.status, 503, "health checks kept running and marked the upstream down\n{}", edge.stderr());
|
edge.https,
|
||||||
assert!(up.requests().iter().filter(|r| r.path == "/healthz").count() >= 4);
|
"hc.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("hc.test", "/"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
r.status,
|
||||||
|
503,
|
||||||
|
"health checks kept running and marked the upstream down\n{}",
|
||||||
|
edge.stderr()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
up.requests()
|
||||||
|
.iter()
|
||||||
|
.filter(|r| r.path == "/healthz")
|
||||||
|
.count()
|
||||||
|
>= 4
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// QC m4: every Upgrade header and every comma-separated token counts.
|
/// QC m4: every Upgrade header and every comma-separated token counts.
|
||||||
@@ -67,37 +108,81 @@ async fn health_checks_survive_informational_answers() {
|
|||||||
async fn websocket_refusal_checks_every_upgrade_token() {
|
async fn websocket_refusal_checks_every_upgrade_token() {
|
||||||
let echo = Echo::start("app").await;
|
let echo = Echo::start("app").await;
|
||||||
let edge = start(EdgeSpec {
|
let edge = start(EdgeSpec {
|
||||||
hosts: vec![host_file("nows.test", &format!("upstreams = [\"{}\"]\nwebsockets = false\n", echo.url()))],
|
hosts: vec![host_file(
|
||||||
|
"nows.test",
|
||||||
|
&format!("upstreams = [\"{}\"]\nwebsockets = false\n", echo.url()),
|
||||||
|
)],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
});
|
});
|
||||||
let cases = [
|
let cases = [
|
||||||
Req::get("nows.test", "/").header("connection", "upgrade").header("upgrade", "h2c").header("upgrade", "websocket"),
|
Req::get("nows.test", "/")
|
||||||
Req::get("nows.test", "/").header("connection", "upgrade").header("upgrade", "websocket, h2c"),
|
.header("connection", "upgrade")
|
||||||
Req::get("nows.test", "/").header("connection", "upgrade").header("upgrade", "h2c , WebSocket"),
|
.header("upgrade", "h2c")
|
||||||
|
.header("upgrade", "websocket"),
|
||||||
|
Req::get("nows.test", "/")
|
||||||
|
.header("connection", "upgrade")
|
||||||
|
.header("upgrade", "websocket, h2c"),
|
||||||
|
Req::get("nows.test", "/")
|
||||||
|
.header("connection", "upgrade")
|
||||||
|
.header("upgrade", "h2c , WebSocket"),
|
||||||
];
|
];
|
||||||
for req in &cases {
|
for req in &cases {
|
||||||
let r = client::https(edge.https, "nows.test", edge.roots(), req).await.unwrap();
|
let r = client::https(edge.https, "nows.test", edge.roots(), req)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
assert_eq!(r.status, 403, "{req:?}");
|
assert_eq!(r.status, 403, "{req:?}");
|
||||||
}
|
}
|
||||||
assert!(echo.proxied().is_empty());
|
assert!(echo.proxied().is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// QC nit: absolute-form request targets are answered and routed by the URI's host
|
/// QC nit: absolute-form request targets are answered, never dropped. Pingora refuses a target
|
||||||
/// (RFC 9112 §3.2.2), as Go/Caddy do.
|
/// whose authority differs from Host (400, on both listeners); a consistent one is routed and
|
||||||
|
/// sent upstream in origin form.
|
||||||
#[tokio::test(flavor = "multi_thread")]
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
async fn absolute_form_requests_are_answered() {
|
async fn absolute_form_requests_are_answered() {
|
||||||
let echo = Echo::start("app").await;
|
let echo = Echo::start("app").await;
|
||||||
let edge = start(EdgeSpec {
|
let edge = start(EdgeSpec {
|
||||||
hosts: vec![host_file("plain.test", &format!("upstreams = [\"{}\"]\n", echo.url()))],
|
hosts: vec![host_file(
|
||||||
|
"plain.test",
|
||||||
|
&format!(
|
||||||
|
"upstreams = [\"{}\"]
|
||||||
|
",
|
||||||
|
echo.url()
|
||||||
|
),
|
||||||
|
)],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
});
|
});
|
||||||
let r = client::http(edge.http, &Req::get("plain.test", "http://evil.test/x")).await.unwrap();
|
let r = client::http(edge.http, &Req::get("plain.test", "http://evil.test/x"))
|
||||||
assert_eq!(r.status, 404, "plain HTTP");
|
|
||||||
let r = client::https(edge.https, "plain.test", edge.roots(), &Req::get("plain.test", "https://evil.test/x"))
|
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(r.status, 404, "HTTPS");
|
assert_eq!(r.status, 400, "plain HTTP, Host differs from the target");
|
||||||
let r = client::http(edge.http, &Req::get("evil.test", "http://plain.test/x?y")).await.unwrap();
|
let r = client::https(
|
||||||
assert_eq!(r.status, 308);
|
edge.https,
|
||||||
|
"plain.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("plain.test", "https://evil.test/x"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 400, "HTTPS, Host differs from the target");
|
||||||
assert!(echo.proxied().is_empty());
|
assert!(echo.proxied().is_empty());
|
||||||
|
|
||||||
|
let r = client::http(edge.http, &Req::get("plain.test", "http://plain.test/x?y"))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 308);
|
||||||
|
assert_eq!(
|
||||||
|
r.header("location"),
|
||||||
|
Some(format!("https://plain.test:{}/x?y", edge.https.port()).as_str())
|
||||||
|
);
|
||||||
|
let r = client::https(
|
||||||
|
edge.https,
|
||||||
|
"plain.test",
|
||||||
|
edge.roots(),
|
||||||
|
&Req::get("plain.test", "https://plain.test/abs?q=1"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
assert!(r.text().contains("\"path\":\"/abs\""), "{}", r.text());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,14 +40,18 @@ pub struct MockAuthelia {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn h(req: &Recorded, name: &str) -> Option<String> {
|
fn h(req: &Recorded, name: &str) -> Option<String> {
|
||||||
req.header(name).map(|v| String::from_utf8_lossy(v).into_owned())
|
req.header(name)
|
||||||
|
.map(|v| String::from_utf8_lossy(v).into_owned())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn text(status: u16, reason: &str, body: &str) -> Vec<u8> {
|
fn text(status: u16, reason: &str, body: &str) -> Vec<u8> {
|
||||||
response(
|
response(
|
||||||
status,
|
status,
|
||||||
reason,
|
reason,
|
||||||
&[("Content-Type", "text/plain; charset=utf-8"), ("X-Sent-Content-Type", "text/plain; charset=utf-8")],
|
&[
|
||||||
|
("Content-Type", "text/plain; charset=utf-8"),
|
||||||
|
("X-Sent-Content-Type", "text/plain; charset=utf-8"),
|
||||||
|
],
|
||||||
body.as_bytes(),
|
body.as_bytes(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -64,9 +68,12 @@ fn decide(req: &Recorded) -> Reply {
|
|||||||
if req.method != "GET" || req.path != PATH {
|
if req.method != "GET" || req.path != PATH {
|
||||||
return Reply::Bytes(text(404, "Not Found", "404 page not found"));
|
return Reply::Bytes(text(404, "Not Found", "404 page not found"));
|
||||||
}
|
}
|
||||||
let (Some(method), Some(proto), Some(host), Some(uri)) =
|
let (Some(method), Some(proto), Some(host), Some(uri)) = (
|
||||||
(h(req, "x-forwarded-method"), h(req, "x-forwarded-proto"), h(req, "x-forwarded-host"), h(req, "x-forwarded-uri"))
|
h(req, "x-forwarded-method"),
|
||||||
else {
|
h(req, "x-forwarded-proto"),
|
||||||
|
h(req, "x-forwarded-host"),
|
||||||
|
h(req, "x-forwarded-uri"),
|
||||||
|
) else {
|
||||||
return Reply::Bytes(text(400, "Bad Request", "missing X-Forwarded headers"));
|
return Reply::Bytes(text(400, "Bad Request", "missing X-Forwarded headers"));
|
||||||
};
|
};
|
||||||
if let Some(auth) = h(req, "authorization") {
|
if let Some(auth) = h(req, "authorization") {
|
||||||
@@ -76,13 +83,20 @@ fn decide(req: &Recorded) -> Reply {
|
|||||||
response(
|
response(
|
||||||
401,
|
401,
|
||||||
"Unauthorized",
|
"Unauthorized",
|
||||||
&[("WWW-Authenticate", "Basic realm=\"Authorization Required\""), ("X-Sent-Content-Type", "none")],
|
&[
|
||||||
|
("WWW-Authenticate", "Basic realm=\"Authorization Required\""),
|
||||||
|
("X-Sent-Content-Type", "none"),
|
||||||
|
],
|
||||||
b"401 Unauthorized",
|
b"401 Unauthorized",
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
let cookie = h(req, "cookie").unwrap_or_default();
|
let cookie = h(req, "cookie").unwrap_or_default();
|
||||||
let session = cookie.split(';').filter_map(|c| c.trim().strip_prefix("authelia_session=")).next().unwrap_or("");
|
let session = cookie
|
||||||
|
.split(';')
|
||||||
|
.filter_map(|c| c.trim().strip_prefix("authelia_session="))
|
||||||
|
.next()
|
||||||
|
.unwrap_or("");
|
||||||
Reply::Bytes(match session {
|
Reply::Bytes(match session {
|
||||||
"good" => allowed(true),
|
"good" => allowed(true),
|
||||||
"nameless" => allowed(false),
|
"nameless" => allowed(false),
|
||||||
@@ -126,7 +140,10 @@ fn decide(req: &Recorded) -> Reply {
|
|||||||
impl MockAuthelia {
|
impl MockAuthelia {
|
||||||
pub async fn start() -> MockAuthelia {
|
pub async fn start() -> MockAuthelia {
|
||||||
let server = RawServer::start(decide).await;
|
let server = RawServer::start(decide).await;
|
||||||
MockAuthelia { addr: server.addr, server }
|
MockAuthelia {
|
||||||
|
addr: server.addr,
|
||||||
|
server,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The `[forward_auth] url` for the site file.
|
/// The `[forward_auth] url` for the site file.
|
||||||
|
|||||||
@@ -27,7 +27,10 @@ pub fn response(status: u16, reason: &str, headers: &[(&str, &str)], body: &[u8]
|
|||||||
for (n, v) in headers {
|
for (n, v) in headers {
|
||||||
out.push_str(&format!("{n}: {v}\r\n"));
|
out.push_str(&format!("{n}: {v}\r\n"));
|
||||||
}
|
}
|
||||||
out.push_str(&format!("Content-Length: {}\r\nConnection: close\r\n\r\n", body.len()));
|
out.push_str(&format!(
|
||||||
|
"Content-Length: {}\r\nConnection: close\r\n\r\n",
|
||||||
|
body.len()
|
||||||
|
));
|
||||||
let mut bytes = out.into_bytes();
|
let mut bytes = out.into_bytes();
|
||||||
bytes.extend_from_slice(body);
|
bytes.extend_from_slice(body);
|
||||||
bytes
|
bytes
|
||||||
@@ -44,12 +47,17 @@ pub struct RawServer {
|
|||||||
impl RawServer {
|
impl RawServer {
|
||||||
pub async fn start(handler: impl Fn(&Recorded) -> Reply + Send + Sync + 'static) -> RawServer {
|
pub async fn start(handler: impl Fn(&Recorded) -> Reply + Send + Sync + 'static) -> RawServer {
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
let server = RawServer { addr: listener.local_addr().unwrap(), requests: Arc::default() };
|
let server = RawServer {
|
||||||
|
addr: listener.local_addr().unwrap(),
|
||||||
|
requests: Arc::default(),
|
||||||
|
};
|
||||||
let handler: Arc<Handler> = Arc::new(handler);
|
let handler: Arc<Handler> = Arc::new(handler);
|
||||||
let requests = server.requests.clone();
|
let requests = server.requests.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
loop {
|
loop {
|
||||||
let Ok((mut stream, _)) = listener.accept().await else { continue };
|
let Ok((mut stream, _)) = listener.accept().await else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
let handler = handler.clone();
|
let handler = handler.clone();
|
||||||
let requests = requests.clone();
|
let requests = requests.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
@@ -97,5 +105,10 @@ fn parse(buf: &[u8]) -> Option<Recorded> {
|
|||||||
.filter_map(|l| l.split_once(':'))
|
.filter_map(|l| l.split_once(':'))
|
||||||
.map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().as_bytes().to_vec()))
|
.map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().as_bytes().to_vec()))
|
||||||
.collect();
|
.collect();
|
||||||
Some(Recorded { method, path, headers, body: Vec::new() })
|
Some(Recorded {
|
||||||
|
method,
|
||||||
|
path,
|
||||||
|
headers,
|
||||||
|
body: Vec::new(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user