[edge] Tests first: QC repros for 1xx, auth timeout, name resolution, Upgrade tokens, Remote-* stripping (red)
This commit is contained in:
+103
-134
@@ -9,61 +9,124 @@
|
||||
//!
|
||||
//! Decisions of the mock (the real Authelia decides from its access-control rules):
|
||||
//! - `Authorization: Bearer good` → 200 with identity; any other Authorization → 401 + WWW-Authenticate
|
||||
//! - cookie `authelia_session=good` → 200 with identity
|
||||
//! - cookie `authelia_session=nameless` → 200 without identity headers
|
||||
//! - cookie `authelia_session=forbidden` → 403
|
||||
//! - cookie `authelia_session=good` → 200 with identity; `nameless` → 200 without identity;
|
||||
//! `forbidden` → 403
|
||||
//! - misbehaving answers, by cookie: `continue-ok` (100 Continue, then 200), `big-ok` /
|
||||
//! `big-deny` (200 / 401 with a 5 MB body), `truncated-ok` (200 whose body is cut short),
|
||||
//! `switch` (101 Switching Protocols), `hang` (never answers)
|
||||
//! - otherwise GET/HEAD → 302 to the portal with `rd`, other methods → 401
|
||||
//!
|
||||
//! Every answer says in `x-sent-content-type` which Content-Type the mock sent (or `none`).
|
||||
|
||||
use std::convert::Infallible;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use bytes::Bytes;
|
||||
use http_body_util::{BodyExt, Full};
|
||||
use hyper::body::Incoming;
|
||||
use hyper::server::conn::http1;
|
||||
use hyper::service::service_fn;
|
||||
use hyper::{Request, Response};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
use crate::raw::{RawServer, Reply, response};
|
||||
use crate::upstream::Recorded;
|
||||
|
||||
pub const PATH: &str = "/api/authz/forward-auth";
|
||||
pub const PORTAL: &str = "https://auth.test/";
|
||||
const IDENTITY: [(&str, &str); 4] = [
|
||||
("Remote-User", "alice"),
|
||||
("Remote-Groups", "admins,dev"),
|
||||
("Remote-Email", "alice@example.org"),
|
||||
("Remote-Name", "Alice Example"),
|
||||
];
|
||||
const BIG: usize = 5_000_000;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MockAuthelia {
|
||||
pub addr: SocketAddr,
|
||||
requests: Arc<Mutex<Vec<Recorded>>>,
|
||||
server: RawServer,
|
||||
}
|
||||
|
||||
fn h(req: &Recorded, name: &str) -> Option<String> {
|
||||
req.header(name).map(|v| String::from_utf8_lossy(v).into_owned())
|
||||
}
|
||||
|
||||
fn text(status: u16, reason: &str, body: &str) -> Vec<u8> {
|
||||
response(
|
||||
status,
|
||||
reason,
|
||||
&[("Content-Type", "text/plain; charset=utf-8"), ("X-Sent-Content-Type", "text/plain; charset=utf-8")],
|
||||
body.as_bytes(),
|
||||
)
|
||||
}
|
||||
|
||||
fn allowed(identity: bool) -> Vec<u8> {
|
||||
let mut hs: Vec<(&str, &str)> = vec![("X-Sent-Content-Type", "none")];
|
||||
if identity {
|
||||
hs.extend(IDENTITY);
|
||||
}
|
||||
response(200, "OK", &hs, b"")
|
||||
}
|
||||
|
||||
fn decide(req: &Recorded) -> Reply {
|
||||
if req.method != "GET" || req.path != PATH {
|
||||
return Reply::Bytes(text(404, "Not Found", "404 page not found"));
|
||||
}
|
||||
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"))
|
||||
else {
|
||||
return Reply::Bytes(text(400, "Bad Request", "missing X-Forwarded headers"));
|
||||
};
|
||||
if let Some(auth) = h(req, "authorization") {
|
||||
return Reply::Bytes(if auth == "Bearer good" {
|
||||
allowed(true)
|
||||
} else {
|
||||
response(
|
||||
401,
|
||||
"Unauthorized",
|
||||
&[("WWW-Authenticate", "Basic realm=\"Authorization Required\""), ("X-Sent-Content-Type", "none")],
|
||||
b"401 Unauthorized",
|
||||
)
|
||||
});
|
||||
}
|
||||
let cookie = h(req, "cookie").unwrap_or_default();
|
||||
let session = cookie.split(';').filter_map(|c| c.trim().strip_prefix("authelia_session=")).next().unwrap_or("");
|
||||
Reply::Bytes(match session {
|
||||
"good" => allowed(true),
|
||||
"nameless" => allowed(false),
|
||||
"forbidden" => text(403, "Forbidden", "403 Forbidden"),
|
||||
"continue-ok" => {
|
||||
let mut b = b"HTTP/1.1 100 Continue\r\n\r\n".to_vec();
|
||||
b.extend(allowed(true));
|
||||
b
|
||||
}
|
||||
"big-ok" => {
|
||||
let mut hs: Vec<(&str, &str)> = vec![("X-Sent-Content-Type", "none")];
|
||||
hs.extend(IDENTITY);
|
||||
response(200, "OK", &hs, &vec![b'a'; BIG])
|
||||
}
|
||||
"big-deny" => response(401, "Unauthorized", &[("X-Sent-Content-Type", "none")], &vec![b'a'; BIG]),
|
||||
"truncated-ok" => {
|
||||
b"HTTP/1.1 200 OK\r\nRemote-User: alice\r\nContent-Length: 1000\r\nConnection: close\r\n\r\nonly-a-bit".to_vec()
|
||||
}
|
||||
"switch" => b"HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n".to_vec(),
|
||||
"hang" => return Reply::Hang,
|
||||
_ if method == "GET" || method == "HEAD" => {
|
||||
let rd = format!("{proto}://{host}{uri}");
|
||||
let location = format!("{PORTAL}?rd={}", percent(&rd));
|
||||
let body = format!("<a href=\"{location}\">302 Found</a>");
|
||||
response(
|
||||
302,
|
||||
"Found",
|
||||
&[
|
||||
("Location", &location),
|
||||
("Set-Cookie", "authelia_flow=1; Path=/; HttpOnly"),
|
||||
("Content-Type", "text/html; charset=utf-8"),
|
||||
("X-Sent-Content-Type", "text/html; charset=utf-8"),
|
||||
],
|
||||
body.as_bytes(),
|
||||
)
|
||||
}
|
||||
_ => text(401, "Unauthorized", "401 Unauthorized"),
|
||||
})
|
||||
}
|
||||
|
||||
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 mm = m.clone();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
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;
|
||||
});
|
||||
}
|
||||
});
|
||||
m
|
||||
let server = RawServer::start(decide).await;
|
||||
MockAuthelia { addr: server.addr, server }
|
||||
}
|
||||
|
||||
/// The `[forward_auth] url` for the site file.
|
||||
@@ -72,101 +135,7 @@ impl MockAuthelia {
|
||||
}
|
||||
|
||||
pub fn requests(&self) -> Vec<Recorded> {
|
||||
self.requests.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
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();
|
||||
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(),
|
||||
body: body.to_vec(),
|
||||
});
|
||||
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)
|
||||
.header("content-type", "text/plain; charset=utf-8")
|
||||
.body(Full::new(Bytes::from(body.to_owned())))
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
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 {
|
||||
return text(400, "missing X-Forwarded headers");
|
||||
};
|
||||
|
||||
let allowed = |identity: bool| {
|
||||
let mut b = Response::builder().status(200);
|
||||
if identity {
|
||||
b = b
|
||||
.header("remote-user", "alice")
|
||||
.header("remote-groups", "admins,dev")
|
||||
.header("remote-email", "alice@example.org")
|
||||
.header("remote-name", "Alice Example");
|
||||
}
|
||||
b.body(Full::new(Bytes::new())).unwrap()
|
||||
};
|
||||
|
||||
if let Some(auth) = h("authorization") {
|
||||
return if auth == "Bearer good" {
|
||||
allowed(true)
|
||||
} else {
|
||||
Response::builder()
|
||||
.status(401)
|
||||
.header("www-authenticate", "Basic realm=\"Authorization Required\"")
|
||||
.body(Full::new(Bytes::from_static(b"401 Unauthorized")))
|
||||
.unwrap()
|
||||
};
|
||||
}
|
||||
let cookie = h("cookie").unwrap_or_default();
|
||||
let session = cookie
|
||||
.split(';')
|
||||
.filter_map(|c| c.trim().strip_prefix("authelia_session="))
|
||||
.next()
|
||||
.unwrap_or("");
|
||||
match session {
|
||||
"good" => allowed(true),
|
||||
"nameless" => allowed(false),
|
||||
"forbidden" => text(403, "403 Forbidden"),
|
||||
_ if method == "GET" || method == "HEAD" => {
|
||||
let rd = format!("{proto}://{host}{uri}");
|
||||
let location = format!("{PORTAL}?rd={}", percent(&rd));
|
||||
Response::builder()
|
||||
.status(302)
|
||||
.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>"
|
||||
))))
|
||||
.unwrap()
|
||||
}
|
||||
_ => text(401, "401 Unauthorized"),
|
||||
}
|
||||
self.server.requests()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user