[core] Schema: host file model and validation with typed errors

This commit is contained in:
2026-11-07 14:36:35 +01:00
parent 9176cc63a4
commit ff087a14dd
2 changed files with 577 additions and 7 deletions
+575 -6
View File
@@ -2,9 +2,21 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Parsing and validation of the routes tree.
//! Parsing and validation of the routes tree. Route files are hostile input: everything is
//! checked, every problem becomes a typed [`ValidationError`], nothing panics.
use crate::{Model, ValidationErrors};
use std::collections::{BTreeMap, BTreeSet};
use std::net::IpAddr;
use serde::Deserialize;
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,
};
/// One route file handed in by the caller (core does no I/O).
#[derive(Debug, Clone, Copy)]
@@ -13,8 +25,565 @@ pub struct SourceFile<'a> {
pub contents: &'a str,
}
/// Parse and validate the site file and every host file.
pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result<Model, ValidationErrors> {
let _ = (site, hosts);
Err(ValidationErrors(Vec::new()))
// ------------------------------------------------------------------ raw file shapes
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawSite {
#[serde(default)]
secrets: Vec<String>,
forward_auth: Option<RawForwardAuth>,
acme: Option<RawAcme>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawForwardAuth {
url: String,
copy_headers: Option<Vec<String>>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawAcme {
email: Option<String>,
directory: Option<String>,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
enum RawTls {
#[default]
Letsencrypt,
Domi,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
enum RawAuth {
#[default]
None,
ForwardAuth,
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
enum RawAccessLog {
#[default]
Off,
Truncated,
}
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
enum RawAction {
Set,
Remove,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawRule {
action: RawAction,
name: String,
value: Option<String>,
secret: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawHealthCheck {
path: String,
/// Signed so that 0 and negative numbers get a typed error instead of a serde one.
#[serde(default = "default_interval")]
interval_secs: i64,
}
fn default_interval() -> i64 {
10
}
fn yes() -> bool {
true
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawHost {
hostname: String,
upstreams: Vec<String>,
#[serde(default)]
tls: RawTls,
#[serde(default)]
auth: RawAuth,
#[serde(default = "yes")]
websockets: bool,
#[serde(default)]
share_links: bool,
#[serde(default)]
access_log: RawAccessLog,
health_check: Option<RawHealthCheck>,
#[serde(default)]
request_headers: Vec<RawRule>,
#[serde(default)]
response_headers: Vec<RawRule>,
}
// ------------------------------------------------------------------ entry point
/// Parse and validate the site file and every host file. Returns every problem found, or the
/// model with hosts sorted by hostname. File order does not matter.
pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result<Model, ValidationErrors> {
let mut errors = Vec::new();
let site_model = match parse::<RawSite>(site) {
Ok(raw) => check_site(site.name, raw, &mut errors),
Err(e) => {
errors.push(e);
None
}
};
// Stable order: by file name. Duplicate file names are an error of their own.
let mut files: Vec<&SourceFile<'_>> = hosts.iter().collect();
files.sort_by(|a, b| a.name.cmp(b.name));
let mut seen_files = BTreeSet::new();
let mut checked = Vec::new();
for f in files {
if !seen_files.insert(f.name) {
errors.push(E::DuplicateFile { file: f.name.to_owned() });
continue;
}
match parse::<RawHost>(f) {
Ok(raw) => {
if let Some(h) = check_host(f.name, raw, site_model.as_ref(), &mut errors) {
checked.push(h);
}
}
Err(e) => errors.push(e),
}
}
let mut by_name: BTreeMap<Hostname, Host> = BTreeMap::new();
for h in checked {
if let Some(first) = by_name.get(&h.hostname) {
errors.push(E::DuplicateHostname {
hostname: h.hostname.to_string(),
first: first.source.clone(),
second: h.source.clone(),
});
} else {
by_name.insert(h.hostname.clone(), h);
}
}
match site_model {
Some(site) if errors.is_empty() => Ok(Model { site, hosts: by_name.into_values().collect() }),
_ => Err(ValidationErrors(errors)),
}
}
// ------------------------------------------------------------------ TOML → raw
fn parse<T: DeserializeOwned>(f: &SourceFile<'_>) -> Result<T, E> {
let file = f.name.to_owned();
// 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 {
file,
line: e.span().map(|s| line_of(f.contents, s.start)),
message: e.message().trim().to_owned(),
});
}
toml::from_str::<T>(f.contents).map_err(|e| classify(file, e.message()))
}
fn line_of(text: &str, offset: usize) -> usize {
text.get(..offset).map_or(0, |t| t.matches('\n').count()) + 1
}
/// Turn serde's standard messages into typed errors.
fn classify(file: String, message: &str) -> E {
let message = message.trim();
let quoted = |prefix: &str| -> Option<String> {
let rest = message.strip_prefix(prefix)?;
let end = rest.find('`')?;
Some(rest[..end].to_owned())
};
if let Some(field) = quoted("unknown field `") {
E::UnknownField { file, field }
} else if let Some(field) = quoted("missing field `") {
E::MissingField { file, field }
} else {
E::InvalidValue { file, message: message.to_owned() }
}
}
// ------------------------------------------------------------------ site file
fn check_site(file: &str, raw: RawSite, errors: &mut Vec<E>) -> Option<Site> {
let before = errors.len();
let mut secrets = BTreeSet::new();
for name in raw.secrets {
if valid_secret_name(&name) {
secrets.insert(SecretName(name));
} else {
errors.push(E::InvalidSecretName { file: file.to_owned(), name });
}
}
let forward_auth = raw.forward_auth.and_then(|fa| {
let bad = |reason| E::BadForwardAuth { file: file.to_owned(), reason };
let (upstream, path_and_query) = match parse_url(&fa.url, true) {
Ok(v) => v,
Err(reason) => {
errors.push(bad(reason));
return None;
}
};
let copy_headers: Vec<String> = match fa.copy_headers {
Some(h) => h,
None => AUTHELIA_COPY_HEADERS.iter().map(|s| (*s).to_owned()).collect(),
};
let mut seen = BTreeSet::new();
for h in &copy_headers {
if !valid_header_name(h) {
errors.push(E::InvalidHeaderName { file: file.to_owned(), name: h.clone() });
} else if is_protected(h) {
errors.push(E::ProtectedHeader { file: file.to_owned(), header: h.clone() });
} else if !seen.insert(h.to_ascii_lowercase()) {
errors.push(bad("copy_headers lists a header twice"));
}
}
Some(ForwardAuth { upstream, path_and_query, copy_headers })
});
let acme = match raw.acme {
None => Acme { email: None, directory: LETSENCRYPT_PRODUCTION.to_owned() },
Some(a) => {
let bad = |reason| E::BadAcme { file: file.to_owned(), reason };
if let Some(email) = &a.email {
if !valid_email(email) {
errors.push(bad("email is not a plain address like admin@example.org"));
}
}
let directory = a.directory.unwrap_or_else(|| LETSENCRYPT_PRODUCTION.to_owned());
if !valid_acme_directory(&directory) {
errors.push(bad("directory must be an https:// URL without credentials or fragment"));
}
Acme { email: a.email, directory }
}
};
(errors.len() == before).then_some(Site { secrets, forward_auth, acme })
}
fn valid_secret_name(n: &str) -> bool {
let b = n.as_bytes();
!b.is_empty()
&& b.len() <= 64
&& (b[0].is_ascii_lowercase() || b[0].is_ascii_digit())
&& b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'_' || *c == b'-')
}
fn valid_email(e: &str) -> bool {
let Some((local, domain)) = e.split_once('@') else { return false };
!local.is_empty()
&& e.len() <= 254
&& check_hostname(domain).is_ok()
&& local.bytes().all(|c| c.is_ascii_graphic() && !b"{}@<>\"\\,;:[]()".contains(&c))
}
fn valid_acme_directory(d: &str) -> bool {
match url::Url::parse(d) {
Ok(u) => {
u.scheme() == "https"
&& u.username().is_empty()
&& u.password().is_none()
&& u.fragment().is_none()
&& u.host().is_some()
&& d.bytes().all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}')
}
Err(_) => false,
}
}
// ------------------------------------------------------------------ host files
fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>) -> Option<Host> {
let before = errors.len();
let f = || file.to_owned();
if let Err(reason) = check_hostname(&raw.hostname) {
errors.push(E::InvalidHostname { file: f(), hostname: raw.hostname.clone(), reason });
}
if raw.upstreams.is_empty() {
errors.push(E::NoUpstreams { file: f() });
}
let mut upstreams: Vec<Upstream> = Vec::new();
for u in &raw.upstreams {
match parse_url(u, false) {
Ok((up, _)) => {
if upstreams.contains(&up) {
errors.push(E::DuplicateUpstream { file: f(), url: u.clone() });
} else {
upstreams.push(up);
}
}
Err(reason) => errors.push(E::BadUpstreamUrl { file: f(), url: u.clone(), reason }),
}
}
let auth = match raw.auth {
RawAuth::None => AuthMode::None,
RawAuth::ForwardAuth => AuthMode::ForwardAuth,
};
if auth == AuthMode::ForwardAuth && site.is_some_and(|s| s.forward_auth.is_none()) {
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(),
};
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);
let health_check = raw.health_check.and_then(|hc| {
let bad = |reason| E::BadHealthCheck { file: f(), reason };
let ok_path = hc.path.starts_with('/')
&& hc.path.len() <= 1024
&& hc.path.bytes().all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}');
if !ok_path {
errors.push(bad("path must start with '/' and contain only visible ASCII without '{' or '}'"));
return None;
}
match u32::try_from(hc.interval_secs) {
Ok(i) if (1..=3600).contains(&i) => Some(HealthCheck { path: hc.path, interval_secs: i }),
_ => {
errors.push(bad("interval_secs must be between 1 and 3600"));
None
}
}
});
if errors.len() != before {
return None;
}
Some(Host {
hostname: Hostname(raw.hostname),
source: f(),
upstreams,
tls: match raw.tls {
RawTls::Letsencrypt => TlsMode::LetsEncrypt,
RawTls::Domi => TlsMode::Domi,
},
auth,
request_headers,
response_headers,
websockets: raw.websockets,
health_check,
share_links: raw.share_links,
access_log: match raw.access_log {
RawAccessLog::Off => AccessLog::Off,
RawAccessLog::Truncated => AccessLog::Truncated,
},
})
}
/// Headers the proxy manages itself (framing, hop-by-hop, forwarding metadata).
const PROTECTED: [&str; 14] = [
"host",
"content-length",
"transfer-encoding",
"connection",
"upgrade",
"keep-alive",
"te",
"trailer",
"proxy-connection",
"x-forwarded-for",
"x-forwarded-proto",
"x-forwarded-host",
"x-forwarded-method",
"x-forwarded-uri",
];
fn is_protected(name: &str) -> bool {
PROTECTED.iter().any(|p| p.eq_ignore_ascii_case(name))
}
fn check_rules(
file: &str,
raw: Vec<RawRule>,
request: bool,
identity: &[String],
site: Option<&Site>,
errors: &mut Vec<E>,
) -> Vec<HeaderRule> {
let f = || file.to_owned();
let mut out = Vec::new();
let mut seen = BTreeSet::new();
for r in raw {
let header = r.name.clone();
if !valid_header_name(&r.name) {
errors.push(E::InvalidHeaderName { file: f(), name: r.name });
continue;
}
let lower = r.name.to_ascii_lowercase();
if is_protected(&r.name) || identity.contains(&lower) {
errors.push(E::ProtectedHeader { file: f(), header });
continue;
}
if !seen.insert(lower) {
errors.push(E::DuplicateHeaderRule { file: f(), header });
continue;
}
let bad = |reason| E::BadHeaderRule { file: f(), header: header.clone(), reason };
match (r.action, r.value, r.secret) {
(RawAction::Remove, None, None) => out.push(HeaderRule::Remove { name: r.name }),
(RawAction::Remove, _, _) => errors.push(bad("remove takes no value or secret")),
(RawAction::Set, Some(_), Some(_)) => errors.push(bad("give either value or secret, not both")),
(RawAction::Set, None, None) => errors.push(bad("set needs a value or a secret")),
(RawAction::Set, Some(v), None) => match check_header_value(&v) {
Ok(()) => out.push(HeaderRule::Set { name: r.name, value: HeaderValue::Literal(v) }),
Err(reason) => errors.push(E::InvalidHeaderValue { file: f(), header, reason }),
},
(RawAction::Set, None, Some(s)) => {
if !request {
errors.push(E::SecretInResponseHeader { file: f(), header });
} else if site.is_some_and(|site| !site.secrets.contains(&SecretName(s.clone()))) {
errors.push(E::UndefinedSecret { file: f(), secret: s });
} else {
out.push(HeaderRule::Set { name: r.name, value: HeaderValue::Secret(SecretName(s)) });
}
}
}
}
out
}
/// RFC 9110 token.
fn valid_header_name(n: &str) -> bool {
!n.is_empty()
&& n.len() <= 256
&& n.bytes().all(|c| c.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&c))
}
fn check_header_value(v: &str) -> Result<(), &'static str> {
if v.is_empty() {
return Err("an empty value is not allowed; use action = \"remove\"");
}
if v.len() > 4096 {
return Err("it is longer than 4096 characters");
}
if !v.bytes().all(|c| (0x20..0x7f).contains(&c)) {
return Err("only visible ASCII characters and spaces are allowed");
}
if v.contains(['{', '}']) {
return Err("'{' and '}' are not allowed (they are placeholders in Caddy)");
}
if v.starts_with(' ') || v.ends_with(' ') {
return Err("it must not start or end with a space");
}
Ok(())
}
// ------------------------------------------------------------------ names and URLs
pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> {
if h.is_empty() {
return Err("it is empty");
}
if h.len() > 253 {
return Err("it is longer than 253 characters");
}
if h.parse::<IpAddr>().is_ok() || h.starts_with('[') {
return Err("IP addresses are not hostnames");
}
if h.contains('*') {
return Err("wildcards are not supported");
}
if h.ends_with('.') {
return Err("it must not end with a dot");
}
if h.bytes().any(|c| c.is_ascii_uppercase()) {
return Err("it must be lowercase");
}
let mut last = "";
for label in h.split('.') {
if label.is_empty() {
return Err("it has an empty label");
}
if label.len() > 63 {
return Err("a label is longer than 63 characters");
}
if !label.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-') {
return Err("only a-z, 0-9, '-' and '.' are allowed");
}
if label.starts_with('-') || label.ends_with('-') {
return Err("a label must not start or end with '-'");
}
last = label;
}
if last.bytes().all(|c| c.is_ascii_digit()) {
return Err("the last label must not be numeric");
}
Ok(())
}
/// Parse an http(s) URL into an upstream. With `allow_path`, also returns path and query
/// (for the forward-auth endpoint); otherwise any path other than `/` is rejected.
fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static str> {
if !raw.bytes().all(|c| c.is_ascii_graphic()) {
return Err("it must be plain ASCII without spaces");
}
let u = url::Url::parse(raw).map_err(|_| "it is not a URL like http://127.0.0.1:8080")?;
let scheme = match u.scheme() {
"http" => Scheme::Http,
"https" => Scheme::Https,
_ => return Err("only http:// and https:// are supported"),
};
if !u.username().is_empty() || u.password().is_some() {
return Err("credentials in the URL are not allowed");
}
if u.fragment().is_some() {
return Err("a #fragment is not allowed");
}
let host = match u.host() {
None => return Err("it has no host"),
Some(url::Host::Ipv4(ip)) => UpstreamHost::Ip(IpAddr::V4(ip)),
Some(url::Host::Ipv6(ip)) => UpstreamHost::Ip(IpAddr::V6(ip)),
Some(url::Host::Domain(d)) => {
if check_hostname(d).is_err() {
return Err("the host name is not valid");
}
UpstreamHost::Name(d.to_owned())
}
};
let port = u.port_or_known_default().ok_or("it has no port")?;
if port == 0 {
return Err("port 0 is not usable");
}
let mut path = u.path().to_owned();
if !allow_path {
if path != "/" && !path.is_empty() {
return Err("a path is not allowed; requests keep their own path");
}
if u.query().is_some() {
return Err("a ?query is not allowed");
}
} else {
if let Some(q) = u.query() {
path.push('?');
path.push_str(q);
}
if path.contains(['{', '}']) {
return Err("'{' and '}' are not allowed");
}
}
Ok((Upstream { scheme, host, port }, path))
}
+2 -1
View File
@@ -397,7 +397,8 @@ fn rejects_invalid_header_names() {
#[test]
fn rejects_invalid_header_values() {
for bad in ["a\nb", "a\rb", "a\u{0}b", "{http.request.host}", "x}", "\u{7f}", " leading", "ü"] {
let e = single_error(&rule("response_headers", &format!("action = \"set\"\nname = \"X-A\"\nvalue = {bad:?}")));
let value = toml::Value::String(bad.to_owned()).to_string();
let e = single_error(&rule("response_headers", &format!("action = \"set\"\nname = \"X-A\"\nvalue = {value}")));
assert!(matches!(e, ValidationError::InvalidHeaderValue { .. }), "{bad:?}: {e:?}");
}
}