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

+221
View File
@@ -0,0 +1,221 @@
use crate::{
auth_provider::{self, CookieSink},
config::ValidationPolicy,
forward_auth, forwarding,
};
use anyhow::Result;
use axum::{body::Body, response::Response};
use http::{header, HeaderMap, HeaderValue, Method, Request, StatusCode, Uri};
use serde::{Deserialize, Serialize};
use std::{
net::SocketAddr,
ops::{Deref, DerefMut},
};
use tokio_util::sync::CancellationToken;
use url::Url;
const OUTPOST_PREFIX: &str = "/outpost.goauthentik.io";
pub fn is_outpost_path(path: &str) -> bool {
path == OUTPOST_PREFIX || path.starts_with("/outpost.goauthentik.io/")
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Settings(forward_auth::Settings);
impl Deref for Settings {
type Target = forward_auth::Settings;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Settings {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Settings {
pub fn validate(&self) -> Result<()> {
self.0.validate::<Adapter>()
}
pub fn compile(
&self,
policy: &ValidationPolicy,
bindings: &[SocketAddr],
) -> Result<Option<Compiled>> {
Ok(self.0.compile::<Adapter>(policy, bindings)?.map(Compiled))
}
}
#[derive(Debug)]
pub struct Compiled(forward_auth::Compiled<Adapter>);
#[derive(Debug)]
pub struct Adapter;
impl forward_auth::Adapter for Adapter {
fn label() -> &'static str {
"authentik"
}
fn verification_path() -> &'static str {
"/outpost.goauthentik.io/auth/nginx"
}
fn denied(
status: StatusCode,
_response_headers: &HeaderMap,
original_url: &str,
_portal: Option<&Url>,
_redirect_forbidden: bool,
) -> std::result::Result<Response, Response> {
if status == StatusCode::UNAUTHORIZED {
let mut location = Url::parse(original_url).map_err(|_| {
forward_auth::invalid("authentik", "invalid original URL for authentik")
})?;
location.set_path("/outpost.goauthentik.io/start");
location.set_query(None);
location.query_pairs_mut().append_pair("rd", original_url);
let mut response = forward_auth::fail(StatusCode::FOUND);
response.headers_mut().insert(
header::LOCATION,
HeaderValue::from_str(location.as_str()).map_err(|_| {
forward_auth::invalid("authentik", "invalid authentik redirect")
})?,
);
Ok(response)
} else if status == StatusCode::FORBIDDEN {
Ok(forward_auth::fail(status))
} else {
Err(forward_auth::invalid(
"authentik",
"authentik returned an unexpected verifier status",
))
}
}
}
impl auth_provider::Provider for Compiled {
fn id(&self) -> &'static str {
"authentik"
}
fn strip_identity(&self, headers: &mut HeaderMap) {
self.0.strip_identity(headers);
}
fn authorize<'a>(
&'a self,
incoming: &'a HeaderMap,
method: &'a Method,
context: &'a forwarding::Context,
shutdown: &'a CancellationToken,
cookies: &'a CookieSink,
) -> auth_provider::Authorization<'a> {
Box::pin(
self.0
.authorize(incoming, method, context, shutdown, cookies),
)
}
fn reserved_path(&self, path: &str) -> bool {
is_outpost_path(path)
}
fn serve_reserved<'a>(
&'a self,
request: Request<Body>,
context: &'a forwarding::Context,
shutdown: &'a CancellationToken,
) -> Option<auth_provider::Route<'a>> {
if !is_outpost_path(request.uri().path()) {
return None;
}
Some(Box::pin(self.proxy_outpost(request, context, shutdown)))
}
}
impl Compiled {
async fn proxy_outpost(
&self,
incoming: Request<Body>,
context: &forwarding::Context,
shutdown: &CancellationToken,
) -> Response {
if !is_outpost_path(incoming.uri().path()) {
return forward_auth::fail(StatusCode::NOT_FOUND);
}
if incoming.method() != Method::GET
&& incoming.method() != Method::HEAD
&& incoming.method() != Method::POST
{
return forward_auth::fail(StatusCode::METHOD_NOT_ALLOWED);
}
let (parts, body) = incoming.into_parts();
let suffix = parts
.uri
.path_and_query()
.map(|value| value.as_str())
.unwrap_or(OUTPOST_PREFIX);
let uri: Uri = match format!("{}{}", self.0.backend.request_origin, suffix).parse() {
Ok(uri) => uri,
Err(_) => return forward_auth::fail(StatusCode::BAD_REQUEST),
};
let mut outbound = match Request::builder()
.method(parts.method.clone())
.uri(uri)
.body(body)
{
Ok(request) => request,
Err(_) => return forward_auth::fail(StatusCode::BAD_REQUEST),
};
*outbound.headers_mut() = parts.headers;
crate::proxy::headers::strip_hop_by_hop(outbound.headers_mut());
crate::proxy::headers::strip_admin_cookie(outbound.headers_mut());
self.0.strip_identity(outbound.headers_mut());
if forward_auth::auth_context(outbound.headers_mut(), &parts.method, context).is_err() {
return forward_auth::fail(StatusCode::BAD_REQUEST);
}
let original_host = match Url::parse(&context.original_url) {
Ok(url) => url,
Err(_) => return forward_auth::fail(StatusCode::BAD_REQUEST),
};
let host = match original_host.port() {
Some(port) => format!("{}:{port}", original_host.host_str().unwrap_or("")),
None => original_host.host_str().unwrap_or("").to_owned(),
};
if host.is_empty() {
return forward_auth::fail(StatusCode::BAD_REQUEST);
}
if let Ok(host) = host.parse::<HeaderValue>() {
outbound.headers_mut().insert(header::HOST, host);
} else {
return forward_auth::fail(StatusCode::BAD_REQUEST);
}
let checked = tokio::select! {
_ = shutdown.cancelled() => return forward_auth::fail(StatusCode::SERVICE_UNAVAILABLE),
result = tokio::time::timeout(self.0.timeout, self.0.backend.client.request(outbound)) => result,
};
let response = match checked {
Ok(Ok(response)) => response,
Ok(Err(error)) => {
tracing::warn!(%error, "authentik outpost connection failed");
return auth_provider::gateway_failure(
"authentik",
auth_provider::GatewayFailure::Connection,
);
}
Err(_) => {
return auth_provider::gateway_failure(
"authentik",
auth_provider::GatewayFailure::Timeout,
)
}
};
let (parts, body) = response.into_parts();
let mut response = Response::new(Body::new(body));
*response.status_mut() = parts.status;
*response.headers_mut() = parts.headers;
crate::proxy::headers::strip_hop_by_hop(response.headers_mut());
response.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static("private, no-store"),
);
response
.extensions_mut()
.insert(auth_provider::AuthenticationResponse);
response
}
}
#[cfg(test)]
include!("tests.rs");
+176
View File
@@ -0,0 +1,176 @@
mod tests {
use super::*;
use crate::auth_provider::{
testing::{context, policy, spawn_mock},
Provider,
};
fn settings(url: &str) -> Settings {
let mut settings = Settings::default();
settings.enabled = true;
settings.url = url.into();
settings.allow_private = true;
settings
}
fn compile(url: &str) -> Compiled {
settings(url).compile(&policy(), &[]).unwrap().unwrap()
}
#[test]
fn legacy_json_and_provider_path_contract_are_preserved() {
let parsed: Settings = serde_json::from_str(
r#"{"enabled":true,"url":"http://127.0.0.1:9300","allow_private":true}"#,
)
.unwrap();
assert_eq!(
serde_json::to_value(&parsed).unwrap()["url"],
"http://127.0.0.1:9300"
);
let auth = compile("http://127.0.0.1:9300");
assert_eq!(auth.id(), "authentik");
assert!(auth.reserved_path("/outpost.goauthentik.io"));
assert!(auth.reserved_path("/outpost.goauthentik.io/start"));
assert!(!auth.reserved_path("/outpost.goauthentik.io-evil"));
assert!(!auth.reserved_path("/other/outpost.goauthentik.io"));
}
#[tokio::test]
async fn unauthorized_redirect_uses_application_domain_not_portal_domain() {
let (url, server) = spawn_mock(
"401 Unauthorized",
"Set-Cookie: authentik_session=abc; Secure; Path=/; HttpOnly\r\n",
)
.await;
let auth = compile(&url);
let incoming = HeaderMap::new();
let response = auth
.authorize(
&incoming,
&Method::POST,
&context(&incoming, "app.other-domain.example"),
&CancellationToken::new(),
&CookieSink::default(),
)
.await
.unwrap_err();
assert_eq!(response.status(), StatusCode::FOUND);
let location = Url::parse(response.headers()[header::LOCATION].to_str().unwrap()).unwrap();
assert_eq!(
location.origin().ascii_serialization(),
"https://app.other-domain.example"
);
assert_eq!(location.path(), "/outpost.goauthentik.io/start");
assert_eq!(
location.query_pairs().find(|(k, _)| k == "rd").unwrap().1,
"https://app.other-domain.example/private?redirect=%2Fhome"
);
assert_eq!(
response.headers()[header::SET_COOKIE],
"authentik_session=abc; Secure; Path=/; HttpOnly"
);
server.await.unwrap();
}
#[tokio::test]
async fn forbidden_response_never_authorizes_backend() {
let (url, server) = spawn_mock("403 Forbidden", "").await;
let auth = compile(&url);
let incoming = HeaderMap::new();
let response = auth
.authorize(
&incoming,
&Method::GET,
&context(&incoming, "app.example.com"),
&CancellationToken::new(),
&CookieSink::default(),
)
.await
.unwrap_err();
assert_eq!(response.status(), StatusCode::FORBIDDEN);
server.await.unwrap();
}
#[tokio::test]
async fn verified_headers_and_refresh_cookie_are_forwarded() {
let (url, server) = spawn_mock("200 OK", "X-Authentik-Username: allowed\r\nSet-Cookie: authentik_session=renew; Path=/; HttpOnly\r\n").await;
let auth = compile(&url);
let incoming = HeaderMap::new();
let cookies = CookieSink::default();
let identity = auth
.authorize(
&incoming,
&Method::GET,
&context(&incoming, "app.example.com"),
&CancellationToken::new(),
&cookies,
)
.await
.unwrap();
let mut headers = HeaderMap::new();
identity.apply(&mut headers);
assert_eq!(headers["x-authentik-username"], "allowed");
let mut response = Response::new(Body::empty());
cookies.apply(&mut response);
assert_eq!(
response.headers()[header::SET_COOKIE],
"authentik_session=renew; Path=/; HttpOnly"
);
server.await.unwrap();
}
#[tokio::test]
async fn outpost_is_proxied_only_on_reserved_path_with_trusted_host() {
let (url, server) = spawn_mock("302 Found", "Location: https://auth.example.com/if/flow/default/\r\nSet-Cookie: authentik=ok; Path=/\r\n").await;
let auth = compile(&url);
let incoming = HeaderMap::new();
let request = Request::builder()
.uri("/outpost.goauthentik.io/start?rd=https%3A%2F%2Fapp.example.com")
.header("X-Forwarded-Host", "spoofed.example")
.header("X-Authentik-Username", "forged")
.body(Body::empty())
.unwrap();
let response = auth
.serve_reserved(
request,
&context(&incoming, "app.example.com"),
&CancellationToken::new(),
)
.unwrap()
.await;
assert_eq!(response.status(), StatusCode::FOUND);
assert_eq!(
response.headers()[header::SET_COOKIE],
"authentik=ok; Path=/"
);
assert_eq!(
response.headers()[header::CACHE_CONTROL],
"private, no-store"
);
let request = server.await.unwrap().to_ascii_lowercase();
assert!(request.starts_with("get /outpost.goauthentik.io/start?rd="));
assert!(request.contains("host: app.example.com"));
assert!(request.contains("x-forwarded-host: app.example.com"));
assert!(!request.contains("spoofed.example"));
assert!(!request.contains("x-authentik-username: forged"));
}
#[tokio::test]
async fn auth_check_uses_provider_specific_endpoint() {
let (url, server) = spawn_mock("200 OK", "X-Authentik-Username: admin\r\n").await;
let auth = compile(&url);
let incoming = HeaderMap::new();
let identity = auth
.authorize(
&incoming,
&Method::GET,
&context(&incoming, "app.example.com"),
&CancellationToken::new(),
&CookieSink::default(),
)
.await
.unwrap();
let mut headers = HeaderMap::new();
identity.apply(&mut headers);
assert_eq!(headers["x-authentik-username"], "admin");
assert!(server
.await
.unwrap()
.to_ascii_lowercase()
.contains("get /outpost.goauthentik.io/auth/nginx"));
}
}