Skip to main content

openmoat_proxy/
requests.rs

1//! A host's request rules at the proxy (`requests:`, ADR-062). A host they
2//! name is terminated like the host of a `tls: terminate` secret (ADR-043),
3//! for a session that trusts the proxy's certificate authority, and each
4//! request read inside its tunnel, or sent to it as plain HTTP, is checked
5//! before anything goes upstream. The rules and their matching are the core's
6//! ([`openmoat_core::RequestRules`]), the same the hook holds.
7//!
8//! A connection to such a host that cannot be terminated (a session that did
9//! not receive the CA, a request without a session) is refused or relayed as
10//! [`Untrusted`] says.
11
12use openmoat_core::rule_id::REQUEST_RULE;
13use openmoat_core::{
14    Decision, RequestCheck, RequestEntry, RequestRules, RequestsUntrusted as Untrusted, Verdict,
15};
16
17/// The request rules of one proxy run. [`Requests::default`] holds none.
18#[derive(Debug, Default)]
19pub struct Requests {
20    entries: Vec<RequestEntry>,
21    rules: RequestRules,
22    untrusted: Untrusted,
23}
24
25/// A request rule that cannot be used.
26#[derive(Debug, thiserror::Error)]
27#[error("request rules: {0}")]
28pub struct RequestRuleError(String);
29
30impl Requests {
31    /// The proxy's half of `entries` (every entry not marked `hook_only`);
32    /// a connection it cannot terminate is handled as `untrusted` says.
33    pub fn new(entries: &[RequestEntry], untrusted: Untrusted) -> Result<Self, RequestRuleError> {
34        let entries: Vec<RequestEntry> = entries.iter().filter(|e| !e.hook_only).cloned().collect();
35        let rules =
36            RequestRules::for_proxy(&entries).map_err(|e| RequestRuleError(e.to_string()))?;
37        Ok(Self {
38            entries,
39            rules,
40            untrusted,
41        })
42    }
43
44    /// These rules, and `host` refusing every request one of `deny` names
45    /// (`METHOD /path`, as a secret's `allow` rules are written).
46    pub fn deny(self, host: &str, deny: &[&str]) -> Result<Self, RequestRuleError> {
47        let mut entries = self.entries;
48        entries.push(RequestEntry {
49            id: format!("rules-{}", entries.len() + 1),
50            host: host.to_owned(),
51            allow: Vec::new(),
52            deny: deny.iter().map(|d| (*d).to_owned()).collect(),
53            hook_only: false,
54        });
55        Self::new(&entries, self.untrusted)
56    }
57
58    /// The hosts these rules name, sorted, once each: what the CA must cover.
59    #[must_use = "the hosts are only listed"]
60    pub fn hosts(&self) -> Vec<String> {
61        self.rules.hosts()
62    }
63
64    /// Whether `host` has rules, so its tunnels are terminated.
65    pub(crate) fn names(&self, host: &str) -> bool {
66        self.rules.names(host)
67    }
68
69    /// What a connection to one of these hosts gets when it cannot be
70    /// terminated: `Ok` the note its allow row carries (relayed), `Err` the
71    /// refusal to record. `why` says why it cannot be terminated.
72    pub(crate) fn untrusted(&self, host: &str, why: &str) -> Result<String, Decision> {
73        match self.untrusted {
74            Untrusted::Relay => Ok(format!(
75                "{host} has request rules, but {why}, so the tunnel is relayed unread \
76                 (`requests_untrusted: relay`)"
77            )),
78            Untrusted::Refuse => Err(Decision::single(
79                Verdict::Deny,
80                REQUEST_RULE,
81                format!(
82                    "{host} has request rules, but {why}, so they cannot be held and the \
83                     connection is refused (`requests_untrusted: refuse`)"
84                ),
85            )),
86        }
87    }
88
89    /// Check `head` (the complete request head the proxy will send) to
90    /// `host`. `Ok` holds the reason for the audit row when `host` has rules;
91    /// `Err` the deny to record. The reasons name the method and the rule,
92    /// never the path, which may carry data.
93    pub(crate) fn check(&self, host: &str, head: &[u8]) -> Result<Option<String>, Decision> {
94        if !self.names(host) {
95            return Ok(None);
96        }
97        let refuse = |why: String| Decision::single(Verdict::Deny, REQUEST_RULE, why);
98        let mut headers = [httparse::EMPTY_HEADER; crate::request::MAX_HEADERS + 2];
99        let mut request = httparse::Request::new(&mut headers);
100        let (Ok(httparse::Status::Complete(_)), Some(method), Some(target)) =
101            (request.parse(head), request.method, request.path)
102        else {
103            return Err(refuse(format!(
104                "the request to {host} could not be read again to check its request rules"
105            )));
106        };
107        let names: Vec<&str> = request.headers.iter().map(|h| h.name).collect();
108        match self.rules.check(host, method, target, &names) {
109            RequestCheck::Refused(why) => Err(refuse(why)),
110            RequestCheck::Passed(why) => Ok(Some(why)),
111            _ => Ok(None),
112        }
113    }
114}
115
116#[cfg(test)]
117mod tests;