// 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/. //! Compilers from the validated [`Model`] to the two engines. Both are pure and deterministic: //! 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; /// In the certificate directory: the CA bundle for device certificates (written by control). pub const DEVICE_CA_FILE: &str = "domi-devices-ca.pem"; /// In the certificate directory: every allowed (issued, not revoked) device certificate. pub const DEVICE_ALLOW_FILE: &str = "domi-devices.pem"; use std::net::SocketAddr; use crate::Model; /// Deployment facts that are not part of the routes repo (they change only with a rebuild). #[derive(Debug, Clone, PartialEq, Eq)] pub struct CompileOptions { pub http_listen: SocketAddr, pub https_listen: SocketAddr, /// Absolute directory with Domi certificates: `.crt` and `.key`. pub cert_dir: String, /// Absolute state directory (edge ACME state, Caddy storage). pub state_dir: String, /// Absolute path of the access log file. pub access_log: String, /// `$CREDENTIALS_DIRECTORY` of the Caddy fallback unit, used in `{file.*}` placeholders. pub caddy_credentials_dir: String, /// Caddy admin endpoint; `None` disables the admin API. pub caddy_admin: Option, /// Caddy admin endpoint on a Unix socket (mode 0660), which control uses to load a changed /// config while Caddy serves. Takes precedence over `caddy_admin`. pub caddy_admin_socket: Option, /// Peers whose `X-Forwarded-For` is believed (a proxy in front, such as Caddy beside /// Ianitor on loopback): the share-link throttle and the access log then see the real /// client. Empty (the default): only the connection's own address counts. pub trusted_proxies: Vec, } #[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, }, #[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 { 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 { 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> { if let Some(s) = &o.caddy_admin_socket { check_path(s).map_err(|reason| CompileError::BadOption { option: "caddy_admin_socket", reason, })?; } 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(()) } /// Identity headers never accepted from clients on forward-auth hosts: Authelia's four, then /// any other configured copy header (case-insensitive, no duplicates). fn strip_headers(fa: &crate::ForwardAuth) -> Vec { let mut out: Vec = crate::AUTHELIA_COPY_HEADERS .iter() .map(|h| (*h).to_owned()) .collect(); for h in &fa.copy_headers { if !out.iter().any(|o| o.eq_ignore_ascii_case(h)) { out.push(h.clone()); } } out } /// Join a validated directory and a validated file name. fn join(dir: &str, file: &str) -> String { format!("{}/{}", dir.trim_end_matches('/'), file) }