[core] Schema: tests first for validation and compiler determinism (red: 37+11 failing)

This commit is contained in:
2026-11-07 14:34:33 +01:00
parent c1abe88688
commit 9176cc63a4
12 changed files with 1231 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
// 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.
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: `<hostname>.crt` and `<hostname>.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<SocketAddr>,
}
#[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<String, CompileError> {
let _ = (model, options);
Err(CompileError::Serialize("not implemented".into()))
}
/// 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()))
}
+103
View File
@@ -0,0 +1,103 @@
// 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/.
//! The compiled runtime config read by ianitor-edge. Produced only by [`crate::compile::edge`].
//! Edge never decides policy: everything it does is spelled out here. Secret values are never
//! part of it, only secret names, resolved by edge from `$CREDENTIALS_DIRECTORY`.
use serde::{Deserialize, Serialize};
/// Bumped on any incompatible change; edge refuses other versions.
pub const EDGE_CONFIG_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeConfig {
pub version: u32,
/// Plain-HTTP listener: ACME HTTP-01 challenges and redirects to HTTPS.
pub http_listen: String,
/// TLS listener serving every host by SNI.
pub https_listen: String,
/// Port used in HTTP→HTTPS redirects (omitted from `Location` when 443).
pub https_port: u16,
/// Directory holding Domi certificates as `<hostname>.crt` / `<hostname>.key`.
pub cert_dir: String,
/// Edge state; ACME account and certificates live in `<state_dir>/acme`.
pub state_dir: String,
/// Access log file (JSON lines). Only hosts with `access_log` enabled write to it.
pub access_log: String,
pub acme: Option<EdgeAcme>,
pub forward_auth: Option<EdgeForwardAuth>,
/// Sorted by hostname.
pub hosts: Vec<EdgeHost>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeAcme {
pub directory: String,
pub email: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeForwardAuth {
pub upstream: EdgeUpstream,
pub path_and_query: String,
pub copy_headers: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeUpstream {
/// `host:port`, IPv6 in brackets.
pub address: String,
pub tls: bool,
/// SNI and certificate name when `tls` is set.
pub sni: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "source")]
pub enum EdgeTls {
/// Obtain and renew through ACME; stored under `<state_dir>/acme`.
Acme,
/// Load from files (Domi CA certificates).
Files { cert: String, key: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "kind")]
pub enum EdgeValue {
Literal { value: String },
Secret { name: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "snake_case", tag = "op")]
pub enum EdgeHeaderOp {
Set { name: String, value: EdgeValue },
Remove { name: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeHealthCheck {
pub path: String,
pub interval_secs: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EdgeHost {
pub hostname: String,
pub tls: EdgeTls,
pub upstreams: Vec<EdgeUpstream>,
pub forward_auth: bool,
pub websockets: bool,
pub request_headers: Vec<EdgeHeaderOp>,
pub response_headers: Vec<EdgeHeaderOp>,
pub health_check: Option<EdgeHealthCheck>,
pub access_log: bool,
}
+92
View File
@@ -0,0 +1,92 @@
// 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/.
//! Typed validation errors. Every message names the file and says what is wrong in plain English,
//! so the UI can show it as is.
use std::fmt;
/// One problem found in the route files.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ValidationError {
#[error("{file}: the file is not valid TOML{}: {message}", line_suffix(*line))]
Syntax { file: String, line: Option<usize>, message: String },
#[error("{file}: unknown field `{field}`")]
UnknownField { file: String, field: String },
#[error("{file}: required field `{field}` is missing")]
MissingField { file: String, field: String },
#[error("{file}: {message}")]
InvalidValue { file: String, message: String },
#[error("{file} appears twice in the routes")]
DuplicateFile { file: String },
#[error("{file}: `{hostname}` is not a valid hostname: {reason}")]
InvalidHostname { file: String, hostname: String, reason: &'static str },
#[error("hostname `{hostname}` is defined twice: in {first} and in {second}")]
DuplicateHostname { hostname: String, first: String, second: String },
#[error("{file}: at least one upstream is needed")]
NoUpstreams { file: String },
#[error("{file}: upstream `{url}` is not usable: {reason}")]
BadUpstreamUrl { file: String, url: String, reason: &'static str },
#[error("{file}: upstream `{url}` is listed twice")]
DuplicateUpstream { file: String, url: String },
#[error("{file}: secret `{secret}` is used but not declared in the site file")]
UndefinedSecret { file: String, secret: String },
#[error("{file}: response header `{header}` may not use a secret; secrets only go to upstreams")]
SecretInResponseHeader { file: String, header: String },
#[error("{file}: `{name}` is not a valid secret name (use a-z, 0-9, '_' and '-', at most 64 characters)")]
InvalidSecretName { file: String, name: String },
#[error("{file}: `{name}` is not a valid header name")]
InvalidHeaderName { file: String, name: String },
#[error("{file}: value for header `{header}` is not allowed: {reason}")]
InvalidHeaderValue { file: String, header: String, reason: &'static str },
#[error("{file}: header `{header}` is managed by the proxy and cannot be changed by a rule")]
ProtectedHeader { file: String, header: String },
#[error("{file}: header `{header}` has more than one rule in the same list")]
DuplicateHeaderRule { file: String, header: String },
#[error("{file}: rule for header `{header}` is incomplete: {reason}")]
BadHeaderRule { file: String, header: String, reason: &'static str },
#[error("{file}: health check is not usable: {reason}")]
BadHealthCheck { file: String, reason: &'static str },
#[error("{file}: auth = \"forward-auth\" needs a [forward_auth] section in the site file")]
ForwardAuthNotConfigured { file: String },
#[error("{file}: forward_auth is not usable: {reason}")]
BadForwardAuth { file: String, reason: &'static str },
#[error("{file}: acme is not usable: {reason}")]
BadAcme { file: String, reason: &'static str },
}
fn line_suffix(line: Option<usize>) -> String {
match line {
Some(l) => format!(" (line {l})"),
None => String::new(),
}
}
/// All problems found in one load, in a stable order (file by file, then hostname checks).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationErrors(pub(crate) Vec<ValidationError>);
impl ValidationErrors {
pub fn errors(&self) -> &[ValidationError] {
&self.0
}
pub fn into_errors(self) -> Vec<ValidationError> {
self.0
}
}
impl fmt::Display for ValidationErrors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, e) in self.0.iter().enumerate() {
if i > 0 {
writeln!(f)?;
}
write!(f, "{e}")?;
}
Ok(())
}
}
impl std::error::Error for ValidationErrors {}
+18
View File
@@ -3,3 +3,21 @@
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Ianitor core: host-file model, validation and compilers. Pure: no I/O, no network.
//!
//! The routes repo holds `ianitor.toml` (site settings) and one TOML file per host.
//! [`load`] turns them into a validated [`Model`]; [`compile::edge`] and [`compile::caddy`]
//! turn the model into the configs of the two engines.
pub mod compile;
pub mod edge_config;
mod error;
mod model;
mod validate;
pub use error::{ValidationError, ValidationErrors};
pub use model::{
AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, HealthCheck, Host, Hostname,
Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost, AUTHELIA_COPY_HEADERS,
LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING,
};
pub use validate::{load, SourceFile};
+225
View File
@@ -0,0 +1,225 @@
// 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/.
//! The validated model. Values of these types only come out of [`crate::load`], so every
//! compiler can rely on them being valid: the structs are `#[non_exhaustive]` and cannot be
//! built outside this crate.
use std::collections::BTreeSet;
use std::fmt;
/// A validated, lowercase DNS hostname (no wildcard, no trailing dot, not an IP address).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Hostname(pub(crate) String);
impl Hostname {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for Hostname {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
/// A validated secret name. It is also the credential file name under `$CREDENTIALS_DIRECTORY`,
/// so it can never contain a path separator.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SecretName(pub(crate) String);
impl SecretName {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for SecretName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl From<&str> for SecretName {
/// For tests and comparisons only; validation happens in [`crate::load`].
fn from(s: &str) -> Self {
SecretName(s.to_owned())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Scheme {
Http,
Https,
}
impl Scheme {
pub fn as_str(self) -> &'static str {
match self {
Scheme::Http => "http",
Scheme::Https => "https",
}
}
}
/// Where the upstream host is: a DNS name or an IP literal (IPv6 without brackets).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum UpstreamHost {
Name(String),
Ip(std::net::IpAddr),
}
/// A validated upstream: scheme, host and explicit port. No path, query, fragment or userinfo.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub struct Upstream {
pub scheme: Scheme,
pub host: UpstreamHost,
pub port: u16,
}
impl Upstream {
/// `host:port` as used for dialing, with IPv6 in brackets.
pub fn authority(&self) -> String {
match &self.host {
UpstreamHost::Name(n) => format!("{n}:{}", self.port),
UpstreamHost::Ip(std::net::IpAddr::V6(ip)) => format!("[{ip}]:{}", self.port),
UpstreamHost::Ip(ip) => format!("{ip}:{}", self.port),
}
}
/// The host part for TLS SNI and certificate verification.
pub fn host_str(&self) -> String {
match &self.host {
UpstreamHost::Name(n) => n.clone(),
UpstreamHost::Ip(ip) => ip.to_string(),
}
}
}
impl fmt::Display for Upstream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}://{}", self.scheme.as_str(), self.authority())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TlsMode {
/// Public certificate from Let's Encrypt via ACME (HTTP-01).
LetsEncrypt,
/// Certificate issued by the Domi CA, read from the certificate directory.
Domi,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthMode {
None,
/// Every request is first checked with the site's forward-auth endpoint (Authelia).
ForwardAuth,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccessLog {
Off,
/// Logged with IPv4 truncated to /24 and IPv6 to /48.
Truncated,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeaderValue {
Literal(String),
/// Resolved by the engine at load time; never part of any compiled output.
Secret(SecretName),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HeaderRule {
Set { name: String, value: HeaderValue },
Remove { name: String },
}
impl HeaderRule {
pub fn name(&self) -> &str {
match self {
HeaderRule::Set { name, .. } | HeaderRule::Remove { name } => name,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HealthCheck {
pub path: String,
pub interval_secs: u32,
}
/// One validated host file.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Host {
pub hostname: Hostname,
/// The route file this host came from, for messages.
pub source: String,
pub upstreams: Vec<Upstream>,
pub tls: TlsMode,
pub auth: AuthMode,
pub request_headers: Vec<HeaderRule>,
pub response_headers: Vec<HeaderRule>,
pub websockets: bool,
pub health_check: Option<HealthCheck>,
pub share_links: bool,
pub access_log: AccessLog,
}
/// The forward-auth endpoint (Authelia's `/api/authz/forward-auth`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ForwardAuth {
pub upstream: Upstream,
/// Path plus optional query, e.g. `/api/authz/forward-auth`.
pub path_and_query: String,
/// Headers copied from a 2xx auth response onto the upstream request.
pub copy_headers: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Acme {
pub email: Option<String>,
pub directory: String,
}
/// Site-wide settings from `ianitor.toml`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Site {
pub secrets: BTreeSet<SecretName>,
pub forward_auth: Option<ForwardAuth>,
pub acme: Acme,
}
/// The whole validated routes tree. Hosts are sorted by hostname.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Model {
pub(crate) site: Site,
pub(crate) hosts: Vec<Host>,
}
impl Model {
pub fn site(&self) -> &Site {
&self.site
}
pub fn hosts(&self) -> &[Host] {
&self.hosts
}
}
/// Let's Encrypt production directory, the default when `[acme] directory` is not set.
pub const LETSENCRYPT_PRODUCTION: &str = "https://acme-v02.api.letsencrypt.org/directory";
/// Let's Encrypt staging 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).
pub const AUTHELIA_COPY_HEADERS: [&str; 4] = ["Remote-User", "Remote-Groups", "Remote-Email", "Remote-Name"];
+20
View File
@@ -0,0 +1,20 @@
// 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/.
//! Parsing and validation of the routes tree.
use crate::{Model, ValidationErrors};
/// One route file handed in by the caller (core does no I/O).
#[derive(Debug, Clone, Copy)]
pub struct SourceFile<'a> {
pub name: &'a str,
pub contents: &'a str,
}
/// Parse and validate the site file and every host file.
pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result<Model, ValidationErrors> {
let _ = (site, hosts);
Err(ValidationErrors(Vec::new()))
}
+173
View File
@@ -0,0 +1,173 @@
// 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/.
//! Compiler tests: both compilers are deterministic (byte-identical output for the same model,
//! whatever the file order), never embed secret values, and match the reviewed golden files.
//! Regenerate the golden files after an intended change with `IANITOR_UPDATE_GOLDEN=1`.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::path::{Path, PathBuf};
use ianitor_core::compile::{self, CompileError, CompileOptions};
use ianitor_core::edge_config::EdgeConfig;
use ianitor_core::{load, Model, SourceFile};
fn fixtures() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/routes")
}
fn read(p: &Path) -> String {
std::fs::read_to_string(p).unwrap().replace("\r\n", "\n")
}
/// (file name, contents) for every host file, in directory order or reversed.
fn host_files(reverse: bool) -> Vec<(String, String)> {
let mut files: Vec<_> = std::fs::read_dir(fixtures().join("hosts"))
.unwrap()
.map(|e| e.unwrap().path())
.collect();
files.sort();
if reverse {
files.reverse();
}
files
.into_iter()
.map(|p| (format!("hosts/{}", p.file_name().unwrap().to_string_lossy()), read(&p)))
.collect()
}
fn model(reverse: bool) -> Model {
let site = read(&fixtures().join("ianitor.toml"));
let files = host_files(reverse);
let sources: Vec<SourceFile> = files.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 {
CompileOptions {
http_listen: "0.0.0.0:80".parse().unwrap(),
https_listen: "0.0.0.0:443".parse().unwrap(),
cert_dir: "/var/lib/ianitor/certs".into(),
state_dir: "/var/lib/ianitor".into(),
access_log: "/var/log/ianitor/access.log".into(),
caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(),
caddy_admin: None,
}
}
#[test]
fn edge_compiler_is_deterministic() {
let m = model(false);
let first = compile::edge(&m, &options()).unwrap();
for _ in 0..50 {
assert_eq!(first, compile::edge(&m, &options()).unwrap());
}
assert_eq!(first, compile::edge(&model(true), &options()).unwrap(), "file order must not matter");
}
#[test]
fn caddy_compiler_is_deterministic() {
let m = model(false);
let first = compile::caddy(&m, &options()).unwrap();
for _ in 0..50 {
assert_eq!(first, compile::caddy(&m, &options()).unwrap());
}
assert_eq!(first, compile::caddy(&model(true), &options()).unwrap(), "file order must not matter");
}
#[test]
fn determinism_holds_across_threads() {
let outputs: Vec<(String, String)> = std::thread::scope(|s| {
let handles: Vec<_> = (0..8)
.map(|i| {
s.spawn(move || {
let m = model(i % 2 == 0);
(compile::edge(&m, &options()).unwrap(), compile::caddy(&m, &options()).unwrap())
})
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
for o in &outputs {
assert_eq!(o, &outputs[0]);
}
}
#[test]
fn edge_output_round_trips_through_the_edge_schema() {
let text = compile::edge(&model(false), &options()).unwrap();
let cfg: EdgeConfig = serde_json::from_str(&text).unwrap();
assert_eq!(cfg.hosts.len(), 3);
let again = serde_json::to_string_pretty(&cfg).unwrap() + "\n";
assert_eq!(text, again);
}
#[test]
fn edge_config_rejects_unknown_fields() {
let text = compile::edge(&model(false), &options()).unwrap();
let mut v: serde_json::Value = serde_json::from_str(&text).unwrap();
v["surprise"] = serde_json::json!(true);
assert!(serde_json::from_value::<EdgeConfig>(v).is_err());
}
#[test]
fn caddy_output_is_valid_json_with_servers() {
let text = compile::caddy(&model(false), &options()).unwrap();
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
assert!(v["apps"]["http"]["servers"].is_object());
assert_eq!(v["admin"]["disabled"], serde_json::json!(true));
}
#[test]
fn outputs_reference_secrets_by_name_only() {
let edge = compile::edge(&model(false), &options()).unwrap();
let caddy = compile::caddy(&model(false), &options()).unwrap();
assert!(edge.contains("\"photos_api_key\""), "edge config names the secret");
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.
for out in [&edge, &caddy] {
assert!(!out.contains("BEGIN"), "no key material");
}
}
#[test]
fn rejects_relative_paths_in_options() {
let mut o = options();
o.cert_dir = "certs".into();
assert!(matches!(compile::edge(&model(false), &o), Err(CompileError::BadOption { .. })));
assert!(matches!(compile::caddy(&model(false), &o), Err(CompileError::BadOption { .. })));
}
#[test]
fn rejects_path_options_that_would_break_out_of_json_or_placeholders() {
for bad in ["/run/x}y", "/run/{x", "/run/a\nb"] {
let mut o = options();
o.caddy_credentials_dir = bad.into();
assert!(compile::caddy(&model(false), &o).is_err(), "{bad:?}");
}
}
fn golden(name: &str, actual: &str) {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden").join(name);
if std::env::var_os("IANITOR_UPDATE_GOLDEN").is_some() {
std::fs::write(&path, actual).unwrap();
return;
}
let expected = read(&path);
assert!(
expected == actual,
"{name} differs from the golden file; review and rerun with IANITOR_UPDATE_GOLDEN=1.\n--- actual ---\n{actual}"
);
}
#[test]
fn edge_output_matches_golden_file() {
golden("edge.json", &compile::edge(&model(false), &options()).unwrap());
}
#[test]
fn caddy_output_matches_golden_file() {
golden("caddy.json", &compile::caddy(&model(false), &options()).unwrap());
}
@@ -0,0 +1,27 @@
hostname = "photos.example.org"
upstreams = ["http://127.0.0.1:2342", "http://127.0.0.1:2343"]
tls = "letsencrypt"
websockets = true
access_log = "truncated"
[health_check]
path = "/api/v1/status"
interval_secs = 15
[[request_headers]]
action = "set"
name = "X-Api-Key"
secret = "photos_api_key"
[[request_headers]]
action = "remove"
name = "X-Debug"
[[response_headers]]
action = "set"
name = "Strict-Transport-Security"
value = "max-age=31536000"
[[response_headers]]
action = "remove"
name = "X-Powered-By"
@@ -0,0 +1,2 @@
hostname = "status.example.org"
upstreams = ["http://[::1]:3001"]
@@ -0,0 +1,10 @@
hostname = "wiki.home.test"
upstreams = ["https://wiki.lan:8443"]
tls = "domi"
auth = "forward-auth"
websockets = false
[[request_headers]]
action = "set"
name = "Authorization"
secret = "wiki_token"
+9
View File
@@ -0,0 +1,9 @@
# Site-wide settings for the routes repo (sample used by the compiler tests).
secrets = ["photos_api_key", "wiki_token"]
[forward_auth]
url = "http://127.0.0.1:9091/api/authz/forward-auth"
[acme]
email = "admin@example.org"
directory = "https://acme-staging-v02.api.letsencrypt.org/directory"
+505
View File
@@ -0,0 +1,505 @@
// 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/.
//! Schema and validation tests. Route files are hostile input: every rejection must be a
//! typed error that names the file, never a panic.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use ianitor_core::{
load, AccessLog, AuthMode, HeaderRule, HeaderValue, SourceFile, TlsMode, ValidationError,
ValidationErrors,
};
const SITE: &str = r#"
secrets = ["api_key", "other-token"]
[forward_auth]
url = "http://127.0.0.1:9091/api/authz/forward-auth"
"#;
fn site() -> SourceFile<'static> {
SourceFile { name: "ianitor.toml", contents: SITE }
}
fn one(contents: &str) -> Result<ianitor_core::Model, ValidationErrors> {
load(&site(), &[SourceFile { name: "hosts/app.test.toml", contents }])
}
fn errors(contents: &str) -> Vec<ValidationError> {
match one(contents) {
Ok(_) => panic!("expected validation to fail for:\n{contents}"),
Err(e) => e.errors().to_vec(),
}
}
fn single_error(contents: &str) -> ValidationError {
let errs = errors(contents);
assert_eq!(errs.len(), 1, "expected exactly one error, got {errs:#?}");
errs.into_iter().next().unwrap()
}
const MINIMAL: &str = r#"
hostname = "app.test"
upstreams = ["http://127.0.0.1:8080"]
"#;
// ---------------------------------------------------------------- accepted input
#[test]
fn minimal_host_gets_documented_defaults() {
let model = one(MINIMAL).expect("minimal host is valid");
let hosts = model.hosts();
assert_eq!(hosts.len(), 1);
let h = &hosts[0];
assert_eq!(h.hostname.as_str(), "app.test");
assert_eq!(h.source, "hosts/app.test.toml");
assert_eq!(h.tls, TlsMode::LetsEncrypt);
assert_eq!(h.auth, AuthMode::None);
assert!(h.websockets, "websockets default on, like Caddy");
assert!(!h.share_links);
assert_eq!(h.access_log, AccessLog::Off);
assert!(h.health_check.is_none());
assert!(h.request_headers.is_empty() && h.response_headers.is_empty());
assert_eq!(h.upstreams.len(), 1);
assert_eq!(h.upstreams[0].to_string(), "http://127.0.0.1:8080");
}
#[test]
fn full_host_is_accepted() {
let model = one(
r#"
hostname = "app.test"
upstreams = ["http://127.0.0.1:8080", "https://backend.lan", "http://[::1]:9000/"]
tls = "domi"
auth = "forward-auth"
websockets = false
share_links = true
access_log = "truncated"
[health_check]
path = "/healthz"
interval_secs = 10
[[request_headers]]
action = "set"
name = "X-Api-Key"
secret = "api_key"
[[request_headers]]
action = "remove"
name = "X-Debug"
[[response_headers]]
action = "set"
name = "Strict-Transport-Security"
value = "max-age=31536000"
"#,
)
.expect("full host is valid");
let h = &model.hosts()[0];
assert_eq!(h.tls, TlsMode::Domi);
assert_eq!(h.auth, AuthMode::ForwardAuth);
assert!(!h.websockets);
assert!(h.share_links);
assert_eq!(h.access_log, AccessLog::Truncated);
let hc = h.health_check.as_ref().unwrap();
assert_eq!(hc.path, "/healthz");
assert_eq!(hc.interval_secs, 10);
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!(
h.request_headers[0],
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.response_headers[0],
HeaderRule::Set {
name: "Strict-Transport-Security".into(),
value: HeaderValue::Literal("max-age=31536000".into())
}
);
}
#[test]
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 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 m2 = load(&site(), &[b, a]).unwrap();
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!(m1, m2);
}
#[test]
fn empty_site_file_is_allowed() {
let m = load(&SourceFile { name: "ianitor.toml", contents: "" }, &[SourceFile { name: "a.toml", contents: MINIMAL }]);
assert!(m.is_ok(), "{m:?}");
}
// ---------------------------------------------------------------- unknown fields
#[test]
fn rejects_unknown_top_level_field() {
let e = single_error(&format!("{MINIMAL}colour = \"red\"\n"));
assert_eq!(e, ValidationError::UnknownField { file: "hosts/app.test.toml".into(), field: "colour".into() });
}
#[test]
fn rejects_misspelled_field() {
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`.
assert!(matches!(e, ValidationError::UnknownField { ref field, .. } if field == "upstream"), "{e:?}");
}
#[test]
fn rejects_unknown_field_in_health_check() {
let e = single_error(&format!("{MINIMAL}[health_check]\npath = \"/h\"\ninterval_secs = 5\ntimeout = 3\n"));
assert!(matches!(e, ValidationError::UnknownField { ref field, .. } if field == "timeout"), "{e:?}");
}
#[test]
fn rejects_unknown_field_in_header_rule() {
let e = single_error(&format!(
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\nappend = true\n"
));
assert!(matches!(e, ValidationError::UnknownField { ref field, .. } if field == "append"), "{e:?}");
}
#[test]
fn rejects_unknown_field_in_site_file() {
let r = load(
&SourceFile { name: "ianitor.toml", contents: "secrets = []\nsecret_values = { a = \"b\" }\n" },
&[SourceFile { name: "a.toml", contents: MINIMAL }],
);
let errs = r.unwrap_err();
assert!(
errs.errors().iter().any(|e| matches!(e, ValidationError::UnknownField { file, field } if file == "ianitor.toml" && field == "secret_values")),
"{errs:?}"
);
}
#[test]
fn rejects_unknown_enum_value() {
let e = single_error("hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\ntls = \"selfsigned\"\n");
assert!(matches!(e, ValidationError::InvalidValue { .. }), "{e:?}");
}
#[test]
fn rejects_wrong_type() {
let e = single_error("hostname = \"app.test\"\nupstreams = \"http://127.0.0.1:1\"\n");
assert!(matches!(e, ValidationError::InvalidValue { .. }), "{e:?}");
}
#[test]
fn rejects_toml_syntax_error() {
let e = single_error("hostname = \"app.test\nupstreams = [\n");
assert!(matches!(e, ValidationError::Syntax { .. }), "{e:?}");
}
// ---------------------------------------------------------------- hostnames
#[test]
fn rejects_missing_hostname() {
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() });
}
#[test]
fn rejects_missing_upstreams() {
let e = single_error("hostname = \"app.test\"\n");
assert_eq!(e, ValidationError::MissingField { file: "hosts/app.test.toml".into(), field: "upstreams".into() });
}
#[test]
fn rejects_bad_hostnames() {
let long_label = format!("{}.test", "a".repeat(64));
let long_name = format!("{}test", "abcdefghi.".repeat(26));
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",
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"));
assert!(
matches!(e, ValidationError::InvalidHostname { ref hostname, .. } if hostname == bad),
"hostname {bad:?} gave {e:?}"
);
}
}
#[test]
fn accepts_good_hostnames() {
for good in ["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:?}");
}
}
#[test]
fn rejects_duplicate_hostnames_across_files() {
let r = load(
&site(),
&[
SourceFile { name: "hosts/one.toml", contents: MINIMAL },
SourceFile { name: "hosts/two.toml", contents: MINIMAL },
],
);
let errs = r.unwrap_err();
assert_eq!(
errs.errors(),
[ValidationError::DuplicateHostname {
hostname: "app.test".into(),
first: "hosts/one.toml".into(),
second: "hosts/two.toml".into()
}]
);
}
#[test]
fn duplicate_detection_is_independent_of_file_order() {
let r = load(
&site(),
&[
SourceFile { name: "hosts/two.toml", contents: MINIMAL },
SourceFile { name: "hosts/one.toml", contents: MINIMAL },
],
);
let errs = r.unwrap_err();
assert!(matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/one.toml" && second == "hosts/two.toml"));
}
#[test]
fn rejects_duplicate_source_file_names() {
let r = load(
&site(),
&[SourceFile { name: "a.toml", contents: MINIMAL }, SourceFile { name: "a.toml", contents: MINIMAL }],
);
assert!(r.unwrap_err().errors().iter().any(|e| matches!(e, ValidationError::DuplicateFile { .. })));
}
// ---------------------------------------------------------------- upstreams
#[test]
fn rejects_bad_upstream_urls() {
for bad in [
"ftp://127.0.0.1:21",
"127.0.0.1:8080",
"http://",
"http://user:pw@127.0.0.1:8080",
"http://user@127.0.0.1:8080",
"http://127.0.0.1:8080/path",
"http://127.0.0.1:8080?q=1",
"http://127.0.0.1:8080#frag",
"http://127.0.0.1:0",
"http://127.0.0.1:99999",
"not a url",
"",
"http://bad_host:80",
"unix:///run/app.sock",
"http://127.0.0.1:80{x}",
] {
let e = single_error(&format!("hostname = \"app.test\"\nupstreams = [{bad:?}]\n"));
assert!(
matches!(e, ValidationError::BadUpstreamUrl { ref url, .. } if url == bad),
"upstream {bad:?} gave {e:?}"
);
}
}
#[test]
fn rejects_empty_upstream_list() {
let e = single_error("hostname = \"app.test\"\nupstreams = []\n");
assert!(matches!(e, ValidationError::NoUpstreams { .. }), "{e:?}");
}
#[test]
fn rejects_duplicate_upstreams() {
let e = single_error("hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:80\", \"http://127.0.0.1\"]\n");
assert!(matches!(e, ValidationError::DuplicateUpstream { .. }), "{e:?}");
}
// ---------------------------------------------------------------- secrets
#[test]
fn rejects_undefined_secret_reference() {
let e = single_error(&format!(
"{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() });
}
#[test]
fn undefined_secret_is_reported_when_site_declares_none() {
let r = load(
&SourceFile { name: "ianitor.toml", contents: "" },
&[SourceFile {
name: "a.toml",
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 { .. })));
}
#[test]
fn rejects_secret_in_response_header() {
let e = single_error(&format!(
"{MINIMAL}[[response_headers]]\naction = \"set\"\nname = \"X-Leak\"\nsecret = \"api_key\"\n"
));
assert!(matches!(e, ValidationError::SecretInResponseHeader { .. }), "{e:?}");
}
#[test]
fn rejects_bad_secret_names_in_site_file() {
for bad in ["../etc/passwd", "a/b", "", "UPPER", "with space", ".hidden"] {
let r = load(
&SourceFile { name: "ianitor.toml", contents: &format!("secrets = [{bad:?}]\n") },
&[SourceFile { name: "a.toml", contents: MINIMAL }],
);
let errs = r.unwrap_err();
assert!(
errs.errors().iter().any(|e| matches!(e, ValidationError::InvalidSecretName { name, .. } if name == bad)),
"{bad:?}: {errs:?}"
);
}
}
// ---------------------------------------------------------------- header rules
fn rule(list: &str, body: &str) -> String {
format!("{MINIMAL}[[{list}]]\n{body}\n")
}
#[test]
fn rejects_malformed_header_rules() {
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\"")),
("value and secret", rule("request_headers", "action = \"set\"\nname = \"X-A\"\nvalue = \"1\"\nsecret = \"api_key\"")),
];
for (what, input) in cases {
let e = single_error(&input);
assert!(matches!(e, ValidationError::BadHeaderRule { .. }), "{what}: {e:?}");
}
}
#[test]
fn rejects_invalid_header_names() {
for bad in ["Bad Header", "", "X:Y", "X\nY", "Ä"] {
let e = single_error(&rule("request_headers", &format!("action = \"remove\"\nname = {bad:?}")));
assert!(matches!(e, ValidationError::InvalidHeaderName { ref name, .. } if name == bad), "{bad:?}: {e:?}");
}
}
#[test]
fn rejects_invalid_header_values() {
for bad in ["a\nb", "a\rb", "a\u{0}b", "{http.request.host}", "x}", "\u{7f}", " leading", "ü"] {
let e = single_error(&rule("response_headers", &format!("action = \"set\"\nname = \"X-A\"\nvalue = {bad:?}")));
assert!(matches!(e, ValidationError::InvalidHeaderValue { .. }), "{bad:?}: {e:?}");
}
}
#[test]
fn rejects_protected_headers() {
for name in ["Host", "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:?}");
}
}
#[test]
fn identity_headers_are_protected_on_forward_auth_hosts() {
let input = format!(
"{MINIMAL}auth = \"forward-auth\"\n[[request_headers]]\naction = \"set\"\nname = \"remote-user\"\nvalue = \"admin\"\n"
);
let e = single_error(&input);
assert!(matches!(e, ValidationError::ProtectedHeader { .. }), "{e:?}");
}
#[test]
fn rejects_duplicate_header_rules_case_insensitively() {
let input = format!(
"{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\n[[request_headers]]\naction = \"remove\"\nname = \"x-a\"\n"
);
let e = single_error(&input);
assert!(matches!(e, ValidationError::DuplicateHeaderRule { .. }), "{e:?}");
}
// ---------------------------------------------------------------- auth and health checks
#[test]
fn forward_auth_requires_site_configuration() {
let r = load(
&SourceFile { 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 { .. })));
}
#[test]
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"] {
let r = load(
&SourceFile { name: "ianitor.toml", contents: &format!("[forward_auth]\nurl = {bad:?}\n") },
&[SourceFile { name: "a.toml", contents: MINIMAL }],
);
assert!(
r.unwrap_err().errors().iter().any(|e| matches!(e, ValidationError::BadForwardAuth { .. })),
"{bad}"
);
}
}
#[test]
fn rejects_bad_health_checks() {
for body in [
"path = \"healthz\"\ninterval_secs = 5",
"path = \"/h z\"\ninterval_secs = 5",
"path = \"/h\"\ninterval_secs = 0",
"path = \"/h\"\ninterval_secs = 86401",
"path = \"/{x}\"\ninterval_secs = 5",
] {
let e = single_error(&format!("{MINIMAL}[health_check]\n{body}\n"));
assert!(matches!(e, ValidationError::BadHealthCheck { .. }), "{body}: {e:?}");
}
}
// ---------------------------------------------------------------- reporting
#[test]
fn collects_errors_from_every_file() {
let r = load(
&site(),
&[
SourceFile { name: "a.toml", 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();
assert_eq!(errs.errors().len(), 2, "{errs:?}");
}
#[test]
fn error_messages_name_the_file_in_plain_english() {
let errs = one("hostname = \"app.test\"\nupstreams = [\"ftp://x\"]\n").unwrap_err();
let text = errs.to_string();
assert!(text.contains("hosts/app.test.toml"), "{text}");
assert!(text.contains("ftp://x"), "{text}");
}
#[test]
fn never_panics_on_garbage() {
let samples = [
"\u{0}\u{1}\u{2}", "[[[[", "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\"]\nrequest_headers = 5",
];
for s in samples {
assert!(one(s).is_err(), "{s:?} unexpectedly valid");
}
}