Files
ianitor/crates/core/tests/compile.rs
T

345 lines
11 KiB
Rust

// 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::{Model, SourceFile, load};
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(),
);
}
#[test]
fn forward_auth_hosts_strip_client_identity_headers_in_both_engines() {
let m = model(false);
let edge: EdgeConfig = serde_json::from_str(&compile::edge(&m, &options()).unwrap()).unwrap();
let strip = edge.forward_auth.unwrap().strip_headers;
for h in [
"Remote-User",
"Remote-Groups",
"Remote-Email",
"Remote-Name",
] {
assert!(
strip.iter().any(|s| s.eq_ignore_ascii_case(h)),
"edge strips {h}"
);
}
let caddy = compile::caddy(&m, &options()).unwrap();
let v: serde_json::Value = serde_json::from_str(&caddy).unwrap();
let routes = v["apps"]["http"]["servers"]["ianitor_https"]["routes"]
.as_array()
.unwrap();
let wiki = routes
.iter()
.find(|r| r["match"][0]["host"][0] == "wiki.home.test")
.unwrap();
let steps = wiki["handle"][0]["routes"].as_array().unwrap();
let first = &steps[0]["handle"][0];
assert_eq!(
first["handler"], "headers",
"identity headers are deleted before forward_auth"
);
let deleted: Vec<&str> = first["request"]["delete"]
.as_array()
.unwrap()
.iter()
.map(|d| d.as_str().unwrap())
.collect();
for h in [
"Remote-User",
"Remote-Groups",
"Remote-Email",
"Remote-Name",
] {
assert!(deleted.contains(&h), "caddy deletes {h}: {deleted:?}");
}
assert_eq!(
steps[1]["handle"][0]["handler"], "reverse_proxy",
"then forward_auth"
);
}
#[test]
fn websocket_refusal_in_caddy_matches_any_upgrade_token() {
let caddy = compile::caddy(&model(false), &options()).unwrap();
assert!(
caddy.contains(r#"(?i)(^|,)\\s*websocket\\s*(,|$)"#),
"token-aware Upgrade matcher"
);
}
#[test]
fn device_cert_hosts_check_client_certificates_in_both_engines() {
let m = model(false);
let edge: EdgeConfig = serde_json::from_str(&compile::edge(&m, &options()).unwrap()).unwrap();
let dc = edge.device_certs.expect("a host needs device certificates");
assert_eq!(dc.ca, "/var/lib/ianitor/certs/domi-devices-ca.pem");
assert_eq!(dc.allow, "/var/lib/ianitor/certs/domi-devices.pem");
let on: Vec<&str> = edge
.hosts
.iter()
.filter(|h| h.device_certs)
.map(|h| h.hostname.as_str())
.collect();
assert_eq!(on, ["status.example.org"]);
let v: serde_json::Value =
serde_json::from_str(&compile::caddy(&m, &options()).unwrap()).unwrap();
let https = &v["apps"]["http"]["servers"]["ianitor_https"];
let policies = https["tls_connection_policies"].as_array().unwrap();
let with_auth: Vec<&serde_json::Value> = policies
.iter()
.filter(|p| p.get("client_authentication").is_some())
.collect();
assert_eq!(
with_auth.len(),
1,
"only the device host asks for a certificate"
);
assert_eq!(with_auth[0]["match"]["sni"][0], "status.example.org");
assert_eq!(
with_auth[0]["client_authentication"]["mode"],
"verify_if_given"
);
let routes = https["routes"].as_array().unwrap();
let status = routes
.iter()
.find(|r| r["match"][0]["host"][0] == "status.example.org")
.unwrap();
let first = &status["handle"][0]["routes"][0];
assert_eq!(
first["handle"][0]["status_code"], 403,
"no certificate: 403 first"
);
// Without a device host, neither engine asks for client certificates.
let plain = ianitor_core::load(
&SourceFile {
name: "ianitor.toml",
contents: "",
},
&[SourceFile {
name: "hosts/a.test.toml",
contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
}],
)
.unwrap();
let e: EdgeConfig = serde_json::from_str(&compile::edge(&plain, &options()).unwrap()).unwrap();
assert!(e.device_certs.is_none());
assert!(
!compile::caddy(&plain, &options())
.unwrap()
.contains("client_authentication")
);
}