0.34.6_repo_cleanup
This commit is contained in:
1 parent
ce1a90397c
commit
133d2f0f91
273 files changed
+5969
-6926
No files matched your search
@@ -0,0 +1,387 @@
|
||||
use crate::{
|
||||
config::{Backend, CompiledBackend, UpstreamProtocol, ValidationPolicy},
|
||||
forwarding,
|
||||
};
|
||||
use anyhow::{ensure, Context as _, Result};
|
||||
use axum::{
|
||||
body::Body,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode, Uri};
|
||||
use http_body_util::{BodyExt, Limited};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{net::SocketAddr, sync::Arc, time::Duration};
|
||||
use url::Url;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Settings {
|
||||
pub enabled: bool,
|
||||
pub url: String,
|
||||
pub login_url: String,
|
||||
pub allow_private: bool,
|
||||
pub address_allowlist: Vec<String>,
|
||||
pub tls_ca_pem: Option<String>,
|
||||
pub connect_timeout_seconds: u64,
|
||||
pub timeout_seconds: u64,
|
||||
pub request_headers: Vec<String>,
|
||||
pub response_headers: Vec<String>,
|
||||
pub redirect_forbidden: bool,
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
url: String::new(),
|
||||
login_url: String::new(),
|
||||
allow_private: false,
|
||||
address_allowlist: Vec::new(),
|
||||
tls_ca_pem: None,
|
||||
connect_timeout_seconds: 5,
|
||||
timeout_seconds: 10,
|
||||
request_headers: vec![
|
||||
"cookie".into(),
|
||||
"authorization".into(),
|
||||
"x-api-key".into(),
|
||||
"user-agent".into(),
|
||||
"accept".into(),
|
||||
],
|
||||
response_headers: vec!["remote-user".into(), "remote-email".into()],
|
||||
redirect_forbidden: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct Compiled {
|
||||
backend: Arc<CompiledBackend>,
|
||||
uri: Uri,
|
||||
login: Url,
|
||||
timeout: Duration,
|
||||
request_headers: Vec<HeaderName>,
|
||||
response_headers: Vec<HeaderName>,
|
||||
redirect_forbidden: bool,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct AuthenticationFailure;
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Identity {
|
||||
headers: HeaderMap,
|
||||
}
|
||||
const STANDARD_IDENTITY: [&str; 6] = [
|
||||
"remote-user",
|
||||
"remote-email",
|
||||
"remote-name",
|
||||
"remote-groups",
|
||||
"remote-sub",
|
||||
"x-auth-request-user",
|
||||
];
|
||||
fn identity_header(name: &HeaderName) -> bool {
|
||||
let name = name.as_str();
|
||||
(name.starts_with("remote-") || name.starts_with("x-"))
|
||||
&& !name.starts_with("x-forwarded-")
|
||||
&& !name.starts_with("x-original-")
|
||||
&& !matches!(name, "x-real-ip" | "x-request-id" | "x-api-key")
|
||||
}
|
||||
fn http_url(value: &str) -> Result<Url> {
|
||||
ensure!(
|
||||
!value.is_empty() && value.len() <= 2048,
|
||||
"Tinyauth URL must contain 1..2048 bytes"
|
||||
);
|
||||
let url = Url::parse(value)?;
|
||||
ensure!(
|
||||
matches!(url.scheme(), "http" | "https") && url.host_str().is_some(),
|
||||
"Tinyauth requires an HTTP(S) URL"
|
||||
);
|
||||
ensure!(
|
||||
url.username().is_empty() && url.password().is_none() && url.fragment().is_none(),
|
||||
"Tinyauth URL cannot contain credentials or fragments"
|
||||
);
|
||||
Ok(url)
|
||||
}
|
||||
impl Settings {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
(1..=30).contains(&self.connect_timeout_seconds)
|
||||
&& (1..=60).contains(&self.timeout_seconds)
|
||||
&& self.connect_timeout_seconds <= self.timeout_seconds,
|
||||
"Tinyauth timeouts require 1..30s connect <= 1..60s total"
|
||||
);
|
||||
ensure!(
|
||||
self.request_headers.len() <= 32 && self.response_headers.len() <= 32,
|
||||
"at most 32 Tinyauth header names per direction"
|
||||
);
|
||||
for raw in &self.request_headers {
|
||||
ensure!(raw.len() <= 128, "Tinyauth header name exceeds 128 bytes");
|
||||
let name: HeaderName = raw.parse()?;
|
||||
ensure!(
|
||||
matches!(
|
||||
name.as_str(),
|
||||
"cookie" | "authorization" | "user-agent" | "accept" | "accept-language"
|
||||
) || (name.as_str().starts_with("x-") && identity_header(&name))
|
||||
|| name == "x-api-key",
|
||||
"unsafe Tinyauth request header: {name}"
|
||||
);
|
||||
}
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for raw in &self.response_headers {
|
||||
ensure!(raw.len() <= 128, "Tinyauth header name exceeds 128 bytes");
|
||||
let name: HeaderName = raw.parse()?;
|
||||
ensure!(
|
||||
identity_header(&name) && names.insert(name),
|
||||
"Tinyauth response headers must be unique Remote-* or safe X-* names"
|
||||
);
|
||||
}
|
||||
if self.enabled {
|
||||
let auth = http_url(&self.url)?;
|
||||
ensure!(
|
||||
auth.query().is_none(),
|
||||
"Tinyauth verification URL cannot include a query"
|
||||
);
|
||||
let login = http_url(&self.login_url)?;
|
||||
ensure!(
|
||||
login.scheme() == "https"
|
||||
|| login.host_str().is_some_and(|host| host == "localhost"
|
||||
|| host
|
||||
.trim_matches(['[', ']'])
|
||||
.parse::<std::net::IpAddr>()
|
||||
.is_ok_and(|ip| ip.is_loopback())),
|
||||
"public Tinyauth login URL must use HTTPS"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn compile(
|
||||
&self,
|
||||
policy: &ValidationPolicy,
|
||||
bindings: &[SocketAddr],
|
||||
) -> Result<Option<Compiled>> {
|
||||
self.validate()?;
|
||||
if !self.enabled {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut endpoint = http_url(&self.url)?;
|
||||
if endpoint.path() == "/" {
|
||||
endpoint.set_path("/api/auth/nginx");
|
||||
}
|
||||
let uri = endpoint.as_str().parse()?;
|
||||
let origin = endpoint.origin().ascii_serialization();
|
||||
let definition = Backend {
|
||||
id: "tinyauth".into(),
|
||||
url: origin,
|
||||
allow_private: self.allow_private,
|
||||
accept_local_listener_risk: false,
|
||||
preserve_host: false,
|
||||
protocol: UpstreamProtocol::Http1,
|
||||
address_allowlist: self.address_allowlist.clone(),
|
||||
tls_ca_pem: self.tls_ca_pem.clone(),
|
||||
tls_server_name: None,
|
||||
tls_verify: true,
|
||||
};
|
||||
let keepalive = crate::balance::Keepalive::default();
|
||||
let mut backend =
|
||||
crate::config::compile_backend(&definition, policy, bindings, &keepalive)?;
|
||||
backend.client = crate::upstream::client_with_timeout(
|
||||
&definition,
|
||||
backend.address_policy.clone(),
|
||||
false,
|
||||
&keepalive,
|
||||
Duration::from_secs(self.connect_timeout_seconds),
|
||||
)?;
|
||||
Ok(Some(Compiled {
|
||||
backend: Arc::new(backend),
|
||||
uri,
|
||||
login: http_url(&self.login_url)?,
|
||||
timeout: Duration::from_secs(self.timeout_seconds),
|
||||
request_headers: self
|
||||
.request_headers
|
||||
.iter()
|
||||
.map(|s| s.parse())
|
||||
.collect::<std::result::Result<_, _>>()?,
|
||||
response_headers: self
|
||||
.response_headers
|
||||
.iter()
|
||||
.map(|s| s.parse())
|
||||
.collect::<std::result::Result<_, _>>()?,
|
||||
redirect_forbidden: self.redirect_forbidden,
|
||||
}))
|
||||
}
|
||||
}
|
||||
fn failure(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(
|
||||
"cache-control",
|
||||
HeaderValue::from_static("private, no-store"),
|
||||
);
|
||||
response.extensions_mut().insert(AuthenticationFailure);
|
||||
response
|
||||
}
|
||||
impl Compiled {
|
||||
pub fn strip_identity(&self, headers: &mut HeaderMap) {
|
||||
let names: Vec<_> = headers
|
||||
.keys()
|
||||
.filter(|name| name.as_str().starts_with("remote-"))
|
||||
.cloned()
|
||||
.collect();
|
||||
for name in names {
|
||||
headers.remove(name);
|
||||
}
|
||||
for name in STANDARD_IDENTITY {
|
||||
headers.remove(name);
|
||||
}
|
||||
for name in &self.response_headers {
|
||||
headers.remove(name);
|
||||
}
|
||||
}
|
||||
fn redirect(
|
||||
&self,
|
||||
raw: Option<&HeaderValue>,
|
||||
original_url: &str,
|
||||
fallback: bool,
|
||||
) -> Option<HeaderValue> {
|
||||
let target = raw
|
||||
.and_then(|raw| raw.to_str().ok())
|
||||
.filter(|s| s.len() <= 8192)
|
||||
.and_then(|raw| {
|
||||
if raw.starts_with('/') && !raw.starts_with("//") {
|
||||
self.login.join(raw).ok()
|
||||
} else {
|
||||
Url::parse(raw).ok()
|
||||
}
|
||||
})
|
||||
.filter(|target| {
|
||||
target.origin() == self.login.origin()
|
||||
&& target.username().is_empty()
|
||||
&& target.password().is_none()
|
||||
&& target.fragment().is_none()
|
||||
});
|
||||
let target = target.or_else(|| {
|
||||
fallback.then(|| {
|
||||
let mut target = self.login.clone();
|
||||
let existing: Vec<_> = target
|
||||
.query_pairs()
|
||||
.filter(|(key, _)| key != "redirect_uri")
|
||||
.map(|(k, v)| (k.into_owned(), v.into_owned()))
|
||||
.collect();
|
||||
target.set_query(None);
|
||||
target
|
||||
.query_pairs_mut()
|
||||
.extend_pairs(existing)
|
||||
.append_pair("redirect_uri", original_url);
|
||||
target
|
||||
})
|
||||
})?;
|
||||
target.as_str().parse().ok()
|
||||
}
|
||||
pub async fn authorize(
|
||||
&self,
|
||||
incoming: &HeaderMap,
|
||||
method: &Method,
|
||||
context: &forwarding::Context,
|
||||
shutdown: &tokio_util::sync::CancellationToken,
|
||||
) -> std::result::Result<Identity, Response> {
|
||||
let result = tokio::select! {
|
||||
_=shutdown.cancelled()=>return Err(failure(StatusCode::SERVICE_UNAVAILABLE)),
|
||||
result=tokio::time::timeout(self.timeout,self.check(incoming,method,context))=>result,
|
||||
};
|
||||
let (status, headers) = match result {
|
||||
Ok(Ok(value)) => value,
|
||||
Ok(Err(error)) => {
|
||||
tracing::debug!(%error,"Tinyauth verification failed");
|
||||
return Err(failure(StatusCode::BAD_GATEWAY));
|
||||
}
|
||||
Err(_) => return Err(failure(StatusCode::GATEWAY_TIMEOUT)),
|
||||
};
|
||||
if status.is_success() {
|
||||
let mut identity = Identity::default();
|
||||
let mut size = 0;
|
||||
for name in &self.response_headers {
|
||||
for value in headers.get_all(name) {
|
||||
size += value.as_bytes().len();
|
||||
if size > 8192 {
|
||||
return Err(failure(StatusCode::BAD_GATEWAY));
|
||||
}
|
||||
identity.headers.append(name.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
return Ok(identity);
|
||||
}
|
||||
if status == StatusCode::UNAUTHORIZED
|
||||
|| (status == StatusCode::FORBIDDEN && self.redirect_forbidden)
|
||||
{
|
||||
if let Some(location) = self.redirect(
|
||||
headers.get("x-tinyauth-location"),
|
||||
&context.original_url,
|
||||
status == StatusCode::UNAUTHORIZED,
|
||||
) {
|
||||
let mut response = failure(StatusCode::FOUND);
|
||||
response.headers_mut().insert("location", location);
|
||||
return Err(response);
|
||||
}
|
||||
}
|
||||
Err(failure(if status == StatusCode::FORBIDDEN {
|
||||
StatusCode::FORBIDDEN
|
||||
} else if status == StatusCode::UNAUTHORIZED {
|
||||
StatusCode::UNAUTHORIZED
|
||||
} else {
|
||||
StatusCode::BAD_GATEWAY
|
||||
}))
|
||||
}
|
||||
async fn check(
|
||||
&self,
|
||||
incoming: &HeaderMap,
|
||||
method: &Method,
|
||||
context: &forwarding::Context,
|
||||
) -> Result<(StatusCode, HeaderMap)> {
|
||||
let mut request = Request::builder()
|
||||
.method(Method::GET)
|
||||
.uri(self.uri.clone())
|
||||
.body(Body::empty())?;
|
||||
for name in &self.request_headers {
|
||||
for value in incoming.get_all(name) {
|
||||
request.headers_mut().append(name.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
crate::proxy::headers::strip_hop_by_hop(request.headers_mut());
|
||||
crate::proxy::headers::strip_admin_cookie(request.headers_mut());
|
||||
self.strip_identity(request.headers_mut());
|
||||
context.apply(request.headers_mut());
|
||||
request
|
||||
.headers_mut()
|
||||
.insert("host", self.backend.host_header.clone());
|
||||
request
|
||||
.headers_mut()
|
||||
.insert("x-original-url", context.original_url.parse()?);
|
||||
request
|
||||
.headers_mut()
|
||||
.insert("x-original-method", method.as_str().parse()?);
|
||||
let response = self
|
||||
.backend
|
||||
.client
|
||||
.request(request)
|
||||
.await
|
||||
.context("Tinyauth request failed")?;
|
||||
let (parts, body) = response.into_parts();
|
||||
Limited::new(body, 16 * 1024)
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Tinyauth response body: {e}"))?;
|
||||
Ok((parts.status, parts.headers))
|
||||
}
|
||||
}
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
include!("tests.rs");
|
||||
Reference in new issue
Block a user