1use serde::{Deserialize, Serialize};
25
26use crate::policy::PolicyError;
27use crate::route::{MAX_ROUTES, METHOD_OVERRIDE_HEADERS, Partial, RequestPath, Route};
28
29pub(crate) mod command;
30pub(crate) mod hook;
31
32pub const REQUESTS_RULE_PREFIX: &str = "requests.";
35
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(deny_unknown_fields)]
39pub struct RequestEntry {
40 pub id: String,
43 pub host: String,
46 #[serde(default, skip_serializing_if = "Vec::is_empty")]
49 pub allow: Vec<String>,
50 #[serde(default, skip_serializing_if = "Vec::is_empty")]
52 pub deny: Vec<String>,
53 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
56 pub hook_only: bool,
57}
58
59#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "lowercase")]
64pub enum Untrusted {
65 #[default]
67 Refuse,
68 Relay,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum RequestCheck {
76 Unlisted,
78 Passed(String),
80 Refused(String),
83}
84
85#[derive(Debug, Clone, Default)]
87pub struct RequestRules {
88 entries: Vec<Compiled>,
89}
90
91#[derive(Debug, Clone)]
92struct Compiled {
93 id: String,
94 host: String,
95 deny: Vec<(String, Route)>,
97 allow: Vec<(String, Route)>,
98}
99
100impl RequestRules {
101 pub fn for_hook(entries: &[RequestEntry]) -> Result<Self, PolicyError> {
103 Self::compile(entries.iter())
104 }
105
106 pub fn for_proxy(entries: &[RequestEntry]) -> Result<Self, PolicyError> {
108 Self::compile(entries.iter().filter(|e| !e.hook_only))
109 }
110
111 fn compile<'a>(entries: impl Iterator<Item = &'a RequestEntry>) -> Result<Self, PolicyError> {
112 let mut out = Vec::new();
113 for entry in entries {
114 let fail = |problem: String| PolicyError::Rule {
115 rule: format!("{REQUESTS_RULE_PREFIX}{}", entry.id),
116 problem,
117 };
118 check_one(entry).map_err(fail)?;
119 let deny = entry
120 .deny
121 .iter()
122 .map(|text| Ok((text.clone(), Route::parse(&fold_rule(text))?)))
123 .collect::<Result<_, String>>()
124 .map_err(fail)?;
125 let allow = entry
126 .allow
127 .iter()
128 .map(|text| Ok((text.clone(), Route::parse(text)?)))
129 .collect::<Result<_, String>>()
130 .map_err(fail)?;
131 out.push(Compiled {
132 id: entry.id.clone(),
133 host: entry.host.clone(),
134 deny,
135 allow,
136 });
137 }
138 Ok(Self { entries: out })
139 }
140
141 #[must_use]
143 pub fn is_empty(&self) -> bool {
144 self.entries.is_empty()
145 }
146
147 #[must_use]
149 pub fn hosts(&self) -> Vec<String> {
150 let mut hosts: Vec<String> = self.entries.iter().map(|e| e.host.clone()).collect();
151 hosts.sort();
152 hosts.dedup();
153 hosts
154 }
155
156 #[must_use]
158 pub fn names(&self, host: &str) -> bool {
159 self.of(Some(host)).next().is_some()
160 }
161
162 fn of<'s>(&'s self, host: Option<&'s str>) -> impl Iterator<Item = &'s Compiled> + 's {
164 self.entries
165 .iter()
166 .filter(move |e| host.is_none_or(|h| e.host.eq_ignore_ascii_case(h)))
167 }
168
169 #[must_use]
172 pub fn check(
173 &self,
174 host: &str,
175 method: &str,
176 target: &str,
177 header_names: &[&str],
178 ) -> RequestCheck {
179 if !self.names(host) {
180 return RequestCheck::Unlisted;
181 }
182 let refused =
183 |why: String| RequestCheck::Refused(format!("{method} request to {host} {why}"));
184 let (exact, folded) = match RequestPath::parse(target) {
187 Ok(exact) => {
188 let folded = exact.folded();
189 (exact, folded)
190 }
191 Err(why) => {
192 return refused(format!(
193 "is refused: {why}, so its request rules cannot tell what the server would read"
194 ));
195 }
196 };
197 if let Some(name) = header_names.iter().find(|name| {
198 METHOD_OVERRIDE_HEADERS
199 .iter()
200 .any(|h| name.eq_ignore_ascii_case(h))
201 }) {
202 return refused(format!(
203 "is refused: its `{name}` header asks the server for another method"
204 ));
205 }
206 if exact.overrides_method() {
207 return refused("is refused: its query names a `_method` parameter".to_owned());
208 }
209 let upper = method.to_ascii_uppercase();
210 let bare = without_trailing_slash(target)
212 .and_then(|t| RequestPath::parse(&t).ok())
213 .map(|p| p.folded());
214 for entry in self.of(Some(host)) {
215 if let Some((text, _)) = entry.deny.iter().find(|(_, r)| {
216 r.matches(&upper, &folded) || bare.as_ref().is_some_and(|b| r.matches(&upper, b))
217 }) {
218 return refused(format!(
219 "is refused by `deny: {text}` of request rules `{}`",
220 entry.id
221 ));
222 }
223 }
224 let mut listing = self
225 .of(Some(host))
226 .filter(|e| !e.allow.is_empty())
227 .peekable();
228 if listing.peek().is_none() {
229 return RequestCheck::Passed(format!(
230 "no request rule for {host} refuses this {method} request"
231 ));
232 }
233 let mut ids = Vec::new();
234 for entry in listing {
235 if let Some((text, _)) = entry.allow.iter().find(|(_, r)| r.matches(method, &exact)) {
236 return RequestCheck::Passed(format!(
237 "{method} request to {host} is named by `allow: {text}` of request rules `{}`",
238 entry.id
239 ));
240 }
241 ids.push(format!("`{}`", entry.id));
242 }
243 refused(format!(
244 "is refused: it matches none of the `allow` rules of request rules {}",
245 ids.join(", ")
246 ))
247 }
248
249 #[must_use]
254 pub(crate) fn could_refuse(
255 &self,
256 host: Option<&str>,
257 method: Option<&str>,
258 path: Option<&[Partial]>,
259 ) -> Option<String> {
260 let upper = method.map(str::to_ascii_uppercase);
261 let folded: Option<Vec<Partial>> = path.map(|p| {
262 let mut folded: Vec<Partial> = p
263 .iter()
264 .map(|s| match s {
265 Partial::Known(k) => Partial::Known(k.to_ascii_lowercase()),
266 other => other.clone(),
267 })
268 .collect();
269 if folded.len() > 1 && folded.last() == Some(&Partial::Known(String::new())) {
271 folded.pop();
272 }
273 folded
274 });
275 for entry in self.of(host) {
276 if let Some((text, _)) = entry
277 .deny
278 .iter()
279 .find(|(_, r)| r.could_match(upper.as_deref(), folded.as_deref()))
280 {
281 return Some(format!(
282 "it may be a request `deny: {text}` of request rules `{}` refuses",
283 entry.id
284 ));
285 }
286 if !entry.allow.is_empty() {
287 return Some(format!(
288 "request rules `{}` allow only the requests they list",
289 entry.id
290 ));
291 }
292 }
293 None
294 }
295}
296
297fn without_trailing_slash(target: &str) -> Option<String> {
299 let (path, query) = target
300 .split_once('?')
301 .map_or((target, None), |(p, q)| (p, Some(q)));
302 let bare = path.strip_suffix('/').filter(|b| !b.is_empty())?;
303 Some(query.map_or_else(|| bare.to_owned(), |q| format!("{bare}?{q}")))
304}
305
306fn fold_rule(text: &str) -> String {
309 text.split_once(' ').map_or_else(
310 || text.to_owned(),
311 |(m, p)| format!("{m} {}", p.to_ascii_lowercase()),
312 )
313}
314
315pub(crate) fn check(entries: &[RequestEntry]) -> Result<(), PolicyError> {
317 for (i, entry) in entries.iter().enumerate() {
318 if entries[..i].iter().any(|e| e.id == entry.id) {
319 return Err(PolicyError::DuplicateId(format!(
320 "{REQUESTS_RULE_PREFIX}{}",
321 entry.id
322 )));
323 }
324 }
325 RequestRules::for_hook(entries).map(drop)
326}
327
328fn check_one(entry: &RequestEntry) -> Result<(), String> {
329 let id = entry.id.rsplit(':').next().unwrap_or_default();
332 if id.is_empty()
333 || id.len() > 64
334 || !id
335 .bytes()
336 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
337 {
338 return Err("id must be 1 to 64 lowercase letters, digits or `-`".into());
339 }
340 if !is_dns_name(&entry.host) {
341 return Err(format!(
342 "host `{}` must be one lowercase DNS name, without address, port or pattern: \
343 the proxy's certificate authority is constrained to names",
344 entry.host
345 ));
346 }
347 if entry.allow.is_empty() && entry.deny.is_empty() {
348 return Err("lists no `allow` or `deny` rule".into());
349 }
350 for (name, list) in [("allow", &entry.allow), ("deny", &entry.deny)] {
351 if list.len() > MAX_ROUTES {
352 return Err(format!("`{name}` lists more than {MAX_ROUTES} rules"));
353 }
354 }
355 Ok(())
356}
357
358fn is_dns_name(host: &str) -> bool {
360 host.len() <= crate::host::MAX_DNS_NAME_LEN
361 && host.parse::<core::net::Ipv4Addr>().is_err()
362 && !host.bytes().all(|b| b.is_ascii_digit() || b == b'.')
363 && host.split('.').all(|label| {
364 !label.is_empty()
365 && label.len() <= crate::host::MAX_DNS_LABEL_LEN
366 && label
367 .bytes()
368 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
369 })
370}
371
372#[cfg(test)]
373mod tests;