[core] Share links and repo layout: HMAC tokens with epoch, prefix check, exact hosts/<hostname>.toml, error codes; edge config v2
This commit is contained in:
+157
-5
@@ -224,23 +224,175 @@ impl ValidationError {
|
||||
|
||||
/// 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 {
|
||||
// Tests first: not written yet.
|
||||
"unknown"
|
||||
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",
|
||||
_ => "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::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> {
|
||||
// Tests first: not written yet.
|
||||
None
|
||||
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()),
|
||||
_ => 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> {
|
||||
// Tests first: not written yet.
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ mod validate;
|
||||
pub use error::{ValidationError, ValidationErrors};
|
||||
pub use model::{
|
||||
AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue,
|
||||
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, Model, Scheme,
|
||||
MAX_FILE_BYTES, MAX_UPSTREAMS, SecretName, Site, TlsMode, Upstream, UpstreamHost,
|
||||
HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, MAX_FILE_BYTES,
|
||||
MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost,
|
||||
};
|
||||
pub use validate::{SourceFile, load};
|
||||
|
||||
@@ -44,18 +44,62 @@ pub fn host_path(hostname: &str) -> String {
|
||||
|
||||
/// Check one path of the repository tree (as listed recursively, `/`-separated).
|
||||
pub fn check_path(path: &str, kind: EntryKind) -> Result<RoutePath, ValidationError> {
|
||||
// Tests first: not written yet.
|
||||
let _ = (kind, reason::PATH_LAYOUT, check_hostname);
|
||||
match path.strip_prefix("hosts/").and_then(|r| r.strip_suffix(".toml")) {
|
||||
Some(h) => Ok(RoutePath::Host { hostname: h.to_owned() }),
|
||||
None => Ok(RoutePath::Site),
|
||||
let bad = |reason| ValidationError::UnexpectedFile {
|
||||
file: path.to_owned(),
|
||||
reason,
|
||||
};
|
||||
if kind != EntryKind::File {
|
||||
return Err(bad(reason::PATH_KIND));
|
||||
}
|
||||
if path == SITE_FILE {
|
||||
return Ok(RoutePath::Site);
|
||||
}
|
||||
let Some(rest) = path.strip_prefix("hosts/") else {
|
||||
return Err(bad(reason::PATH_LAYOUT));
|
||||
};
|
||||
if rest.contains(['/', '\\']) {
|
||||
return Err(bad(reason::PATH_SUBDIR));
|
||||
}
|
||||
let Some(hostname) = rest.strip_suffix(".toml") else {
|
||||
return Err(bad(reason::PATH_NAME));
|
||||
};
|
||||
if check_hostname(hostname).is_err() {
|
||||
return Err(bad(reason::PATH_NAME));
|
||||
}
|
||||
Ok(RoutePath::Host {
|
||||
hostname: hostname.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Check a whole tree listing.
|
||||
/// Check a whole tree listing. Returns every problem; at most [`MAX_HOST_FILES`] host files.
|
||||
pub fn check_tree<'a>(
|
||||
entries: impl IntoIterator<Item = (&'a str, EntryKind)>,
|
||||
) -> Result<(), Vec<ValidationError>> {
|
||||
let _ = entries.into_iter().count();
|
||||
Ok(())
|
||||
let mut errors = Vec::new();
|
||||
let mut hosts = 0usize;
|
||||
let mut site = false;
|
||||
for (path, kind) in entries {
|
||||
match check_path(path, kind) {
|
||||
Ok(RoutePath::Site) => site = true,
|
||||
Ok(RoutePath::Host { .. }) => hosts += 1,
|
||||
Err(e) => errors.push(e),
|
||||
}
|
||||
}
|
||||
if !site {
|
||||
errors.push(ValidationError::MissingField {
|
||||
file: SITE_FILE.into(),
|
||||
field: "(the file itself)".into(),
|
||||
});
|
||||
}
|
||||
if hosts > MAX_HOST_FILES {
|
||||
errors.push(ValidationError::UnexpectedFile {
|
||||
file: HOSTS_DIR.into(),
|
||||
reason: "more than 1000 host files",
|
||||
});
|
||||
}
|
||||
if errors.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(errors)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,6 +276,9 @@ fn decode(token: &str, prefix: &str) -> Result<(Claims, Vec<u8>, Vec<u8>), Rejec
|
||||
x.copy_from_slice(&p[21..29]);
|
||||
let prefix = std::str::from_utf8(&p[FIXED_LEN..]).map_err(|_| Rejection::Malformed)?;
|
||||
// A token whose prefix is not in normal form was never minted.
|
||||
if check_prefix(prefix).ok().as_deref() != Some(prefix) {
|
||||
return Err(Rejection::Malformed);
|
||||
}
|
||||
Ok((
|
||||
Claims {
|
||||
id: ShareId(id),
|
||||
@@ -306,8 +309,15 @@ pub fn verify_link(
|
||||
now: u64,
|
||||
revocations: &Revocations,
|
||||
) -> Result<Claims, Rejection> {
|
||||
let _ = (key, host, password, now, revocations);
|
||||
peek(token)
|
||||
let (claims, p, mac) = decode(token, LINK_PREFIX)?;
|
||||
let password = match (claims.password, password) {
|
||||
(true, None) => return Err(Rejection::PasswordRequired),
|
||||
(true, Some(pw)) => Some(pw),
|
||||
(false, _) => None,
|
||||
};
|
||||
let msg = link_message(key, host, &p, &claims.id, password);
|
||||
hmac::verify(&key.0, &msg, &mac).map_err(|_| Rejection::Invalid)?;
|
||||
finish(claims, now, revocations)
|
||||
}
|
||||
|
||||
fn finish(claims: Claims, now: u64, revocations: &Revocations) -> Result<Claims, Rejection> {
|
||||
@@ -346,16 +356,45 @@ pub fn verify_session(
|
||||
now: u64,
|
||||
revocations: &Revocations,
|
||||
) -> Result<Claims, Rejection> {
|
||||
let _ = (key, host, now, revocations);
|
||||
decode(value, SESSION_PREFIX).map(|(c, _, _)| c)
|
||||
let (claims, p, mac) = decode(value, SESSION_PREFIX)?;
|
||||
hmac::verify(&key.0, &session_message(host, &p), &mac).map_err(|_| Rejection::Invalid)?;
|
||||
finish(claims, now, revocations)
|
||||
}
|
||||
|
||||
/// Normalise and check a path prefix: starts with `/`, at most [`MAX_PREFIX_LEN`] bytes, only
|
||||
/// unreserved characters and `!$&'()*+,=:@-._~`, no `%`, `;`, backslash, empty segment or dot
|
||||
/// segment. A trailing `/` is dropped (except for `/` itself).
|
||||
pub fn check_prefix(prefix: &str) -> Result<String, &'static str> {
|
||||
// Tests first: not written yet.
|
||||
Ok(prefix.to_owned())
|
||||
if !prefix.starts_with('/') {
|
||||
return Err("it must start with /");
|
||||
}
|
||||
if prefix.len() > MAX_PREFIX_LEN {
|
||||
return Err("it is longer than 256 characters");
|
||||
}
|
||||
let ok = |c: u8| c.is_ascii_alphanumeric() || b"/!$&'()*+,=:@-._~".contains(&c);
|
||||
if !prefix.bytes().all(ok) {
|
||||
return Err("only letters, digits, / and -._~!$&'()*+,=:@ are allowed");
|
||||
}
|
||||
if prefix.contains("//") {
|
||||
return Err("it has an empty segment (//)");
|
||||
}
|
||||
let trimmed = if prefix.len() > 1 {
|
||||
prefix.strip_suffix('/').unwrap_or(prefix)
|
||||
} else {
|
||||
prefix
|
||||
};
|
||||
if trimmed == "/" {
|
||||
return Ok("/".into());
|
||||
}
|
||||
for seg in trimmed[1..].split('/') {
|
||||
if seg.is_empty() {
|
||||
return Err("it has an empty segment (//)");
|
||||
}
|
||||
if seg.bytes().all(|c| c == b'.') {
|
||||
return Err("it has a . or .. segment");
|
||||
}
|
||||
}
|
||||
Ok(trimmed.to_owned())
|
||||
}
|
||||
|
||||
/// Is `raw_path` (the request path exactly as sent, still percent-encoded) under `prefix`?
|
||||
@@ -365,6 +404,35 @@ pub fn check_prefix(prefix: &str) -> Result<String, &'static str> {
|
||||
/// forms of `.`, `/`, `\`, `%` and NUL. Other paths match on whole segments, case-sensitively:
|
||||
/// prefix `/a` covers `/a` and `/a/x`, not `/ab` or `/A`.
|
||||
pub fn path_within(prefix: &str, raw_path: &str) -> bool {
|
||||
// Tests first: not written yet.
|
||||
raw_path.starts_with(prefix)
|
||||
if !raw_path.starts_with('/')
|
||||
|| !raw_path.bytes().all(|c| c.is_ascii_graphic())
|
||||
|| raw_path.contains('\\')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let lower = raw_path.to_ascii_lowercase();
|
||||
if ["%2e", "%2f", "%5c", "%25", "%00"]
|
||||
.iter()
|
||||
.any(|bad| lower.contains(bad))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// An empty segment anywhere but at the end (a trailing slash) is `//`.
|
||||
if raw_path.contains("//") {
|
||||
return false;
|
||||
}
|
||||
for seg in raw_path[1..].split('/') {
|
||||
// `..;x` is `..` to Tomcat and friends.
|
||||
let name = seg.split(';').next().unwrap_or(seg);
|
||||
if !name.is_empty() && name.bytes().all(|c| c == b'.') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if prefix == "/" {
|
||||
return true;
|
||||
}
|
||||
match raw_path.strip_prefix(prefix) {
|
||||
Some(rest) => rest.is_empty() || rest.starts_with('/'),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -377,9 +377,8 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
||||
reason,
|
||||
}),
|
||||
Ok(()) => {
|
||||
// One TOML per host, named after it: `hosts/<hostname>.toml`.
|
||||
let base = file.rsplit(['/', '\\']).next().unwrap_or(file);
|
||||
if base != format!("{}.toml", raw.hostname) {
|
||||
// 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(),
|
||||
@@ -481,9 +480,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec<E>
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_graphic() && !b"{}#".contains(&c));
|
||||
if !ok_path {
|
||||
errors.push(bad(
|
||||
r::HEALTH_PATH,
|
||||
));
|
||||
errors.push(bad(r::HEALTH_PATH));
|
||||
return None;
|
||||
}
|
||||
match u32::try_from(hc.interval_secs) {
|
||||
@@ -594,14 +591,16 @@ fn check_rules(
|
||||
file: f(),
|
||||
header: header.clone(),
|
||||
reason,
|
||||
field: at(if reason == r::RULE_NEITHER { "value" } else { "" }),
|
||||
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, 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 {
|
||||
|
||||
Reference in New Issue
Block a user