[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/.
|
||||
|
||||
//! Compilers from the validated [`Model`] to the two engines. Both are pure and deterministic:
|
||||
//! the same model and options always give byte-identical output.
|
||||
//! the same model and options always give byte-identical output (no hash maps, hosts sorted,
|
||||
//! rules in file order). Neither ever sees a secret value, only secret names.
|
||||
//!
|
||||
//! Shared semantics, kept honest by the differential tests in `tests/diff`:
|
||||
//! - HTTP listener: `308` to `https://host[:port]/uri` for known hosts, `404` otherwise.
|
||||
//! - HTTPS listener: host chosen by the `Host` header (certificate by SNI); unknown host `404`.
|
||||
//! - Per host, in order: forward-auth (non-2xx auth answer goes back to the client verbatim;
|
||||
//! on 2xx the identity headers are copied onto the request), websocket refusal (`403` when
|
||||
//! `websockets = false`), then the reverse proxy with header rules, round-robin over healthy
|
||||
//! upstreams, `503` when none is healthy, `502` when the upstream cannot be reached.
|
||||
|
||||
mod caddy;
|
||||
mod edge;
|
||||
|
||||
use std::net::SocketAddr;
|
||||
|
||||
@@ -29,19 +41,74 @@ pub struct CompileOptions {
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum CompileError {
|
||||
#[error("compile option `{option}` is not usable: {reason}")]
|
||||
BadOption { option: &'static str, reason: &'static str },
|
||||
BadOption {
|
||||
option: &'static str,
|
||||
reason: &'static str,
|
||||
},
|
||||
#[error("could not serialise the compiled config: {0}")]
|
||||
Serialize(String),
|
||||
}
|
||||
|
||||
/// Compile to the Pingora runtime config read by ianitor-edge.
|
||||
pub fn edge(model: &Model, options: &CompileOptions) -> Result<String, CompileError> {
|
||||
let _ = (model, options);
|
||||
Err(CompileError::Serialize("not implemented".into()))
|
||||
check_options(options)?;
|
||||
let cfg = edge::compile(model, options);
|
||||
serde_json::to_string_pretty(&cfg)
|
||||
.map(|s| s + "\n")
|
||||
.map_err(|e| CompileError::Serialize(e.to_string()))
|
||||
}
|
||||
|
||||
/// Compile to Caddy JSON for the caddy-fallback unit.
|
||||
pub fn caddy(model: &Model, options: &CompileOptions) -> Result<String, CompileError> {
|
||||
let _ = (model, options);
|
||||
Err(CompileError::Serialize("not implemented".into()))
|
||||
check_options(options)?;
|
||||
let v = caddy::compile(model, options);
|
||||
serde_json::to_string_pretty(&v)
|
||||
.map(|s| s + "\n")
|
||||
.map_err(|e| CompileError::Serialize(e.to_string()))
|
||||
}
|
||||
|
||||
fn check_options(o: &CompileOptions) -> Result<(), CompileError> {
|
||||
for (option, value) in [
|
||||
("cert_dir", &o.cert_dir),
|
||||
("state_dir", &o.state_dir),
|
||||
("access_log", &o.access_log),
|
||||
("caddy_credentials_dir", &o.caddy_credentials_dir),
|
||||
] {
|
||||
check_path(value).map_err(|reason| CompileError::BadOption { option, reason })?;
|
||||
}
|
||||
if o.http_listen.port() == 0 || o.https_listen.port() == 0 {
|
||||
return Err(CompileError::BadOption {
|
||||
option: "listen",
|
||||
reason: "port 0 is not usable",
|
||||
});
|
||||
}
|
||||
if o.http_listen == o.https_listen {
|
||||
return Err(CompileError::BadOption {
|
||||
option: "listen",
|
||||
reason: "HTTP and HTTPS need different addresses",
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Paths end up inside JSON strings and Caddy `{file.*}` placeholders.
|
||||
fn check_path(p: &str) -> Result<(), &'static str> {
|
||||
if !p.starts_with('/') {
|
||||
return Err("it must be an absolute path");
|
||||
}
|
||||
if p.len() > 1024 {
|
||||
return Err("it is longer than 1024 characters");
|
||||
}
|
||||
if !p
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}' && c != b'\\')
|
||||
{
|
||||
return Err("only visible ASCII without '{', '}' or '\\' is allowed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Join a validated directory and a validated file name.
|
||||
fn join(dir: &str, file: &str) -> String {
|
||||
format!("{}/{}", dir.trim_end_matches('/'), file)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user