[core] Schema: reject wildcard header names, cap file size and upstreams, require <hostname>.toml

This commit is contained in:
2026-11-07 15:44:09 +01:00
parent 58d0397875
commit 60aee5d78a
11 changed files with 221 additions and 59 deletions
+4 -2
View File
@@ -10,7 +10,7 @@
use serde_json::{Map, Value, json};
use super::{CompileOptions, join};
use super::{CompileOptions, join, strip_headers};
use crate::{
AccessLog, AuthMode, ForwardAuth, HeaderRule, HeaderValue, Host, Model, Scheme, TlsMode,
Upstream,
@@ -204,11 +204,13 @@ fn logging(file: &str) -> Value {
fn host_route(h: &Host, fa: Option<&ForwardAuth>, o: &CompileOptions) -> Value {
let mut steps = Vec::new();
if let (AuthMode::ForwardAuth, Some(fa)) = (h.auth, fa) {
// Client-sent identity headers never reach the auth server or the upstream.
steps.push(json!({ "handle": [{ "handler": "headers", "request": { "delete": strip_headers(fa) } }] }));
steps.push(json!({ "handle": [forward_auth(fa)] }));
}
if !h.websockets {
steps.push(json!({
"match": [{ "header_regexp": { "Upgrade": { "pattern": "(?i)^websocket$" } } }],
"match": [{ "header_regexp": { "Upgrade": { "pattern": "(?i)(^|,)\\s*websocket\\s*(,|$)" } } }],
"handle": [{ "handler": "static_response", "status_code": 403 }]
}));
}
+2 -1
View File
@@ -4,7 +4,7 @@
//! Model → [`EdgeConfig`] for the Pingora data plane.
use super::{CompileOptions, join};
use super::{CompileOptions, join, strip_headers};
use crate::edge_config::{
EDGE_CONFIG_VERSION, EdgeAcme, EdgeConfig, EdgeForwardAuth, EdgeHeaderOp, EdgeHealthCheck,
EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
@@ -30,6 +30,7 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig {
upstream: upstream(&fa.upstream),
path_and_query: fa.path_and_query.clone(),
copy_headers: fa.copy_headers.clone(),
strip_headers: strip_headers(fa),
}),
hosts: model
.hosts()
+15
View File
@@ -108,6 +108,21 @@ fn check_path(p: &str) -> Result<(), &'static str> {
Ok(())
}
/// Identity headers never accepted from clients on forward-auth hosts: Authelia's four, then
/// any other configured copy header (case-insensitive, no duplicates).
fn strip_headers(fa: &crate::ForwardAuth) -> Vec<String> {
let mut out: Vec<String> = crate::AUTHELIA_COPY_HEADERS
.iter()
.map(|h| (*h).to_owned())
.collect();
for h in &fa.copy_headers {
if !out.iter().any(|o| o.eq_ignore_ascii_case(h)) {
out.push(h.clone());
}
}
out
}
/// Join a validated directory and a validated file name.
fn join(dir: &str, file: &str) -> String {
format!("{}/{}", dir.trim_end_matches('/'), file)
+3
View File
@@ -46,6 +46,9 @@ pub struct EdgeForwardAuth {
pub upstream: EdgeUpstream,
pub path_and_query: String,
pub copy_headers: Vec<String>,
/// Removed from every client request on a forward-auth host before the auth check:
/// Authelia's four identity headers plus the copy headers.
pub strip_headers: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+6
View File
@@ -24,6 +24,12 @@ pub enum ValidationError {
InvalidValue { file: String, message: String },
#[error("{file} appears twice in the routes")]
DuplicateFile { file: String },
#[error("{file} is larger than {max} bytes")]
FileTooLarge { file: String, max: usize },
#[error("{file} must be named after its hostname: {hostname}.toml")]
FileNameMismatch { file: String, hostname: String },
#[error("{file}: at most {max} upstreams per host")]
TooManyUpstreams { file: String, max: usize },
#[error("{file}: `{hostname}` is not a valid hostname: {reason}")]
InvalidHostname {
file: String,
+4
View File
@@ -221,6 +221,10 @@ impl Model {
pub const LETSENCRYPT_PRODUCTION: &str = "https://acme-v02.api.letsencrypt.org/directory";
/// Let's Encrypt staging directory.
pub const LETSENCRYPT_STAGING: &str = "https://acme-staging-v02.api.letsencrypt.org/directory";
/// Largest route file accepted (site or host).
pub const MAX_FILE_BYTES: usize = 1 << 20;
/// Most upstreams one host may list.
pub const MAX_UPSTREAMS: usize = 64;
/// Identity headers Authelia returns on success (Authelia's Caddy integration guide).
pub const AUTHELIA_COPY_HEADERS: [&str; 4] = [
"Remote-User",
+53 -25
View File
@@ -14,8 +14,8 @@ use serde::de::DeserializeOwned;
use crate::error::{ValidationError as E, ValidationErrors};
use crate::model::{
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, Model, Scheme, SecretName, Site, TlsMode,
Upstream, UpstreamHost,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model,
Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost,
};
/// One route file handed in by the caller (core does no I/O).
@@ -192,6 +192,12 @@ pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result<Model, Va
fn parse<T: DeserializeOwned>(f: &SourceFile<'_>) -> Result<T, E> {
let file = f.name.to_owned();
if f.contents.len() > MAX_FILE_BYTES {
return Err(E::FileTooLarge {
file,
max: MAX_FILE_BYTES,
});
}
// A plain table parse first tells syntax errors apart from schema errors.
if let Err(e) = toml::from_str::<toml::Table>(f.contents) {
return Err(E::Syntax {
@@ -362,28 +368,45 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
let before = errors.len();
let f = || file.to_owned();
if let Err(reason) = check_hostname(&raw.hostname) {
errors.push(E::InvalidHostname {
match check_hostname(&raw.hostname) {
Err(reason) => errors.push(E::InvalidHostname {
file: f(),
hostname: raw.hostname.clone(),
reason,
});
}),
Ok(()) => {
// One TOML per host, named after it: `hosts/<hostname>.toml`.
let base = file.rsplit(['/', '\\']).next().unwrap_or(file);
if base != format!("{}.toml", raw.hostname) {
errors.push(E::FileNameMismatch {
file: f(),
hostname: raw.hostname.clone(),
});
}
}
}
if raw.upstreams.is_empty() {
errors.push(E::NoUpstreams { file: f() });
}
if raw.upstreams.len() > MAX_UPSTREAMS {
errors.push(E::TooManyUpstreams {
file: f(),
max: MAX_UPSTREAMS,
});
}
let mut upstreams: Vec<Upstream> = Vec::new();
for u in &raw.upstreams {
let mut seen_upstreams = BTreeSet::new();
for u in raw.upstreams.iter().take(MAX_UPSTREAMS) {
match parse_url(u, false) {
Ok((up, _)) => {
if upstreams.contains(&up) {
if seen_upstreams.insert(up.clone()) {
upstreams.push(up);
} else {
errors.push(E::DuplicateUpstream {
file: f(),
url: u.clone(),
});
} else {
upstreams.push(up);
}
}
Err(reason) => errors.push(E::BadUpstreamUrl {
@@ -410,18 +433,22 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
errors.push(E::ForwardAuthNotConfigured { file: f() });
}
// Identity headers set by forward-auth must not be overridable by a rule.
let identity: Vec<String> = match (auth, site.and_then(|s| s.forward_auth.as_ref())) {
(AuthMode::ForwardAuth, Some(fa)) => fa
.copy_headers
.iter()
.map(|h| h.to_ascii_lowercase())
.collect(),
(AuthMode::ForwardAuth, None) => AUTHELIA_COPY_HEADERS
.iter()
.map(|h| h.to_ascii_lowercase())
.collect(),
_ => Vec::new(),
// Identity headers (Authelia's four, plus any configured copy header) must not be
// overridable by a rule on a forward-auth host.
let identity: Vec<String> = match auth {
AuthMode::ForwardAuth => {
let extra = site
.and_then(|s| s.forward_auth.as_ref())
.map(|fa| fa.copy_headers.clone())
.unwrap_or_default();
AUTHELIA_COPY_HEADERS
.iter()
.map(|h| (*h).to_owned())
.chain(extra)
.map(|h| h.to_ascii_lowercase())
.collect()
}
AuthMode::None => Vec::new(),
};
let request_headers = check_rules(file, raw.request_headers, true, &identity, site, errors);
let response_headers = check_rules(file, raw.response_headers, false, &[], site, errors);
@@ -433,10 +460,10 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
&& hc
.path
.bytes()
.all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}');
.all(|c| c.is_ascii_graphic() && !b"{}#".contains(&c));
if !ok_path {
errors.push(bad(
"path must start with '/' and contain only visible ASCII without '{' or '}'",
"path must start with '/' and contain only visible ASCII without '{', '}' or '#'",
));
return None;
}
@@ -570,12 +597,13 @@ fn check_rules(
out
}
/// RFC 9110 token.
/// RFC 9110 token minus `*`, which is a wildcard in Caddy's header operations but a literal
/// character in edge; allowing it would let the engines disagree.
fn valid_header_name(n: &str) -> bool {
!n.is_empty()
&& n.len() <= 256
&& n.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&c))
.all(|c| c.is_ascii_alphanumeric() || b"!#$%&'+-.^_`|~".contains(&c))
}
fn check_header_value(v: &str) -> Result<(), &'static str> {
+41 -10
View File
@@ -223,26 +223,57 @@ fn forward_auth_hosts_strip_client_identity_headers_in_both_engines() {
let m = model(false);
let edge: EdgeConfig = serde_json::from_str(&compile::edge(&m, &options()).unwrap()).unwrap();
let strip = edge.forward_auth.unwrap().strip_headers;
for h in ["Remote-User", "Remote-Groups", "Remote-Email", "Remote-Name"] {
assert!(strip.iter().any(|s| s.eq_ignore_ascii_case(h)), "edge strips {h}");
for h in [
"Remote-User",
"Remote-Groups",
"Remote-Email",
"Remote-Name",
] {
assert!(
strip.iter().any(|s| s.eq_ignore_ascii_case(h)),
"edge strips {h}"
);
}
let caddy = compile::caddy(&m, &options()).unwrap();
let v: serde_json::Value = serde_json::from_str(&caddy).unwrap();
let routes = v["apps"]["http"]["servers"]["ianitor_https"]["routes"].as_array().unwrap();
let wiki = routes.iter().find(|r| r["match"][0]["host"][0] == "wiki.home.test").unwrap();
let routes = v["apps"]["http"]["servers"]["ianitor_https"]["routes"]
.as_array()
.unwrap();
let wiki = routes
.iter()
.find(|r| r["match"][0]["host"][0] == "wiki.home.test")
.unwrap();
let steps = wiki["handle"][0]["routes"].as_array().unwrap();
let first = &steps[0]["handle"][0];
assert_eq!(first["handler"], "headers", "identity headers are deleted before forward_auth");
let deleted: Vec<&str> =
first["request"]["delete"].as_array().unwrap().iter().map(|d| d.as_str().unwrap()).collect();
for h in ["Remote-User", "Remote-Groups", "Remote-Email", "Remote-Name"] {
assert_eq!(
first["handler"], "headers",
"identity headers are deleted before forward_auth"
);
let deleted: Vec<&str> = first["request"]["delete"]
.as_array()
.unwrap()
.iter()
.map(|d| d.as_str().unwrap())
.collect();
for h in [
"Remote-User",
"Remote-Groups",
"Remote-Email",
"Remote-Name",
] {
assert!(deleted.contains(&h), "caddy deletes {h}: {deleted:?}");
}
assert_eq!(steps[1]["handle"][0]["handler"], "reverse_proxy", "then forward_auth");
assert_eq!(
steps[1]["handle"][0]["handler"], "reverse_proxy",
"then forward_auth"
);
}
#[test]
fn websocket_refusal_in_caddy_matches_any_upgrade_token() {
let caddy = compile::caddy(&model(false), &options()).unwrap();
assert!(caddy.contains(r#"(?i)(^|,)\\s*websocket\\s*(,|$)"#), "token-aware Upgrade matcher");
assert!(
caddy.contains(r#"(?i)(^|,)\\s*websocket\\s*(,|$)"#),
"token-aware Upgrade matcher"
);
}
+16 -1
View File
@@ -179,6 +179,21 @@
{
"handler": "subroute",
"routes": [
{
"handle": [
{
"handler": "headers",
"request": {
"delete": [
"Remote-User",
"Remote-Groups",
"Remote-Email",
"Remote-Name"
]
}
}
]
},
{
"handle": [
{
@@ -392,7 +407,7 @@
{
"header_regexp": {
"Upgrade": {
"pattern": "(?i)^websocket$"
"pattern": "(?i)(^|,)\\s*websocket\\s*(,|$)"
}
}
}
+6
View File
@@ -22,6 +22,12 @@
"Remote-Groups",
"Remote-Email",
"Remote-Name"
],
"strip_headers": [
"Remote-User",
"Remote-Groups",
"Remote-Email",
"Remote-Name"
]
},
"hosts": [
+71 -20
View File
@@ -336,7 +336,13 @@ fn accepts_good_hostnames() {
] {
let contents = format!("hostname = {good:?}\nupstreams = [\"http://127.0.0.1:1\"]\n");
let name = format!("hosts/{good}.toml");
let r = load(&site(), &[SourceFile { name: &name, contents: &contents }]);
let r = load(
&site(),
&[SourceFile {
name: &name,
contents: &contents,
}],
);
assert!(r.is_ok(), "{good}: {r:?}");
}
}
@@ -785,7 +791,13 @@ fn never_panics_on_garbage() {
#[test]
fn file_name_must_match_the_hostname() {
let r = load(&site(), &[SourceFile { name: "hosts/other.test.toml", contents: MINIMAL }]);
let r = load(
&site(),
&[SourceFile {
name: "hosts/other.test.toml",
contents: MINIMAL,
}],
);
let errs = r.unwrap_err();
assert_eq!(
errs.errors(),
@@ -817,14 +829,24 @@ fn rejects_wildcards_in_copy_headers() {
name: "ianitor.toml",
contents: "[forward_auth]\nurl = \"http://127.0.0.1:9091/x\"\ncopy_headers = [\"Remote-*\"]\n",
},
&[SourceFile { name: "app.test.toml", contents: MINIMAL }],
&[SourceFile {
name: "app.test.toml",
contents: MINIMAL,
}],
);
assert!(
r.unwrap_err()
.errors()
.iter()
.any(|e| matches!(e, ValidationError::InvalidHeaderName { .. }))
);
assert!(r.unwrap_err().errors().iter().any(|e| matches!(e, ValidationError::InvalidHeaderName { .. })));
}
#[test]
fn rejects_fragment_in_health_check_path() {
let e = single_error(&format!("{MINIMAL}[health_check]\npath = \"/h#x\"\ninterval_secs = 5\n"));
let e = single_error(&format!(
"{MINIMAL}[health_check]\npath = \"/h#x\"\ninterval_secs = 5\n"
));
assert!(matches!(e, ValidationError::BadHealthCheck { .. }), "{e:?}");
}
@@ -834,23 +856,43 @@ fn rejects_oversized_route_files() {
let e = single_error(&big);
assert!(matches!(e, ValidationError::FileTooLarge { .. }), "{e:?}");
let r = load(
&SourceFile { name: "ianitor.toml", contents: &big },
&[SourceFile { name: "app.test.toml", contents: MINIMAL }],
&SourceFile {
name: "ianitor.toml",
contents: &big,
},
&[SourceFile {
name: "app.test.toml",
contents: MINIMAL,
}],
);
assert!(r
.unwrap_err()
.errors()
.iter()
.any(|e| matches!(e, ValidationError::FileTooLarge { file, .. } if file == "ianitor.toml")));
assert!(r.unwrap_err().errors().iter().any(
|e| matches!(e, ValidationError::FileTooLarge { file, .. } if file == "ianitor.toml")
));
}
#[test]
fn rejects_too_many_upstreams() {
let ups: Vec<String> = (1..=65).map(|p| format!("\"http://127.0.0.1:{p}\"")).collect();
let e = single_error(&format!("hostname = \"app.test\"\nupstreams = [{}]\n", ups.join(", ")));
assert!(matches!(e, ValidationError::TooManyUpstreams { .. }), "{e:?}");
let ups: Vec<String> = (1..=64).map(|p| format!("\"http://127.0.0.1:{p}\"")).collect();
assert!(one(&format!("hostname = \"app.test\"\nupstreams = [{}]\n", ups.join(", "))).is_ok());
let ups: Vec<String> = (1..=65)
.map(|p| format!("\"http://127.0.0.1:{p}\""))
.collect();
let e = single_error(&format!(
"hostname = \"app.test\"\nupstreams = [{}]\n",
ups.join(", ")
));
assert!(
matches!(e, ValidationError::TooManyUpstreams { .. }),
"{e:?}"
);
let ups: Vec<String> = (1..=64)
.map(|p| format!("\"http://127.0.0.1:{p}\""))
.collect();
assert!(
one(&format!(
"hostname = \"app.test\"\nupstreams = [{}]\n",
ups.join(", ")
))
.is_ok()
);
}
#[test]
@@ -861,11 +903,20 @@ fn identity_headers_stay_protected_with_a_custom_copy_list() {
"{MINIMAL}auth = \"forward-auth\"\n[[request_headers]]\naction = \"set\"\nname = \"{header}\"\nvalue = \"x\"\n"
);
let r = load(
&SourceFile { name: "ianitor.toml", contents: site },
&[SourceFile { name: "hosts/app.test.toml", contents: &host }],
&SourceFile {
name: "ianitor.toml",
contents: site,
},
&[SourceFile {
name: "hosts/app.test.toml",
contents: &host,
}],
);
assert!(
r.unwrap_err().errors().iter().any(|e| matches!(e, ValidationError::ProtectedHeader { .. })),
r.unwrap_err()
.errors()
.iter()
.any(|e| matches!(e, ValidationError::ProtectedHeader { .. })),
"{header}"
);
}