// 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 = 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, caddy_admin_socket: None, trusted_proxies: Vec::new(), proxy_socket: 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::(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 trusted_proxies_reach_both_engines_only_when_set() { let edge = compile::edge(&model(false), &options()).unwrap(); let caddy = compile::caddy(&model(false), &options()).unwrap(); assert!(!edge.contains("trusted_proxies") && !caddy.contains("trusted_proxies")); let mut o = options(); o.trusted_proxies = vec!["127.0.0.1".parse().unwrap()]; let cfg: EdgeConfig = serde_json::from_str(&compile::edge(&model(false), &o).unwrap()).unwrap(); assert_eq!(cfg.trusted_proxies, vec!["127.0.0.1".to_owned()]); let v: serde_json::Value = serde_json::from_str(&compile::caddy(&model(false), &o).unwrap()).unwrap(); let servers = v["apps"]["http"]["servers"].as_object().unwrap(); let https = servers .values() .find(|s| s["listen"][0] == "0.0.0.0:443") .unwrap(); assert_eq!( https["trusted_proxies"], serde_json::json!({"source": "static", "ranges": ["127.0.0.1"]}) ); assert_eq!(https["trusted_proxies_strict"], serde_json::json!(1)); } #[test] fn the_proxy_socket_reaches_both_engines_only_when_set() { let edge = compile::edge(&model(false), &options()).unwrap(); let caddy = compile::caddy(&model(false), &options()).unwrap(); assert!(!edge.contains("proxy_socket") && !caddy.contains("ianitor_proxy")); let mut o = options(); o.proxy_socket = Some("/run/ianitor-proxy/edge.sock".into()); let cfg: EdgeConfig = serde_json::from_str(&compile::edge(&model(false), &o).unwrap()).unwrap(); assert_eq!( cfg.proxy_socket.as_deref(), Some("/run/ianitor-proxy/edge.sock") ); let v: serde_json::Value = serde_json::from_str(&compile::caddy(&model(false), &o).unwrap()).unwrap(); let servers = &v["apps"]["http"]["servers"]; let proxy = &servers["ianitor_proxy"]; assert_eq!( proxy["listen"], serde_json::json!(["unix//run/ianitor-proxy/edge.sock|0660"]) ); // The same routes as the HTTPS server, no TLS, the socket's peer trusted. assert_eq!(proxy["routes"], servers["ianitor_https"]["routes"]); assert_eq!( proxy["automatic_https"], serde_json::json!({"disable": true}) ); assert_eq!(proxy["trusted_proxies_unix"], serde_json::json!(true)); assert!(proxy.get("tls_connection_policies").is_none()); let long = format!("/{}", "a".repeat(120)); for bad in ["relative.sock", "/run/{env.HOME}.sock", long.as_str()] { let mut o = options(); o.proxy_socket = Some(bad.to_owned()); assert!(compile::edge(&model(false), &o).is_err(), "{bad}"); assert!(compile::caddy(&model(false), &o).is_err(), "{bad}"); } } #[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") ); }