Skip to main content

openmoat_core/
requests.rs

1//! Method and path rules for allowed hosts: the policy's `requests:` list
2//! (ADR-062, docs/POLICY.md §2.2).
3//!
4//! An entry names one host and lists `deny` and `allow` rules written as a
5//! brokered secret's (`METHOD /path`, `crate::route`). `deny` is tried first
6//! and is absolute; with an `allow` list, a request no rule of it names is
7//! refused too; a host's entries only narrow what the `net` and `fetch` rules
8//! allow. Two places hold them:
9//!
10//! - the hook (`requests/hook.rs`), which reads the method and URL a command
11//!   or a fetch tool will send (`curl -X POST …`, `gh api`, `gh gist create`)
12//!   and denies what a rule refuses, or holds for review what it cannot read
13//!   in full; it never allows;
14//! - the proxy (`openmoat-proxy`), which reads the request itself inside a
15//!   tunnel it terminates. An entry with `hook_only: true` is left to the hook:
16//!   it needs no certificate authority and changes nothing at the proxy.
17//!
18//! Deny rules match the method and the path in any letter case (a server may
19//! read `post /Gists` as the route a rule names), so a deny list errs wide;
20//! allow rules match as written, so an allow list errs closed. A request whose
21//! path the server could read as another, or that asks the server for another
22//! method, is refused, as a secret's rules refuse it (ADR-043).
23
24use 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
32/// What a `requests:` entry's id is prefixed with where it stands for a rule
33/// id: lint warnings and policy errors (`requests.<id>`).
34pub const REQUESTS_RULE_PREFIX: &str = "requests.";
35
36/// One `requests:` entry: one host's request rules.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(deny_unknown_fields)]
39pub struct RequestEntry {
40    /// Stable identifier: lowercase letters, digits and `-`. Named in the
41    /// reason of every refusal.
42    pub id: String,
43    /// The one host (a lowercase DNS name, no address, port or pattern) whose
44    /// requests these rules decide.
45    pub host: String,
46    /// Requests that may be sent, `METHOD /path` each; empty, every request
47    /// `deny` does not name. Only the person's own policy may list them.
48    #[serde(default, skip_serializing_if = "Vec::is_empty")]
49    pub allow: Vec<String>,
50    /// Requests that are refused, whatever `allow` or a secret's rules say.
51    #[serde(default, skip_serializing_if = "Vec::is_empty")]
52    pub deny: Vec<String>,
53    /// Decided by the hook only: the proxy neither terminates the host for
54    /// this entry nor refuses a session that cannot be terminated.
55    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
56    pub hook_only: bool,
57}
58
59/// What `openmoat proxy` does with a connection to a `requests:` host it
60/// cannot terminate (`requests_untrusted:`): a session that did not receive
61/// OpenMoat's certificate authority, or a request without a session.
62#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "lowercase")]
64pub enum Untrusted {
65    /// Refuse it (`request-rule`): the rules cannot be held otherwise.
66    #[default]
67    Refuse,
68    /// Relay it unread, as before ADR-062, and say so on its row.
69    Relay,
70}
71
72/// What a host's request rules say about one request.
73#[derive(Debug, Clone, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum RequestCheck {
76    /// No entry names the host.
77    Unlisted,
78    /// The rules let it pass; why, for the audit row.
79    Passed(String),
80    /// The rules refuse it; why, naming the method and the rule, never the
81    /// path, which may carry data.
82    Refused(String),
83}
84
85/// The `requests:` entries of a policy, their rules parsed, for one enforcer.
86#[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    /// Each rule's text and the rule, its path folded to lowercase.
96    deny: Vec<(String, Route)>,
97    allow: Vec<(String, Route)>,
98}
99
100impl RequestRules {
101    /// The rules the hook holds: every entry.
102    pub fn for_hook(entries: &[RequestEntry]) -> Result<Self, PolicyError> {
103        Self::compile(entries.iter())
104    }
105
106    /// The rules the proxy holds: every entry not marked `hook_only`.
107    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    /// Whether no entry is held.
142    #[must_use]
143    pub fn is_empty(&self) -> bool {
144        self.entries.is_empty()
145    }
146
147    /// The hosts the entries name, sorted, once each: what a proxy CA must cover.
148    #[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    /// Whether an entry names `host`.
157    #[must_use]
158    pub fn names(&self, host: &str) -> bool {
159        self.of(Some(host)).next().is_some()
160    }
161
162    /// The entries for `host`, every entry for `None` (a host not known).
163    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    /// What the rules say about a `method` request for `target` (the request
170    /// line's target) to `host`, whose headers are named `header_names`.
171    #[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        // Folded after decoding: `/%47ists` is `/gists` to a server that
185        // ignores case.
186        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        // A server may read `/gists/` as `/gists`: a deny rule matches both.
211        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    /// Why a request known only in part could be refused, if it could:
250    /// `host` `None` is any host an entry names, `method` `None` any method,
251    /// `path` `None` any path. An entry with an `allow` list could refuse
252    /// any request it does not see in full.
253    #[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            // As in `check`: `/gists/` is matched as `/gists` too.
270            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
297/// `target` without the `/` that ends its path, when it has one past the root.
298fn 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
306/// `text` with its path in lowercase, as a deny rule is matched; the method
307/// stays as written, which [`Route::parse`] wants in capitals.
308fn 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
315/// Validate the `requests:` list. Errors name the entry as `requests.<id>`.
316pub(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    // A repository's or a pack's entries keep their `repo:` or
330    // `pack:<name>:` prefix once merged.
331    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
358/// A lowercase DNS name that is not an IPv4 address.
359fn 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;