Files
ianitor/crates/core/src/compile/caddy.rs
T

415 lines
15 KiB
Rust

// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution
// License 1.0: see LICENSE (its Exhibit A is this file's notice).
//! 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, DEVICE_ALLOW_FILE, DEVICE_CA_FILE, join, strip_headers};
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";
const PROXY_SERVER: &str = "ianitor_proxy";
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_socket, o.caddy_admin) {
// Only the ianitor group (control) can reach it; no TCP port for local processes.
(Some(s), _) => {
json!({ "listen": format!("unix//{}|0660", s.trim_start_matches('/')) })
}
(None, Some(addr)) => json!({ "listen": addr.to_string() }),
(None, 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();
// One policy per host that needs one: a Domi certificate, device certificates, or both.
let mut policies: Vec<Value> = hosts
.iter()
.filter(|h| h.tls == TlsMode::Domi || h.device_certs)
.map(|h| {
let mut p = Map::new();
p.insert("match".into(), json!({ "sni": [h.hostname.as_str()] }));
if h.tls == TlsMode::Domi {
p.insert(
"certificate_selection".into(),
json!({ "any_tag": [cert_tag(h)] }),
);
}
if h.device_certs {
p.insert("client_authentication".into(), client_auth(o));
}
Value::Object(p)
})
.collect();
policies.push(json!({}));
// ---- The front proxy's socket: the same routes in plain HTTP, its peer trusted (edge:
// `client_ip` on the socket). No TLS here, so no certificates are managed for it.
let mut proxy = o.proxy_socket.as_ref().map(|sock| {
let mut p = Map::new();
p.insert(
"listen".into(),
json!([format!("unix//{}|0660", sock.trim_start_matches('/'))]),
);
p.insert("routes".into(), Value::Array(routes.clone()));
p.insert("automatic_https".into(), json!({ "disable": true }));
p.insert("protocols".into(), json!(["h1"]));
p.insert("trusted_proxies_unix".into(), json!(true));
p.insert("client_ip_headers".into(), json!(["X-Forwarded-For"]));
p.insert("trusted_proxies_strict".into(), json!(1));
p
});
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 !o.trusted_proxies.is_empty() {
// Like edge: X-Forwarded-For from these peers names the client (logs, `client_ip`).
https.insert(
"trusted_proxies".into(),
json!({
"source": "static",
"ranges": o.trusted_proxies.iter().map(ToString::to_string).collect::<Vec<_>>()
}),
);
https.insert("client_ip_headers".into(), json!(["X-Forwarded-For"]));
https.insert("trusted_proxies_strict".into(), json!(1));
}
if !logged.is_empty() {
let names: Map<String, Value> = logged
.iter()
.map(|h| (h.hostname.to_string(), json!([ACCESS_LOGGER])))
.collect();
let logs = json!({ "logger_names": names, "skip_unmapped_hosts": true });
if let Some(p) = proxy.as_mut() {
p.insert("logs".into(), logs.clone());
}
https.insert("logs".into(), logs);
}
// ---- 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);
if let Some(p) = proxy {
servers.insert(PROXY_SERVER.into(), Value::Object(p));
}
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 h.device_certs {
// No client certificate on this connection: 403, like edge. A certificate that is not
// trusted or not on the allow list never gets this far (the handshake fails).
steps.push(json!({
"match": [{ "vars": { "{http.request.tls.client.fingerprint}": [""] } }],
"handle": [{ "handler": "static_response", "status_code": 403 }]
}));
}
if let (AuthMode::ForwardAuth, Some(fa)) = (h.auth, fa) {
// Client-sent identity headers never reach the auth server or the upstream.
steps.push(json!({ "handle": [{ "handler": "headers", "request": { "delete": strip_headers(fa) } }] }));
steps.push(json!({ "handle": [forward_auth(fa)] }));
}
if !h.websockets {
steps.push(json!({
"match": [{ "header_regexp": { "Upgrade": { "pattern": "(?i)(^|,)\\s*websocket\\s*(,|$)" } } }],
"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| match u.unix_path() {
// Caddy's network address: `unix/` then the absolute path.
Some(p) => json!({ "dial": format!("unix/{p}") }),
None => 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)
}
/// Device certificates: optional in the handshake (a missing one is a 403 in the route, as in
/// edge), but one that is presented must chain to the Domi CA bundle and be on the allow list.
fn client_auth(o: &CompileOptions) -> Value {
json!({
"ca": { "provider": "file", "pem_files": [join(&o.cert_dir, DEVICE_CA_FILE)] },
"verifiers": [{
"verifier": "leaf",
"leaf_certs_loaders": [{ "loader": "file", "files": [join(&o.cert_dir, DEVICE_ALLOW_FILE)] }]
}],
"mode": "verify_if_given"
})
}