[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:
2026-11-07 17:32:44 +01:00
parent 73a9f3da45
commit 94ba18d38b
8 changed files with 348 additions and 48 deletions
+157 -5
View File
@@ -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
}
}
+2 -2
View File
@@ -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};
+52 -8
View File
@@ -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)
}
}
+76 -8
View File
@@ -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,
}
}
+9 -10
View File
@@ -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 {
+7 -4
View File
@@ -1,5 +1,5 @@
{
"version": 1,
"version": 2,
"http_listen": "0.0.0.0:80",
"https_listen": "0.0.0.0:443",
"https_port": 443,
@@ -82,7 +82,8 @@
"path": "/api/v1/status",
"interval_secs": 15
},
"access_log": true
"access_log": true,
"share_links": false
},
{
"hostname": "status.example.org",
@@ -101,7 +102,8 @@
"request_headers": [],
"response_headers": [],
"health_check": null,
"access_log": false
"access_log": false,
"share_links": false
},
{
"hostname": "wiki.home.test",
@@ -131,7 +133,8 @@
],
"response_headers": [],
"health_check": null,
"access_log": false
"access_log": false,
"share_links": false
}
]
}
+9 -2
View File
@@ -145,7 +145,11 @@ fn errors_have_codes_fields_and_params_for_the_ui() {
"host.hostname.missing",
Some("hostname"),
),
("hostname = \"app.test\"\n", "host.upstreams.missing", Some("upstreams")),
(
"hostname = \"app.test\"\n",
"host.upstreams.missing",
Some("upstreams"),
),
(
"hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n",
"host.hostname.uppercase",
@@ -227,7 +231,10 @@ fn params_carry_suggestions() {
.unwrap();
assert_eq!(e.params()["suggestion"], "app.test");
let errs = errors_for("hostname = \"app.test\"\nupstreams = [\"http://10.0.0.2:3000/app\"]\n");
let e = errs.iter().find(|e| e.code() == "host.upstream.path").unwrap();
let e = errs
.iter()
.find(|e| e.code() == "host.upstream.path")
.unwrap();
assert_eq!(e.params()["suggestion"], "http://10.0.0.2:3000");
assert_eq!(e.params()["url"], "http://10.0.0.2:3000/app");
}
+36 -9
View File
@@ -90,7 +90,12 @@ fn an_expired_token_is_refused_as_expired() {
#[test]
fn a_token_for_another_host_is_refused() {
let t = token("/", None);
for host in ["other.home.test", "PHOTOS.home.test", "photos.home.test.", "photos.home"] {
for host in [
"other.home.test",
"PHOTOS.home.test",
"photos.home.test.",
"photos.home",
] {
assert_eq!(
verify_link(&key(), host, &t, None, NOW, &none()),
Err(Rejection::Invalid),
@@ -111,7 +116,9 @@ fn a_token_made_with_another_key_is_refused() {
#[test]
fn every_single_bit_flip_is_refused() {
let t = token("/albums", None);
let raw = URL_SAFE_NO_PAD.decode(t.strip_prefix("ish1.").unwrap()).unwrap();
let raw = URL_SAFE_NO_PAD
.decode(t.strip_prefix("ish1.").unwrap())
.unwrap();
for i in 0..raw.len() {
for bit in 0..8 {
let mut r = raw.clone();
@@ -132,7 +139,9 @@ fn every_single_bit_flip_is_refused() {
#[test]
fn a_longer_expiry_or_wider_prefix_cannot_be_spliced_in() {
let t = token("/albums/summer", None);
let raw = URL_SAFE_NO_PAD.decode(t.strip_prefix("ish1.").unwrap()).unwrap();
let raw = URL_SAFE_NO_PAD
.decode(t.strip_prefix("ish1.").unwrap())
.unwrap();
let (payload, mac) = raw.split_at(raw.len() - 32);
// Same MAC, prefix cut down to "/albums".
let mut p = payload[..30].to_vec();
@@ -198,8 +207,12 @@ fn the_token_carries_no_password_hash() {
// Two links that differ only in the password have the same payload; only the MAC differs.
let a = token("/", Some("password-one"));
let b = token("/", Some("password-two"));
let ra = URL_SAFE_NO_PAD.decode(a.strip_prefix("ish1.").unwrap()).unwrap();
let rb = URL_SAFE_NO_PAD.decode(b.strip_prefix("ish1.").unwrap()).unwrap();
let ra = URL_SAFE_NO_PAD
.decode(a.strip_prefix("ish1.").unwrap())
.unwrap();
let rb = URL_SAFE_NO_PAD
.decode(b.strip_prefix("ish1.").unwrap())
.unwrap();
assert_eq!(ra.len(), rb.len());
assert_eq!(ra[..ra.len() - 32], rb[..rb.len() - 32]);
assert_ne!(ra[ra.len() - 32..], rb[rb.len() - 32..]);
@@ -208,7 +221,9 @@ fn the_token_carries_no_password_hash() {
#[test]
fn a_dropped_password_flag_does_not_open_the_link() {
let t = token("/", Some("correct horse"));
let mut raw = URL_SAFE_NO_PAD.decode(t.strip_prefix("ish1.").unwrap()).unwrap();
let mut raw = URL_SAFE_NO_PAD
.decode(t.strip_prefix("ish1.").unwrap())
.unwrap();
raw[29] = 0;
let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&raw));
assert_eq!(
@@ -290,7 +305,10 @@ fn short_keys_are_refused() {
fn prefixes_are_normalised_or_refused() {
assert_eq!(check_prefix("/").unwrap(), "/");
assert_eq!(check_prefix("/a/").unwrap(), "/a");
assert_eq!(check_prefix("/albums/summer-2026").unwrap(), "/albums/summer-2026");
assert_eq!(
check_prefix("/albums/summer-2026").unwrap(),
"/albums/summer-2026"
);
for bad in [
"", "a", "//", "/a//b", "/a/../b", "/..", "/.", "/a/./b", "/a%2fb", "/a\\b", "/a b",
"/a;b", "/ä", "/a?b", "/a#b",
@@ -307,7 +325,13 @@ fn ids_round_trip_as_hex() {
let i = ShareId([0xab; 16]);
assert_eq!(i.to_hex(), "ab".repeat(16));
assert_eq!(ShareId::from_hex(&i.to_hex()), Some(i));
for bad in ["", "ab", &"AB".repeat(16), &"zz".repeat(16), &"a".repeat(33)] {
for bad in [
"",
"ab",
&"AB".repeat(16),
&"zz".repeat(16),
&"a".repeat(33),
] {
assert_eq!(ShareId::from_hex(bad), None, "{bad:?}");
}
}
@@ -373,6 +397,9 @@ fn no_path_trick_escapes_the_prefix() {
("/", "/%2e%2e/x"),
];
for (prefix, path) in cases {
assert!(!path_within(prefix, path), "{prefix} must not cover {path:?}");
assert!(
!path_within(prefix, path),
"{prefix} must not cover {path:?}"
);
}
}