Skip to main content

openmoat_proxy/
requests.rs

1//! Method and path rules for a host with no brokered secret (ADR-062, step 0:
2//! the proof of concept). A host listed here is terminated in `openmoat run`
3//! like the host of a `tls: terminate` secret (ADR-043), and each request read
4//! inside its tunnel is refused when a `deny` rule names it, before anything
5//! goes upstream; every other request passes unchanged.
6//!
7//! The rules are ADR-043's `METHOD /path` rules (`openmoat_core::SecretRoute`),
8//! matched the same way, with two differences that make a deny list err wide:
9//! the method and the path are compared in any letter case (a server may read
10//! `post` or `/Gists` as the route the rule names), and a request whose path
11//! the server could read as another, or that asks the server for another
12//! method, is refused instead of being matched.
13//!
14//! There is no policy schema for these rules yet: the CLI builds them from an
15//! unlisted setting of `openmoat run`, which ADR-062 step 0 measures.
16
17use openmoat_core::rule_id::PROXY_REQUEST_RULE;
18use openmoat_core::{Decision, METHOD_OVERRIDE_HEADERS, RequestPath, SecretRoute, Verdict};
19
20/// The request rules of one proxy run. [`Requests::default`] holds none.
21#[derive(Debug, Default)]
22pub struct Requests {
23    hosts: Vec<HostRules>,
24}
25
26/// One host's `deny` rules, each with the text it was written as.
27#[derive(Debug)]
28struct HostRules {
29    host: String,
30    deny: Vec<(String, SecretRoute)>,
31}
32
33/// A request rule that cannot be used.
34#[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    /// These rules, and `host` refused every request one of `deny` names
43    /// (`METHOD /path`, as a secret's `allow` rules are written).
44    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            // The method stays as written: `Route::parse` wants it in capitals.
55            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    /// The hosts these rules name, as the CA must cover them.
72    #[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    /// Whether `host` has rules, so its tunnels are terminated.
78    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    /// Check `head` (the complete request head the proxy will send) to
89    /// `host`. `Ok` holds the reason for the audit row when `host` has rules;
90    /// `Err` the deny to record. The reasons name the method and the rule,
91    /// never the path, which may carry data.
92    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;