// SPDX-License-Identifier: CPAL-1.0 // Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution // License 1.0: see LICENSE (its Exhibit A is this file's notice). //! 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; `nameless` → 200 without identity; //! `forbidden` → 403 //! - misbehaving answers, by cookie: `continue-ok` (100 Continue, then 200), `continue-xN` //! (N × 102 Processing, 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::net::SocketAddr; 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, server: RawServer, } fn h(req: &Recorded, name: &str) -> Option { req.header(name) .map(|v| String::from_utf8_lossy(v).into_owned()) } fn text(status: u16, reason: &str, body: &str) -> Vec { 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 { 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 } s if s.starts_with("continue-x") => { // `continue-xN`: N informational heads (102 Processing), then 200. let n: usize = s["continue-x".len()..].parse().unwrap_or(1); let mut b = b"HTTP/1.1 102 Processing\r\n\r\n".repeat(n); 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!("302 Found"); 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 server = RawServer::start(decide).await; MockAuthelia { addr: server.addr, server, } } /// The `[forward_auth] url` for the site file. pub fn url(&self) -> String { format!("http://{}{PATH}", self.addr) } pub fn requests(&self) -> Vec { self.server.requests() } } 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 }