[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)
|
||||
}
|
||||
Reference in New Issue
Block a user