[core] Schema: tests first for validation and compiler determinism (red: 37+11 failing)
This commit is contained in:
@@ -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"
|
||||
@@ -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"
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user