830 lines
25 KiB
Rust
830 lines
25 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/.
|
|
|
|
//! Parsing and validation of the routes tree. Route files are hostile input: everything is
|
|
//! checked, every problem becomes a typed [`ValidationError`], nothing panics.
|
|
|
|
use std::collections::{BTreeMap, BTreeSet};
|
|
use std::net::IpAddr;
|
|
|
|
use serde::Deserialize;
|
|
use serde::de::DeserializeOwned;
|
|
|
|
use crate::error::{ValidationError as E, ValidationErrors, reason as r};
|
|
use crate::model::{
|
|
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
|
|
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model,
|
|
Scheme, SecretName, Site, TlsMode, UI_PROOF_SECRET, Upstream, UpstreamHost,
|
|
};
|
|
|
|
/// 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,
|
|
}
|
|
|
|
// ------------------------------------------------------------------ raw file shapes
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RawSite {
|
|
#[serde(default)]
|
|
secrets: Vec<String>,
|
|
forward_auth: Option<RawForwardAuth>,
|
|
acme: Option<RawAcme>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RawForwardAuth {
|
|
url: String,
|
|
copy_headers: Option<Vec<String>>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RawAcme {
|
|
email: Option<String>,
|
|
directory: Option<String>,
|
|
}
|
|
|
|
#[derive(Deserialize, Default)]
|
|
#[serde(rename_all = "kebab-case")]
|
|
enum RawTls {
|
|
#[default]
|
|
Letsencrypt,
|
|
Domi,
|
|
}
|
|
|
|
#[derive(Deserialize, Default)]
|
|
#[serde(rename_all = "kebab-case")]
|
|
enum RawAuth {
|
|
#[default]
|
|
None,
|
|
ForwardAuth,
|
|
}
|
|
|
|
#[derive(Deserialize, Default)]
|
|
#[serde(rename_all = "kebab-case")]
|
|
enum RawAccessLog {
|
|
#[default]
|
|
Off,
|
|
Truncated,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(rename_all = "kebab-case")]
|
|
enum RawAction {
|
|
Set,
|
|
Remove,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RawRule {
|
|
action: RawAction,
|
|
name: String,
|
|
value: Option<String>,
|
|
secret: Option<String>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RawHealthCheck {
|
|
path: String,
|
|
/// Signed so that 0 and negative numbers get a typed error instead of a serde one.
|
|
#[serde(default = "default_interval")]
|
|
interval_secs: i64,
|
|
}
|
|
|
|
fn default_interval() -> i64 {
|
|
10
|
|
}
|
|
|
|
fn yes() -> bool {
|
|
true
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct RawHost {
|
|
hostname: String,
|
|
upstreams: Vec<String>,
|
|
#[serde(default)]
|
|
tls: RawTls,
|
|
#[serde(default)]
|
|
auth: RawAuth,
|
|
#[serde(default = "yes")]
|
|
websockets: bool,
|
|
#[serde(default)]
|
|
share_links: bool,
|
|
#[serde(default)]
|
|
device_certs: bool,
|
|
#[serde(default)]
|
|
access_log: RawAccessLog,
|
|
health_check: Option<RawHealthCheck>,
|
|
#[serde(default)]
|
|
request_headers: Vec<RawRule>,
|
|
#[serde(default)]
|
|
response_headers: Vec<RawRule>,
|
|
}
|
|
|
|
// ------------------------------------------------------------------ entry point
|
|
|
|
/// Parse and validate the site file and every host file. Returns every problem found, or the
|
|
/// model with hosts sorted by hostname. File order does not matter.
|
|
pub fn load(site: &SourceFile<'_>, hosts: &[SourceFile<'_>]) -> Result<Model, ValidationErrors> {
|
|
let mut errors = Vec::new();
|
|
|
|
let site_model = match parse::<RawSite>(site) {
|
|
Ok(raw) => check_site(site.name, raw, &mut errors),
|
|
Err(e) => {
|
|
errors.push(e);
|
|
None
|
|
}
|
|
};
|
|
|
|
// Stable order: by file name. Duplicate file names are an error of their own.
|
|
let mut files: Vec<&SourceFile<'_>> = hosts.iter().collect();
|
|
files.sort_by(|a, b| a.name.cmp(b.name));
|
|
let mut seen_files = BTreeSet::new();
|
|
let mut checked = Vec::new();
|
|
for f in files {
|
|
if !seen_files.insert(f.name) {
|
|
errors.push(E::DuplicateFile {
|
|
file: f.name.to_owned(),
|
|
});
|
|
continue;
|
|
}
|
|
match parse::<RawHost>(f) {
|
|
Ok(raw) => {
|
|
if let Some(h) = check_host(f.name, raw, site_model.as_ref(), &mut errors) {
|
|
checked.push(h);
|
|
}
|
|
}
|
|
Err(e) => errors.push(e),
|
|
}
|
|
}
|
|
|
|
let mut by_name: BTreeMap<Hostname, Host> = BTreeMap::new();
|
|
for h in checked {
|
|
if let Some(first) = by_name.get(&h.hostname) {
|
|
errors.push(E::DuplicateHostname {
|
|
hostname: h.hostname.to_string(),
|
|
first: first.source.clone(),
|
|
second: h.source.clone(),
|
|
});
|
|
} else {
|
|
by_name.insert(h.hostname.clone(), h);
|
|
}
|
|
}
|
|
|
|
match site_model {
|
|
Some(site) if errors.is_empty() => Ok(Model {
|
|
site,
|
|
hosts: by_name.into_values().collect(),
|
|
}),
|
|
_ => Err(ValidationErrors(errors)),
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------ TOML → raw
|
|
|
|
fn parse<T: DeserializeOwned>(f: &SourceFile<'_>) -> Result<T, E> {
|
|
let file = f.name.to_owned();
|
|
if f.contents.len() > MAX_FILE_BYTES {
|
|
return Err(E::FileTooLarge {
|
|
file,
|
|
max: MAX_FILE_BYTES,
|
|
});
|
|
}
|
|
// A plain table parse first tells syntax errors apart from schema errors.
|
|
if let Err(e) = toml::from_str::<toml::Table>(f.contents) {
|
|
return Err(E::Syntax {
|
|
file,
|
|
line: e.span().map(|s| line_of(f.contents, s.start)),
|
|
message: e.message().trim().to_owned(),
|
|
});
|
|
}
|
|
toml::from_str::<T>(f.contents).map_err(|e| classify(file, e.message()))
|
|
}
|
|
|
|
fn line_of(text: &str, offset: usize) -> usize {
|
|
text.get(..offset).map_or(0, |t| t.matches('\n').count()) + 1
|
|
}
|
|
|
|
/// Turn serde's standard messages into typed errors.
|
|
fn classify(file: String, message: &str) -> E {
|
|
let message = message.trim();
|
|
let quoted = |prefix: &str| -> Option<String> {
|
|
let rest = message.strip_prefix(prefix)?;
|
|
let end = rest.find('`')?;
|
|
Some(rest[..end].to_owned())
|
|
};
|
|
if let Some(field) = quoted("unknown field `") {
|
|
E::UnknownField { file, field }
|
|
} else if let Some(field) = quoted("missing field `") {
|
|
E::MissingField { file, field }
|
|
} else {
|
|
E::InvalidValue {
|
|
file,
|
|
message: message.to_owned(),
|
|
}
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------ site file
|
|
|
|
fn check_site(file: &str, raw: RawSite, errors: &mut Vec<E>) -> Option<Site> {
|
|
let before = errors.len();
|
|
let mut secrets = BTreeSet::new();
|
|
for name in raw.secrets {
|
|
if valid_secret_name(&name) {
|
|
secrets.insert(SecretName(name));
|
|
} else {
|
|
errors.push(E::InvalidSecretName {
|
|
file: file.to_owned(),
|
|
name,
|
|
});
|
|
}
|
|
}
|
|
|
|
let forward_auth = raw.forward_auth.and_then(|fa| {
|
|
let bad = |reason| E::BadForwardAuth {
|
|
file: file.to_owned(),
|
|
reason,
|
|
};
|
|
let (upstream, path_and_query) = match parse_url(&fa.url, true) {
|
|
Ok(v) => v,
|
|
Err(reason) => {
|
|
errors.push(bad(reason));
|
|
return None;
|
|
}
|
|
};
|
|
let copy_headers: Vec<String> = match fa.copy_headers {
|
|
Some(h) => h,
|
|
None => AUTHELIA_COPY_HEADERS
|
|
.iter()
|
|
.map(|s| (*s).to_owned())
|
|
.collect(),
|
|
};
|
|
let mut seen = BTreeSet::new();
|
|
for h in ©_headers {
|
|
if !valid_header_name(h) {
|
|
errors.push(E::InvalidHeaderName {
|
|
file: file.to_owned(),
|
|
name: h.clone(),
|
|
field: "forward_auth.copy_headers".into(),
|
|
});
|
|
} else if is_protected(h) {
|
|
errors.push(E::ProtectedHeader {
|
|
file: file.to_owned(),
|
|
header: h.clone(),
|
|
field: "forward_auth.copy_headers".into(),
|
|
});
|
|
} else if !seen.insert(h.to_ascii_lowercase()) {
|
|
errors.push(bad("copy_headers lists a header twice"));
|
|
}
|
|
}
|
|
Some(ForwardAuth {
|
|
upstream,
|
|
path_and_query,
|
|
copy_headers,
|
|
})
|
|
});
|
|
|
|
let acme = match raw.acme {
|
|
None => Acme {
|
|
email: None,
|
|
directory: LETSENCRYPT_PRODUCTION.to_owned(),
|
|
},
|
|
Some(a) => {
|
|
let bad = |reason| E::BadAcme {
|
|
file: file.to_owned(),
|
|
reason,
|
|
};
|
|
if a.email.as_deref().is_some_and(|e| !valid_email(e)) {
|
|
errors.push(bad("email is not a plain address like admin@example.org"));
|
|
}
|
|
let directory = a
|
|
.directory
|
|
.unwrap_or_else(|| LETSENCRYPT_PRODUCTION.to_owned());
|
|
if !valid_acme_directory(&directory) {
|
|
errors.push(bad(
|
|
"directory must be an https:// URL without credentials or fragment",
|
|
));
|
|
}
|
|
Acme {
|
|
email: a.email,
|
|
directory,
|
|
}
|
|
}
|
|
};
|
|
|
|
(errors.len() == before).then_some(Site {
|
|
secrets,
|
|
forward_auth,
|
|
acme,
|
|
})
|
|
}
|
|
|
|
fn valid_secret_name(n: &str) -> bool {
|
|
let b = n.as_bytes();
|
|
!b.is_empty()
|
|
&& b.len() <= 64
|
|
&& (b[0].is_ascii_lowercase() || b[0].is_ascii_digit())
|
|
&& b.iter()
|
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'_' || *c == b'-')
|
|
}
|
|
|
|
fn valid_email(e: &str) -> bool {
|
|
let Some((local, domain)) = e.split_once('@') else {
|
|
return false;
|
|
};
|
|
!local.is_empty()
|
|
&& e.len() <= 254
|
|
&& check_hostname(domain).is_ok()
|
|
&& local
|
|
.bytes()
|
|
.all(|c| c.is_ascii_graphic() && !b"{}@<>\"\\,;:[]()".contains(&c))
|
|
}
|
|
|
|
fn valid_acme_directory(d: &str) -> bool {
|
|
match url::Url::parse(d) {
|
|
Ok(u) => {
|
|
u.scheme() == "https"
|
|
&& u.username().is_empty()
|
|
&& u.password().is_none()
|
|
&& u.fragment().is_none()
|
|
&& u.host().is_some()
|
|
&& d.bytes()
|
|
.all(|c| c.is_ascii_graphic() && c != b'{' && c != b'}')
|
|
}
|
|
Err(_) => false,
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------ host files
|
|
|
|
fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>) -> Option<Host> {
|
|
let before = errors.len();
|
|
let f = || file.to_owned();
|
|
|
|
match check_hostname(&raw.hostname) {
|
|
Err(reason) => errors.push(E::InvalidHostname {
|
|
file: f(),
|
|
hostname: raw.hostname.clone(),
|
|
reason,
|
|
}),
|
|
Ok(()) => {
|
|
// One TOML per host, named after it: exactly `hosts/<hostname>.toml`.
|
|
if file != format!("hosts/{}.toml", raw.hostname) {
|
|
errors.push(E::FileNameMismatch {
|
|
file: f(),
|
|
hostname: raw.hostname.clone(),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
if raw.upstreams.is_empty() {
|
|
errors.push(E::NoUpstreams { file: f() });
|
|
}
|
|
if raw.upstreams.len() > MAX_UPSTREAMS {
|
|
errors.push(E::TooManyUpstreams {
|
|
file: f(),
|
|
max: MAX_UPSTREAMS,
|
|
});
|
|
}
|
|
let mut upstreams: Vec<Upstream> = Vec::new();
|
|
let mut seen_upstreams = BTreeSet::new();
|
|
for (index, u) in raw.upstreams.iter().take(MAX_UPSTREAMS).enumerate() {
|
|
match parse_url(u, false) {
|
|
Ok((up, _)) => {
|
|
if seen_upstreams.insert(up.clone()) {
|
|
upstreams.push(up);
|
|
} else {
|
|
errors.push(E::DuplicateUpstream {
|
|
file: f(),
|
|
url: shown_url(u),
|
|
index,
|
|
});
|
|
}
|
|
}
|
|
Err(reason) => errors.push(E::BadUpstreamUrl {
|
|
file: f(),
|
|
url: shown_url(u),
|
|
reason,
|
|
index: Some(index),
|
|
}),
|
|
}
|
|
}
|
|
|
|
if upstreams.windows(2).any(|w| w[0].scheme != w[1].scheme) {
|
|
errors.push(E::BadUpstreamUrl {
|
|
file: f(),
|
|
url: raw
|
|
.upstreams
|
|
.iter()
|
|
.map(|u| shown_url(u))
|
|
.collect::<Vec<_>>()
|
|
.join(", "),
|
|
reason: r::URL_MIXED,
|
|
index: None,
|
|
});
|
|
}
|
|
|
|
let auth = match raw.auth {
|
|
RawAuth::None => AuthMode::None,
|
|
RawAuth::ForwardAuth => AuthMode::ForwardAuth,
|
|
};
|
|
if auth == AuthMode::ForwardAuth && site.is_some_and(|s| s.forward_auth.is_none()) {
|
|
errors.push(E::ForwardAuthNotConfigured { file: f() });
|
|
}
|
|
|
|
// Identity headers (Authelia's four, plus any configured copy header) must not be
|
|
// overridable by a rule on a forward-auth host.
|
|
let identity: Vec<String> = match auth {
|
|
AuthMode::ForwardAuth => {
|
|
let extra = site
|
|
.and_then(|s| s.forward_auth.as_ref())
|
|
.map(|fa| fa.copy_headers.clone())
|
|
.unwrap_or_default();
|
|
AUTHELIA_COPY_HEADERS
|
|
.iter()
|
|
.map(|h| (*h).to_owned())
|
|
.chain(extra)
|
|
.map(|h| h.to_ascii_lowercase())
|
|
.collect()
|
|
}
|
|
AuthMode::None => Vec::new(),
|
|
};
|
|
let request_headers = check_rules(
|
|
file,
|
|
"request_headers",
|
|
raw.request_headers,
|
|
&identity,
|
|
site,
|
|
errors,
|
|
);
|
|
let response_headers = check_rules(
|
|
file,
|
|
"response_headers",
|
|
raw.response_headers,
|
|
&[],
|
|
site,
|
|
errors,
|
|
);
|
|
|
|
let health_check = raw.health_check.and_then(|hc| {
|
|
let bad = |reason| E::BadHealthCheck { file: f(), reason };
|
|
let ok_path = hc.path.starts_with('/')
|
|
&& hc.path.len() <= 1024
|
|
&& hc
|
|
.path
|
|
.bytes()
|
|
.all(|c| c.is_ascii_graphic() && !b"{}#".contains(&c));
|
|
if !ok_path {
|
|
errors.push(bad(r::HEALTH_PATH));
|
|
return None;
|
|
}
|
|
match u32::try_from(hc.interval_secs) {
|
|
Ok(i) if (1..=3600).contains(&i) => Some(HealthCheck {
|
|
path: hc.path,
|
|
interval_secs: i,
|
|
}),
|
|
_ => {
|
|
errors.push(bad(r::HEALTH_INTERVAL));
|
|
None
|
|
}
|
|
}
|
|
});
|
|
|
|
// The web UI's per-boot proof (docs/api.md, "Sign-in") may only ride on a host whose
|
|
// visitors were checked by forward-auth: edge strips client `Remote-*` headers only there.
|
|
let sends_proof = request_headers.iter().any(|r| {
|
|
matches!(r, HeaderRule::Set { value: HeaderValue::Secret(s), .. } if s.as_str() == UI_PROOF_SECRET)
|
|
});
|
|
if sends_proof && auth != AuthMode::ForwardAuth {
|
|
errors.push(E::ProofWithoutSignIn { file: f() });
|
|
}
|
|
|
|
if errors.len() != before {
|
|
return None;
|
|
}
|
|
Some(Host {
|
|
hostname: Hostname(raw.hostname),
|
|
source: f(),
|
|
upstreams,
|
|
tls: match raw.tls {
|
|
RawTls::Letsencrypt => TlsMode::LetsEncrypt,
|
|
RawTls::Domi => TlsMode::Domi,
|
|
},
|
|
auth,
|
|
request_headers,
|
|
response_headers,
|
|
websockets: raw.websockets,
|
|
health_check,
|
|
share_links: raw.share_links,
|
|
device_certs: raw.device_certs,
|
|
access_log: match raw.access_log {
|
|
RawAccessLog::Off => AccessLog::Off,
|
|
RawAccessLog::Truncated => AccessLog::Truncated,
|
|
},
|
|
})
|
|
}
|
|
|
|
/// Headers the proxy manages itself (framing, hop-by-hop, forwarding metadata).
|
|
const PROTECTED: [&str; 14] = [
|
|
"host",
|
|
"content-length",
|
|
"transfer-encoding",
|
|
"connection",
|
|
"upgrade",
|
|
"keep-alive",
|
|
"te",
|
|
"trailer",
|
|
"proxy-connection",
|
|
"x-forwarded-for",
|
|
"x-forwarded-proto",
|
|
"x-forwarded-host",
|
|
"x-forwarded-method",
|
|
"x-forwarded-uri",
|
|
];
|
|
|
|
fn is_protected(name: &str) -> bool {
|
|
PROTECTED.iter().any(|p| p.eq_ignore_ascii_case(name))
|
|
}
|
|
|
|
fn check_rules(
|
|
file: &str,
|
|
list: &str,
|
|
raw: Vec<RawRule>,
|
|
identity: &[String],
|
|
site: Option<&Site>,
|
|
errors: &mut Vec<E>,
|
|
) -> Vec<HeaderRule> {
|
|
let request = list == "request_headers";
|
|
let f = || file.to_owned();
|
|
let mut out = Vec::new();
|
|
let mut seen = BTreeSet::new();
|
|
for (i, r) in raw.into_iter().enumerate() {
|
|
let at = |part: &str| {
|
|
if part.is_empty() {
|
|
format!("{list}[{i}]")
|
|
} else {
|
|
format!("{list}[{i}].{part}")
|
|
}
|
|
};
|
|
let header = r.name.clone();
|
|
if !valid_header_name(&r.name) {
|
|
errors.push(E::InvalidHeaderName {
|
|
file: f(),
|
|
name: r.name,
|
|
field: at("name"),
|
|
});
|
|
continue;
|
|
}
|
|
let lower = r.name.to_ascii_lowercase();
|
|
if is_protected(&r.name) || identity.contains(&lower) {
|
|
errors.push(E::ProtectedHeader {
|
|
file: f(),
|
|
header,
|
|
field: at("name"),
|
|
});
|
|
continue;
|
|
}
|
|
if !seen.insert(lower) {
|
|
errors.push(E::DuplicateHeaderRule {
|
|
file: f(),
|
|
header,
|
|
field: at("name"),
|
|
});
|
|
continue;
|
|
}
|
|
let bad = |reason| E::BadHeaderRule {
|
|
file: f(),
|
|
header: header.clone(),
|
|
reason,
|
|
field: at(if reason == r::RULE_NEITHER {
|
|
"value"
|
|
} else {
|
|
""
|
|
}),
|
|
};
|
|
match (r.action, r.value, r.secret) {
|
|
(RawAction::Remove, None, None) => out.push(HeaderRule::Remove { name: r.name }),
|
|
(RawAction::Remove, _, _) => errors.push(bad(r::RULE_REMOVE_VALUE)),
|
|
(RawAction::Set, Some(_), Some(_)) => errors.push(bad(r::RULE_BOTH)),
|
|
(RawAction::Set, None, None) => errors.push(bad(r::RULE_NEITHER)),
|
|
(RawAction::Set, Some(v), None) => match check_header_value(&v) {
|
|
Ok(()) => out.push(HeaderRule::Set {
|
|
name: r.name,
|
|
value: HeaderValue::Literal(v),
|
|
}),
|
|
Err(reason) => errors.push(E::InvalidHeaderValue {
|
|
file: f(),
|
|
header,
|
|
reason,
|
|
field: at("value"),
|
|
}),
|
|
},
|
|
(RawAction::Set, None, Some(s)) => {
|
|
if !request {
|
|
errors.push(E::SecretInResponseHeader {
|
|
file: f(),
|
|
header,
|
|
field: at(""),
|
|
});
|
|
} else if site.is_some_and(|site| !site.secrets.contains(&SecretName(s.clone()))) {
|
|
errors.push(E::UndefinedSecret {
|
|
file: f(),
|
|
secret: s,
|
|
field: at("secret"),
|
|
});
|
|
} else {
|
|
out.push(HeaderRule::Set {
|
|
name: r.name,
|
|
value: HeaderValue::Secret(SecretName(s)),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
/// RFC 9110 token minus `*`, which is a wildcard in Caddy's header operations but a literal
|
|
/// character in edge; allowing it would let the engines disagree.
|
|
fn valid_header_name(n: &str) -> bool {
|
|
!n.is_empty()
|
|
&& n.len() <= 256
|
|
&& n.bytes()
|
|
.all(|c| c.is_ascii_alphanumeric() || b"!#$%&'+-.^_`|~".contains(&c))
|
|
}
|
|
|
|
fn check_header_value(v: &str) -> Result<(), &'static str> {
|
|
if v.is_empty() {
|
|
return Err(r::VALUE_EMPTY);
|
|
}
|
|
if v.len() > 4096 {
|
|
return Err(r::VALUE_LONG);
|
|
}
|
|
if !v.bytes().all(|c| (0x20..0x7f).contains(&c)) {
|
|
return Err(r::VALUE_ASCII);
|
|
}
|
|
if v.contains(['{', '}']) {
|
|
return Err(r::VALUE_BRACES);
|
|
}
|
|
if v.starts_with(' ') || v.ends_with(' ') {
|
|
return Err(r::VALUE_EDGE_SPACE);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
// ------------------------------------------------------------------ names and URLs
|
|
|
|
pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> {
|
|
if h.is_empty() {
|
|
return Err(r::HOST_EMPTY);
|
|
}
|
|
if h.len() > 253 {
|
|
return Err(r::HOST_TOO_LONG);
|
|
}
|
|
if h.parse::<IpAddr>().is_ok() || h.starts_with('[') {
|
|
return Err(r::HOST_IP);
|
|
}
|
|
if h.contains('*') {
|
|
return Err(r::HOST_WILDCARD);
|
|
}
|
|
if h.contains(char::is_whitespace) {
|
|
return Err(r::HOST_SPACES);
|
|
}
|
|
if h.ends_with('.') {
|
|
return Err(r::HOST_TRAILING_DOT);
|
|
}
|
|
if h.bytes().any(|c| c.is_ascii_uppercase()) {
|
|
return Err(r::HOST_UPPERCASE);
|
|
}
|
|
let mut last = "";
|
|
for label in h.split('.') {
|
|
if label.is_empty() {
|
|
return Err(r::HOST_EMPTY_LABEL);
|
|
}
|
|
if label.len() > 63 {
|
|
return Err(r::HOST_LABEL_LONG);
|
|
}
|
|
if !label
|
|
.bytes()
|
|
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
|
|
{
|
|
return Err(r::HOST_CHARACTERS);
|
|
}
|
|
if label.starts_with('-') || label.ends_with('-') {
|
|
return Err(r::HOST_LABEL_DASH);
|
|
}
|
|
last = label;
|
|
}
|
|
if last.bytes().all(|c| c.is_ascii_digit()) {
|
|
return Err(r::HOST_NUMERIC);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Parse an http(s) URL into an upstream. With `allow_path`, also returns path and query
|
|
/// (for the forward-auth endpoint); otherwise any path other than `/` is rejected.
|
|
fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static str> {
|
|
if !raw.bytes().all(|c| c.is_ascii_graphic()) {
|
|
return Err(r::URL_ASCII);
|
|
}
|
|
let u = url::Url::parse(raw).map_err(|_| r::URL_NOT_URL)?;
|
|
let scheme = match u.scheme() {
|
|
"http" => Scheme::Http,
|
|
"https" => Scheme::Https,
|
|
_ => return Err(r::URL_SCHEME),
|
|
};
|
|
if !u.username().is_empty() || u.password().is_some() {
|
|
return Err(r::URL_CREDENTIALS);
|
|
}
|
|
if u.fragment().is_some() {
|
|
return Err(r::URL_FRAGMENT);
|
|
}
|
|
let host = match u.host() {
|
|
None => return Err(r::URL_NO_HOST),
|
|
Some(url::Host::Ipv4(ip)) => UpstreamHost::Ip(IpAddr::V4(ip)),
|
|
Some(url::Host::Ipv6(ip)) => UpstreamHost::Ip(IpAddr::V6(ip)),
|
|
Some(url::Host::Domain(d)) => {
|
|
if check_hostname(d).is_err() {
|
|
return Err(r::URL_HOST_NAME);
|
|
}
|
|
UpstreamHost::Name(d.to_owned())
|
|
}
|
|
};
|
|
let port = u.port_or_known_default().ok_or(r::URL_NO_PORT)?;
|
|
if port == 0 {
|
|
return Err(r::URL_PORT_ZERO);
|
|
}
|
|
let mut path = u.path().to_owned();
|
|
if !allow_path {
|
|
if path != "/" && !path.is_empty() {
|
|
return Err(r::URL_PATH);
|
|
}
|
|
if u.query().is_some() {
|
|
return Err(r::URL_QUERY);
|
|
}
|
|
} else {
|
|
if let Some(q) = u.query() {
|
|
path.push('?');
|
|
path.push_str(q);
|
|
}
|
|
if path.contains(['{', '}']) {
|
|
return Err(r::URL_BRACES);
|
|
}
|
|
}
|
|
Ok((Upstream { scheme, host, port }, path))
|
|
}
|
|
|
|
/// A URL as an error may show it: everything before the last `@` (after the scheme) is
|
|
/// replaced by `…`, so a user name or password, even one containing `/`, `?` or `#`, never
|
|
/// reaches a message, a log or the API. A URL with no `@` is shown as it is.
|
|
pub(crate) fn shown_url(raw: &str) -> String {
|
|
let (scheme, rest) = match raw.find("://") {
|
|
Some(i) => (&raw[..i + 3], &raw[i + 3..]),
|
|
None => ("", raw),
|
|
};
|
|
match rest.rfind('@') {
|
|
Some(at) => format!("{scheme}\u{2026}@{}", &rest[at + 1..]),
|
|
None => raw.to_owned(),
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod shown_tests {
|
|
use super::shown_url;
|
|
|
|
#[test]
|
|
fn userinfo_is_hidden() {
|
|
assert_eq!(
|
|
shown_url("http://user:hunter2@10.0.0.1:80/x"),
|
|
"http://\u{2026}@10.0.0.1:80/x"
|
|
);
|
|
assert_eq!(shown_url("user:hunter2@host:80"), "\u{2026}@host:80");
|
|
assert_eq!(shown_url("http://10.0.0.1:80"), "http://10.0.0.1:80");
|
|
assert_eq!(shown_url("http://h/a@b"), "http://\u{2026}@b");
|
|
assert_eq!(
|
|
shown_url("http://admin:hunter/2@10.0.0.1:80"),
|
|
"http://\u{2026}@10.0.0.1:80"
|
|
);
|
|
assert_eq!(
|
|
shown_url("http://admin:hunter?2@10.0.0.1:80"),
|
|
"http://\u{2026}@10.0.0.1:80"
|
|
);
|
|
assert_eq!(
|
|
shown_url("http://admin:hunter#2@10.0.0.1:80"),
|
|
"http://\u{2026}@10.0.0.1:80"
|
|
);
|
|
}
|
|
}
|