openmoat_proxy/
requests.rs1use openmoat_core::rule_id::PROXY_REQUEST_RULE;
18use openmoat_core::{Decision, METHOD_OVERRIDE_HEADERS, RequestPath, SecretRoute, Verdict};
19
20#[derive(Debug, Default)]
22pub struct Requests {
23 hosts: Vec<HostRules>,
24}
25
26#[derive(Debug)]
28struct HostRules {
29 host: String,
30 deny: Vec<(String, SecretRoute)>,
31}
32
33#[derive(Debug, thiserror::Error)]
35#[error("request rules for {host}: {why}")]
36pub struct RequestRuleError {
37 host: String,
38 why: String,
39}
40
41impl Requests {
42 pub fn deny(mut self, host: &str, deny: &[&str]) -> Result<Self, RequestRuleError> {
45 let fail = |why: String| RequestRuleError {
46 host: host.to_owned(),
47 why,
48 };
49 if host.is_empty() || host.contains(['*', ':', '/']) {
50 return Err(fail("the host must be one DNS name".to_owned()));
51 }
52 let mut rules = Vec::with_capacity(deny.len());
53 for text in deny {
54 let folded = text.split_once(' ').map_or_else(
56 || (*text).to_owned(),
57 |(m, p)| format!("{m} {}", p.to_ascii_lowercase()),
58 );
59 rules.push((
60 (*text).to_owned(),
61 SecretRoute::parse(&folded).map_err(fail)?,
62 ));
63 }
64 self.hosts.push(HostRules {
65 host: host.to_ascii_lowercase(),
66 deny: rules,
67 });
68 Ok(self)
69 }
70
71 #[must_use = "the hosts are only listed"]
73 pub fn hosts(&self) -> impl Iterator<Item = &str> {
74 self.hosts.iter().map(|h| h.host.as_str())
75 }
76
77 pub(crate) fn names(&self, host: &str) -> bool {
79 self.rules(host).is_some()
80 }
81
82 fn rules(&self, host: &str) -> Option<&HostRules> {
83 self.hosts
84 .iter()
85 .find(|h| h.host.eq_ignore_ascii_case(host))
86 }
87
88 pub(crate) fn check(&self, host: &str, head: &[u8]) -> Result<Option<String>, Decision> {
93 let Some(rules) = self.rules(host) else {
94 return Ok(None);
95 };
96 let refuse = |why: String| Decision::single(Verdict::Deny, PROXY_REQUEST_RULE, why);
97 let mut headers = [httparse::EMPTY_HEADER; crate::request::MAX_HEADERS + 2];
98 let mut request = httparse::Request::new(&mut headers);
99 let (Ok(httparse::Status::Complete(_)), Some(method), Some(target)) =
100 (request.parse(head), request.method, request.path)
101 else {
102 return Err(refuse(format!(
103 "the request to {host} could not be read again to check its request rules"
104 )));
105 };
106 let method = method.to_ascii_uppercase();
107 let path = RequestPath::parse(&target.to_ascii_lowercase()).map_err(|why| {
108 refuse(format!(
109 "{method} request to {host}: {why}, so the request rules cannot tell what the \
110 server would read"
111 ))
112 })?;
113 let overriding = request.headers.iter().find(|h| {
114 METHOD_OVERRIDE_HEADERS
115 .iter()
116 .any(|o| h.name.eq_ignore_ascii_case(o))
117 });
118 if let Some(header) = overriding {
119 return Err(refuse(format!(
120 "{method} request to {host}: its `{}` header asks the server for another method",
121 header.name
122 )));
123 }
124 if path.overrides_method() {
125 return Err(refuse(format!(
126 "{method} request to {host}: its query names a `_method` parameter"
127 )));
128 }
129 match rules
130 .deny
131 .iter()
132 .find(|(_, rule)| rule.matches(&method, &path))
133 {
134 Some((text, _)) => Err(refuse(format!(
135 "{method} request to {host} is refused by the request rule `deny: {text}` \
136 (ADR-062 proof of concept)"
137 ))),
138 None => Ok(Some(format!(
139 "no request rule for {host} refuses this {method} request"
140 ))),
141 }
142 }
143}
144
145#[cfg(test)]
146mod tests;