diff --git a/Cargo.lock b/Cargo.lock index be5f6ae..57d267c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1010,6 +1010,8 @@ version = "0.1.0" name = "ianitor-core" version = "0.1.0" dependencies = [ + "base64 0.22.1", + "ring", "serde", "serde_json", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 2259be2..f9d8cc9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,8 @@ serde_json = "1.0.145" toml = "1.2.1" thiserror = "2.0.17" url = "2.5.7" +ring = "0.17.14" +base64 = "0.22.1" tokio = { version = "1.48", features = ["full"] } bytes = "1.10" http = "1.3" diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 51de11d..93c7462 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -13,6 +13,8 @@ serde_json.workspace = true toml.workspace = true thiserror.workspace = true url.workspace = true +ring.workspace = true +base64.workspace = true [lints] workspace = true diff --git a/crates/core/src/compile/edge.rs b/crates/core/src/compile/edge.rs index e6d7e13..65a80c3 100644 --- a/crates/core/src/compile/edge.rs +++ b/crates/core/src/compile/edge.rs @@ -54,6 +54,7 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig { interval_secs: hc.interval_secs, }), access_log: h.access_log == AccessLog::Truncated, + share_links: h.share_links, }) .collect(), } diff --git a/crates/core/src/edge_config.rs b/crates/core/src/edge_config.rs index a50d8c9..fdece67 100644 --- a/crates/core/src/edge_config.rs +++ b/crates/core/src/edge_config.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; /// Bumped on any incompatible change; edge refuses other versions. -pub const EDGE_CONFIG_VERSION: u32 = 1; +pub const EDGE_CONFIG_VERSION: u32 = 2; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -103,4 +103,7 @@ pub struct EdgeHost { pub response_headers: Vec, pub health_check: Option, pub access_log: bool, + /// Share-link tokens (see `ianitor_core::share`) let visitors in on this host without + /// forward-auth. Checked against the key credential and the revocation file. + pub share_links: bool, } diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index ed088dd..e3560c4 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -2,11 +2,67 @@ // 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, -//! so the UI can show it as is. +//! 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_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/.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 { @@ -26,8 +82,10 @@ pub enum ValidationError { DuplicateFile { file: String }, #[error("{file} is larger than {max} bytes")] FileTooLarge { file: String, max: usize }, - #[error("{file} must be named after its hostname: {hostname}.toml")] + #[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}")] @@ -49,36 +107,64 @@ pub enum ValidationError { file: String, url: String, reason: &'static str, + /// Position in `upstreams`; `None` when the problem is about the list as a whole. + index: Option, }, #[error("{file}: upstream `{url}` is listed twice")] - DuplicateUpstream { file: String, url: String }, + 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 }, + 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 }, + 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 }, + 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 }, + 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 }, + 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 }, @@ -97,6 +183,68 @@ fn line_suffix(line: Option) -> String { } } +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::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 { + // Tests first: not written yet. + "unknown" + } + + /// 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 { + // Tests first: not written yet. + 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. + let mut p = BTreeMap::new(); + p.insert("file", self.file().to_owned()); + 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); @@ -109,6 +257,11 @@ impl ValidationErrors { pub fn into_errors(self) -> Vec { self.0 } + + /// Wrap errors found outside [`crate::load`] (e.g. by [`crate::routes::check_path`]). + pub fn from_errors(errors: Vec) -> ValidationErrors { + ValidationErrors(errors) + } } impl fmt::Display for ValidationErrors { diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index eda6c33..01d47c5 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -12,12 +12,14 @@ pub mod compile; pub mod edge_config; mod error; mod model; +pub mod routes; +pub mod share; 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, - SecretName, Site, TlsMode, Upstream, UpstreamHost, + MAX_FILE_BYTES, MAX_UPSTREAMS, SecretName, Site, TlsMode, Upstream, UpstreamHost, }; pub use validate::{SourceFile, load}; diff --git a/crates/core/src/routes.rs b/crates/core/src/routes.rs new file mode 100644 index 0000000..8bb863a --- /dev/null +++ b/crates/core/src/routes.rs @@ -0,0 +1,61 @@ +// 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/. + +//! The shape of the routes repository: exactly `ianitor.toml` and `hosts/.toml`, +//! regular files only. Anything else (other names, folders inside `hosts/`, symbolic links, +//! submodules, executables) is refused, so the repository can never hold something the +//! compilers do not read. + +use crate::error::{ValidationError, reason}; +use crate::validate::check_hostname; + +/// The site file at the root of the repository. +pub const SITE_FILE: &str = "ianitor.toml"; +/// The folder holding one file per host. +pub const HOSTS_DIR: &str = "hosts"; +/// Most host files one repository may hold. +pub const MAX_HOST_FILES: usize = 1000; + +/// What a tree entry is, as git reports it (`git ls-tree` modes). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EntryKind { + /// Mode 100644. + File, + /// Mode 100755. + Executable, + /// Mode 120000. + Symlink, + /// Mode 160000. + Submodule, +} + +/// A path the repository may hold. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RoutePath { + Site, + Host { hostname: String }, +} + +/// The path of the file for `hostname`. +pub fn host_path(hostname: &str) -> String { + format!("{HOSTS_DIR}/{hostname}.toml") +} + +/// Check one path of the repository tree (as listed recursively, `/`-separated). +pub fn check_path(path: &str, kind: EntryKind) -> Result { + // 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), + } +} + +/// Check a whole tree listing. +pub fn check_tree<'a>( + entries: impl IntoIterator, +) -> Result<(), Vec> { + let _ = entries.into_iter().count(); + Ok(()) +} diff --git a/crates/core/src/share.rs b/crates/core/src/share.rs new file mode 100644 index 0000000..884b961 --- /dev/null +++ b/crates/core/src/share.rs @@ -0,0 +1,370 @@ +// 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/. + +//! Share links: stateless tokens minted by control and checked by edge. +//! +//! A link token is `ish1.` + base64url(payload ‖ mac): +//! +//! ```text +//! payload = version (1) ‖ id (16) ‖ epoch (u32 BE) ‖ expires_at (u64 BE, Unix s) ‖ flags (1) ‖ path prefix +//! mac = HMAC-SHA256(key, "ianitor share link v1" 0 host 0 payload [0 HMAC-SHA256(key, "ianitor share password v1" 0 id password)]) +//! ``` +//! +//! - The host is not in the token but in the MAC, so a token for one host fails on another. +//! - With a password (flag bit 0), the MAC can only be checked by someone who has both the key +//! and the password: the token carries no password hash, so holding a link does not allow +//! guessing its password offline. Edge rate-limits guesses. +//! - The session cookie edge sets after a successful check is `iss1.` + base64url(payload ‖ +//! HMAC(key, "ianitor share session v1" 0 host 0 payload)): a different domain, so a link +//! token is never accepted as a cookie and a cookie never as a link (and a cookie for a +//! password link proves the password was given). +//! - Revocation: every token carries the epoch it was minted in; edge refuses tokens from an +//! older epoch ("stop all") and ids on the deny list ("stop this link"). +//! +//! [`path_within`] decides whether a raw request path lies under a link's prefix. It refuses +//! anything an upstream might read differently from a plain byte comparison. + +use std::collections::BTreeSet; +use std::fmt; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use ring::hmac; + +/// Name of the credential (`$CREDENTIALS_DIRECTORY/`) holding the share-link key, read by +/// both edge and control. +pub const KEY_CREDENTIAL: &str = "share-link-key"; +/// Shortest key accepted, in bytes. +pub const MIN_KEY_LEN: usize = 32; +/// Query parameter carrying a link token. Edge only takes values that start with +/// [`LINK_PREFIX`]; anything else is left to the upstream. +pub const QUERY_PARAM: &str = "share"; +/// Start of every link token. +pub const LINK_PREFIX: &str = "ish1."; +/// Start of every session cookie value. +pub const SESSION_PREFIX: &str = "iss1."; +/// Session cookie name (`__Secure-`: browsers only accept it with `Secure`). +pub const COOKIE_NAME: &str = "__Secure-ianitor-share"; +/// Path the password form posts to, on hosts with share links. +pub const PASSWORD_PATH: &str = "/.well-known/ianitor/share"; +/// Longest path prefix. +pub const MAX_PREFIX_LEN: usize = 256; +/// Password length limits, in characters. +pub const MIN_PASSWORD_CHARS: usize = 8; +pub const MAX_PASSWORD_CHARS: usize = 128; + +const VERSION: u8 = 1; +const FLAG_PASSWORD: u8 = 1; +const FIXED_LEN: usize = 1 + 16 + 4 + 8 + 1; +const MAC_LEN: usize = 32; +/// Longest token or cookie accepted before decoding. +const MAX_ENCODED_LEN: usize = 1024; + +/// A link id: 16 random bytes, written as 32 lowercase hex digits. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ShareId(pub [u8; 16]); + +impl ShareId { + pub fn to_hex(&self) -> String { + self.0.iter().map(|b| format!("{b:02x}")).collect() + } + + pub fn from_hex(s: &str) -> Option { + if s.len() != 32 + || !s + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + { + return None; + } + let mut out = [0u8; 16]; + for (i, o) in out.iter_mut().enumerate() { + *o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?; + } + Some(ShareId(out)) + } +} + +impl fmt::Display for ShareId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.to_hex()) + } +} + +/// The HMAC key. Never printed. +pub struct ShareKey(hmac::Key); + +impl fmt::Debug for ShareKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ShareKey()") + } +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ShareError { + #[error("the share-link key must be at least {MIN_KEY_LEN} bytes")] + KeyTooShort, + #[error("the path prefix is not usable: {0}")] + Prefix(&'static str), + #[error("the password must be {MIN_PASSWORD_CHARS} to {MAX_PASSWORD_CHARS} characters")] + Password, +} + +impl ShareKey { + pub fn new(bytes: &[u8]) -> Result { + if bytes.len() < MIN_KEY_LEN { + return Err(ShareError::KeyTooShort); + } + Ok(ShareKey(hmac::Key::new(hmac::HMAC_SHA256, bytes))) + } +} + +/// What a token says. For a token checked with [`verify_link`] or [`verify_session`], all of +/// it is proven by the MAC; from [`peek`], none of it is. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Claims { + pub id: ShareId, + pub epoch: u32, + pub expires_at: u64, + pub password: bool, + pub prefix: String, +} + +/// What to mint. +#[derive(Debug, Clone)] +pub struct LinkSpec<'a> { + pub id: ShareId, + pub epoch: u32, + pub expires_at: u64, + /// Already checked with [`check_prefix`]. + pub prefix: &'a str, + pub password: Option<&'a str>, +} + +/// Why a token was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Rejection { + /// Not a token at all (bad encoding, wrong version, too long). + Malformed, + /// The MAC does not match: altered, minted for another host, made with another key, or + /// (for a password link) the wrong password. + Invalid, + /// The link needs a password and none was given. + PasswordRequired, + /// Proven genuine, but past its expiry. + Expired { expires_at: u64 }, + /// Proven genuine, but stopped (deny list or an older epoch). + Revoked, +} + +/// The revocation state edge checks against (from the deny-list file control writes). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Revocations { + /// Tokens minted in an older epoch are refused ("stop all"). + pub epoch: u32, + /// Stopped links. + pub deny: BTreeSet, +} + +impl Revocations { + pub fn is_revoked(&self, c: &Claims) -> bool { + c.epoch < self.epoch || self.deny.contains(&c.id) + } +} + +fn payload(spec: &LinkSpec<'_>) -> Vec { + let mut p = Vec::with_capacity(FIXED_LEN + spec.prefix.len()); + p.push(VERSION); + p.extend_from_slice(&spec.id.0); + p.extend_from_slice(&spec.epoch.to_be_bytes()); + p.extend_from_slice(&spec.expires_at.to_be_bytes()); + p.push(if spec.password.is_some() { + FLAG_PASSWORD + } else { + 0 + }); + p.extend_from_slice(spec.prefix.as_bytes()); + p +} + +fn password_tag(key: &ShareKey, id: &ShareId, password: &str) -> hmac::Tag { + let mut ctx = hmac::Context::with_key(&key.0); + ctx.update(b"ianitor share password v1\0"); + ctx.update(&id.0); + ctx.update(password.as_bytes()); + ctx.sign() +} + +fn link_message( + key: &ShareKey, + host: &str, + payload: &[u8], + id: &ShareId, + password: Option<&str>, +) -> Vec { + let mut m = Vec::with_capacity(64 + host.len() + payload.len()); + m.extend_from_slice(b"ianitor share link v1\0"); + m.extend_from_slice(host.as_bytes()); + m.push(0); + m.extend_from_slice(payload); + if let Some(pw) = password { + m.push(0); + m.extend_from_slice(password_tag(key, id, pw).as_ref()); + } + m +} + +fn session_message(host: &str, payload: &[u8]) -> Vec { + let mut m = Vec::with_capacity(64 + host.len() + payload.len()); + m.extend_from_slice(b"ianitor share session v1\0"); + m.extend_from_slice(host.as_bytes()); + m.push(0); + m.extend_from_slice(payload); + m +} + +fn check_password(pw: &str) -> Result<(), ShareError> { + let n = pw.chars().count(); + if (MIN_PASSWORD_CHARS..=MAX_PASSWORD_CHARS).contains(&n) { + Ok(()) + } else { + Err(ShareError::Password) + } +} + +/// Mint a link token for `host` (a validated hostname). +pub fn mint(key: &ShareKey, host: &str, spec: &LinkSpec<'_>) -> Result { + let prefix = check_prefix(spec.prefix).map_err(ShareError::Prefix)?; + if prefix != spec.prefix { + return Err(ShareError::Prefix("it is not in its normal form")); + } + if let Some(pw) = spec.password { + check_password(pw)?; + } + let p = payload(spec); + let tag = hmac::sign( + &key.0, + &link_message(key, host, &p, &spec.id, spec.password), + ); + let mut raw = p; + raw.extend_from_slice(tag.as_ref()); + Ok(format!("{LINK_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw))) +} + +/// Split and decode without checking the MAC. Only for showing a password page. +fn decode(token: &str, prefix: &str) -> Result<(Claims, Vec, Vec), Rejection> { + if token.len() > MAX_ENCODED_LEN { + return Err(Rejection::Malformed); + } + let body = token.strip_prefix(prefix).ok_or(Rejection::Malformed)?; + let raw = URL_SAFE_NO_PAD + .decode(body) + .map_err(|_| Rejection::Malformed)?; + if raw.len() < FIXED_LEN + MAC_LEN + 1 { + return Err(Rejection::Malformed); + } + let (p, mac) = raw.split_at(raw.len() - MAC_LEN); + if p[0] != VERSION || p[FIXED_LEN - 1] & !FLAG_PASSWORD != 0 { + return Err(Rejection::Malformed); + } + let mut id = [0u8; 16]; + id.copy_from_slice(&p[1..17]); + let mut e = [0u8; 4]; + e.copy_from_slice(&p[17..21]); + let mut x = [0u8; 8]; + 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. + Ok(( + Claims { + id: ShareId(id), + epoch: u32::from_be_bytes(e), + expires_at: u64::from_be_bytes(x), + password: p[FIXED_LEN - 1] & FLAG_PASSWORD != 0, + prefix: prefix.to_owned(), + }, + p.to_vec(), + mac.to_vec(), + )) +} + +/// What a link token claims, unchecked (for the password page: is a password needed, and +/// until when does it claim to work). Never grant anything on this alone. +pub fn peek(token: &str) -> Result { + decode(token, LINK_PREFIX).map(|(c, _, _)| c) +} + +/// Check a link token for `host`. The order of checks fixes what a visitor learns: a password +/// is asked for before anything else is proven; expiry and revocation are reported only for +/// tokens proven genuine. +pub fn verify_link( + key: &ShareKey, + host: &str, + token: &str, + password: Option<&str>, + now: u64, + revocations: &Revocations, +) -> Result { + let _ = (key, host, password, now, revocations); + peek(token) +} + +fn finish(claims: Claims, now: u64, revocations: &Revocations) -> Result { + if now >= claims.expires_at { + return Err(Rejection::Expired { + expires_at: claims.expires_at, + }); + } + if revocations.is_revoked(&claims) { + return Err(Rejection::Revoked); + } + Ok(claims) +} + +/// The session cookie value for claims proven by [`verify_link`]. +pub fn session_value(key: &ShareKey, host: &str, claims: &Claims) -> String { + let spec = LinkSpec { + id: claims.id, + epoch: claims.epoch, + expires_at: claims.expires_at, + prefix: &claims.prefix, + password: claims.password.then_some(""), + }; + let p = payload(&spec); + let tag = hmac::sign(&key.0, &session_message(host, &p)); + let mut raw = p; + raw.extend_from_slice(tag.as_ref()); + format!("{SESSION_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw)) +} + +/// Check a session cookie value for `host`. +pub fn verify_session( + key: &ShareKey, + host: &str, + value: &str, + now: u64, + revocations: &Revocations, +) -> Result { + let _ = (key, host, now, revocations); + decode(value, SESSION_PREFIX).map(|(c, _, _)| c) +} + +/// 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 { + // Tests first: not written yet. + Ok(prefix.to_owned()) +} + +/// Is `raw_path` (the request path exactly as sent, still percent-encoded) under `prefix`? +/// +/// Refused outright, whatever the prefix: anything but visible ASCII, a backslash, an empty +/// segment (`//`), a dot segment (`.`, `..`, also with `;params`), and the percent-encoded +/// 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) +} diff --git a/crates/core/src/validate.rs b/crates/core/src/validate.rs index f86c154..0158415 100644 --- a/crates/core/src/validate.rs +++ b/crates/core/src/validate.rs @@ -11,7 +11,7 @@ use std::net::IpAddr; use serde::Deserialize; use serde::de::DeserializeOwned; -use crate::error::{ValidationError as E, ValidationErrors}; +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, @@ -274,11 +274,13 @@ fn check_site(file: &str, raw: RawSite, errors: &mut Vec) -> Option { 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")); @@ -397,7 +399,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec } let mut upstreams: Vec = Vec::new(); let mut seen_upstreams = BTreeSet::new(); - for u in raw.upstreams.iter().take(MAX_UPSTREAMS) { + for (index, u) in raw.upstreams.iter().take(MAX_UPSTREAMS).enumerate() { match parse_url(u, false) { Ok((up, _)) => { if seen_upstreams.insert(up.clone()) { @@ -406,6 +408,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec errors.push(E::DuplicateUpstream { file: f(), url: u.clone(), + index, }); } } @@ -413,6 +416,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec file: f(), url: u.clone(), reason, + index: Some(index), }), } } @@ -421,7 +425,8 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec errors.push(E::BadUpstreamUrl { file: f(), url: raw.upstreams.join(", "), - reason: "all upstreams of a host must use the same scheme", + reason: r::URL_MIXED, + index: None, }); } @@ -450,8 +455,22 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec } AuthMode::None => Vec::new(), }; - let request_headers = check_rules(file, raw.request_headers, true, &identity, site, errors); - let response_headers = check_rules(file, raw.response_headers, false, &[], site, errors); + 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 }; @@ -463,7 +482,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec .all(|c| c.is_ascii_graphic() && !b"{}#".contains(&c)); if !ok_path { errors.push(bad( - "path must start with '/' and contain only visible ASCII without '{', '}' or '#'", + r::HEALTH_PATH, )); return None; } @@ -473,7 +492,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec interval_secs: i, }), _ => { - errors.push(bad("interval_secs must be between 1 and 3600")); + errors.push(bad(r::HEALTH_INTERVAL)); None } } @@ -527,45 +546,63 @@ fn is_protected(name: &str) -> bool { fn check_rules( file: &str, + list: &str, raw: Vec, - request: bool, identity: &[String], site: Option<&Site>, errors: &mut Vec, ) -> Vec { + let request = list == "request_headers"; let f = || file.to_owned(); let mut out = Vec::new(); let mut seen = BTreeSet::new(); - for r in raw { + 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 }); + errors.push(E::ProtectedHeader { + file: f(), + header, + field: at("name"), + }); continue; } if !seen.insert(lower) { - errors.push(E::DuplicateHeaderRule { file: f(), header }); + 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("remove takes no value or secret")), + (RawAction::Remove, _, _) => errors.push(bad(r::RULE_REMOVE_VALUE)), (RawAction::Set, Some(_), Some(_)) => { - errors.push(bad("give either value or secret, not both")) + errors.push(bad(r::RULE_BOTH)) } - (RawAction::Set, None, None) => errors.push(bad("set needs a value or a secret")), + (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, @@ -575,15 +612,21 @@ fn check_rules( file: f(), header, reason, + field: at("value"), }), }, (RawAction::Set, None, Some(s)) => { if !request { - errors.push(E::SecretInResponseHeader { file: f(), header }); + 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 { @@ -608,19 +651,19 @@ fn valid_header_name(n: &str) -> bool { fn check_header_value(v: &str) -> Result<(), &'static str> { if v.is_empty() { - return Err("an empty value is not allowed; use action = \"remove\""); + return Err(r::VALUE_EMPTY); } if v.len() > 4096 { - return Err("it is longer than 4096 characters"); + return Err(r::VALUE_LONG); } if !v.bytes().all(|c| (0x20..0x7f).contains(&c)) { - return Err("only visible ASCII characters and spaces are allowed"); + return Err(r::VALUE_ASCII); } if v.contains(['{', '}']) { - return Err("'{' and '}' are not allowed (they are placeholders in Caddy)"); + return Err(r::VALUE_BRACES); } if v.starts_with(' ') || v.ends_with(' ') { - return Err("it must not start or end with a space"); + return Err(r::VALUE_EDGE_SPACE); } Ok(()) } @@ -629,44 +672,47 @@ fn check_header_value(v: &str) -> Result<(), &'static str> { pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> { if h.is_empty() { - return Err("it is empty"); + return Err(r::HOST_EMPTY); } if h.len() > 253 { - return Err("it is longer than 253 characters"); + return Err(r::HOST_TOO_LONG); } if h.parse::().is_ok() || h.starts_with('[') { - return Err("IP addresses are not hostnames"); + return Err(r::HOST_IP); } if h.contains('*') { - return Err("wildcards are not supported"); + return Err(r::HOST_WILDCARD); + } + if h.contains(char::is_whitespace) { + return Err(r::HOST_SPACES); } if h.ends_with('.') { - return Err("it must not end with a dot"); + return Err(r::HOST_TRAILING_DOT); } if h.bytes().any(|c| c.is_ascii_uppercase()) { - return Err("it must be lowercase"); + return Err(r::HOST_UPPERCASE); } let mut last = ""; for label in h.split('.') { if label.is_empty() { - return Err("it has an empty label"); + return Err(r::HOST_EMPTY_LABEL); } if label.len() > 63 { - return Err("a label is longer than 63 characters"); + return Err(r::HOST_LABEL_LONG); } if !label .bytes() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-') { - return Err("only a-z, 0-9, '-' and '.' are allowed"); + return Err(r::HOST_CHARACTERS); } if label.starts_with('-') || label.ends_with('-') { - return Err("a label must not start or end with '-'"); + return Err(r::HOST_LABEL_DASH); } last = label; } if last.bytes().all(|c| c.is_ascii_digit()) { - return Err("the last label must not be numeric"); + return Err(r::HOST_NUMERIC); } Ok(()) } @@ -675,42 +721,42 @@ pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> { /// (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("it must be plain ASCII without spaces"); + return Err(r::URL_ASCII); } - let u = url::Url::parse(raw).map_err(|_| "it is not a URL like http://127.0.0.1:8080")?; + 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("only http:// and https:// are supported"), + _ => return Err(r::URL_SCHEME), }; if !u.username().is_empty() || u.password().is_some() { - return Err("credentials in the URL are not allowed"); + return Err(r::URL_CREDENTIALS); } if u.fragment().is_some() { - return Err("a #fragment is not allowed"); + return Err(r::URL_FRAGMENT); } let host = match u.host() { - None => return Err("it has no 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("the host name is not valid"); + return Err(r::URL_HOST_NAME); } UpstreamHost::Name(d.to_owned()) } }; - let port = u.port_or_known_default().ok_or("it has no port")?; + let port = u.port_or_known_default().ok_or(r::URL_NO_PORT)?; if port == 0 { - return Err("port 0 is not usable"); + return Err(r::URL_PORT_ZERO); } let mut path = u.path().to_owned(); if !allow_path { if path != "/" && !path.is_empty() { - return Err("a path is not allowed; requests keep their own path"); + return Err(r::URL_PATH); } if u.query().is_some() { - return Err("a ?query is not allowed"); + return Err(r::URL_QUERY); } } else { if let Some(q) = u.query() { @@ -718,7 +764,7 @@ fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static path.push_str(q); } if path.contains(['{', '}']) { - return Err("'{' and '}' are not allowed"); + return Err(r::URL_BRACES); } } Ok((Upstream { scheme, host, port }, path)) diff --git a/crates/core/tests/routes.rs b/crates/core/tests/routes.rs new file mode 100644 index 0000000..f288343 --- /dev/null +++ b/crates/core/tests/routes.rs @@ -0,0 +1,233 @@ +// 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/. + +//! The routes repository holds exactly `ianitor.toml` and `hosts/.toml`, and the +//! loader requires the exact path (ROADMAP §10: the check used to look at the base name only). +//! Validation errors carry a stable code, a field path and params for the UI (docs/ui-api.md §3.1). + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use ianitor_core::routes::{EntryKind, RoutePath, check_path, check_tree}; +use ianitor_core::{SourceFile, ValidationError, load}; + +#[test] +fn only_the_site_file_and_host_files_are_allowed() { + assert_eq!( + check_path("ianitor.toml", EntryKind::File).unwrap(), + RoutePath::Site + ); + assert_eq!( + check_path("hosts/wiki.home.test.toml", EntryKind::File).unwrap(), + RoutePath::Host { + hostname: "wiki.home.test".into() + } + ); + for bad in [ + "README.md", + ".gitattributes", + "hosts.toml", + "other/wiki.home.test.toml", + "hosts/sub/wiki.home.test.toml", + "hosts/wiki.home.test.toml/x", + "hosts/Wiki.home.test.toml", + "hosts/wiki.home.test.TOML", + "hosts/wiki.home.test", + "hosts/.toml", + "hosts/*.home.test.toml", + "hosts/wiki..test.toml", + "hosts/10.0.0.1.toml", + "hosts/wiki home.toml", + "hosts\\wiki.home.test.toml", + "hosts/wiki\\x.toml", + "IANITOR.toml", + "./ianitor.toml", + ] { + let e = check_path(bad, EntryKind::File).unwrap_err(); + assert!( + matches!(e, ValidationError::UnexpectedFile { ref file, .. } if file == bad), + "{bad}: {e:?}" + ); + assert_eq!(e.code(), "repo.unexpected_file"); + } +} + +#[test] +fn links_executables_and_submodules_are_refused() { + for kind in [ + EntryKind::Symlink, + EntryKind::Submodule, + EntryKind::Executable, + ] { + assert!(check_path("hosts/a.test.toml", kind).is_err(), "{kind:?}"); + assert!(check_path("ianitor.toml", kind).is_err(), "{kind:?}"); + } +} + +#[test] +fn a_tree_needs_the_site_file_and_reports_every_stray_file() { + let ok = [ + ("ianitor.toml", EntryKind::File), + ("hosts/a.test.toml", EntryKind::File), + ]; + assert!(check_tree(ok).is_ok()); + let errs = check_tree([ + ("hosts/a.test.toml", EntryKind::File), + ("notes.txt", EntryKind::File), + ("hosts/b/c.toml", EntryKind::File), + ]) + .unwrap_err(); + assert_eq!(errs.len(), 3, "{errs:?}"); +} + +#[test] +fn the_loader_requires_the_exact_path() { + let site = SourceFile { + name: "ianitor.toml", + contents: "", + }; + let body = "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n"; + for name in [ + "app.test.toml", + "other/app.test.toml", + "hosts/x/app.test.toml", + "hosts\\app.test.toml", + "./hosts/app.test.toml", + ] { + let errs = load( + &site, + &[SourceFile { + name, + contents: body, + }], + ) + .unwrap_err(); + assert!( + errs.errors() + .iter() + .any(|e| matches!(e, ValidationError::FileNameMismatch { .. })), + "{name}: {errs:?}" + ); + } + assert!( + load( + &site, + &[SourceFile { + name: "hosts/app.test.toml", + contents: body + }] + ) + .is_ok() + ); +} + +fn errors_for(body: &str) -> Vec { + let site = SourceFile { + name: "ianitor.toml", + contents: "secrets = [\"api_key\"]\n", + }; + load( + &site, + &[SourceFile { + name: "hosts/app.test.toml", + contents: body, + }], + ) + .unwrap_err() + .into_errors() +} + +#[test] +fn errors_have_codes_fields_and_params_for_the_ui() { + let cases: &[(&str, &str, Option<&str>)] = &[ + ( + "upstreams = [\"http://127.0.0.1:1\"]\n", + "host.hostname.missing", + Some("hostname"), + ), + ("hostname = \"app.test\"\n", "host.upstreams.missing", Some("upstreams")), + ( + "hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", + "host.hostname.uppercase", + Some("hostname"), + ), + ( + "hostname = \"app test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", + "host.hostname.spaces", + Some("hostname"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"ftp://x\"]\n", + "host.upstream.scheme", + Some("upstreams[1]"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1/x\"]\n", + "host.upstream.path", + Some("upstreams[0]"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"http://127.0.0.1:1\"]\n", + "host.upstream.duplicate", + Some("upstreams[1]"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"https://127.0.0.1:2\"]\n", + "host.upstream.mixed_schemes", + Some("upstreams"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\ncolour = 1\n", + "host.field.unknown", + Some("colour"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\n[[request_headers]]\naction = \"set\"\nname = \"Host\"\nvalue = \"x\"\n", + "host.header.protected", + Some("request_headers[1].name"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[response_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"api_key\"\n", + "host.header.secret_response", + Some("response_headers[0]"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"nope\"\n", + "host.header.secret_unknown", + Some("request_headers[0].secret"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[health_check]\npath = \"/x\"\ninterval_secs = 0\n", + "host.health.interval", + Some("health_check.interval_secs"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\nauth = \"forward-auth\"\n", + "host.auth.not_configured", + Some("auth"), + ), + ]; + for (body, code, field) in cases { + let errs = errors_for(body); + let e = errs + .iter() + .find(|e| e.code() == *code) + .unwrap_or_else(|| panic!("no {code} for {body:?}: {errs:?}")); + assert_eq!(e.field().as_deref(), *field, "{code}"); + assert_eq!(e.params()["file"], "hosts/app.test.toml"); + } +} + +#[test] +fn params_carry_suggestions() { + let errs = errors_for("hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n"); + let e = errs + .iter() + .find(|e| e.code() == "host.hostname.uppercase") + .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(); + assert_eq!(e.params()["suggestion"], "http://10.0.0.2:3000"); + assert_eq!(e.params()["url"], "http://10.0.0.2:3000/app"); +} diff --git a/crates/core/tests/schema.rs b/crates/core/tests/schema.rs index bcd4845..f1ecd49 100644 --- a/crates/core/tests/schema.rs +++ b/crates/core/tests/schema.rs @@ -148,11 +148,11 @@ value = "max-age=31536000" #[test] fn hosts_are_sorted_by_hostname_whatever_the_file_order() { let a = SourceFile { - name: "b.test.toml", + name: "hosts/b.test.toml", contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", }; let b = SourceFile { - name: "a.test.toml", + name: "hosts/a.test.toml", contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", }; let m1 = load(&site(), &[a, b]).unwrap(); @@ -175,7 +175,7 @@ fn empty_site_file_is_allowed() { contents: "", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -236,7 +236,7 @@ fn rejects_unknown_field_in_site_file() { contents: "secrets = []\nsecret_values = { a = \"b\" }\n", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -348,10 +348,11 @@ fn accepts_good_hostnames() { } #[test] -fn rejects_duplicate_hostnames_across_files() { - let r = load( - &site(), - &[ +fn a_second_file_for_the_same_host_is_refused_by_its_path() { + // With the exact `hosts/.toml` rule, two files can never hold one hostname: + // the second one is in the wrong place, whatever the file order. + for order in [false, true] { + let mut files = vec![ SourceFile { name: "hosts/app.test.toml", contents: MINIMAL, @@ -360,38 +361,19 @@ fn rejects_duplicate_hostnames_across_files() { name: "other/app.test.toml", contents: MINIMAL, }, - ], - ); - let errs = r.unwrap_err(); - assert_eq!( - errs.errors(), - [ValidationError::DuplicateHostname { - hostname: "app.test".into(), - first: "hosts/app.test.toml".into(), - second: "other/app.test.toml".into() - }] - ); -} - -#[test] -fn duplicate_detection_is_independent_of_file_order() { - let r = load( - &site(), - &[ - SourceFile { - name: "other/app.test.toml", - contents: MINIMAL, - }, - SourceFile { - name: "hosts/app.test.toml", - contents: MINIMAL, - }, - ], - ); - let errs = r.unwrap_err(); - assert!( - matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/app.test.toml" && second == "other/app.test.toml") - ); + ]; + if order { + files.reverse(); + } + let errs = load(&site(), &files).unwrap_err(); + assert_eq!( + errs.errors(), + [ValidationError::FileNameMismatch { + file: "other/app.test.toml".into(), + hostname: "app.test".into() + }] + ); + } } #[test] @@ -400,11 +382,11 @@ fn rejects_duplicate_source_file_names() { &site(), &[ SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }, SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }, ], @@ -485,7 +467,8 @@ fn rejects_undefined_secret_reference() { e, ValidationError::UndefinedSecret { file: "hosts/app.test.toml".into(), - secret: "nope".into() + secret: "nope".into(), + field: "request_headers[0].secret".into() } ); } @@ -498,7 +481,7 @@ fn undefined_secret_is_reported_when_site_declares_none() { contents: "", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: &format!( "{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-K\"\nsecret = \"api_key\"\n" ), @@ -532,7 +515,7 @@ fn rejects_bad_secret_names_in_site_file() { contents: &format!("secrets = [{bad:?}]\n"), }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -678,7 +661,7 @@ fn forward_auth_requires_site_configuration() { contents: "", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: &format!("{MINIMAL}auth = \"forward-auth\"\n"), }], ); @@ -704,7 +687,7 @@ fn rejects_bad_forward_auth_site_config() { contents: &format!("[forward_auth]\nurl = {bad:?}\n"), }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -743,15 +726,15 @@ fn collects_errors_from_every_file() { &site(), &[ SourceFile { - name: "a.test.toml", + name: "hosts/a.test.toml", contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n", }, SourceFile { - name: "B.test.toml", + name: "hosts/B.test.toml", contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", }, SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }, ], @@ -830,7 +813,7 @@ fn rejects_wildcards_in_copy_headers() { contents: "[forward_auth]\nurl = \"http://127.0.0.1:9091/x\"\ncopy_headers = [\"Remote-*\"]\n", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -861,7 +844,7 @@ fn rejects_oversized_route_files() { contents: &big, }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); diff --git a/crates/core/tests/share.rs b/crates/core/tests/share.rs new file mode 100644 index 0000000..f7f8146 --- /dev/null +++ b/crates/core/tests/share.rs @@ -0,0 +1,378 @@ +// 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/. + +//! Share-link tokens (ROADMAP §6 phase 2, tests first): a token is refused when expired, for +//! the wrong path, for the wrong host, tampered, without its password or with a wrong one, +//! and no path trick lets it escape its prefix. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::BTreeSet; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use ianitor_core::share::{ + Claims, LinkSpec, Rejection, Revocations, ShareId, ShareKey, check_prefix, mint, path_within, + peek, session_value, verify_link, verify_session, +}; + +const NOW: u64 = 1_800_000_000; +const HOST: &str = "photos.home.test"; + +fn key() -> ShareKey { + ShareKey::new(b"0123456789abcdef0123456789abcdef-test-key").unwrap() +} + +fn other_key() -> ShareKey { + ShareKey::new(b"fedcba9876543210fedcba9876543210-test-key").unwrap() +} + +fn id(n: u8) -> ShareId { + ShareId([n; 16]) +} + +fn spec<'a>(prefix: &'a str, password: Option<&'a str>) -> LinkSpec<'a> { + LinkSpec { + id: id(7), + epoch: 3, + expires_at: NOW + 3600, + prefix, + password, + } +} + +fn none() -> Revocations { + Revocations { + epoch: 3, + deny: BTreeSet::new(), + } +} + +fn token(prefix: &str, password: Option<&str>) -> String { + mint(&key(), HOST, &spec(prefix, password)).unwrap() +} + +#[test] +fn a_fresh_token_is_accepted_and_says_what_it_covers() { + let t = token("/albums/summer", None); + assert!(t.starts_with("ish1."), "{t}"); + let c = verify_link(&key(), HOST, &t, None, NOW, &none()).unwrap(); + assert_eq!( + c, + Claims { + id: id(7), + epoch: 3, + expires_at: NOW + 3600, + password: false, + prefix: "/albums/summer".into() + } + ); +} + +#[test] +fn an_expired_token_is_refused_as_expired() { + let t = token("/", None); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW + 3600, &none()), + Err(Rejection::Expired { + expires_at: NOW + 3600 + }) + ); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW + 99_999, &none()), + Err(Rejection::Expired { + expires_at: NOW + 3600 + }) + ); +} + +#[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"] { + assert_eq!( + verify_link(&key(), host, &t, None, NOW, &none()), + Err(Rejection::Invalid), + "{host}" + ); + } +} + +#[test] +fn a_token_made_with_another_key_is_refused() { + let t = mint(&other_key(), HOST, &spec("/", None)).unwrap(); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW, &none()), + Err(Rejection::Invalid) + ); +} + +#[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(); + for i in 0..raw.len() { + for bit in 0..8 { + let mut r = raw.clone(); + r[i] ^= 1 << bit; + let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&r)); + let got = verify_link(&key(), HOST, &forged, None, NOW, &none()); + assert!( + matches!( + got, + Err(Rejection::Invalid | Rejection::Malformed | Rejection::PasswordRequired) + ), + "byte {i} bit {bit}: {got:?}" + ); + } + } +} + +#[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 (payload, mac) = raw.split_at(raw.len() - 32); + // Same MAC, prefix cut down to "/albums". + let mut p = payload[..30].to_vec(); + p.extend_from_slice(b"/albums"); + p.extend_from_slice(mac); + let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&p)); + assert_eq!( + verify_link(&key(), HOST, &forged, None, NOW, &none()), + Err(Rejection::Invalid) + ); + // Same MAC, expiry pushed out. + let mut p = payload.to_vec(); + p[21..29].copy_from_slice(&(NOW + 10 * 3600).to_be_bytes()); + p.extend_from_slice(mac); + let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&p)); + assert_eq!( + verify_link(&key(), HOST, &forged, None, NOW, &none()), + Err(Rejection::Invalid) + ); +} + +#[test] +fn garbage_is_malformed_never_a_panic() { + for bad in [ + "", + "ish1.", + "ish1.!!!!", + "ish2.AAAA", + "iss1.AAAA", + "ish1.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + &"ish1.".repeat(400), + "ish1.\u{0}", + ] { + assert_eq!( + verify_link(&key(), HOST, bad, None, NOW, &none()), + Err(Rejection::Malformed), + "{bad:?}" + ); + } +} + +#[test] +fn a_password_link_needs_its_password() { + let t = token("/", Some("correct horse")); + assert!(peek(&t).unwrap().password); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW, &none()), + Err(Rejection::PasswordRequired) + ); + for wrong in ["", "correct hors", "correct horse ", "Correct horse", "x"] { + assert_eq!( + verify_link(&key(), HOST, &t, Some(wrong), NOW, &none()), + Err(Rejection::Invalid), + "{wrong:?}" + ); + } + let c = verify_link(&key(), HOST, &t, Some("correct horse"), NOW, &none()).unwrap(); + assert!(c.password); +} + +#[test] +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(); + 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..]); +} + +#[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(); + raw[29] = 0; + let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&raw)); + assert_eq!( + verify_link(&key(), HOST, &forged, None, NOW, &none()), + Err(Rejection::Invalid) + ); +} + +#[test] +fn passwords_are_8_to_128_characters() { + assert!(mint(&key(), HOST, &spec("/", Some("short"))).is_err()); + assert!(mint(&key(), HOST, &spec("/", Some(&"x".repeat(129)))).is_err()); + assert!(mint(&key(), HOST, &spec("/", Some("12345678"))).is_ok()); +} + +#[test] +fn stopped_links_and_older_epochs_are_revoked() { + let t = token("/", None); + let mut r = none(); + r.deny.insert(id(7)); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW, &r), + Err(Rejection::Revoked) + ); + let r = Revocations { + epoch: 4, + deny: BTreeSet::new(), + }; + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW, &r), + Err(Rejection::Revoked) + ); + // Another link on the deny list does not matter. + let mut r = none(); + r.deny.insert(id(8)); + assert!(verify_link(&key(), HOST, &t, None, NOW, &r).is_ok()); +} + +#[test] +fn session_cookies_and_link_tokens_are_not_interchangeable() { + let t = token("/albums", Some("correct horse")); + let c = verify_link(&key(), HOST, &t, Some("correct horse"), NOW, &none()).unwrap(); + let s = session_value(&key(), HOST, &c); + assert!(s.starts_with("iss1.")); + assert_eq!(verify_session(&key(), HOST, &s, NOW, &none()).unwrap(), c); + // A cookie is not a link, a link is not a cookie, even with the prefix swapped. + assert!(verify_link(&key(), HOST, &s, None, NOW, &none()).is_err()); + assert!(verify_session(&key(), HOST, &t, NOW, &none()).is_err()); + let swapped = s.replacen("iss1.", "ish1.", 1); + assert!(verify_link(&key(), HOST, &swapped, Some("correct horse"), NOW, &none()).is_err()); + let swapped = t.replacen("ish1.", "iss1.", 1); + assert!(verify_session(&key(), HOST, &swapped, NOW, &none()).is_err()); + // Cookies are host-bound, expire and are revoked like links. + assert_eq!( + verify_session(&key(), "other.home.test", &s, NOW, &none()), + Err(Rejection::Invalid) + ); + assert!(matches!( + verify_session(&key(), HOST, &s, NOW + 3600, &none()), + Err(Rejection::Expired { .. }) + )); + let mut r = none(); + r.deny.insert(id(7)); + assert_eq!( + verify_session(&key(), HOST, &s, NOW, &r), + Err(Rejection::Revoked) + ); +} + +#[test] +fn short_keys_are_refused() { + assert!(ShareKey::new(b"short").is_err()); + assert!(ShareKey::new(&[0u8; 31]).is_err()); + assert!(ShareKey::new(&[0u8; 32]).is_ok()); + assert!(!format!("{:?}", key()).contains("0123")); +} + +#[test] +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"); + for bad in [ + "", "a", "//", "/a//b", "/a/../b", "/..", "/.", "/a/./b", "/a%2fb", "/a\\b", "/a b", + "/a;b", "/ä", "/a?b", "/a#b", + ] { + assert!(check_prefix(bad).is_err(), "{bad:?} accepted"); + } + assert!(check_prefix(&format!("/{}", "a".repeat(256))).is_err()); + // A prefix that is not in normal form is not minted. + assert!(mint(&key(), HOST, &spec("/a/", None)).is_err()); +} + +#[test] +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)] { + assert_eq!(ShareId::from_hex(bad), None, "{bad:?}"); + } +} + +// ------------------------------------------------------------------ prefix escapes + +#[test] +fn paths_under_the_prefix_are_within() { + for (prefix, path) in [ + ("/a", "/a"), + ("/a", "/a/"), + ("/a", "/a/b"), + ("/a", "/a/b/c.jpg"), + ("/a", "/a/b%20c"), + ("/a", "/a/%E2%9C%93"), + ("/", "/"), + ("/", "/anything/at/all"), + ("/a/b", "/a/b/c"), + ("/a", "/a/b;v=1"), + ("/a", "/a/.well"), + ] { + assert!(path_within(prefix, path), "{prefix} should cover {path}"); + } +} + +#[test] +fn no_path_trick_escapes_the_prefix() { + let cases = [ + ("/a", "/ab"), + ("/a", "/abc/d"), + ("/a", "/A"), + ("/a", "/A/b"), + ("/a/b", "/a"), + ("/a/b", "/a/bc"), + ("/a", "/b"), + ("/a", "/a/../b"), + ("/a", "/a/.."), + ("/a", "/a/./../b"), + ("/a", "/a/%2e%2e/b"), + ("/a", "/a/%2E%2E/b"), + ("/a", "/a/.%2e/b"), + ("/a", "/a/%2e./b"), + ("/a", "/a/%252e%252e/b"), + ("/a", "/a/%25252e/b"), + ("/a", "/a%2f..%2fb"), + ("/a", "/a%2F..%2Fb"), + ("/a", "/a/..%2fb"), + ("/a", "/a//b"), + ("/a", "//a/b"), + ("/a", "/a\\..\\b"), + ("/a", "/a/..\\b"), + ("/a", "/a%5c..%5cb"), + ("/a", "/a/..;/b"), + ("/a", "/a/.;/b"), + ("/a", "/a/%00/b"), + ("/a", "/a/b c"), + ("/a", "/a/\tb"), + ("/a", "a/b"), + ("/a", ""), + ("/a", "/a/ä"), + ("/", "/../etc/passwd"), + ("/", "//evil"), + ("/", "/%2e%2e/x"), + ]; + for (prefix, path) in cases { + assert!(!path_within(prefix, path), "{prefix} must not cover {path:?}"); + } +}