[core] Compilers: Pingora runtime config and Caddy JSON, golden files
This commit is contained in:
@@ -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)
|
||||||
|
}
|
||||||
@@ -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() },
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,19 @@
|
|||||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
// 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:
|
//! 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;
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
@@ -29,19 +41,74 @@ pub struct CompileOptions {
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
pub enum CompileError {
|
pub enum CompileError {
|
||||||
#[error("compile option `{option}` is not usable: {reason}")]
|
#[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}")]
|
#[error("could not serialise the compiled config: {0}")]
|
||||||
Serialize(String),
|
Serialize(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Compile to the Pingora runtime config read by ianitor-edge.
|
/// Compile to the Pingora runtime config read by ianitor-edge.
|
||||||
pub fn edge(model: &Model, options: &CompileOptions) -> Result<String, CompileError> {
|
pub fn edge(model: &Model, options: &CompileOptions) -> Result<String, CompileError> {
|
||||||
let _ = (model, options);
|
check_options(options)?;
|
||||||
Err(CompileError::Serialize("not implemented".into()))
|
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.
|
/// Compile to Caddy JSON for the caddy-fallback unit.
|
||||||
pub fn caddy(model: &Model, options: &CompileOptions) -> Result<String, CompileError> {
|
pub fn caddy(model: &Model, options: &CompileOptions) -> Result<String, CompileError> {
|
||||||
let _ = (model, options);
|
check_options(options)?;
|
||||||
Err(CompileError::Serialize("not implemented".into()))
|
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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,11 @@ use std::fmt;
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
pub enum ValidationError {
|
pub enum ValidationError {
|
||||||
#[error("{file}: the file is not valid TOML{}: {message}", line_suffix(*line))]
|
#[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}`")]
|
#[error("{file}: unknown field `{field}`")]
|
||||||
UnknownField { file: String, field: String },
|
UnknownField { file: String, field: String },
|
||||||
#[error("{file}: required field `{field}` is missing")]
|
#[error("{file}: required field `{field}` is missing")]
|
||||||
@@ -21,31 +25,55 @@ pub enum ValidationError {
|
|||||||
#[error("{file} appears twice in the routes")]
|
#[error("{file} appears twice in the routes")]
|
||||||
DuplicateFile { file: String },
|
DuplicateFile { file: String },
|
||||||
#[error("{file}: `{hostname}` is not a valid hostname: {reason}")]
|
#[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}")]
|
#[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")]
|
#[error("{file}: at least one upstream is needed")]
|
||||||
NoUpstreams { file: String },
|
NoUpstreams { file: String },
|
||||||
#[error("{file}: upstream `{url}` is not usable: {reason}")]
|
#[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")]
|
#[error("{file}: upstream `{url}` is listed twice")]
|
||||||
DuplicateUpstream { file: String, url: String },
|
DuplicateUpstream { file: String, url: String },
|
||||||
#[error("{file}: secret `{secret}` is used but not declared in the site file")]
|
#[error("{file}: secret `{secret}` is used but not declared in the site file")]
|
||||||
UndefinedSecret { file: String, secret: String },
|
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 },
|
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 },
|
InvalidSecretName { file: String, name: String },
|
||||||
#[error("{file}: `{name}` is not a valid header name")]
|
#[error("{file}: `{name}` is not a valid header name")]
|
||||||
InvalidHeaderName { file: String, name: String },
|
InvalidHeaderName { file: String, name: String },
|
||||||
#[error("{file}: value for header `{header}` is not allowed: {reason}")]
|
#[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")]
|
#[error("{file}: header `{header}` is managed by the proxy and cannot be changed by a rule")]
|
||||||
ProtectedHeader { file: String, header: String },
|
ProtectedHeader { file: String, header: String },
|
||||||
#[error("{file}: header `{header}` has more than one rule in the same list")]
|
#[error("{file}: header `{header}` has more than one rule in the same list")]
|
||||||
DuplicateHeaderRule { file: String, header: String },
|
DuplicateHeaderRule { file: String, header: String },
|
||||||
#[error("{file}: rule for header `{header}` is incomplete: {reason}")]
|
#[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}")]
|
#[error("{file}: health check is not usable: {reason}")]
|
||||||
BadHealthCheck { file: String, reason: &'static str },
|
BadHealthCheck { file: String, reason: &'static str },
|
||||||
#[error("{file}: auth = \"forward-auth\" needs a [forward_auth] section in the site file")]
|
#[error("{file}: auth = \"forward-auth\" needs a [forward_auth] section in the site file")]
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ mod validate;
|
|||||||
|
|
||||||
pub use error::{ValidationError, ValidationErrors};
|
pub use error::{ValidationError, ValidationErrors};
|
||||||
pub use model::{
|
pub use model::{
|
||||||
AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, HealthCheck, Host, Hostname,
|
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
|
||||||
Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost, AUTHELIA_COPY_HEADERS,
|
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, Model, Scheme,
|
||||||
LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING,
|
SecretName, Site, TlsMode, Upstream, UpstreamHost,
|
||||||
};
|
};
|
||||||
pub use validate::{load, SourceFile};
|
pub use validate::{SourceFile, load};
|
||||||
|
|||||||
@@ -222,4 +222,9 @@ pub const LETSENCRYPT_PRODUCTION: &str = "https://acme-v02.api.letsencrypt.org/d
|
|||||||
/// Let's Encrypt staging directory.
|
/// Let's Encrypt staging directory.
|
||||||
pub const LETSENCRYPT_STAGING: &str = "https://acme-staging-v02.api.letsencrypt.org/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).
|
/// 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",
|
||||||
|
];
|
||||||
|
|||||||
+147
-39
@@ -151,7 +151,9 @@ pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result<Model, Va
|
|||||||
let mut checked = Vec::new();
|
let mut checked = Vec::new();
|
||||||
for f in files {
|
for f in files {
|
||||||
if !seen_files.insert(f.name) {
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
match parse::<RawHost>(f) {
|
match parse::<RawHost>(f) {
|
||||||
@@ -178,7 +180,10 @@ pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result<Model, Va
|
|||||||
}
|
}
|
||||||
|
|
||||||
match site_model {
|
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)),
|
_ => Err(ValidationErrors(errors)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -215,7 +220,10 @@ fn classify(file: String, message: &str) -> E {
|
|||||||
} else if let Some(field) = quoted("missing field `") {
|
} else if let Some(field) = quoted("missing field `") {
|
||||||
E::MissingField { file, field }
|
E::MissingField { file, field }
|
||||||
} else {
|
} 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) {
|
if valid_secret_name(&name) {
|
||||||
secrets.insert(SecretName(name));
|
secrets.insert(SecretName(name));
|
||||||
} else {
|
} 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 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) {
|
let (upstream, path_and_query) = match parse_url(&fa.url, true) {
|
||||||
Ok(v) => v,
|
Ok(v) => v,
|
||||||
Err(reason) => {
|
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 {
|
let copy_headers: Vec<String> = match fa.copy_headers {
|
||||||
Some(h) => h,
|
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();
|
let mut seen = BTreeSet::new();
|
||||||
for h in ©_headers {
|
for h in ©_headers {
|
||||||
if !valid_header_name(h) {
|
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) {
|
} 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()) {
|
} else if !seen.insert(h.to_ascii_lowercase()) {
|
||||||
errors.push(bad("copy_headers lists a header twice"));
|
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 {
|
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) => {
|
Some(a) => {
|
||||||
let bad = |reason| E::BadAcme { file: file.to_owned(), reason };
|
let bad = |reason| E::BadAcme {
|
||||||
if let Some(email) = &a.email {
|
file: file.to_owned(),
|
||||||
if !valid_email(email) {
|
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"));
|
errors.push(bad("email is not a plain address like admin@example.org"));
|
||||||
}
|
}
|
||||||
}
|
let directory = a
|
||||||
let directory = a.directory.unwrap_or_else(|| LETSENCRYPT_PRODUCTION.to_owned());
|
.directory
|
||||||
|
.unwrap_or_else(|| LETSENCRYPT_PRODUCTION.to_owned());
|
||||||
if !valid_acme_directory(&directory) {
|
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 {
|
fn valid_secret_name(n: &str) -> bool {
|
||||||
@@ -283,15 +325,20 @@ fn valid_secret_name(n: &str) -> bool {
|
|||||||
!b.is_empty()
|
!b.is_empty()
|
||||||
&& b.len() <= 64
|
&& b.len() <= 64
|
||||||
&& (b[0].is_ascii_lowercase() || b[0].is_ascii_digit())
|
&& (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 {
|
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()
|
!local.is_empty()
|
||||||
&& e.len() <= 254
|
&& e.len() <= 254
|
||||||
&& check_hostname(domain).is_ok()
|
&& 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 {
|
fn valid_acme_directory(d: &str) -> bool {
|
||||||
@@ -302,7 +349,8 @@ fn valid_acme_directory(d: &str) -> bool {
|
|||||||
&& u.password().is_none()
|
&& u.password().is_none()
|
||||||
&& u.fragment().is_none()
|
&& u.fragment().is_none()
|
||||||
&& u.host().is_some()
|
&& 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,
|
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();
|
let f = || file.to_owned();
|
||||||
|
|
||||||
if let Err(reason) = check_hostname(&raw.hostname) {
|
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() {
|
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) {
|
match parse_url(u, false) {
|
||||||
Ok((up, _)) => {
|
Ok((up, _)) => {
|
||||||
if upstreams.contains(&up) {
|
if upstreams.contains(&up) {
|
||||||
errors.push(E::DuplicateUpstream { file: f(), url: u.clone() });
|
errors.push(E::DuplicateUpstream {
|
||||||
|
file: f(),
|
||||||
|
url: u.clone(),
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
upstreams.push(up);
|
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 {
|
let auth = match raw.auth {
|
||||||
RawAuth::None => AuthMode::None,
|
RawAuth::None => AuthMode::None,
|
||||||
RawAuth::ForwardAuth => AuthMode::ForwardAuth,
|
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.
|
// 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())) {
|
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, Some(fa)) => fa
|
||||||
(AuthMode::ForwardAuth, None) => AUTHELIA_COPY_HEADERS.iter().map(|h| h.to_ascii_lowercase()).collect(),
|
.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(),
|
_ => Vec::new(),
|
||||||
};
|
};
|
||||||
let request_headers = check_rules(file, raw.request_headers, true, &identity, site, errors);
|
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 bad = |reason| E::BadHealthCheck { file: f(), reason };
|
||||||
let ok_path = hc.path.starts_with('/')
|
let ok_path = hc.path.starts_with('/')
|
||||||
&& hc.path.len() <= 1024
|
&& 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 {
|
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;
|
return None;
|
||||||
}
|
}
|
||||||
match u32::try_from(hc.interval_secs) {
|
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"));
|
errors.push(bad("interval_secs must be between 1 and 3600"));
|
||||||
None
|
None
|
||||||
@@ -430,7 +512,10 @@ fn check_rules(
|
|||||||
for r in raw {
|
for r in raw {
|
||||||
let header = r.name.clone();
|
let header = r.name.clone();
|
||||||
if !valid_header_name(&r.name) {
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
let lower = r.name.to_ascii_lowercase();
|
let lower = r.name.to_ascii_lowercase();
|
||||||
@@ -442,23 +527,42 @@ fn check_rules(
|
|||||||
errors.push(E::DuplicateHeaderRule { file: f(), header });
|
errors.push(E::DuplicateHeaderRule { file: f(), header });
|
||||||
continue;
|
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) {
|
match (r.action, r.value, r.secret) {
|
||||||
(RawAction::Remove, None, None) => out.push(HeaderRule::Remove { name: r.name }),
|
(RawAction::Remove, None, None) => out.push(HeaderRule::Remove { name: r.name }),
|
||||||
(RawAction::Remove, _, _) => errors.push(bad("remove takes no value or secret")),
|
(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, None, None) => errors.push(bad("set needs a value or a secret")),
|
||||||
(RawAction::Set, Some(v), None) => match check_header_value(&v) {
|
(RawAction::Set, Some(v), None) => match check_header_value(&v) {
|
||||||
Ok(()) => out.push(HeaderRule::Set { name: r.name, value: HeaderValue::Literal(v) }),
|
Ok(()) => out.push(HeaderRule::Set {
|
||||||
Err(reason) => errors.push(E::InvalidHeaderValue { file: f(), header, reason }),
|
name: r.name,
|
||||||
|
value: HeaderValue::Literal(v),
|
||||||
|
}),
|
||||||
|
Err(reason) => errors.push(E::InvalidHeaderValue {
|
||||||
|
file: f(),
|
||||||
|
header,
|
||||||
|
reason,
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
(RawAction::Set, None, Some(s)) => {
|
(RawAction::Set, None, Some(s)) => {
|
||||||
if !request {
|
if !request {
|
||||||
errors.push(E::SecretInResponseHeader { file: f(), header });
|
errors.push(E::SecretInResponseHeader { file: f(), header });
|
||||||
} else if site.is_some_and(|site| !site.secrets.contains(&SecretName(s.clone()))) {
|
} 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 {
|
} 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 {
|
fn valid_header_name(n: &str) -> bool {
|
||||||
!n.is_empty()
|
!n.is_empty()
|
||||||
&& n.len() <= 256
|
&& 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> {
|
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 {
|
if label.len() > 63 {
|
||||||
return Err("a label is longer than 63 characters");
|
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");
|
return Err("only a-z, 0-9, '-' and '.' are allowed");
|
||||||
}
|
}
|
||||||
if label.starts_with('-') || label.ends_with('-') {
|
if label.starts_with('-') || label.ends_with('-') {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ use std::path::{Path, PathBuf};
|
|||||||
|
|
||||||
use ianitor_core::compile::{self, CompileError, CompileOptions};
|
use ianitor_core::compile::{self, CompileError, CompileOptions};
|
||||||
use ianitor_core::edge_config::EdgeConfig;
|
use ianitor_core::edge_config::EdgeConfig;
|
||||||
use ianitor_core::{load, Model, SourceFile};
|
use ianitor_core::{Model, SourceFile, load};
|
||||||
|
|
||||||
fn fixtures() -> PathBuf {
|
fn fixtures() -> PathBuf {
|
||||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/routes")
|
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/routes")
|
||||||
@@ -34,15 +34,33 @@ fn host_files(reverse: bool) -> Vec<(String, String)> {
|
|||||||
}
|
}
|
||||||
files
|
files
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|p| (format!("hosts/{}", p.file_name().unwrap().to_string_lossy()), read(&p)))
|
.map(|p| {
|
||||||
|
(
|
||||||
|
format!("hosts/{}", p.file_name().unwrap().to_string_lossy()),
|
||||||
|
read(&p),
|
||||||
|
)
|
||||||
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn model(reverse: bool) -> Model {
|
fn model(reverse: bool) -> Model {
|
||||||
let site = read(&fixtures().join("ianitor.toml"));
|
let site = read(&fixtures().join("ianitor.toml"));
|
||||||
let files = host_files(reverse);
|
let files = host_files(reverse);
|
||||||
let sources: Vec<SourceFile> = files.iter().map(|(n, c)| SourceFile { name: n, contents: c }).collect();
|
let sources: Vec<SourceFile> = files
|
||||||
load(&SourceFile { name: "ianitor.toml", contents: &site }, &sources).expect("fixtures are valid")
|
.iter()
|
||||||
|
.map(|(n, c)| SourceFile {
|
||||||
|
name: n,
|
||||||
|
contents: c,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: &site,
|
||||||
|
},
|
||||||
|
&sources,
|
||||||
|
)
|
||||||
|
.expect("fixtures are valid")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn options() -> CompileOptions {
|
fn options() -> CompileOptions {
|
||||||
@@ -64,7 +82,11 @@ fn edge_compiler_is_deterministic() {
|
|||||||
for _ in 0..50 {
|
for _ in 0..50 {
|
||||||
assert_eq!(first, compile::edge(&m, &options()).unwrap());
|
assert_eq!(first, compile::edge(&m, &options()).unwrap());
|
||||||
}
|
}
|
||||||
assert_eq!(first, compile::edge(&model(true), &options()).unwrap(), "file order must not matter");
|
assert_eq!(
|
||||||
|
first,
|
||||||
|
compile::edge(&model(true), &options()).unwrap(),
|
||||||
|
"file order must not matter"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -74,7 +96,11 @@ fn caddy_compiler_is_deterministic() {
|
|||||||
for _ in 0..50 {
|
for _ in 0..50 {
|
||||||
assert_eq!(first, compile::caddy(&m, &options()).unwrap());
|
assert_eq!(first, compile::caddy(&m, &options()).unwrap());
|
||||||
}
|
}
|
||||||
assert_eq!(first, compile::caddy(&model(true), &options()).unwrap(), "file order must not matter");
|
assert_eq!(
|
||||||
|
first,
|
||||||
|
compile::caddy(&model(true), &options()).unwrap(),
|
||||||
|
"file order must not matter"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -84,7 +110,10 @@ fn determinism_holds_across_threads() {
|
|||||||
.map(|i| {
|
.map(|i| {
|
||||||
s.spawn(move || {
|
s.spawn(move || {
|
||||||
let m = model(i % 2 == 0);
|
let m = model(i % 2 == 0);
|
||||||
(compile::edge(&m, &options()).unwrap(), compile::caddy(&m, &options()).unwrap())
|
(
|
||||||
|
compile::edge(&m, &options()).unwrap(),
|
||||||
|
compile::caddy(&m, &options()).unwrap(),
|
||||||
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -124,7 +153,10 @@ fn caddy_output_is_valid_json_with_servers() {
|
|||||||
fn outputs_reference_secrets_by_name_only() {
|
fn outputs_reference_secrets_by_name_only() {
|
||||||
let edge = compile::edge(&model(false), &options()).unwrap();
|
let edge = compile::edge(&model(false), &options()).unwrap();
|
||||||
let caddy = compile::caddy(&model(false), &options()).unwrap();
|
let caddy = compile::caddy(&model(false), &options()).unwrap();
|
||||||
assert!(edge.contains("\"photos_api_key\""), "edge config names the secret");
|
assert!(
|
||||||
|
edge.contains("\"photos_api_key\""),
|
||||||
|
"edge config names the secret"
|
||||||
|
);
|
||||||
assert!(caddy.contains("{file./run/credentials/caddy-fallback.service/photos_api_key}"));
|
assert!(caddy.contains("{file./run/credentials/caddy-fallback.service/photos_api_key}"));
|
||||||
// The compilers never see secret values, so nothing secret-shaped can be in the output.
|
// The compilers never see secret values, so nothing secret-shaped can be in the output.
|
||||||
for out in [&edge, &caddy] {
|
for out in [&edge, &caddy] {
|
||||||
@@ -136,8 +168,14 @@ fn outputs_reference_secrets_by_name_only() {
|
|||||||
fn rejects_relative_paths_in_options() {
|
fn rejects_relative_paths_in_options() {
|
||||||
let mut o = options();
|
let mut o = options();
|
||||||
o.cert_dir = "certs".into();
|
o.cert_dir = "certs".into();
|
||||||
assert!(matches!(compile::edge(&model(false), &o), Err(CompileError::BadOption { .. })));
|
assert!(matches!(
|
||||||
assert!(matches!(compile::caddy(&model(false), &o), Err(CompileError::BadOption { .. })));
|
compile::edge(&model(false), &o),
|
||||||
|
Err(CompileError::BadOption { .. })
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
compile::caddy(&model(false), &o),
|
||||||
|
Err(CompileError::BadOption { .. })
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -150,7 +188,9 @@ fn rejects_path_options_that_would_break_out_of_json_or_placeholders() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn golden(name: &str, actual: &str) {
|
fn golden(name: &str, actual: &str) {
|
||||||
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden").join(name);
|
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
.join("tests/golden")
|
||||||
|
.join(name);
|
||||||
if std::env::var_os("IANITOR_UPDATE_GOLDEN").is_some() {
|
if std::env::var_os("IANITOR_UPDATE_GOLDEN").is_some() {
|
||||||
std::fs::write(&path, actual).unwrap();
|
std::fs::write(&path, actual).unwrap();
|
||||||
return;
|
return;
|
||||||
@@ -164,10 +204,16 @@ fn golden(name: &str, actual: &str) {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn edge_output_matches_golden_file() {
|
fn edge_output_matches_golden_file() {
|
||||||
golden("edge.json", &compile::edge(&model(false), &options()).unwrap());
|
golden(
|
||||||
|
"edge.json",
|
||||||
|
&compile::edge(&model(false), &options()).unwrap(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn caddy_output_matches_golden_file() {
|
fn caddy_output_matches_golden_file() {
|
||||||
golden("caddy.json", &compile::caddy(&model(false), &options()).unwrap());
|
golden(
|
||||||
|
"caddy.json",
|
||||||
|
&compile::caddy(&model(false), &options()).unwrap(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,558 @@
|
|||||||
|
{
|
||||||
|
"admin": {
|
||||||
|
"disabled": true
|
||||||
|
},
|
||||||
|
"apps": {
|
||||||
|
"http": {
|
||||||
|
"http_port": 80,
|
||||||
|
"https_port": 443,
|
||||||
|
"servers": {
|
||||||
|
"ianitor_http": {
|
||||||
|
"automatic_https": {
|
||||||
|
"disable_redirects": true
|
||||||
|
},
|
||||||
|
"listen": [
|
||||||
|
"0.0.0.0:80"
|
||||||
|
],
|
||||||
|
"protocols": [
|
||||||
|
"h1"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "static_response",
|
||||||
|
"headers": {
|
||||||
|
"Location": [
|
||||||
|
"https://{http.request.host}{http.request.uri}"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"status_code": 308
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"photos.example.org",
|
||||||
|
"status.example.org",
|
||||||
|
"wiki.home.test"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "static_response",
|
||||||
|
"status_code": 404
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"ianitor_https": {
|
||||||
|
"automatic_https": {
|
||||||
|
"disable_redirects": true,
|
||||||
|
"skip_certificates": [
|
||||||
|
"wiki.home.test"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"listen": [
|
||||||
|
"0.0.0.0:443"
|
||||||
|
],
|
||||||
|
"logs": {
|
||||||
|
"logger_names": {
|
||||||
|
"photos.example.org": [
|
||||||
|
"ianitor_access"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"skip_unmapped_hosts": true
|
||||||
|
},
|
||||||
|
"protocols": [
|
||||||
|
"h1",
|
||||||
|
"h2"
|
||||||
|
],
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "reverse_proxy",
|
||||||
|
"headers": {
|
||||||
|
"request": {
|
||||||
|
"delete": [
|
||||||
|
"X-Debug"
|
||||||
|
],
|
||||||
|
"set": {
|
||||||
|
"X-Api-Key": [
|
||||||
|
"{file./run/credentials/caddy-fallback.service/photos_api_key}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"response": {
|
||||||
|
"delete": [
|
||||||
|
"X-Powered-By"
|
||||||
|
],
|
||||||
|
"set": {
|
||||||
|
"Strict-Transport-Security": [
|
||||||
|
"max-age=31536000"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"health_checks": {
|
||||||
|
"active": {
|
||||||
|
"interval": "15s",
|
||||||
|
"timeout": "5s",
|
||||||
|
"uri": "/api/v1/status"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"load_balancing": {
|
||||||
|
"selection_policy": {
|
||||||
|
"policy": "round_robin"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"dial": "127.0.0.1:2342"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"dial": "127.0.0.1:2343"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"photos.example.org"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "reverse_proxy",
|
||||||
|
"load_balancing": {
|
||||||
|
"selection_policy": {
|
||||||
|
"policy": "round_robin"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"dial": "[::1]:3001"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"status.example.org"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "subroute",
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handle_response": [
|
||||||
|
{
|
||||||
|
"match": {
|
||||||
|
"status_code": [
|
||||||
|
2
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"routes": [
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "vars"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"delete": [
|
||||||
|
"Remote-User"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"set": {
|
||||||
|
"Remote-User": [
|
||||||
|
"{http.reverse_proxy.header.Remote-User}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"not": [
|
||||||
|
{
|
||||||
|
"vars": {
|
||||||
|
"{http.reverse_proxy.header.Remote-User}": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"delete": [
|
||||||
|
"Remote-Groups"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"set": {
|
||||||
|
"Remote-Groups": [
|
||||||
|
"{http.reverse_proxy.header.Remote-Groups}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"not": [
|
||||||
|
{
|
||||||
|
"vars": {
|
||||||
|
"{http.reverse_proxy.header.Remote-Groups}": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"delete": [
|
||||||
|
"Remote-Email"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"set": {
|
||||||
|
"Remote-Email": [
|
||||||
|
"{http.reverse_proxy.header.Remote-Email}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"not": [
|
||||||
|
{
|
||||||
|
"vars": {
|
||||||
|
"{http.reverse_proxy.header.Remote-Email}": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"delete": [
|
||||||
|
"Remote-Name"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "headers",
|
||||||
|
"request": {
|
||||||
|
"set": {
|
||||||
|
"Remote-Name": [
|
||||||
|
"{http.reverse_proxy.header.Remote-Name}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"not": [
|
||||||
|
{
|
||||||
|
"vars": {
|
||||||
|
"{http.reverse_proxy.header.Remote-Name}": [
|
||||||
|
""
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"handler": "reverse_proxy",
|
||||||
|
"headers": {
|
||||||
|
"request": {
|
||||||
|
"set": {
|
||||||
|
"X-Forwarded-Method": [
|
||||||
|
"{http.request.method}"
|
||||||
|
],
|
||||||
|
"X-Forwarded-Uri": [
|
||||||
|
"{http.request.uri}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"rewrite": {
|
||||||
|
"method": "GET",
|
||||||
|
"uri": "/api/authz/forward-auth"
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"dial": "127.0.0.1:9091"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "static_response",
|
||||||
|
"status_code": 403
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"header_regexp": {
|
||||||
|
"Upgrade": {
|
||||||
|
"pattern": "(?i)^websocket$"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "reverse_proxy",
|
||||||
|
"headers": {
|
||||||
|
"request": {
|
||||||
|
"set": {
|
||||||
|
"Authorization": [
|
||||||
|
"{file./run/credentials/caddy-fallback.service/wiki_token}"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"load_balancing": {
|
||||||
|
"selection_policy": {
|
||||||
|
"policy": "round_robin"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"transport": {
|
||||||
|
"protocol": "http",
|
||||||
|
"tls": {}
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"dial": "wiki.lan:8443"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"match": [
|
||||||
|
{
|
||||||
|
"host": [
|
||||||
|
"wiki.home.test"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"terminal": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"handle": [
|
||||||
|
{
|
||||||
|
"handler": "static_response",
|
||||||
|
"status_code": 404
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"tls_connection_policies": [
|
||||||
|
{
|
||||||
|
"certificate_selection": {
|
||||||
|
"any_tag": [
|
||||||
|
"ianitor:wiki.home.test"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"match": {
|
||||||
|
"sni": [
|
||||||
|
"wiki.home.test"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"tls": {
|
||||||
|
"automation": {
|
||||||
|
"policies": [
|
||||||
|
{
|
||||||
|
"issuers": [
|
||||||
|
{
|
||||||
|
"ca": "https://acme-staging-v02.api.letsencrypt.org/directory",
|
||||||
|
"email": "admin@example.org",
|
||||||
|
"module": "acme"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"subjects": [
|
||||||
|
"photos.example.org",
|
||||||
|
"status.example.org"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"certificates": {
|
||||||
|
"load_files": [
|
||||||
|
{
|
||||||
|
"certificate": "/var/lib/ianitor/certs/wiki.home.test.crt",
|
||||||
|
"key": "/var/lib/ianitor/certs/wiki.home.test.key",
|
||||||
|
"tags": [
|
||||||
|
"ianitor:wiki.home.test"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"logging": {
|
||||||
|
"logs": {
|
||||||
|
"default": {
|
||||||
|
"exclude": [
|
||||||
|
"http.log.access.ianitor_access"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"ianitor_access": {
|
||||||
|
"encoder": {
|
||||||
|
"fields": {
|
||||||
|
"request>client_ip": {
|
||||||
|
"filter": "ip_mask",
|
||||||
|
"ipv4_cidr": 24,
|
||||||
|
"ipv6_cidr": 48
|
||||||
|
},
|
||||||
|
"request>headers": {
|
||||||
|
"filter": "delete"
|
||||||
|
},
|
||||||
|
"request>remote_ip": {
|
||||||
|
"filter": "ip_mask",
|
||||||
|
"ipv4_cidr": 24,
|
||||||
|
"ipv6_cidr": 48
|
||||||
|
},
|
||||||
|
"request>remote_port": {
|
||||||
|
"filter": "delete"
|
||||||
|
},
|
||||||
|
"request>tls": {
|
||||||
|
"filter": "delete"
|
||||||
|
},
|
||||||
|
"request>uri": {
|
||||||
|
"filter": "regexp",
|
||||||
|
"regexp": "\\?.*$",
|
||||||
|
"value": ""
|
||||||
|
},
|
||||||
|
"resp_headers": {
|
||||||
|
"filter": "delete"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"format": "filter",
|
||||||
|
"wrap": {
|
||||||
|
"format": "json"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"http.log.access.ianitor_access"
|
||||||
|
],
|
||||||
|
"writer": {
|
||||||
|
"filename": "/var/log/ianitor/access.log",
|
||||||
|
"output": "file"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"storage": {
|
||||||
|
"module": "file_system",
|
||||||
|
"root": "/var/lib/ianitor/caddy"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"http_listen": "0.0.0.0:80",
|
||||||
|
"https_listen": "0.0.0.0:443",
|
||||||
|
"https_port": 443,
|
||||||
|
"cert_dir": "/var/lib/ianitor/certs",
|
||||||
|
"state_dir": "/var/lib/ianitor",
|
||||||
|
"access_log": "/var/log/ianitor/access.log",
|
||||||
|
"acme": {
|
||||||
|
"directory": "https://acme-staging-v02.api.letsencrypt.org/directory",
|
||||||
|
"email": "admin@example.org"
|
||||||
|
},
|
||||||
|
"forward_auth": {
|
||||||
|
"upstream": {
|
||||||
|
"address": "127.0.0.1:9091",
|
||||||
|
"tls": false,
|
||||||
|
"sni": ""
|
||||||
|
},
|
||||||
|
"path_and_query": "/api/authz/forward-auth",
|
||||||
|
"copy_headers": [
|
||||||
|
"Remote-User",
|
||||||
|
"Remote-Groups",
|
||||||
|
"Remote-Email",
|
||||||
|
"Remote-Name"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"hosts": [
|
||||||
|
{
|
||||||
|
"hostname": "photos.example.org",
|
||||||
|
"tls": {
|
||||||
|
"source": "acme"
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"address": "127.0.0.1:2342",
|
||||||
|
"tls": false,
|
||||||
|
"sni": ""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"address": "127.0.0.1:2343",
|
||||||
|
"tls": false,
|
||||||
|
"sni": ""
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"forward_auth": false,
|
||||||
|
"websockets": true,
|
||||||
|
"request_headers": [
|
||||||
|
{
|
||||||
|
"op": "set",
|
||||||
|
"name": "X-Api-Key",
|
||||||
|
"value": {
|
||||||
|
"kind": "secret",
|
||||||
|
"name": "photos_api_key"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"op": "remove",
|
||||||
|
"name": "X-Debug"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"response_headers": [
|
||||||
|
{
|
||||||
|
"op": "set",
|
||||||
|
"name": "Strict-Transport-Security",
|
||||||
|
"value": {
|
||||||
|
"kind": "literal",
|
||||||
|
"value": "max-age=31536000"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"op": "remove",
|
||||||
|
"name": "X-Powered-By"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"health_check": {
|
||||||
|
"path": "/api/v1/status",
|
||||||
|
"interval_secs": 15
|
||||||
|
},
|
||||||
|
"access_log": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"hostname": "status.example.org",
|
||||||
|
"tls": {
|
||||||
|
"source": "acme"
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"address": "[::1]:3001",
|
||||||
|
"tls": false,
|
||||||
|
"sni": ""
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"forward_auth": false,
|
||||||
|
"websockets": true,
|
||||||
|
"request_headers": [],
|
||||||
|
"response_headers": [],
|
||||||
|
"health_check": null,
|
||||||
|
"access_log": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"hostname": "wiki.home.test",
|
||||||
|
"tls": {
|
||||||
|
"source": "files",
|
||||||
|
"cert": "/var/lib/ianitor/certs/wiki.home.test.crt",
|
||||||
|
"key": "/var/lib/ianitor/certs/wiki.home.test.key"
|
||||||
|
},
|
||||||
|
"upstreams": [
|
||||||
|
{
|
||||||
|
"address": "wiki.lan:8443",
|
||||||
|
"tls": true,
|
||||||
|
"sni": "wiki.lan"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"forward_auth": true,
|
||||||
|
"websockets": false,
|
||||||
|
"request_headers": [
|
||||||
|
{
|
||||||
|
"op": "set",
|
||||||
|
"name": "Authorization",
|
||||||
|
"value": {
|
||||||
|
"kind": "secret",
|
||||||
|
"name": "wiki_token"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"response_headers": [],
|
||||||
|
"health_check": null,
|
||||||
|
"access_log": false
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
+352
-76
@@ -8,8 +8,8 @@
|
|||||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
|
||||||
use ianitor_core::{
|
use ianitor_core::{
|
||||||
load, AccessLog, AuthMode, HeaderRule, HeaderValue, SourceFile, TlsMode, ValidationError,
|
AccessLog, AuthMode, HeaderRule, HeaderValue, SourceFile, TlsMode, ValidationError,
|
||||||
ValidationErrors,
|
ValidationErrors, load,
|
||||||
};
|
};
|
||||||
|
|
||||||
const SITE: &str = r#"
|
const SITE: &str = r#"
|
||||||
@@ -20,11 +20,20 @@ url = "http://127.0.0.1:9091/api/authz/forward-auth"
|
|||||||
"#;
|
"#;
|
||||||
|
|
||||||
fn site() -> SourceFile<'static> {
|
fn site() -> SourceFile<'static> {
|
||||||
SourceFile { name: "ianitor.toml", contents: SITE }
|
SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: SITE,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn one(contents: &str) -> Result<ianitor_core::Model, ValidationErrors> {
|
fn one(contents: &str) -> Result<ianitor_core::Model, ValidationErrors> {
|
||||||
load(&site(), &[SourceFile { name: "hosts/app.test.toml", contents }])
|
load(
|
||||||
|
&site(),
|
||||||
|
&[SourceFile {
|
||||||
|
name: "hosts/app.test.toml",
|
||||||
|
contents,
|
||||||
|
}],
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn errors(contents: &str) -> Vec<ValidationError> {
|
fn errors(contents: &str) -> Vec<ValidationError> {
|
||||||
@@ -68,10 +77,9 @@ fn minimal_host_gets_documented_defaults() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn full_host_is_accepted() {
|
fn full_host_is_accepted() {
|
||||||
let model = one(
|
let model = one(r#"
|
||||||
r#"
|
|
||||||
hostname = "app.test"
|
hostname = "app.test"
|
||||||
upstreams = ["http://127.0.0.1:8080", "https://backend.lan", "http://[::1]:9000/"]
|
upstreams = ["https://127.0.0.1:8443", "https://backend.lan", "https://[::1]:9000/"]
|
||||||
tls = "domi"
|
tls = "domi"
|
||||||
auth = "forward-auth"
|
auth = "forward-auth"
|
||||||
websockets = false
|
websockets = false
|
||||||
@@ -95,8 +103,7 @@ name = "X-Debug"
|
|||||||
action = "set"
|
action = "set"
|
||||||
name = "Strict-Transport-Security"
|
name = "Strict-Transport-Security"
|
||||||
value = "max-age=31536000"
|
value = "max-age=31536000"
|
||||||
"#,
|
"#)
|
||||||
)
|
|
||||||
.expect("full host is valid");
|
.expect("full host is valid");
|
||||||
let h = &model.hosts()[0];
|
let h = &model.hosts()[0];
|
||||||
assert_eq!(h.tls, TlsMode::Domi);
|
assert_eq!(h.tls, TlsMode::Domi);
|
||||||
@@ -108,12 +115,27 @@ value = "max-age=31536000"
|
|||||||
assert_eq!(hc.path, "/healthz");
|
assert_eq!(hc.path, "/healthz");
|
||||||
assert_eq!(hc.interval_secs, 10);
|
assert_eq!(hc.interval_secs, 10);
|
||||||
let ups: Vec<String> = h.upstreams.iter().map(|u| u.to_string()).collect();
|
let ups: Vec<String> = h.upstreams.iter().map(|u| u.to_string()).collect();
|
||||||
assert_eq!(ups, ["http://127.0.0.1:8080", "https://backend.lan:443", "http://[::1]:9000"]);
|
assert_eq!(
|
||||||
|
ups,
|
||||||
|
[
|
||||||
|
"https://127.0.0.1:8443",
|
||||||
|
"https://backend.lan:443",
|
||||||
|
"https://[::1]:9000"
|
||||||
|
]
|
||||||
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
h.request_headers[0],
|
h.request_headers[0],
|
||||||
HeaderRule::Set { name: "X-Api-Key".into(), value: HeaderValue::Secret("api_key".into()) }
|
HeaderRule::Set {
|
||||||
|
name: "X-Api-Key".into(),
|
||||||
|
value: HeaderValue::Secret("api_key".into())
|
||||||
|
}
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
h.request_headers[1],
|
||||||
|
HeaderRule::Remove {
|
||||||
|
name: "X-Debug".into()
|
||||||
|
}
|
||||||
);
|
);
|
||||||
assert_eq!(h.request_headers[1], HeaderRule::Remove { name: "X-Debug".into() });
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
h.response_headers[0],
|
h.response_headers[0],
|
||||||
HeaderRule::Set {
|
HeaderRule::Set {
|
||||||
@@ -125,18 +147,38 @@ value = "max-age=31536000"
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn hosts_are_sorted_by_hostname_whatever_the_file_order() {
|
fn hosts_are_sorted_by_hostname_whatever_the_file_order() {
|
||||||
let a = SourceFile { name: "b.toml", contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n" };
|
let a = SourceFile {
|
||||||
let b = SourceFile { name: "a.toml", contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n" };
|
name: "b.toml",
|
||||||
|
contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||||
|
};
|
||||||
|
let b = SourceFile {
|
||||||
|
name: "a.toml",
|
||||||
|
contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||||
|
};
|
||||||
let m1 = load(&site(), &[a, b]).unwrap();
|
let m1 = load(&site(), &[a, b]).unwrap();
|
||||||
let m2 = load(&site(), &[b, a]).unwrap();
|
let m2 = load(&site(), &[b, a]).unwrap();
|
||||||
let names = |m: &ianitor_core::Model| m.hosts().iter().map(|h| h.hostname.to_string()).collect::<Vec<_>>();
|
let names = |m: &ianitor_core::Model| {
|
||||||
|
m.hosts()
|
||||||
|
.iter()
|
||||||
|
.map(|h| h.hostname.to_string())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
};
|
||||||
assert_eq!(names(&m1), ["a.test", "b.test"]);
|
assert_eq!(names(&m1), ["a.test", "b.test"]);
|
||||||
assert_eq!(m1, m2);
|
assert_eq!(m1, m2);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn empty_site_file_is_allowed() {
|
fn empty_site_file_is_allowed() {
|
||||||
let m = load(&SourceFile { name: "ianitor.toml", contents: "" }, &[SourceFile { name: "a.toml", contents: MINIMAL }]);
|
let m = load(
|
||||||
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: "",
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "a.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
}],
|
||||||
|
);
|
||||||
assert!(m.is_ok(), "{m:?}");
|
assert!(m.is_ok(), "{m:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,20 +187,34 @@ fn empty_site_file_is_allowed() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn rejects_unknown_top_level_field() {
|
fn rejects_unknown_top_level_field() {
|
||||||
let e = single_error(&format!("{MINIMAL}colour = \"red\"\n"));
|
let e = single_error(&format!("{MINIMAL}colour = \"red\"\n"));
|
||||||
assert_eq!(e, ValidationError::UnknownField { file: "hosts/app.test.toml".into(), field: "colour".into() });
|
assert_eq!(
|
||||||
|
e,
|
||||||
|
ValidationError::UnknownField {
|
||||||
|
file: "hosts/app.test.toml".into(),
|
||||||
|
field: "colour".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_misspelled_field() {
|
fn rejects_misspelled_field() {
|
||||||
let e = single_error("hostname = \"app.test\"\nupstream = [\"http://127.0.0.1:1\"]\n");
|
let e = single_error("hostname = \"app.test\"\nupstream = [\"http://127.0.0.1:1\"]\n");
|
||||||
// `upstream` is unknown; it is reported before the missing `upstreams`.
|
// `upstream` is unknown; it is reported before the missing `upstreams`.
|
||||||
assert!(matches!(e, ValidationError::UnknownField { ref field, .. } if field == "upstream"), "{e:?}");
|
assert!(
|
||||||
|
matches!(e, ValidationError::UnknownField { ref field, .. } if field == "upstream"),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_unknown_field_in_health_check() {
|
fn rejects_unknown_field_in_health_check() {
|
||||||
let e = single_error(&format!("{MINIMAL}[health_check]\npath = \"/h\"\ninterval_secs = 5\ntimeout = 3\n"));
|
let e = single_error(&format!(
|
||||||
assert!(matches!(e, ValidationError::UnknownField { ref field, .. } if field == "timeout"), "{e:?}");
|
"{MINIMAL}[health_check]\npath = \"/h\"\ninterval_secs = 5\ntimeout = 3\n"
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::UnknownField { ref field, .. } if field == "timeout"),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -166,14 +222,23 @@ fn rejects_unknown_field_in_header_rule() {
|
|||||||
let e = single_error(&format!(
|
let e = single_error(&format!(
|
||||||
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\nappend = true\n"
|
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\nappend = true\n"
|
||||||
));
|
));
|
||||||
assert!(matches!(e, ValidationError::UnknownField { ref field, .. } if field == "append"), "{e:?}");
|
assert!(
|
||||||
|
matches!(e, ValidationError::UnknownField { ref field, .. } if field == "append"),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_unknown_field_in_site_file() {
|
fn rejects_unknown_field_in_site_file() {
|
||||||
let r = load(
|
let r = load(
|
||||||
&SourceFile { name: "ianitor.toml", contents: "secrets = []\nsecret_values = { a = \"b\" }\n" },
|
&SourceFile {
|
||||||
&[SourceFile { name: "a.toml", contents: MINIMAL }],
|
name: "ianitor.toml",
|
||||||
|
contents: "secrets = []\nsecret_values = { a = \"b\" }\n",
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "a.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
}],
|
||||||
);
|
);
|
||||||
let errs = r.unwrap_err();
|
let errs = r.unwrap_err();
|
||||||
assert!(
|
assert!(
|
||||||
@@ -184,7 +249,9 @@ fn rejects_unknown_field_in_site_file() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_unknown_enum_value() {
|
fn rejects_unknown_enum_value() {
|
||||||
let e = single_error("hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\ntls = \"selfsigned\"\n");
|
let e = single_error(
|
||||||
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\ntls = \"selfsigned\"\n",
|
||||||
|
);
|
||||||
assert!(matches!(e, ValidationError::InvalidValue { .. }), "{e:?}");
|
assert!(matches!(e, ValidationError::InvalidValue { .. }), "{e:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,13 +272,25 @@ fn rejects_toml_syntax_error() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn rejects_missing_hostname() {
|
fn rejects_missing_hostname() {
|
||||||
let e = single_error("upstreams = [\"http://127.0.0.1:8080\"]\n");
|
let e = single_error("upstreams = [\"http://127.0.0.1:8080\"]\n");
|
||||||
assert_eq!(e, ValidationError::MissingField { file: "hosts/app.test.toml".into(), field: "hostname".into() });
|
assert_eq!(
|
||||||
|
e,
|
||||||
|
ValidationError::MissingField {
|
||||||
|
file: "hosts/app.test.toml".into(),
|
||||||
|
field: "hostname".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_missing_upstreams() {
|
fn rejects_missing_upstreams() {
|
||||||
let e = single_error("hostname = \"app.test\"\n");
|
let e = single_error("hostname = \"app.test\"\n");
|
||||||
assert_eq!(e, ValidationError::MissingField { file: "hosts/app.test.toml".into(), field: "upstreams".into() });
|
assert_eq!(
|
||||||
|
e,
|
||||||
|
ValidationError::MissingField {
|
||||||
|
file: "hosts/app.test.toml".into(),
|
||||||
|
field: "upstreams".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -219,11 +298,26 @@ fn rejects_bad_hostnames() {
|
|||||||
let long_label = format!("{}.test", "a".repeat(64));
|
let long_label = format!("{}.test", "a".repeat(64));
|
||||||
let long_name = format!("{}test", "abcdefghi.".repeat(26));
|
let long_name = format!("{}test", "abcdefghi.".repeat(26));
|
||||||
for bad in [
|
for bad in [
|
||||||
"", "UPPER.test", "-bad.test", "bad-.test", "a..b", "*.wild.test", "1.2.3.4", "[::1]",
|
"",
|
||||||
"has space.test", "under_score.test", "app.test.", ".app.test", "app.test:443",
|
"UPPER.test",
|
||||||
long_label.as_str(), long_name.as_str(), "ünicode.test",
|
"-bad.test",
|
||||||
|
"bad-.test",
|
||||||
|
"a..b",
|
||||||
|
"*.wild.test",
|
||||||
|
"1.2.3.4",
|
||||||
|
"[::1]",
|
||||||
|
"has space.test",
|
||||||
|
"under_score.test",
|
||||||
|
"app.test.",
|
||||||
|
".app.test",
|
||||||
|
"app.test:443",
|
||||||
|
long_label.as_str(),
|
||||||
|
long_name.as_str(),
|
||||||
|
"ünicode.test",
|
||||||
] {
|
] {
|
||||||
let e = single_error(&format!("hostname = {bad:?}\nupstreams = [\"http://127.0.0.1:1\"]\n"));
|
let e = single_error(&format!(
|
||||||
|
"hostname = {bad:?}\nupstreams = [\"http://127.0.0.1:1\"]\n"
|
||||||
|
));
|
||||||
assert!(
|
assert!(
|
||||||
matches!(e, ValidationError::InvalidHostname { ref hostname, .. } if hostname == bad),
|
matches!(e, ValidationError::InvalidHostname { ref hostname, .. } if hostname == bad),
|
||||||
"hostname {bad:?} gave {e:?}"
|
"hostname {bad:?} gave {e:?}"
|
||||||
@@ -233,8 +327,16 @@ fn rejects_bad_hostnames() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn accepts_good_hostnames() {
|
fn accepts_good_hostnames() {
|
||||||
for good in ["localhost", "a.b", "app.test", "x-1.example.org", "0day.example.org"] {
|
for good in [
|
||||||
let r = one(&format!("hostname = {good:?}\nupstreams = [\"http://127.0.0.1:1\"]\n"));
|
"localhost",
|
||||||
|
"a.b",
|
||||||
|
"app.test",
|
||||||
|
"x-1.example.org",
|
||||||
|
"0day.example.org",
|
||||||
|
] {
|
||||||
|
let r = one(&format!(
|
||||||
|
"hostname = {good:?}\nupstreams = [\"http://127.0.0.1:1\"]\n"
|
||||||
|
));
|
||||||
assert!(r.is_ok(), "{good}: {r:?}");
|
assert!(r.is_ok(), "{good}: {r:?}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -244,8 +346,14 @@ fn rejects_duplicate_hostnames_across_files() {
|
|||||||
let r = load(
|
let r = load(
|
||||||
&site(),
|
&site(),
|
||||||
&[
|
&[
|
||||||
SourceFile { name: "hosts/one.toml", contents: MINIMAL },
|
SourceFile {
|
||||||
SourceFile { name: "hosts/two.toml", contents: MINIMAL },
|
name: "hosts/one.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
},
|
||||||
|
SourceFile {
|
||||||
|
name: "hosts/two.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
},
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
let errs = r.unwrap_err();
|
let errs = r.unwrap_err();
|
||||||
@@ -264,21 +372,43 @@ fn duplicate_detection_is_independent_of_file_order() {
|
|||||||
let r = load(
|
let r = load(
|
||||||
&site(),
|
&site(),
|
||||||
&[
|
&[
|
||||||
SourceFile { name: "hosts/two.toml", contents: MINIMAL },
|
SourceFile {
|
||||||
SourceFile { name: "hosts/one.toml", contents: MINIMAL },
|
name: "hosts/two.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
},
|
||||||
|
SourceFile {
|
||||||
|
name: "hosts/one.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
},
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
let errs = r.unwrap_err();
|
let errs = r.unwrap_err();
|
||||||
assert!(matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/one.toml" && second == "hosts/two.toml"));
|
assert!(
|
||||||
|
matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/one.toml" && second == "hosts/two.toml")
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_duplicate_source_file_names() {
|
fn rejects_duplicate_source_file_names() {
|
||||||
let r = load(
|
let r = load(
|
||||||
&site(),
|
&site(),
|
||||||
&[SourceFile { name: "a.toml", contents: MINIMAL }, SourceFile { name: "a.toml", contents: MINIMAL }],
|
&[
|
||||||
|
SourceFile {
|
||||||
|
name: "a.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
},
|
||||||
|
SourceFile {
|
||||||
|
name: "a.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
r.unwrap_err()
|
||||||
|
.errors()
|
||||||
|
.iter()
|
||||||
|
.any(|e| matches!(e, ValidationError::DuplicateFile { .. }))
|
||||||
);
|
);
|
||||||
assert!(r.unwrap_err().errors().iter().any(|e| matches!(e, ValidationError::DuplicateFile { .. })));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- upstreams
|
// ---------------------------------------------------------------- upstreams
|
||||||
@@ -310,6 +440,17 @@ fn rejects_bad_upstream_urls() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_mixed_upstream_schemes() {
|
||||||
|
// Caddy has one transport per reverse_proxy handler, so a host cannot mix http and https.
|
||||||
|
let e = single_error(
|
||||||
|
"hostname = \"app.test\"
|
||||||
|
upstreams = [\"http://127.0.0.1:1\", \"https://127.0.0.1:2\"]
|
||||||
|
",
|
||||||
|
);
|
||||||
|
assert!(matches!(e, ValidationError::BadUpstreamUrl { .. }), "{e:?}");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_empty_upstream_list() {
|
fn rejects_empty_upstream_list() {
|
||||||
let e = single_error("hostname = \"app.test\"\nupstreams = []\n");
|
let e = single_error("hostname = \"app.test\"\nupstreams = []\n");
|
||||||
@@ -318,8 +459,13 @@ fn rejects_empty_upstream_list() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_duplicate_upstreams() {
|
fn rejects_duplicate_upstreams() {
|
||||||
let e = single_error("hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:80\", \"http://127.0.0.1\"]\n");
|
let e = single_error(
|
||||||
assert!(matches!(e, ValidationError::DuplicateUpstream { .. }), "{e:?}");
|
"hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:80\", \"http://127.0.0.1\"]\n",
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::DuplicateUpstream { .. }),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- secrets
|
// ---------------------------------------------------------------- secrets
|
||||||
@@ -329,19 +475,35 @@ fn rejects_undefined_secret_reference() {
|
|||||||
let e = single_error(&format!(
|
let e = single_error(&format!(
|
||||||
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-Api-Key\"\nsecret = \"nope\"\n"
|
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-Api-Key\"\nsecret = \"nope\"\n"
|
||||||
));
|
));
|
||||||
assert_eq!(e, ValidationError::UndefinedSecret { file: "hosts/app.test.toml".into(), secret: "nope".into() });
|
assert_eq!(
|
||||||
|
e,
|
||||||
|
ValidationError::UndefinedSecret {
|
||||||
|
file: "hosts/app.test.toml".into(),
|
||||||
|
secret: "nope".into()
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn undefined_secret_is_reported_when_site_declares_none() {
|
fn undefined_secret_is_reported_when_site_declares_none() {
|
||||||
let r = load(
|
let r = load(
|
||||||
&SourceFile { name: "ianitor.toml", contents: "" },
|
&SourceFile {
|
||||||
|
name: "ianitor.toml",
|
||||||
|
contents: "",
|
||||||
|
},
|
||||||
&[SourceFile {
|
&[SourceFile {
|
||||||
name: "a.toml",
|
name: "a.toml",
|
||||||
contents: &format!("{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-K\"\nsecret = \"api_key\"\n"),
|
contents: &format!(
|
||||||
|
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-K\"\nsecret = \"api_key\"\n"
|
||||||
|
),
|
||||||
}],
|
}],
|
||||||
);
|
);
|
||||||
assert!(r.unwrap_err().errors().iter().any(|e| matches!(e, ValidationError::UndefinedSecret { .. })));
|
assert!(
|
||||||
|
r.unwrap_err()
|
||||||
|
.errors()
|
||||||
|
.iter()
|
||||||
|
.any(|e| matches!(e, ValidationError::UndefinedSecret { .. }))
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -349,19 +511,30 @@ fn rejects_secret_in_response_header() {
|
|||||||
let e = single_error(&format!(
|
let e = single_error(&format!(
|
||||||
"{MINIMAL}[[response_headers]]\naction = \"set\"\nname = \"X-Leak\"\nsecret = \"api_key\"\n"
|
"{MINIMAL}[[response_headers]]\naction = \"set\"\nname = \"X-Leak\"\nsecret = \"api_key\"\n"
|
||||||
));
|
));
|
||||||
assert!(matches!(e, ValidationError::SecretInResponseHeader { .. }), "{e:?}");
|
assert!(
|
||||||
|
matches!(e, ValidationError::SecretInResponseHeader { .. }),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_bad_secret_names_in_site_file() {
|
fn rejects_bad_secret_names_in_site_file() {
|
||||||
for bad in ["../etc/passwd", "a/b", "", "UPPER", "with space", ".hidden"] {
|
for bad in ["../etc/passwd", "a/b", "", "UPPER", "with space", ".hidden"] {
|
||||||
let r = load(
|
let r = load(
|
||||||
&SourceFile { name: "ianitor.toml", contents: &format!("secrets = [{bad:?}]\n") },
|
&SourceFile {
|
||||||
&[SourceFile { name: "a.toml", contents: MINIMAL }],
|
name: "ianitor.toml",
|
||||||
|
contents: &format!("secrets = [{bad:?}]\n"),
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "a.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
}],
|
||||||
);
|
);
|
||||||
let errs = r.unwrap_err();
|
let errs = r.unwrap_err();
|
||||||
assert!(
|
assert!(
|
||||||
errs.errors().iter().any(|e| matches!(e, ValidationError::InvalidSecretName { name, .. } if name == bad)),
|
errs.errors().iter().any(
|
||||||
|
|e| matches!(e, ValidationError::InvalidSecretName { name, .. } if name == bad)
|
||||||
|
),
|
||||||
"{bad:?}: {errs:?}"
|
"{bad:?}: {errs:?}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -376,38 +549,92 @@ fn rule(list: &str, body: &str) -> String {
|
|||||||
#[test]
|
#[test]
|
||||||
fn rejects_malformed_header_rules() {
|
fn rejects_malformed_header_rules() {
|
||||||
let cases = [
|
let cases = [
|
||||||
("set without value", rule("request_headers", "action = \"set\"\nname = \"X-A\"")),
|
(
|
||||||
("remove with value", rule("request_headers", "action = \"remove\"\nname = \"X-A\"\nvalue = \"1\"")),
|
"set without value",
|
||||||
("value and secret", rule("request_headers", "action = \"set\"\nname = \"X-A\"\nvalue = \"1\"\nsecret = \"api_key\"")),
|
rule("request_headers", "action = \"set\"\nname = \"X-A\""),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"remove with value",
|
||||||
|
rule(
|
||||||
|
"request_headers",
|
||||||
|
"action = \"remove\"\nname = \"X-A\"\nvalue = \"1\"",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"value and secret",
|
||||||
|
rule(
|
||||||
|
"request_headers",
|
||||||
|
"action = \"set\"\nname = \"X-A\"\nvalue = \"1\"\nsecret = \"api_key\"",
|
||||||
|
),
|
||||||
|
),
|
||||||
];
|
];
|
||||||
for (what, input) in cases {
|
for (what, input) in cases {
|
||||||
let e = single_error(&input);
|
let e = single_error(&input);
|
||||||
assert!(matches!(e, ValidationError::BadHeaderRule { .. }), "{what}: {e:?}");
|
assert!(
|
||||||
|
matches!(e, ValidationError::BadHeaderRule { .. }),
|
||||||
|
"{what}: {e:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_invalid_header_names() {
|
fn rejects_invalid_header_names() {
|
||||||
for bad in ["Bad Header", "", "X:Y", "X\nY", "Ä"] {
|
for bad in ["Bad Header", "", "X:Y", "X\nY", "Ä"] {
|
||||||
let e = single_error(&rule("request_headers", &format!("action = \"remove\"\nname = {bad:?}")));
|
let e = single_error(&rule(
|
||||||
assert!(matches!(e, ValidationError::InvalidHeaderName { ref name, .. } if name == bad), "{bad:?}: {e:?}");
|
"request_headers",
|
||||||
|
&format!("action = \"remove\"\nname = {bad:?}"),
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::InvalidHeaderName { ref name, .. } if name == bad),
|
||||||
|
"{bad:?}: {e:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_invalid_header_values() {
|
fn rejects_invalid_header_values() {
|
||||||
for bad in ["a\nb", "a\rb", "a\u{0}b", "{http.request.host}", "x}", "\u{7f}", " leading", "ü"] {
|
for bad in [
|
||||||
|
"a\nb",
|
||||||
|
"a\rb",
|
||||||
|
"a\u{0}b",
|
||||||
|
"{http.request.host}",
|
||||||
|
"x}",
|
||||||
|
"\u{7f}",
|
||||||
|
" leading",
|
||||||
|
"ü",
|
||||||
|
] {
|
||||||
let value = toml::Value::String(bad.to_owned()).to_string();
|
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}")));
|
let e = single_error(&rule(
|
||||||
assert!(matches!(e, ValidationError::InvalidHeaderValue { .. }), "{bad:?}: {e:?}");
|
"response_headers",
|
||||||
|
&format!("action = \"set\"\nname = \"X-A\"\nvalue = {value}"),
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::InvalidHeaderValue { .. }),
|
||||||
|
"{bad:?}: {e:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_protected_headers() {
|
fn rejects_protected_headers() {
|
||||||
for name in ["Host", "content-length", "Transfer-Encoding", "Connection", "Upgrade", "X-Forwarded-For", "x-forwarded-proto", "X-Forwarded-Host"] {
|
for name in [
|
||||||
let e = single_error(&rule("request_headers", &format!("action = \"remove\"\nname = {name:?}")));
|
"Host",
|
||||||
assert!(matches!(e, ValidationError::ProtectedHeader { .. }), "{name}: {e:?}");
|
"content-length",
|
||||||
|
"Transfer-Encoding",
|
||||||
|
"Connection",
|
||||||
|
"Upgrade",
|
||||||
|
"X-Forwarded-For",
|
||||||
|
"x-forwarded-proto",
|
||||||
|
"X-Forwarded-Host",
|
||||||
|
] {
|
||||||
|
let e = single_error(&rule(
|
||||||
|
"request_headers",
|
||||||
|
&format!("action = \"remove\"\nname = {name:?}"),
|
||||||
|
));
|
||||||
|
assert!(
|
||||||
|
matches!(e, ValidationError::ProtectedHeader { .. }),
|
||||||
|
"{name}: {e:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -417,7 +644,10 @@ fn identity_headers_are_protected_on_forward_auth_hosts() {
|
|||||||
"{MINIMAL}auth = \"forward-auth\"\n[[request_headers]]\naction = \"set\"\nname = \"remote-user\"\nvalue = \"admin\"\n"
|
"{MINIMAL}auth = \"forward-auth\"\n[[request_headers]]\naction = \"set\"\nname = \"remote-user\"\nvalue = \"admin\"\n"
|
||||||
);
|
);
|
||||||
let e = single_error(&input);
|
let e = single_error(&input);
|
||||||
assert!(matches!(e, ValidationError::ProtectedHeader { .. }), "{e:?}");
|
assert!(
|
||||||
|
matches!(e, ValidationError::ProtectedHeader { .. }),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -426,7 +656,10 @@ fn rejects_duplicate_header_rules_case_insensitively() {
|
|||||||
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\n[[request_headers]]\naction = \"remove\"\nname = \"x-a\"\n"
|
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\n[[request_headers]]\naction = \"remove\"\nname = \"x-a\"\n"
|
||||||
);
|
);
|
||||||
let e = single_error(&input);
|
let e = single_error(&input);
|
||||||
assert!(matches!(e, ValidationError::DuplicateHeaderRule { .. }), "{e:?}");
|
assert!(
|
||||||
|
matches!(e, ValidationError::DuplicateHeaderRule { .. }),
|
||||||
|
"{e:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------- auth and health checks
|
// ---------------------------------------------------------------- auth and health checks
|
||||||
@@ -434,21 +667,46 @@ fn rejects_duplicate_header_rules_case_insensitively() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn forward_auth_requires_site_configuration() {
|
fn forward_auth_requires_site_configuration() {
|
||||||
let r = load(
|
let r = load(
|
||||||
&SourceFile { name: "ianitor.toml", contents: "" },
|
&SourceFile {
|
||||||
&[SourceFile { name: "a.toml", contents: &format!("{MINIMAL}auth = \"forward-auth\"\n") }],
|
name: "ianitor.toml",
|
||||||
|
contents: "",
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "a.toml",
|
||||||
|
contents: &format!("{MINIMAL}auth = \"forward-auth\"\n"),
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
r.unwrap_err()
|
||||||
|
.errors()
|
||||||
|
.iter()
|
||||||
|
.any(|e| matches!(e, ValidationError::ForwardAuthNotConfigured { .. }))
|
||||||
);
|
);
|
||||||
assert!(r.unwrap_err().errors().iter().any(|e| matches!(e, ValidationError::ForwardAuthNotConfigured { .. })));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rejects_bad_forward_auth_site_config() {
|
fn rejects_bad_forward_auth_site_config() {
|
||||||
for bad in ["ftp://127.0.0.1/x", "http://u:p@127.0.0.1:9091/api", "http://127.0.0.1:9091/api#x", "nope"] {
|
for bad in [
|
||||||
|
"ftp://127.0.0.1/x",
|
||||||
|
"http://u:p@127.0.0.1:9091/api",
|
||||||
|
"http://127.0.0.1:9091/api#x",
|
||||||
|
"nope",
|
||||||
|
] {
|
||||||
let r = load(
|
let r = load(
|
||||||
&SourceFile { name: "ianitor.toml", contents: &format!("[forward_auth]\nurl = {bad:?}\n") },
|
&SourceFile {
|
||||||
&[SourceFile { name: "a.toml", contents: MINIMAL }],
|
name: "ianitor.toml",
|
||||||
|
contents: &format!("[forward_auth]\nurl = {bad:?}\n"),
|
||||||
|
},
|
||||||
|
&[SourceFile {
|
||||||
|
name: "a.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
}],
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
r.unwrap_err().errors().iter().any(|e| matches!(e, ValidationError::BadForwardAuth { .. })),
|
r.unwrap_err()
|
||||||
|
.errors()
|
||||||
|
.iter()
|
||||||
|
.any(|e| matches!(e, ValidationError::BadForwardAuth { .. })),
|
||||||
"{bad}"
|
"{bad}"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -464,7 +722,10 @@ fn rejects_bad_health_checks() {
|
|||||||
"path = \"/{x}\"\ninterval_secs = 5",
|
"path = \"/{x}\"\ninterval_secs = 5",
|
||||||
] {
|
] {
|
||||||
let e = single_error(&format!("{MINIMAL}[health_check]\n{body}\n"));
|
let e = single_error(&format!("{MINIMAL}[health_check]\n{body}\n"));
|
||||||
assert!(matches!(e, ValidationError::BadHealthCheck { .. }), "{body}: {e:?}");
|
assert!(
|
||||||
|
matches!(e, ValidationError::BadHealthCheck { .. }),
|
||||||
|
"{body}: {e:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -475,9 +736,18 @@ fn collects_errors_from_every_file() {
|
|||||||
let r = load(
|
let r = load(
|
||||||
&site(),
|
&site(),
|
||||||
&[
|
&[
|
||||||
SourceFile { name: "a.toml", contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n" },
|
SourceFile {
|
||||||
SourceFile { name: "b.toml", contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n" },
|
name: "a.toml",
|
||||||
SourceFile { name: "c.toml", contents: MINIMAL },
|
contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n",
|
||||||
|
},
|
||||||
|
SourceFile {
|
||||||
|
name: "b.toml",
|
||||||
|
contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
|
||||||
|
},
|
||||||
|
SourceFile {
|
||||||
|
name: "c.toml",
|
||||||
|
contents: MINIMAL,
|
||||||
|
},
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
let errs = r.unwrap_err();
|
let errs = r.unwrap_err();
|
||||||
@@ -495,8 +765,14 @@ fn error_messages_name_the_file_in_plain_english() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn never_panics_on_garbage() {
|
fn never_panics_on_garbage() {
|
||||||
let samples = [
|
let samples = [
|
||||||
"\u{0}\u{1}\u{2}", "[[[[", "hostname = 1", "hostname = [\"a\"]", "= =", "[health_check]\npath = 1",
|
"\u{0}\u{1}\u{2}",
|
||||||
"hostname = \"a.test\"\nupstreams = [1, 2]", "hostname = \"a.test\"\nupstreams = [[]]",
|
"[[[[",
|
||||||
|
"hostname = 1",
|
||||||
|
"hostname = [\"a\"]",
|
||||||
|
"= =",
|
||||||
|
"[health_check]\npath = 1",
|
||||||
|
"hostname = \"a.test\"\nupstreams = [1, 2]",
|
||||||
|
"hostname = \"a.test\"\nupstreams = [[]]",
|
||||||
"hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\n",
|
"hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\n",
|
||||||
"hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\nrequest_headers = 5",
|
"hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\nrequest_headers = 5",
|
||||||
];
|
];
|
||||||
|
|||||||
Reference in New Issue
Block a user