[core] Tests first: share tokens, prefix escapes, repo layout, exact host path, error codes (red)
This commit is contained in:
@@ -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(),
|
||||
}
|
||||
|
||||
@@ -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<EdgeHeaderOp>,
|
||||
pub health_check: Option<EdgeHealthCheck>,
|
||||
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,
|
||||
}
|
||||
|
||||
+162
-9
@@ -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/<hostname>.toml belong in the routes repository";
|
||||
pub const PATH_SUBDIR: &str = "folders inside hosts/ are not allowed";
|
||||
pub const PATH_NAME: &str = "the file name must be a lowercase hostname followed by .toml";
|
||||
pub const PATH_KIND: &str = "symbolic links, executables and submodules are not allowed";
|
||||
}
|
||||
|
||||
/// One problem found in the route files.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ValidationError {
|
||||
@@ -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<usize>,
|
||||
},
|
||||
#[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<usize>) -> 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<String> {
|
||||
// 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<ValidationError>);
|
||||
@@ -109,6 +257,11 @@ impl ValidationErrors {
|
||||
pub fn into_errors(self) -> Vec<ValidationError> {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Wrap errors found outside [`crate::load`] (e.g. by [`crate::routes::check_path`]).
|
||||
pub fn from_errors(errors: Vec<ValidationError>) -> ValidationErrors {
|
||||
ValidationErrors(errors)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ValidationErrors {
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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/<hostname>.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<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),
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a whole tree listing.
|
||||
pub fn check_tree<'a>(
|
||||
entries: impl IntoIterator<Item = (&'a str, EntryKind)>,
|
||||
) -> Result<(), Vec<ValidationError>> {
|
||||
let _ = entries.into_iter().count();
|
||||
Ok(())
|
||||
}
|
||||
@@ -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/<name>`) 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<ShareId> {
|
||||
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(<redacted>)")
|
||||
}
|
||||
}
|
||||
|
||||
#[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<ShareKey, ShareError> {
|
||||
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<ShareId>,
|
||||
}
|
||||
|
||||
impl Revocations {
|
||||
pub fn is_revoked(&self, c: &Claims) -> bool {
|
||||
c.epoch < self.epoch || self.deny.contains(&c.id)
|
||||
}
|
||||
}
|
||||
|
||||
fn payload(spec: &LinkSpec<'_>) -> Vec<u8> {
|
||||
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<u8> {
|
||||
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<u8> {
|
||||
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<String, ShareError> {
|
||||
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<u8>, Vec<u8>), 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<Claims, Rejection> {
|
||||
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<Claims, Rejection> {
|
||||
let _ = (key, host, password, now, revocations);
|
||||
peek(token)
|
||||
}
|
||||
|
||||
fn finish(claims: Claims, now: u64, revocations: &Revocations) -> Result<Claims, Rejection> {
|
||||
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<Claims, Rejection> {
|
||||
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<String, &'static str> {
|
||||
// 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)
|
||||
}
|
||||
+89
-43
@@ -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<E>) -> Option<Site> {
|
||||
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<E>
|
||||
}
|
||||
let mut upstreams: Vec<Upstream> = 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<E>
|
||||
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<E>
|
||||
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<E>
|
||||
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<E>
|
||||
}
|
||||
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<E>
|
||||
.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<E>
|
||||
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<RawRule>,
|
||||
request: bool,
|
||||
identity: &[String],
|
||||
site: Option<&Site>,
|
||||
errors: &mut Vec<E>,
|
||||
) -> Vec<HeaderRule> {
|
||||
let request = list == "request_headers";
|
||||
let f = || file.to_owned();
|
||||
let mut out = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
for 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::<IpAddr>().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))
|
||||
|
||||
Reference in New Issue
Block a user