This commit is contained in:
Mateusz Gruszczyński committed 2026-10-27 12:18:20 +01:00
1 parent 62b7574553
commit e364392659
47 files changed
+2164 -257

No files matched your search

+160
View File
@@ -0,0 +1,160 @@
use axum::response::{IntoResponse, Response};
use http::{header, HeaderValue, StatusCode};
use super::AuthenticationResponse;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GatewayFailure {
Connection,
Timeout,
Verification,
}
pub fn deny(status: StatusCode) -> Response {
let body = format!(
"{} {}\n",
status.as_u16(),
status.canonical_reason().unwrap_or("Error")
);
let mut response = (status, body).into_response();
response.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static("private, no-store"),
);
response.extensions_mut().insert(AuthenticationResponse);
response
}
fn escape_html(raw: &str) -> String {
raw.replace('&', "&")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
.replace('\'', "&#39;")
.replace('{', "&#123;")
.replace('}', "&#125;")
}
pub fn gateway_failure(provider_name: &str, kind: GatewayFailure) -> Response {
let (status, label, message) = match kind {
GatewayFailure::Connection => (
StatusCode::BAD_GATEWAY,
"connection error",
"Unable to connect to the",
),
GatewayFailure::Timeout => (StatusCode::GATEWAY_TIMEOUT, "timeout", "The"),
GatewayFailure::Verification => (StatusCode::BAD_GATEWAY, "verification error", "The"),
};
let name = escape_html(provider_name);
let explanation = match kind {
GatewayFailure::Connection => format!("{message} {name} authentication service."),
GatewayFailure::Timeout => {
format!("{message} {name} authentication service did not respond in time.")
}
GatewayFailure::Verification => {
format!("{message} {name} authentication service returned an invalid response.")
}
};
let html = include_str!("../admin/web/error_auth_provider.html")
.replace("{{STATUS}}", &status.as_u16().to_string())
.replace("{{PROVIDER}}", &name)
.replace("{{ERROR}}", label)
.replace("{{MESSAGE}}", &explanation);
let mut response = (status, html).into_response();
response.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/html; charset=utf-8"),
);
response.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static("private, no-store"),
);
response.headers_mut().insert(
"x-content-type-options",
HeaderValue::from_static("nosniff"),
);
response.extensions_mut().insert(AuthenticationResponse);
response
}
#[cfg(test)]
mod tests {
use super::*;
use http_body_util::BodyExt;
#[tokio::test]
async fn one_template_covers_every_provider_and_gateway_failure() {
for name in ["Tinyauth", "Authelia", "authentik", "Future Provider"] {
for (kind, status, description) in [
(
GatewayFailure::Connection,
StatusCode::BAD_GATEWAY,
"connection error",
),
(
GatewayFailure::Verification,
StatusCode::BAD_GATEWAY,
"verification error",
),
(
GatewayFailure::Timeout,
StatusCode::GATEWAY_TIMEOUT,
"timeout",
),
] {
let response = gateway_failure(name, kind);
assert_eq!(response.status(), status);
assert_eq!(
response.headers()[header::CONTENT_TYPE],
"text/html; charset=utf-8"
);
assert_eq!(
response.headers()[header::CACHE_CONTROL],
"private, no-store"
);
assert_eq!(response.headers()["x-content-type-options"], "nosniff");
assert!(response
.extensions()
.get::<AuthenticationResponse>()
.is_some());
let body = response.into_body().collect().await.unwrap().to_bytes();
let html = std::str::from_utf8(&body).unwrap();
assert!(html.contains(&format!("{} - {name} {description}", status.as_u16())));
assert!(
!html.contains("{{")
&& !html.contains("<script")
&& !html.contains("127.0.0.1")
);
}
}
}
#[tokio::test]
async fn provider_name_cannot_inject_html() {
let response = gateway_failure("<script>alert(1)</script>", GatewayFailure::Connection);
let html = String::from_utf8(
response
.into_body()
.collect()
.await
.unwrap()
.to_bytes()
.to_vec(),
)
.unwrap();
assert!(html.contains("&lt;script&gt;"));
assert!(!html.contains("<script>"));
}
#[test]
fn denied_responses_are_marked_and_not_cached() {
let response = deny(StatusCode::UNAUTHORIZED);
assert!(response
.extensions()
.get::<AuthenticationResponse>()
.is_some());
assert_eq!(
response.headers()[header::CACHE_CONTROL],
"private, no-store"
);
}
}
+263
View File
@@ -0,0 +1,263 @@
use crate::{authelia, authentik, config::ValidationPolicy, forwarding, tinyauth};
use anyhow::{ensure, Result};
use axum::{body::Body, response::Response};
use http::{header, HeaderMap, HeaderValue, Method, Request};
use std::{
future::Future,
net::SocketAddr,
pin::Pin,
sync::{Arc, Mutex},
};
use tokio_util::sync::CancellationToken;
pub type Authorization<'a> =
Pin<Box<dyn Future<Output = std::result::Result<Identity, Response>> + Send + 'a>>;
pub type Route<'a> = Pin<Box<dyn Future<Output = Response> + Send + 'a>>;
mod errors;
pub use errors::{deny, gateway_failure, GatewayFailure};
#[derive(Debug, Default)]
pub struct Identity {
pub(crate) headers: HeaderMap,
}
impl Identity {
pub fn apply(&self, headers: &mut HeaderMap) {
for name in self.headers.keys() {
headers.remove(name);
}
for (name, value) in &self.headers {
headers.append(name.clone(), value.clone());
}
}
}
pub trait Provider: Send + Sync + std::fmt::Debug {
fn id(&self) -> &'static str;
fn strip_identity(&self, headers: &mut HeaderMap);
fn authorize<'a>(
&'a self,
incoming: &'a HeaderMap,
method: &'a Method,
context: &'a forwarding::Context,
shutdown: &'a CancellationToken,
cookies: &'a CookieSink,
) -> Authorization<'a>;
fn reserved_path(&self, _path: &str) -> bool {
false
}
fn serve_reserved<'a>(
&'a self,
_request: Request<Body>,
_context: &'a forwarding::Context,
_shutdown: &'a CancellationToken,
) -> Option<Route<'a>> {
None
}
}
#[derive(Debug)]
pub struct Compiled(Box<dyn Provider>);
impl Compiled {
fn new<T: Provider + 'static>(provider: T) -> Self {
Self(Box::new(provider))
}
pub fn id(&self) -> &'static str {
self.0.id()
}
pub fn strip_identity(&self, headers: &mut HeaderMap) {
self.0.strip_identity(headers);
}
pub fn reserved_path(&self, path: &str) -> bool {
self.0.reserved_path(path)
}
pub fn serve_reserved<'a>(
&'a self,
request: Request<Body>,
context: &'a forwarding::Context,
shutdown: &'a CancellationToken,
) -> Option<Route<'a>> {
self.0.serve_reserved(request, context, shutdown)
}
pub async fn authorize(
&self,
incoming: &HeaderMap,
method: &Method,
context: &forwarding::Context,
shutdown: &CancellationToken,
cookies: &CookieSink,
) -> std::result::Result<Identity, Response> {
self.0
.authorize(incoming, method, context, shutdown, cookies)
.await
}
}
pub struct Selection<'a> {
pub basic_enabled: bool,
pub tinyauth: &'a tinyauth::Settings,
pub authelia: &'a authelia::Settings,
pub authentik: &'a authentik::Settings,
}
impl Selection<'_> {
pub fn validate(&self) -> Result<()> {
self.tinyauth.validate()?;
self.authelia.validate()?;
self.authentik.validate()?;
let active = [
self.basic_enabled,
self.tinyauth.enabled,
self.authelia.enabled,
self.authentik.enabled,
];
ensure!(
active.iter().filter(|enabled| **enabled).count() <= 1,
"choose only one authentication provider (Basic, Tinyauth, Authelia or authentik)"
);
Ok(())
}
pub fn compile(
&self,
policy: &ValidationPolicy,
bindings: &[SocketAddr],
) -> Result<Option<Compiled>> {
self.validate()?;
if self.tinyauth.enabled {
return Ok(self.tinyauth.compile(policy, bindings)?.map(Compiled::new));
}
if self.authelia.enabled {
return Ok(self.authelia.compile(policy, bindings)?.map(Compiled::new));
}
if self.authentik.enabled {
return Ok(self.authentik.compile(policy, bindings)?.map(Compiled::new));
}
Ok(None)
}
}
#[derive(Clone)]
pub struct AuthenticationResponse;
#[derive(Clone, Default)]
pub struct CookieSink(Arc<Mutex<Vec<HeaderValue>>>);
impl CookieSink {
pub(crate) fn collect(&self, headers: &HeaderMap) -> bool {
let cookies: Vec<_> = headers
.get_all(header::SET_COOKIE)
.iter()
.cloned()
.collect();
let bytes: usize = cookies.iter().map(|value| value.as_bytes().len()).sum();
if cookies.len() > 8 || bytes > 16384 {
return false;
}
if !cookies.is_empty() {
let mut store = self.0.lock().unwrap_or_else(|poison| poison.into_inner());
if store.len() + cookies.len() > 8
|| store.iter().map(|c| c.as_bytes().len()).sum::<usize>() + bytes > 16384
{
return false;
}
store.extend(cookies);
}
true
}
pub fn apply(&self, response: &mut Response) {
let mut cookies = self.0.lock().unwrap_or_else(|poison| poison.into_inner());
for cookie in cookies.drain(..) {
response.headers_mut().append(header::SET_COOKIE, cookie);
}
}
}
#[cfg(test)]
pub(crate) mod testing;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn legacy_vhost_keys_are_still_accepted_and_no_provider_is_enabled_by_default() {
let host: crate::vhost::Vhost = serde_json::from_value(serde_json::json!({
"id": "test", "frontend": {"hosts": ["app.example.com"], "listener_ids": ["https"]}
}))
.unwrap();
let selection = Selection {
basic_enabled: host.basic_auth.enabled,
tinyauth: &host.tinyauth,
authelia: &host.authelia,
authentik: &host.authentik,
};
assert!(selection.validate().is_ok());
}
#[test]
fn rejects_multiple_active_providers_before_compilation() {
let mut tinyauth = tinyauth::Settings::default();
let mut authelia = authelia::Settings::default();
let authentik = authentik::Settings::default();
tinyauth.enabled = true;
authelia.enabled = true;
let selection = Selection {
basic_enabled: false,
tinyauth: &tinyauth,
authelia: &authelia,
authentik: &authentik,
};
assert!(selection.validate().is_err());
}
#[derive(Debug)]
struct FutureProvider;
impl Provider for FutureProvider {
fn id(&self) -> &'static str {
"future"
}
fn strip_identity(&self, _headers: &mut HeaderMap) {}
fn authorize<'a>(
&'a self,
_incoming: &'a HeaderMap,
_method: &'a Method,
_context: &'a forwarding::Context,
_shutdown: &'a CancellationToken,
_cookies: &'a CookieSink,
) -> Authorization<'a> {
Box::pin(async { Err(deny(http::StatusCode::UNAUTHORIZED)) })
}
}
#[tokio::test]
async fn future_providers_can_use_runtime_interface_without_proxy_branches() {
let provider = Compiled::new(FutureProvider);
assert_eq!(provider.id(), "future");
assert!(!provider.reserved_path("/"));
let headers = HeaderMap::new();
let response = provider
.authorize(
&headers,
&Method::GET,
&testing::context(&headers, "app.example.com"),
&CancellationToken::new(),
&CookieSink::default(),
)
.await
.unwrap_err();
assert_eq!(response.status(), http::StatusCode::UNAUTHORIZED);
assert!(response
.extensions()
.get::<AuthenticationResponse>()
.is_some());
}
#[test]
fn cookie_sink_is_request_scoped_and_bounded() {
let first = CookieSink::default();
let second = CookieSink::default();
let mut headers = HeaderMap::new();
headers.append(header::SET_COOKIE, "session=ok; Path=/".parse().unwrap());
assert!(first.collect(&headers));
let mut resp = Response::new(Body::empty());
second.apply(&mut resp);
assert!(resp.headers().get(header::SET_COOKIE).is_none());
first.apply(&mut resp);
assert_eq!(resp.headers()[header::SET_COOKIE], "session=ok; Path=/");
assert_eq!(first.0.lock().unwrap().len(), 0);
}
}
+55
View File
@@ -0,0 +1,55 @@
use crate::{config::ValidationPolicy, forwarding};
use http::HeaderMap;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
pub(crate) fn policy() -> ValidationPolicy {
ValidationPolicy {
proxy_addr: "127.0.0.1:8080".parse().unwrap(),
admin_addr: "127.0.0.1:9090".parse().unwrap(),
tls_addr: None,
cert_dir: None,
data_dir: None,
}
}
pub(crate) fn context(incoming: &HeaderMap, host: &str) -> forwarding::Context {
forwarding::Settings::default()
.compile()
.unwrap()
.context(
incoming,
"192.0.2.20:34567".parse().unwrap(),
"10.0.0.1:443".parse().unwrap(),
true,
&host.parse().unwrap(),
&"/private?redirect=%2Fhome".parse().unwrap(),
)
.unwrap()
}
pub(crate) async fn spawn_mock(
status: &str,
response_headers: &str,
) -> (String, tokio::task::JoinHandle<String>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let response = format!(
"HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n{response_headers}\r\n"
);
let task = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut bytes = Vec::new();
let mut chunk = [0u8; 4096];
loop {
let n = stream.read(&mut chunk).await.unwrap();
if n == 0 {
break;
}
bytes.extend_from_slice(&chunk[..n]);
if bytes.windows(4).any(|value| value == b"\r\n\r\n") {
break;
}
}
stream.write_all(response.as_bytes()).await.unwrap();
String::from_utf8_lossy(&bytes).into_owned()
});
(format!("http://{address}"), task)
}