openmoat_proxy/
requests.rs1use openmoat_core::rule_id::REQUEST_RULE;
13use openmoat_core::{
14 Decision, RequestCheck, RequestEntry, RequestRules, RequestsUntrusted as Untrusted, Verdict,
15};
16
17#[derive(Debug, Default)]
19pub struct Requests {
20 entries: Vec<RequestEntry>,
21 rules: RequestRules,
22 untrusted: Untrusted,
23}
24
25#[derive(Debug, thiserror::Error)]
27#[error("request rules: {0}")]
28pub struct RequestRuleError(String);
29
30impl Requests {
31 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 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 #[must_use = "the hosts are only listed"]
60 pub fn hosts(&self) -> Vec<String> {
61 self.rules.hosts()
62 }
63
64 pub(crate) fn names(&self, host: &str) -> bool {
66 self.rules.names(host)
67 }
68
69 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 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;