Files
ianitor/tests/support/src/authelia.rs
T

158 lines
6.1 KiB
Rust

// 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/.
//! A mock of Authelia's ForwardAuth endpoint (`GET /api/authz/forward-auth`), following
//! Authelia's proxy-authorization guide: the proxy must send X-Forwarded-Method, -Proto, -Host
//! and -URI; a 2xx answer allows the request and carries Remote-User, Remote-Groups,
//! Remote-Email and Remote-Name; anything else is returned to the client as is.
//!
//! 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
//! - otherwise GET/HEAD → 302 to the portal with `rd`, other methods → 401
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::upstream::Recorded;
pub const PATH: &str = "/api/authz/forward-auth";
pub const PORTAL: &str = "https://auth.test/";
#[derive(Clone)]
pub struct MockAuthelia {
pub addr: SocketAddr,
requests: Arc<Mutex<Vec<Recorded>>>,
}
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
}
/// The `[forward_auth] url` for the site file.
pub fn url(&self) -> String {
format!("http://{}{PATH}", self.addr)
}
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"),
}
}
}
fn percent(s: &str) -> String {
let mut out = String::new();
for b in s.bytes() {
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
out.push(char::from(b));
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}