use serde::{Deserialize, Serialize};
use crate::policy::PolicyError;
use crate::route::{MAX_ROUTES, METHOD_OVERRIDE_HEADERS, Partial, RequestPath, Route};
pub(crate) mod command;
pub(crate) mod hook;
pub const REQUESTS_RULE_PREFIX: &str = "requests.";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RequestEntry {
pub id: String,
pub host: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub allow: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub deny: Vec<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub hook_only: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Untrusted {
#[default]
Refuse,
Relay,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RequestCheck {
Unlisted,
Passed(String),
Refused(String),
}
#[derive(Debug, Clone, Default)]
pub struct RequestRules {
entries: Vec<Compiled>,
}
#[derive(Debug, Clone)]
struct Compiled {
id: String,
host: String,
deny: Vec<(String, Route)>,
allow: Vec<(String, Route)>,
}
impl RequestRules {
pub fn for_hook(entries: &[RequestEntry]) -> Result<Self, PolicyError> {
Self::compile(entries.iter())
}
pub fn for_proxy(entries: &[RequestEntry]) -> Result<Self, PolicyError> {
Self::compile(entries.iter().filter(|e| !e.hook_only))
}
fn compile<'a>(entries: impl Iterator<Item = &'a RequestEntry>) -> Result<Self, PolicyError> {
let mut out = Vec::new();
for entry in entries {
let fail = |problem: String| PolicyError::Rule {
rule: format!("{REQUESTS_RULE_PREFIX}{}", entry.id),
problem,
};
check_one(entry).map_err(fail)?;
let deny = entry
.deny
.iter()
.map(|text| Ok((text.clone(), Route::parse(&fold_rule(text))?)))
.collect::<Result<_, String>>()
.map_err(fail)?;
let allow = entry
.allow
.iter()
.map(|text| Ok((text.clone(), Route::parse(text)?)))
.collect::<Result<_, String>>()
.map_err(fail)?;
out.push(Compiled {
id: entry.id.clone(),
host: entry.host.clone(),
deny,
allow,
});
}
Ok(Self { entries: out })
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
#[must_use]
pub fn hosts(&self) -> Vec<String> {
let mut hosts: Vec<String> = self.entries.iter().map(|e| e.host.clone()).collect();
hosts.sort();
hosts.dedup();
hosts
}
#[must_use]
pub fn names(&self, host: &str) -> bool {
self.of(Some(host)).next().is_some()
}
fn of<'s>(&'s self, host: Option<&'s str>) -> impl Iterator<Item = &'s Compiled> + 's {
self.entries
.iter()
.filter(move |e| host.is_none_or(|h| e.host.eq_ignore_ascii_case(h)))
}
#[must_use]
pub fn check(
&self,
host: &str,
method: &str,
target: &str,
header_names: &[&str],
) -> RequestCheck {
if !self.names(host) {
return RequestCheck::Unlisted;
}
let refused =
|why: String| RequestCheck::Refused(format!("{method} request to {host} {why}"));
let (exact, folded) = match RequestPath::parse(target) {
Ok(exact) => {
let folded = exact.folded();
(exact, folded)
}
Err(why) => {
return refused(format!(
"is refused: {why}, so its request rules cannot tell what the server would read"
));
}
};
if let Some(name) = header_names.iter().find(|name| {
METHOD_OVERRIDE_HEADERS
.iter()
.any(|h| name.eq_ignore_ascii_case(h))
}) {
return refused(format!(
"is refused: its `{name}` header asks the server for another method"
));
}
if exact.overrides_method() {
return refused("is refused: its query names a `_method` parameter".to_owned());
}
let upper = method.to_ascii_uppercase();
let bare = without_trailing_slash(target)
.and_then(|t| RequestPath::parse(&t).ok())
.map(|p| p.folded());
for entry in self.of(Some(host)) {
if let Some((text, _)) = entry.deny.iter().find(|(_, r)| {
r.matches(&upper, &folded) || bare.as_ref().is_some_and(|b| r.matches(&upper, b))
}) {
return refused(format!(
"is refused by `deny: {text}` of request rules `{}`",
entry.id
));
}
}
let mut listing = self
.of(Some(host))
.filter(|e| !e.allow.is_empty())
.peekable();
if listing.peek().is_none() {
return RequestCheck::Passed(format!(
"no request rule for {host} refuses this {method} request"
));
}
let mut ids = Vec::new();
for entry in listing {
if let Some((text, _)) = entry.allow.iter().find(|(_, r)| r.matches(method, &exact)) {
return RequestCheck::Passed(format!(
"{method} request to {host} is named by `allow: {text}` of request rules `{}`",
entry.id
));
}
ids.push(format!("`{}`", entry.id));
}
refused(format!(
"is refused: it matches none of the `allow` rules of request rules {}",
ids.join(", ")
))
}
#[must_use]
pub(crate) fn could_refuse(
&self,
host: Option<&str>,
method: Option<&str>,
path: Option<&[Partial]>,
) -> Option<String> {
let upper = method.map(str::to_ascii_uppercase);
let folded: Option<Vec<Partial>> = path.map(|p| {
let mut folded: Vec<Partial> = p
.iter()
.map(|s| match s {
Partial::Known(k) => Partial::Known(k.to_ascii_lowercase()),
other => other.clone(),
})
.collect();
if folded.len() > 1 && folded.last() == Some(&Partial::Known(String::new())) {
folded.pop();
}
folded
});
for entry in self.of(host) {
if let Some((text, _)) = entry
.deny
.iter()
.find(|(_, r)| r.could_match(upper.as_deref(), folded.as_deref()))
{
return Some(format!(
"it may be a request `deny: {text}` of request rules `{}` refuses",
entry.id
));
}
if !entry.allow.is_empty() {
return Some(format!(
"request rules `{}` allow only the requests they list",
entry.id
));
}
}
None
}
}
fn without_trailing_slash(target: &str) -> Option<String> {
let (path, query) = target
.split_once('?')
.map_or((target, None), |(p, q)| (p, Some(q)));
let bare = path.strip_suffix('/').filter(|b| !b.is_empty())?;
Some(query.map_or_else(|| bare.to_owned(), |q| format!("{bare}?{q}")))
}
fn fold_rule(text: &str) -> String {
text.split_once(' ').map_or_else(
|| text.to_owned(),
|(m, p)| format!("{m} {}", p.to_ascii_lowercase()),
)
}
pub(crate) fn check(entries: &[RequestEntry]) -> Result<(), PolicyError> {
for (i, entry) in entries.iter().enumerate() {
if entries[..i].iter().any(|e| e.id == entry.id) {
return Err(PolicyError::DuplicateId(format!(
"{REQUESTS_RULE_PREFIX}{}",
entry.id
)));
}
}
RequestRules::for_hook(entries).map(drop)
}
fn check_one(entry: &RequestEntry) -> Result<(), String> {
let id = entry.id.rsplit(':').next().unwrap_or_default();
if id.is_empty()
|| id.len() > 64
|| !id
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
{
return Err("id must be 1 to 64 lowercase letters, digits or `-`".into());
}
if !is_dns_name(&entry.host) {
return Err(format!(
"host `{}` must be one lowercase DNS name, without address, port or pattern: \
the proxy's certificate authority is constrained to names",
entry.host
));
}
if entry.allow.is_empty() && entry.deny.is_empty() {
return Err("lists no `allow` or `deny` rule".into());
}
for (name, list) in [("allow", &entry.allow), ("deny", &entry.deny)] {
if list.len() > MAX_ROUTES {
return Err(format!("`{name}` lists more than {MAX_ROUTES} rules"));
}
}
Ok(())
}
fn is_dns_name(host: &str) -> bool {
host.len() <= crate::host::MAX_DNS_NAME_LEN
&& host.parse::<core::net::Ipv4Addr>().is_err()
&& !host.bytes().all(|b| b.is_ascii_digit() || b == b'.')
&& host.split('.').all(|label| {
!label.is_empty()
&& label.len() <= crate::host::MAX_DNS_LABEL_LEN
&& label
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
})
}
#[cfg(test)]
mod tests;