[core] Compilers: Pingora runtime config and Caddy JSON, golden files

This commit is contained in:
2026-11-07 14:39:34 +01:00
parent ff087a14dd
commit a5823ba33d
11 changed files with 1794 additions and 148 deletions
+339
View File
@@ -0,0 +1,339 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Model → Caddy JSON (Caddy v2 native config) for the caddy-fallback unit.
//!
//! Built with `serde_json::Value`, whose maps are ordered, so the output is deterministic.
//! The forward-auth block mirrors what `caddy adapt` produces for Authelia's documented
//! `forward_auth … { uri /api/authz/forward-auth; copy_headers … }` snippet.
use serde_json::{Map, Value, json};
use super::{CompileOptions, join};
use crate::{
AccessLog, AuthMode, ForwardAuth, HeaderRule, HeaderValue, Host, Model, Scheme, TlsMode,
Upstream,
};
const ACCESS_LOGGER: &str = "ianitor_access";
const HTTPS_SERVER: &str = "ianitor_https";
const HTTP_SERVER: &str = "ianitor_http";
pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value {
let hosts = model.hosts();
let mut root = Map::new();
root.insert(
"admin".into(),
match o.caddy_admin {
Some(addr) => json!({ "listen": addr.to_string() }),
None => json!({ "disabled": true }),
},
);
root.insert(
"storage".into(),
json!({ "module": "file_system", "root": join(&o.state_dir, "caddy") }),
);
let logged: Vec<&Host> = hosts
.iter()
.filter(|h| h.access_log == AccessLog::Truncated)
.collect();
if !logged.is_empty() {
root.insert("logging".into(), logging(&o.access_log));
}
// ---- HTTPS server: one route per host, then a catch-all 404.
let mut routes: Vec<Value> = hosts
.iter()
.map(|h| host_route(h, model.site().forward_auth.as_ref(), o))
.collect();
routes.push(not_found());
let domi: Vec<&Host> = hosts.iter().filter(|h| h.tls == TlsMode::Domi).collect();
let mut policies: Vec<Value> = domi
.iter()
.map(|h| {
json!({
"match": { "sni": [h.hostname.as_str()] },
"certificate_selection": { "any_tag": [cert_tag(h)] }
})
})
.collect();
policies.push(json!({}));
let mut https = Map::new();
https.insert("listen".into(), json!([o.https_listen.to_string()]));
https.insert("routes".into(), Value::Array(routes));
https.insert("tls_connection_policies".into(), Value::Array(policies));
https.insert(
"automatic_https".into(),
json!({
"disable_redirects": true,
"skip_certificates": domi.iter().map(|h| h.hostname.as_str()).collect::<Vec<_>>()
}),
);
https.insert("protocols".into(), json!(["h1", "h2"]));
if !logged.is_empty() {
let names: Map<String, Value> = logged
.iter()
.map(|h| (h.hostname.to_string(), json!([ACCESS_LOGGER])))
.collect();
https.insert(
"logs".into(),
json!({ "logger_names": names, "skip_unmapped_hosts": true }),
);
}
// ---- HTTP server: redirect known hosts to HTTPS (ACME HTTP-01 is answered by Caddy itself).
let port = o.https_listen.port();
let location = if port == 443 {
"https://{http.request.host}{http.request.uri}".to_owned()
} else {
format!("https://{{http.request.host}}:{port}{{http.request.uri}}")
};
let mut http_routes = Vec::new();
if !hosts.is_empty() {
http_routes.push(json!({
"match": [{ "host": hosts.iter().map(|h| h.hostname.as_str()).collect::<Vec<_>>() }],
"handle": [{
"handler": "static_response",
"status_code": 308,
"headers": { "Location": [location] }
}],
"terminal": true
}));
}
http_routes.push(not_found());
let http = json!({
"listen": [o.http_listen.to_string()],
"routes": http_routes,
"automatic_https": { "disable_redirects": true },
"protocols": ["h1"]
});
let mut servers = Map::new();
servers.insert(HTTPS_SERVER.into(), Value::Object(https));
servers.insert(HTTP_SERVER.into(), http);
let mut tls = Map::new();
if !domi.is_empty() {
let files: Vec<Value> = domi
.iter()
.map(|h| {
json!({
"certificate": join(&o.cert_dir, &format!("{}.crt", h.hostname)),
"key": join(&o.cert_dir, &format!("{}.key", h.hostname)),
"tags": [cert_tag(h)]
})
})
.collect();
tls.insert("certificates".into(), json!({ "load_files": files }));
}
let acme_hosts: Vec<&str> = hosts
.iter()
.filter(|h| h.tls == TlsMode::LetsEncrypt)
.map(|h| h.hostname.as_str())
.collect();
if !acme_hosts.is_empty() {
let acme = &model.site().acme;
let mut issuer = Map::new();
issuer.insert("module".into(), json!("acme"));
issuer.insert("ca".into(), json!(acme.directory));
if let Some(email) = &acme.email {
issuer.insert("email".into(), json!(email));
}
tls.insert(
"automation".into(),
json!({ "policies": [{ "subjects": acme_hosts, "issuers": [Value::Object(issuer)] }] }),
);
}
let mut apps = Map::new();
apps.insert(
"http".into(),
json!({
"http_port": o.http_listen.port(),
"https_port": o.https_listen.port(),
"servers": servers
}),
);
if !tls.is_empty() {
apps.insert("tls".into(), Value::Object(tls));
}
root.insert("apps".into(), Value::Object(apps));
Value::Object(root)
}
fn cert_tag(h: &Host) -> String {
format!("ianitor:{}", h.hostname)
}
fn not_found() -> Value {
json!({ "handle": [{ "handler": "static_response", "status_code": 404 }] })
}
fn logging(file: &str) -> Value {
let mask = json!({ "filter": "ip_mask", "ipv4_cidr": 24, "ipv6_cidr": 48 });
let delete = json!({ "filter": "delete" });
json!({
"logs": {
"default": { "exclude": [format!("http.log.access.{ACCESS_LOGGER}")] },
"ianitor_access": {
"writer": { "output": "file", "filename": file },
"encoder": {
"format": "filter",
"wrap": { "format": "json" },
"fields": {
"request>remote_ip": mask,
"request>client_ip": mask,
"request>remote_port": delete,
"request>headers": delete,
"request>tls": delete,
"request>uri": { "filter": "regexp", "regexp": "\\?.*$", "value": "" },
"resp_headers": delete
}
},
"include": [format!("http.log.access.{ACCESS_LOGGER}")]
}
}
})
}
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) {
steps.push(json!({ "handle": [forward_auth(fa)] }));
}
if !h.websockets {
steps.push(json!({
"match": [{ "header_regexp": { "Upgrade": { "pattern": "(?i)^websocket$" } } }],
"handle": [{ "handler": "static_response", "status_code": 403 }]
}));
}
steps.push(json!({ "handle": [reverse_proxy(h, o)] }));
json!({
"match": [{ "host": [h.hostname.as_str()] }],
"handle": [{ "handler": "subroute", "routes": steps }],
"terminal": true
})
}
fn upstreams(list: &[&Upstream]) -> Value {
Value::Array(
list.iter()
.map(|u| json!({ "dial": u.authority() }))
.collect(),
)
}
fn transport(list: &[&Upstream]) -> Option<Value> {
// Validation guarantees one scheme per host.
list.first()
.filter(|u| u.scheme == Scheme::Https)
.map(|_| json!({ "protocol": "http", "tls": {} }))
}
fn reverse_proxy(h: &Host, o: &CompileOptions) -> Value {
let ups: Vec<&Upstream> = h.upstreams.iter().collect();
let mut rp = Map::new();
rp.insert("handler".into(), json!("reverse_proxy"));
rp.insert("upstreams".into(), upstreams(&ups));
rp.insert(
"load_balancing".into(),
json!({ "selection_policy": { "policy": "round_robin" } }),
);
if let Some(t) = transport(&ups) {
rp.insert("transport".into(), t);
}
if let Some(hc) = &h.health_check {
rp.insert(
"health_checks".into(),
json!({ "active": { "uri": hc.path, "interval": format!("{}s", hc.interval_secs), "timeout": "5s" } }),
);
}
let mut headers = Map::new();
if let Some(ops) = header_ops(&h.request_headers, o) {
headers.insert("request".into(), ops);
}
if let Some(ops) = header_ops(&h.response_headers, o) {
headers.insert("response".into(), ops);
}
if !headers.is_empty() {
rp.insert("headers".into(), Value::Object(headers));
}
Value::Object(rp)
}
fn header_ops(rules: &[HeaderRule], o: &CompileOptions) -> Option<Value> {
if rules.is_empty() {
return None;
}
let mut set = Map::new();
let mut delete = Vec::new();
for r in rules {
match r {
HeaderRule::Set { name, value } => {
let v = match value {
HeaderValue::Literal(v) => v.clone(),
// Caddy reads the credential file itself; the value never enters the config.
HeaderValue::Secret(s) => {
format!("{{file.{}}}", join(&o.caddy_credentials_dir, s.as_str()))
}
};
set.insert(name.clone(), json!([v]));
}
HeaderRule::Remove { name } => delete.push(json!(name)),
}
}
let mut ops = Map::new();
if !set.is_empty() {
ops.insert("set".into(), Value::Object(set));
}
if !delete.is_empty() {
ops.insert("delete".into(), Value::Array(delete));
}
Some(Value::Object(ops))
}
/// Exactly the handler `caddy adapt` builds from Caddy's `forward_auth` directive.
fn forward_auth(fa: &ForwardAuth) -> Value {
let mut copy_routes = vec![json!({ "handle": [{ "handler": "vars" }] })];
for name in &fa.copy_headers {
let placeholder = format!("{{http.reverse_proxy.header.{name}}}");
copy_routes
.push(json!({ "handle": [{ "handler": "headers", "request": { "delete": [name] } }] }));
let mut vars = Map::new();
vars.insert(placeholder.clone(), json!([""]));
let mut set = Map::new();
set.insert(name.clone(), json!([placeholder]));
copy_routes.push(json!({
"match": [{ "not": [{ "vars": Value::Object(vars) }] }],
"handle": [{ "handler": "headers", "request": { "set": Value::Object(set) } }]
}));
}
let ups = [&fa.upstream];
let mut rp = Map::new();
rp.insert("handler".into(), json!("reverse_proxy"));
rp.insert("upstreams".into(), upstreams(&ups));
if let Some(t) = transport(&ups) {
rp.insert("transport".into(), t);
}
rp.insert(
"rewrite".into(),
json!({ "method": "GET", "uri": fa.path_and_query }),
);
rp.insert(
"headers".into(),
json!({ "request": { "set": {
"X-Forwarded-Method": ["{http.request.method}"],
"X-Forwarded-Uri": ["{http.request.uri}"]
} } }),
);
rp.insert(
"handle_response".into(),
json!([{ "match": { "status_code": [2] }, "routes": copy_routes }]),
);
Value::Object(rp)
}
+88
View File
@@ -0,0 +1,88 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// 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/.
//! Model → [`EdgeConfig`] for the Pingora data plane.
use super::{CompileOptions, join};
use crate::edge_config::{
EDGE_CONFIG_VERSION, EdgeAcme, EdgeConfig, EdgeForwardAuth, EdgeHeaderOp, EdgeHealthCheck,
EdgeHost, EdgeTls, EdgeUpstream, EdgeValue,
};
use crate::{
AccessLog, AuthMode, HeaderRule, HeaderValue, Model, Scheme, TlsMode, Upstream, UpstreamHost,
};
pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig {
let site = model.site();
let any_acme = model.hosts().iter().any(|h| h.tls == TlsMode::LetsEncrypt);
EdgeConfig {
version: EDGE_CONFIG_VERSION,
http_listen: o.http_listen.to_string(),
https_listen: o.https_listen.to_string(),
https_port: o.https_listen.port(),
cert_dir: o.cert_dir.clone(),
state_dir: o.state_dir.clone(),
access_log: o.access_log.clone(),
acme: any_acme.then(|| EdgeAcme {
directory: site.acme.directory.clone(),
email: site.acme.email.clone(),
}),
forward_auth: site.forward_auth.as_ref().map(|fa| EdgeForwardAuth {
upstream: upstream(&fa.upstream),
path_and_query: fa.path_and_query.clone(),
copy_headers: fa.copy_headers.clone(),
}),
hosts: model
.hosts()
.iter()
.map(|h| EdgeHost {
hostname: h.hostname.to_string(),
tls: match h.tls {
TlsMode::LetsEncrypt => EdgeTls::Acme,
TlsMode::Domi => EdgeTls::Files {
cert: join(&o.cert_dir, &format!("{}.crt", h.hostname)),
key: join(&o.cert_dir, &format!("{}.key", h.hostname)),
},
},
upstreams: h.upstreams.iter().map(upstream).collect(),
forward_auth: h.auth == AuthMode::ForwardAuth,
websockets: h.websockets,
request_headers: h.request_headers.iter().map(op).collect(),
response_headers: h.response_headers.iter().map(op).collect(),
health_check: h.health_check.as_ref().map(|hc| EdgeHealthCheck {
path: hc.path.clone(),
interval_secs: hc.interval_secs,
}),
access_log: h.access_log == AccessLog::Truncated,
})
.collect(),
}
}
fn upstream(u: &Upstream) -> EdgeUpstream {
EdgeUpstream {
address: u.authority(),
tls: u.scheme == Scheme::Https,
// Like Go's TLS client in Caddy: SNI is the host name; IP literals send none.
sni: match &u.host {
UpstreamHost::Name(n) => n.clone(),
UpstreamHost::Ip(_) => String::new(),
},
}
}
fn op(r: &HeaderRule) -> EdgeHeaderOp {
match r {
HeaderRule::Set { name, value } => EdgeHeaderOp::Set {
name: name.clone(),
value: match value {
HeaderValue::Literal(v) => EdgeValue::Literal { value: v.clone() },
HeaderValue::Secret(s) => EdgeValue::Secret {
name: s.to_string(),
},
},
},
HeaderRule::Remove { name } => EdgeHeaderOp::Remove { name: name.clone() },
}
}
+73 -6
View File
@@ -3,7 +3,19 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Compilers from the validated [`Model`] to the two engines. Both are pure and deterministic:
//! the same model and options always give byte-identical output.
//! the same model and options always give byte-identical output (no hash maps, hosts sorted,
//! rules in file order). Neither ever sees a secret value, only secret names.
//!
//! Shared semantics, kept honest by the differential tests in `tests/diff`:
//! - HTTP listener: `308` to `https://host[:port]/uri` for known hosts, `404` otherwise.
//! - HTTPS listener: host chosen by the `Host` header (certificate by SNI); unknown host `404`.
//! - Per host, in order: forward-auth (non-2xx auth answer goes back to the client verbatim;
//! on 2xx the identity headers are copied onto the request), websocket refusal (`403` when
//! `websockets = false`), then the reverse proxy with header rules, round-robin over healthy
//! upstreams, `503` when none is healthy, `502` when the upstream cannot be reached.
mod caddy;
mod edge;
use std::net::SocketAddr;
@@ -29,19 +41,74 @@ pub struct CompileOptions {
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum CompileError {
#[error("compile option `{option}` is not usable: {reason}")]
BadOption { option: &'static str, reason: &'static str },
BadOption {
option: &'static str,
reason: &'static str,
},
#[error("could not serialise the compiled config: {0}")]
Serialize(String),
}
/// Compile to the Pingora runtime config read by ianitor-edge.
pub fn edge(model: &Model, options: &CompileOptions) -> Result<String, CompileError> {
let _ = (model, options);
Err(CompileError::Serialize("not implemented".into()))
check_options(options)?;
let cfg = edge::compile(model, options);
serde_json::to_string_pretty(&cfg)
.map(|s| s + "\n")
.map_err(|e| CompileError::Serialize(e.to_string()))
}
/// Compile to Caddy JSON for the caddy-fallback unit.
pub fn caddy(model: &Model, options: &CompileOptions) -> Result<String, CompileError> {
let _ = (model, options);
Err(CompileError::Serialize("not implemented".into()))
check_options(options)?;
let v = caddy::compile(model, options);
serde_json::to_string_pretty(&v)
.map(|s| s + "\n")
.map_err(|e| CompileError::Serialize(e.to_string()))
}
fn check_options(o: &CompileOptions) -> Result<(), CompileError> {
for (option, value) in [
("cert_dir", &o.cert_dir),
("state_dir", &o.state_dir),
("access_log", &o.access_log),
("caddy_credentials_dir", &o.caddy_credentials_dir),
] {
check_path(value).map_err(|reason| CompileError::BadOption { option, reason })?;
}
if o.http_listen.port() == 0 || o.https_listen.port() == 0 {
return Err(CompileError::BadOption {
option: "listen",
reason: "port 0 is not usable",
});
}
if o.http_listen == o.https_listen {
return Err(CompileError::BadOption {
option: "listen",
reason: "HTTP and HTTPS need different addresses",
});
}
Ok(())
}
/// Paths end up inside JSON strings and Caddy `{file.*}` placeholders.
fn check_path(p: &str) -> Result<(), &'static str> {
if !p.starts_with('/') {
return Err("it must be an absolute path");
}
if p.len() > 1024 {
return Err("it is longer than 1024 characters");
}
if !p
.bytes()
.all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}' && c != b'\\')
{
return Err("only visible ASCII without '{', '}' or '\\' is allowed");
}
Ok(())
}
/// Join a validated directory and a validated file name.
fn join(dir: &str, file: &str) -> String {
format!("{}/{}", dir.trim_end_matches('/'), file)
}
+36 -8
View File
@@ -11,7 +11,11 @@ use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ValidationError {
#[error("{file}: the file is not valid TOML{}: {message}", line_suffix(*line))]
Syntax { file: String, line: Option<usize>, message: String },
Syntax {
file: String,
line: Option<usize>,
message: String,
},
#[error("{file}: unknown field `{field}`")]
UnknownField { file: String, field: String },
#[error("{file}: required field `{field}` is missing")]
@@ -21,31 +25,55 @@ pub enum ValidationError {
#[error("{file} appears twice in the routes")]
DuplicateFile { file: String },
#[error("{file}: `{hostname}` is not a valid hostname: {reason}")]
InvalidHostname { file: String, hostname: String, reason: &'static str },
InvalidHostname {
file: String,
hostname: String,
reason: &'static str,
},
#[error("hostname `{hostname}` is defined twice: in {first} and in {second}")]
DuplicateHostname { hostname: String, first: String, second: String },
DuplicateHostname {
hostname: String,
first: String,
second: String,
},
#[error("{file}: at least one upstream is needed")]
NoUpstreams { file: String },
#[error("{file}: upstream `{url}` is not usable: {reason}")]
BadUpstreamUrl { file: String, url: String, reason: &'static str },
BadUpstreamUrl {
file: String,
url: String,
reason: &'static str,
},
#[error("{file}: upstream `{url}` is listed twice")]
DuplicateUpstream { file: String, url: String },
#[error("{file}: secret `{secret}` is used but not declared in the site file")]
UndefinedSecret { file: String, secret: String },
#[error("{file}: response header `{header}` may not use a secret; secrets only go to upstreams")]
#[error(
"{file}: response header `{header}` may not use a secret; secrets only go to upstreams"
)]
SecretInResponseHeader { file: String, header: String },
#[error("{file}: `{name}` is not a valid secret name (use a-z, 0-9, '_' and '-', at most 64 characters)")]
#[error(
"{file}: `{name}` is not a valid secret name (use a-z, 0-9, '_' and '-', at most 64 characters)"
)]
InvalidSecretName { file: String, name: String },
#[error("{file}: `{name}` is not a valid header name")]
InvalidHeaderName { file: String, name: String },
#[error("{file}: value for header `{header}` is not allowed: {reason}")]
InvalidHeaderValue { file: String, header: String, reason: &'static str },
InvalidHeaderValue {
file: String,
header: String,
reason: &'static str,
},
#[error("{file}: header `{header}` is managed by the proxy and cannot be changed by a rule")]
ProtectedHeader { file: String, header: String },
#[error("{file}: header `{header}` has more than one rule in the same list")]
DuplicateHeaderRule { file: String, header: String },
#[error("{file}: rule for header `{header}` is incomplete: {reason}")]
BadHeaderRule { file: String, header: String, reason: &'static str },
BadHeaderRule {
file: String,
header: String,
reason: &'static str,
},
#[error("{file}: health check is not usable: {reason}")]
BadHealthCheck { file: String, reason: &'static str },
#[error("{file}: auth = \"forward-auth\" needs a [forward_auth] section in the site file")]
+4 -4
View File
@@ -16,8 +16,8 @@ mod validate;
pub use error::{ValidationError, ValidationErrors};
pub use model::{
AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, HealthCheck, Host, Hostname,
Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost, AUTHELIA_COPY_HEADERS,
LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING,
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, Model, Scheme,
SecretName, Site, TlsMode, Upstream, UpstreamHost,
};
pub use validate::{load, SourceFile};
pub use validate::{SourceFile, load};
+6 -1
View File
@@ -222,4 +222,9 @@ pub const LETSENCRYPT_PRODUCTION: &str = "https://acme-v02.api.letsencrypt.org/d
/// Let's Encrypt staging directory.
pub const LETSENCRYPT_STAGING: &str = "https://acme-staging-v02.api.letsencrypt.org/directory";
/// Identity headers Authelia returns on success (Authelia's Caddy integration guide).
pub const AUTHELIA_COPY_HEADERS: [&str; 4] = ["Remote-User", "Remote-Groups", "Remote-Email", "Remote-Name"];
pub const AUTHELIA_COPY_HEADERS: [&str; 4] = [
"Remote-User",
"Remote-Groups",
"Remote-Email",
"Remote-Name",
];
+148 -40
View File
@@ -151,7 +151,9 @@ pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result<Model, Va
let mut checked = Vec::new();
for f in files {
if !seen_files.insert(f.name) {
errors.push(E::DuplicateFile { file: f.name.to_owned() });
errors.push(E::DuplicateFile {
file: f.name.to_owned(),
});
continue;
}
match parse::<RawHost>(f) {
@@ -178,7 +180,10 @@ pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result<Model, Va
}
match site_model {
Some(site) if errors.is_empty() => Ok(Model { site, hosts: by_name.into_values().collect() }),
Some(site) if errors.is_empty() => Ok(Model {
site,
hosts: by_name.into_values().collect(),
}),
_ => Err(ValidationErrors(errors)),
}
}
@@ -215,7 +220,10 @@ fn classify(file: String, message: &str) -> E {
} else if let Some(field) = quoted("missing field `") {
E::MissingField { file, field }
} else {
E::InvalidValue { file, message: message.to_owned() }
E::InvalidValue {
file,
message: message.to_owned(),
}
}
}
@@ -228,12 +236,18 @@ fn check_site(file: &str, raw: RawSite, errors: &mut Vec<E>) -> Option<Site> {
if valid_secret_name(&name) {
secrets.insert(SecretName(name));
} else {
errors.push(E::InvalidSecretName { file: file.to_owned(), name });
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 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) => {
@@ -243,39 +257,67 @@ fn check_site(file: &str, raw: RawSite, errors: &mut Vec<E>) -> Option<Site> {
};
let copy_headers: Vec<String> = match fa.copy_headers {
Some(h) => h,
None => AUTHELIA_COPY_HEADERS.iter().map(|s| (*s).to_owned()).collect(),
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() });
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() });
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 })
Some(ForwardAuth {
upstream,
path_and_query,
copy_headers,
})
});
let acme = match raw.acme {
None => Acme { email: None, directory: LETSENCRYPT_PRODUCTION.to_owned() },
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 bad = |reason| E::BadAcme {
file: file.to_owned(),
reason,
};
if a.email.as_deref().is_some_and(|e| !valid_email(e)) {
errors.push(bad("email is not a plain address like admin@example.org"));
}
let directory = a.directory.unwrap_or_else(|| LETSENCRYPT_PRODUCTION.to_owned());
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"));
errors.push(bad(
"directory must be an https:// URL without credentials or fragment",
));
}
Acme {
email: a.email,
directory,
}
Acme { email: a.email, directory }
}
};
(errors.len() == before).then_some(Site { secrets, forward_auth, acme })
(errors.len() == before).then_some(Site {
secrets,
forward_auth,
acme,
})
}
fn valid_secret_name(n: &str) -> bool {
@@ -283,15 +325,20 @@ fn valid_secret_name(n: &str) -> bool {
!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'-')
&& 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 };
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))
&& local
.bytes()
.all(|c| c.is_ascii_graphic() && !b"{}@<>\"\\,;:[]()".contains(&c))
}
fn valid_acme_directory(d: &str) -> bool {
@@ -302,7 +349,8 @@ fn valid_acme_directory(d: &str) -> bool {
&& u.password().is_none()
&& u.fragment().is_none()
&& u.host().is_some()
&& d.bytes().all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}')
&& d.bytes()
.all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}')
}
Err(_) => false,
}
@@ -315,7 +363,11 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
let f = || file.to_owned();
if let Err(reason) = check_hostname(&raw.hostname) {
errors.push(E::InvalidHostname { file: f(), hostname: raw.hostname.clone(), reason });
errors.push(E::InvalidHostname {
file: f(),
hostname: raw.hostname.clone(),
reason,
});
}
if raw.upstreams.is_empty() {
@@ -326,15 +378,30 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
match parse_url(u, false) {
Ok((up, _)) => {
if upstreams.contains(&up) {
errors.push(E::DuplicateUpstream { file: f(), url: u.clone() });
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 }),
Err(reason) => errors.push(E::BadUpstreamUrl {
file: f(),
url: u.clone(),
reason,
}),
}
}
if upstreams.windows(2).any(|w| w[0].scheme != w[1].scheme) {
errors.push(E::BadUpstreamUrl {
file: f(),
url: raw.upstreams.join(", "),
reason: "all upstreams of a host must use the same scheme",
});
}
let auth = match raw.auth {
RawAuth::None => AuthMode::None,
RawAuth::ForwardAuth => AuthMode::ForwardAuth,
@@ -345,8 +412,15 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
// 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(),
(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);
@@ -356,13 +430,21 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
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'}');
&& 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 '}'"));
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 }),
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
@@ -430,7 +512,10 @@ fn check_rules(
for r in raw {
let header = r.name.clone();
if !valid_header_name(&r.name) {
errors.push(E::InvalidHeaderName { file: f(), name: r.name });
errors.push(E::InvalidHeaderName {
file: f(),
name: r.name,
});
continue;
}
let lower = r.name.to_ascii_lowercase();
@@ -442,23 +527,42 @@ fn check_rules(
errors.push(E::DuplicateHeaderRule { file: f(), header });
continue;
}
let bad = |reason| E::BadHeaderRule { file: f(), header: header.clone(), reason };
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, 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 }),
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 });
errors.push(E::UndefinedSecret {
file: f(),
secret: s,
});
} else {
out.push(HeaderRule::Set { name: r.name, value: HeaderValue::Secret(SecretName(s)) });
out.push(HeaderRule::Set {
name: r.name,
value: HeaderValue::Secret(SecretName(s)),
});
}
}
}
@@ -470,7 +574,8 @@ fn check_rules(
fn valid_header_name(n: &str) -> bool {
!n.is_empty()
&& n.len() <= 256
&& n.bytes().all(|c| c.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&c))
&& n.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&c))
}
fn check_header_value(v: &str) -> Result<(), &'static str> {
@@ -521,7 +626,10 @@ pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> {
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'-') {
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('-') {