441 lines
19 KiB
Rust
441 lines
19 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/.
|
|
|
|
//! Typed validation errors. Every message names the file and says what is wrong in plain English.
|
|
//!
|
|
//! Each error also has a stable [`ValidationError::code`], the form field it is about
|
|
//! ([`ValidationError::field`], e.g. `upstreams[1]`) and the values the UI shows in bold
|
|
//! ([`ValidationError::params`]). The control API maps the code to the UI's copy
|
|
//! (docs/ui-api.md §3.1) and keeps the `Display` text below as the technical detail.
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::fmt;
|
|
|
|
/// The reasons carried in `&'static str` fields. [`ValidationError::code`] compares them by
|
|
/// value, so every reason is written once, here.
|
|
pub(crate) mod reason {
|
|
pub const HOST_EMPTY: &str = "it is empty";
|
|
pub const HOST_TOO_LONG: &str = "it is longer than 253 characters";
|
|
pub const HOST_IP: &str = "IP addresses are not hostnames";
|
|
pub const HOST_WILDCARD: &str = "wildcards are not supported";
|
|
pub const HOST_TRAILING_DOT: &str = "it must not end with a dot";
|
|
pub const HOST_UPPERCASE: &str = "it must be lowercase";
|
|
pub const HOST_SPACES: &str = "it must not contain spaces";
|
|
pub const HOST_EMPTY_LABEL: &str = "it has an empty label";
|
|
pub const HOST_LABEL_LONG: &str = "a label is longer than 63 characters";
|
|
pub const HOST_CHARACTERS: &str = "only a-z, 0-9, '-' and '.' are allowed";
|
|
pub const HOST_LABEL_DASH: &str = "a label must not start or end with '-'";
|
|
pub const HOST_NUMERIC: &str = "the last label must not be numeric";
|
|
|
|
pub const URL_ASCII: &str = "it must be plain ASCII without spaces";
|
|
pub const URL_NOT_URL: &str = "it is not a URL like http://127.0.0.1:8080";
|
|
pub const URL_SCHEME: &str = "only http:// and https:// are supported";
|
|
pub const URL_CREDENTIALS: &str = "credentials in the URL are not allowed";
|
|
pub const URL_FRAGMENT: &str = "a #fragment is not allowed";
|
|
pub const URL_NO_HOST: &str = "it has no host";
|
|
pub const URL_UNIX_PATH: &str = "a socket upstream is unix:/absolute/path: letters, digits, '.', '_', '-' and single '/' only, no '.' or '..' parts, at most 100 characters";
|
|
pub const URL_HOST_NAME: &str = "the host name is not valid";
|
|
pub const URL_NO_PORT: &str = "it has no port";
|
|
pub const URL_PORT_ZERO: &str = "port 0 is not usable";
|
|
pub const URL_PATH: &str = "a path is not allowed; requests keep their own path";
|
|
pub const URL_QUERY: &str = "a ?query is not allowed";
|
|
pub const URL_BRACES: &str = "'{' and '}' are not allowed";
|
|
pub const URL_MIXED: &str = "all upstreams of a host must use the same scheme";
|
|
|
|
pub const VALUE_EMPTY: &str = "an empty value is not allowed; use action = \"remove\"";
|
|
pub const VALUE_LONG: &str = "it is longer than 4096 characters";
|
|
pub const VALUE_ASCII: &str = "only visible ASCII characters and spaces are allowed";
|
|
pub const VALUE_BRACES: &str = "'{' and '}' are not allowed (they are placeholders in Caddy)";
|
|
pub const VALUE_EDGE_SPACE: &str = "it must not start or end with a space";
|
|
|
|
pub const RULE_REMOVE_VALUE: &str = "remove takes no value or secret";
|
|
pub const RULE_BOTH: &str = "give either value or secret, not both";
|
|
pub const RULE_NEITHER: &str = "set needs a value or a secret";
|
|
|
|
pub const HEALTH_PATH: &str =
|
|
"path must start with '/' and contain only visible ASCII without '{', '}' or '#'";
|
|
pub const HEALTH_INTERVAL: &str = "interval_secs must be between 1 and 3600";
|
|
|
|
pub const PATH_LAYOUT: &str =
|
|
"only ianitor.toml and hosts/<hostname>.toml belong in the routes repository";
|
|
pub const PATH_SUBDIR: &str = "folders inside hosts/ are not allowed";
|
|
pub const PATH_NAME: &str = "the file name must be a lowercase hostname followed by .toml";
|
|
pub const PATH_KIND: &str = "symbolic links, executables and submodules are not allowed";
|
|
}
|
|
|
|
/// 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} is larger than {max} bytes")]
|
|
FileTooLarge { file: String, max: usize },
|
|
#[error("{file} must be named after its hostname: hosts/{hostname}.toml")]
|
|
FileNameMismatch { file: String, hostname: String },
|
|
#[error("{file}: {reason}")]
|
|
UnexpectedFile { file: String, reason: &'static str },
|
|
#[error("{file}: at most {max} upstreams per host")]
|
|
TooManyUpstreams { file: String, max: usize },
|
|
#[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,
|
|
/// Position in `upstreams`; `None` when the problem is about the list as a whole.
|
|
index: Option<usize>,
|
|
},
|
|
#[error("{file}: upstream `{url}` is listed twice")]
|
|
DuplicateUpstream {
|
|
file: String,
|
|
url: String,
|
|
index: usize,
|
|
},
|
|
#[error("{file}: secret `{secret}` is used but not declared in the site file")]
|
|
UndefinedSecret {
|
|
file: String,
|
|
secret: String,
|
|
field: String,
|
|
},
|
|
#[error(
|
|
"{file}: response header `{header}` may not use a secret; secrets only go to upstreams"
|
|
)]
|
|
SecretInResponseHeader {
|
|
file: String,
|
|
header: String,
|
|
field: 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,
|
|
field: String,
|
|
},
|
|
#[error("{file}: value for header `{header}` is not allowed: {reason}")]
|
|
InvalidHeaderValue {
|
|
file: String,
|
|
header: String,
|
|
reason: &'static str,
|
|
field: String,
|
|
},
|
|
#[error("{file}: header `{header}` is managed by the proxy and cannot be changed by a rule")]
|
|
ProtectedHeader {
|
|
file: String,
|
|
header: String,
|
|
field: String,
|
|
},
|
|
#[error("{file}: header `{header}` has more than one rule in the same list")]
|
|
DuplicateHeaderRule {
|
|
file: String,
|
|
header: String,
|
|
field: String,
|
|
},
|
|
#[error("{file}: rule for header `{header}` is incomplete: {reason}")]
|
|
BadHeaderRule {
|
|
file: String,
|
|
header: String,
|
|
reason: &'static str,
|
|
field: String,
|
|
},
|
|
#[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}: only a host behind sign-in (auth = \"forward-auth\") may send the `ui-proof` secret; it is the web UI's admin host"
|
|
)]
|
|
ProofWithoutSignIn { 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(),
|
|
}
|
|
}
|
|
|
|
impl ValidationError {
|
|
/// The file the problem is in (for a duplicate hostname: the second file).
|
|
pub fn file(&self) -> &str {
|
|
use ValidationError as E;
|
|
match self {
|
|
E::Syntax { file, .. }
|
|
| E::UnknownField { file, .. }
|
|
| E::MissingField { file, .. }
|
|
| E::InvalidValue { file, .. }
|
|
| E::DuplicateFile { file }
|
|
| E::FileTooLarge { file, .. }
|
|
| E::FileNameMismatch { file, .. }
|
|
| E::UnexpectedFile { file, .. }
|
|
| E::TooManyUpstreams { file, .. }
|
|
| E::InvalidHostname { file, .. }
|
|
| E::NoUpstreams { file }
|
|
| E::BadUpstreamUrl { file, .. }
|
|
| E::DuplicateUpstream { file, .. }
|
|
| E::UndefinedSecret { file, .. }
|
|
| E::SecretInResponseHeader { file, .. }
|
|
| E::InvalidSecretName { file, .. }
|
|
| E::InvalidHeaderName { file, .. }
|
|
| E::InvalidHeaderValue { file, .. }
|
|
| E::ProtectedHeader { file, .. }
|
|
| E::DuplicateHeaderRule { file, .. }
|
|
| E::BadHeaderRule { file, .. }
|
|
| E::BadHealthCheck { file, .. }
|
|
| E::ForwardAuthNotConfigured { file }
|
|
| E::ProofWithoutSignIn { file }
|
|
| E::BadForwardAuth { file, .. }
|
|
| E::BadAcme { file, .. } => file,
|
|
E::DuplicateHostname { second, .. } => second,
|
|
}
|
|
}
|
|
|
|
/// True when the problem is in the site file (or a stray file), not in a host file.
|
|
pub fn in_site_file(&self) -> bool {
|
|
!self.file().starts_with("hosts/")
|
|
}
|
|
|
|
/// A stable code the UI switches on, e.g. `host.upstream.no_port` (docs/ui-api.md §3.1).
|
|
pub fn code(&self) -> &'static str {
|
|
use ValidationError as E;
|
|
use reason as r;
|
|
let site = self.in_site_file();
|
|
match self {
|
|
E::Syntax { .. } => "file.syntax",
|
|
E::UnknownField { .. } if site => "site.field.unknown",
|
|
E::UnknownField { .. } => "host.field.unknown",
|
|
E::MissingField { field, .. } if !site && field == "hostname" => {
|
|
"host.hostname.missing"
|
|
}
|
|
E::MissingField { field, .. } if !site && field == "upstreams" => {
|
|
"host.upstreams.missing"
|
|
}
|
|
E::MissingField { .. } => "file.field.missing",
|
|
E::InvalidValue { .. } => "file.field.invalid",
|
|
E::DuplicateFile { .. } => "repo.duplicate_file",
|
|
E::FileTooLarge { .. } => "file.too_large",
|
|
E::FileNameMismatch { .. } => "host.file_name",
|
|
E::UnexpectedFile { .. } => "repo.unexpected_file",
|
|
E::TooManyUpstreams { .. } => "host.upstream.too_many",
|
|
E::InvalidHostname { reason, .. } => match *reason {
|
|
x if x == r::HOST_EMPTY => "host.hostname.missing",
|
|
x if x == r::HOST_TOO_LONG => "host.hostname.too_long",
|
|
x if x == r::HOST_IP || x == r::HOST_NUMERIC => "host.hostname.numeric",
|
|
x if x == r::HOST_WILDCARD => "host.hostname.wildcard",
|
|
x if x == r::HOST_TRAILING_DOT => "host.hostname.trailing_dot",
|
|
x if x == r::HOST_UPPERCASE => "host.hostname.uppercase",
|
|
x if x == r::HOST_SPACES => "host.hostname.spaces",
|
|
x if x == r::HOST_EMPTY_LABEL => "host.hostname.empty_label",
|
|
x if x == r::HOST_LABEL_LONG => "host.hostname.label_long",
|
|
x if x == r::HOST_LABEL_DASH => "host.hostname.label_dash",
|
|
_ => "host.hostname.characters",
|
|
},
|
|
E::DuplicateHostname { .. } => "host.hostname.taken",
|
|
E::NoUpstreams { .. } => "host.upstreams.missing",
|
|
E::BadUpstreamUrl { reason, .. } => match *reason {
|
|
x if x == r::URL_SCHEME => "host.upstream.scheme",
|
|
x if x == r::URL_CREDENTIALS => "host.upstream.credentials",
|
|
x if x == r::URL_FRAGMENT => "host.upstream.fragment",
|
|
x if x == r::URL_NO_HOST => "host.upstream.no_host",
|
|
x if x == r::URL_HOST_NAME => "host.upstream.host_name",
|
|
x if x == r::URL_NO_PORT => "host.upstream.no_port",
|
|
x if x == r::URL_PORT_ZERO => "host.upstream.port_zero",
|
|
x if x == r::URL_PATH => "host.upstream.path",
|
|
x if x == r::URL_QUERY => "host.upstream.query",
|
|
x if x == r::URL_MIXED => "host.upstream.mixed_schemes",
|
|
x if x == r::URL_UNIX_PATH => "host.upstream.unix_path",
|
|
_ => "host.upstream.not_url",
|
|
},
|
|
E::DuplicateUpstream { .. } => "host.upstream.duplicate",
|
|
E::UndefinedSecret { .. } => "host.header.secret_unknown",
|
|
E::SecretInResponseHeader { .. } => "host.header.secret_response",
|
|
E::InvalidSecretName { .. } => "site.secret.name",
|
|
E::InvalidHeaderName { .. } | E::ProtectedHeader { .. } if site => {
|
|
"site.forward_auth.header"
|
|
}
|
|
E::InvalidHeaderName { .. } => "host.header.name",
|
|
E::InvalidHeaderValue { reason, .. } if *reason == r::VALUE_EMPTY => {
|
|
"host.header.empty"
|
|
}
|
|
E::InvalidHeaderValue { .. } => "host.header.value",
|
|
E::ProtectedHeader { .. } => "host.header.protected",
|
|
E::DuplicateHeaderRule { .. } => "host.header.duplicate",
|
|
E::BadHeaderRule { reason, .. } => match *reason {
|
|
x if x == r::RULE_BOTH => "host.header.both",
|
|
x if x == r::RULE_REMOVE_VALUE => "host.header.remove_value",
|
|
_ => "host.header.empty",
|
|
},
|
|
E::BadHealthCheck { reason, .. } if *reason == r::HEALTH_INTERVAL => {
|
|
"host.health.interval"
|
|
}
|
|
E::BadHealthCheck { .. } => "host.health.path",
|
|
E::ForwardAuthNotConfigured { .. } => "host.auth.not_configured",
|
|
E::ProofWithoutSignIn { .. } => "host.header.proof",
|
|
E::BadForwardAuth { .. } => "site.forward_auth",
|
|
E::BadAcme { .. } => "site.acme",
|
|
}
|
|
}
|
|
|
|
/// The form field the problem is about, as a path into the host body (`hostname`,
|
|
/// `upstreams[0]`, `request_headers[2].name`, `health_check.path`), or `None`.
|
|
pub fn field(&self) -> Option<String> {
|
|
use ValidationError as E;
|
|
if self.in_site_file() {
|
|
return None;
|
|
}
|
|
match self {
|
|
E::UnknownField { field, .. } | E::MissingField { field, .. } => Some(field.clone()),
|
|
E::FileNameMismatch { .. }
|
|
| E::InvalidHostname { .. }
|
|
| E::DuplicateHostname { .. } => Some("hostname".into()),
|
|
E::TooManyUpstreams { .. } | E::NoUpstreams { .. } => Some("upstreams".into()),
|
|
E::BadUpstreamUrl { index, .. } => Some(match index {
|
|
Some(i) => format!("upstreams[{i}]"),
|
|
None => "upstreams".into(),
|
|
}),
|
|
E::DuplicateUpstream { index, .. } => Some(format!("upstreams[{index}]")),
|
|
E::UndefinedSecret { field, .. }
|
|
| E::SecretInResponseHeader { field, .. }
|
|
| E::InvalidHeaderName { field, .. }
|
|
| E::InvalidHeaderValue { field, .. }
|
|
| E::ProtectedHeader { field, .. }
|
|
| E::DuplicateHeaderRule { field, .. }
|
|
| E::BadHeaderRule { field, .. } => Some(field.clone()),
|
|
E::BadHealthCheck { reason, .. } if *reason == reason::HEALTH_INTERVAL => {
|
|
Some("health_check.interval_secs".into())
|
|
}
|
|
E::BadHealthCheck { .. } => Some("health_check.path".into()),
|
|
E::ForwardAuthNotConfigured { .. } => Some("auth".into()),
|
|
E::ProofWithoutSignIn { .. } => Some("auth".into()),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// The values a message shows: always `file`, plus `line`, `field`, `max`, `hostname`,
|
|
/// `suggestion`, `url`, `name` or `secret` where they apply.
|
|
pub fn params(&self) -> BTreeMap<&'static str, String> {
|
|
use ValidationError as E;
|
|
let mut p = BTreeMap::new();
|
|
p.insert("file", self.file().to_owned());
|
|
match self {
|
|
E::Syntax { line: Some(l), .. } => {
|
|
p.insert("line", l.to_string());
|
|
}
|
|
E::UnknownField { field, .. } | E::MissingField { field, .. } => {
|
|
p.insert("field", field.clone());
|
|
}
|
|
E::FileTooLarge { max, .. } | E::TooManyUpstreams { max, .. } => {
|
|
p.insert("max", max.to_string());
|
|
}
|
|
E::FileNameMismatch { hostname, .. } | E::DuplicateHostname { hostname, .. } => {
|
|
p.insert("hostname", hostname.clone());
|
|
}
|
|
E::InvalidHostname {
|
|
hostname, reason, ..
|
|
} => {
|
|
p.insert("hostname", hostname.clone());
|
|
if *reason == reason::HOST_UPPERCASE || *reason == reason::HOST_TRAILING_DOT {
|
|
p.insert(
|
|
"suggestion",
|
|
hostname.trim_end_matches('.').to_ascii_lowercase(),
|
|
);
|
|
}
|
|
}
|
|
E::BadUpstreamUrl { url, reason, .. } => {
|
|
p.insert("url", url.clone());
|
|
if [reason::URL_PATH, reason::URL_QUERY, reason::URL_FRAGMENT].contains(reason)
|
|
&& let Ok(u) = url::Url::parse(url)
|
|
&& let Some(host) = u.host_str()
|
|
{
|
|
let port = u.port().map(|p| format!(":{p}")).unwrap_or_default();
|
|
p.insert("suggestion", format!("{}://{host}{port}", u.scheme()));
|
|
}
|
|
}
|
|
E::DuplicateUpstream { url, .. } => {
|
|
p.insert("url", url.clone());
|
|
}
|
|
E::UndefinedSecret { secret, .. } => {
|
|
p.insert("secret", secret.clone());
|
|
}
|
|
E::InvalidSecretName { name, .. } | E::InvalidHeaderName { name, .. } => {
|
|
p.insert("name", name.clone());
|
|
}
|
|
E::SecretInResponseHeader { header, .. }
|
|
| E::InvalidHeaderValue { header, .. }
|
|
| E::ProtectedHeader { header, .. }
|
|
| E::DuplicateHeaderRule { header, .. }
|
|
| E::BadHeaderRule { header, .. } => {
|
|
p.insert("name", header.clone());
|
|
}
|
|
_ => {}
|
|
}
|
|
p
|
|
}
|
|
}
|
|
|
|
/// 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
|
|
}
|
|
|
|
/// Wrap errors found outside [`crate::load`] (e.g. by [`crate::routes::check_path`]).
|
|
pub fn from_errors(errors: Vec<ValidationError>) -> ValidationErrors {
|
|
ValidationErrors(errors)
|
|
}
|
|
}
|
|
|
|
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 {}
|