Skip to main content

openmoat_core/
route.rs

1//! Method and path rules for HTTP requests (ADR-043): which requests a
2//! brokered secret's `allow:` rules let receive its value, and the request path
3//! in the form they are matched against. Shared with a host's request rules
4//! (`requests:`, ADR-062), which match paths the same way, at the proxy and in
5//! the hook.
6//!
7//! A rule is `METHOD /path`: the method in capitals, compared exactly, and a
8//! path of `/`-separated segments, each a literal, `*` (exactly one non-empty
9//! segment) or `**` (any number of segments, none included). The query is not
10//! matched.
11//!
12//! The path a request names is matched as the server reads it: each segment
13//! percent-decoded once. A path the server could read as another one is
14//! refused instead of matched ([`PathRefusal`]): a `.` or `..` segment in any
15//! spelling, an encoded `/` or `\`, a second layer of encoding, a `;` (matrix
16//! parameters, Tomcat's `..;`), an empty segment, a byte outside visible
17//! ASCII. A request that asks the server to run another method than its own
18//! (a [`METHOD_OVERRIDE_HEADERS`] header, a `_method` query parameter) is
19//! refused too.
20
21use std::fmt;
22
23/// Most rules one secret may list, and most segments one rule may have: the
24/// match costs at most rules × segments × request segments steps.
25pub const MAX_ROUTES: usize = 64;
26const MAX_SEGMENTS: usize = 64;
27
28/// Headers some frameworks read as the request's real method. A request that
29/// carries one is refused for a secret with rules: the server would run a
30/// method the rules never saw.
31pub const METHOD_OVERRIDE_HEADERS: &[&str] = &[
32    "x-http-method-override",
33    "x-http-method",
34    "x-method-override",
35];
36
37/// Methods no rule may name.
38const ECHOING: &[&str] = &["TRACE", "TRACK", "CONNECT"];
39
40/// The query parameter Rails, Laravel and others read as the real method.
41const METHOD_OVERRIDE_PARAMETER: &str = "_method";
42
43/// One `METHOD /path` rule.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct Route {
46    method: String,
47    segments: Vec<Segment>,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
51enum Segment {
52    Literal(String),
53    /// `*`: exactly one non-empty segment.
54    One,
55    /// `**`: zero or more segments.
56    Any,
57}
58
59impl Route {
60    /// Parse `METHOD /path`; the error says what is wrong.
61    pub fn parse(text: &str) -> Result<Self, String> {
62        let (method, path) = text
63            .split_once(' ')
64            .ok_or_else(|| format!("rule `{text}` must be `METHOD /path`"))?;
65        if method.is_empty() || !method.bytes().all(|b| b.is_ascii_uppercase()) {
66            return Err(format!(
67                "rule `{text}`: the method must be capital letters (`GET`, `POST`)"
68            ));
69        }
70        // The answer to `TRACE` is the request as the server got it, value
71        // included; `CONNECT` opens a tunnel nothing reads.
72        if ECHOING.contains(&method) {
73            return Err(format!(
74                "rule `{text}`: {method} is never given a secret: the server would send it back \
75                 or the proxy could not read what follows"
76            ));
77        }
78        let Some(rest) = path.strip_prefix('/') else {
79            return Err(format!("rule `{text}`: the path must start with `/`"));
80        };
81        let mut segments = Vec::new();
82        let parts: Vec<&str> = if rest.is_empty() {
83            Vec::new()
84        } else {
85            rest.split('/').collect()
86        };
87        for (n, part) in parts.iter().enumerate() {
88            let last = n + 1 == parts.len();
89            segments.push(match *part {
90                "*" => Segment::One,
91                "**" => Segment::Any,
92                // A rule ending in `/` names the path with its trailing slash.
93                "" if last => Segment::Literal(String::new()),
94                "" => return Err(format!("rule `{text}`: the path has an empty segment")),
95                "." | ".." => return Err(format!("rule `{text}`: `.` and `..` are not segments")),
96                literal if literal.bytes().all(is_literal_byte) => {
97                    Segment::Literal(literal.to_owned())
98                }
99                _ => {
100                    return Err(format!(
101                        "rule `{text}`: a segment is a literal of letters, digits and \
102                         `-._~!$&'()+,=:@`, `*` or `**`"
103                    ));
104                }
105            });
106        }
107        if segments.len() > MAX_SEGMENTS {
108            return Err(format!(
109                "rule `{text}` has more than {MAX_SEGMENTS} segments"
110            ));
111        }
112        Ok(Self {
113            method: method.to_owned(),
114            segments,
115        })
116    }
117
118    /// Whether a `method` request for `path` matches this rule.
119    #[must_use]
120    pub fn matches(&self, method: &str, path: &RequestPath) -> bool {
121        self.method == method && matches(&self.segments, &path.segments)
122    }
123
124    /// Whether a request known only in part could match this rule: `method`
125    /// `None` is any method, `path` `None` any path, and a path's
126    /// [`Partial::One`] and [`Partial::Rest`] segments anything they may
127    /// hold (ADR-062: what the hook reads in a command before it runs).
128    #[must_use]
129    pub fn could_match(&self, method: Option<&str>, path: Option<&[Partial]>) -> bool {
130        method.is_none_or(|m| m == self.method) && path.is_none_or(|p| could(&self.segments, p))
131    }
132}
133
134/// One segment of a request path known only in part before the request is
135/// sent: a command's URL built from a variable, or `gh api`'s `{owner}`.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum Partial {
138    /// A segment as the server reads it (decoded).
139    Known(String),
140    /// Exactly one segment, its text unknown.
141    One,
142    /// Any number of segments, none included, their text unknown.
143    Rest,
144}
145
146/// Whether `rule` could match some path `path` stands for: `memo[i][j]` holds
147/// whether the rule from segment `i` could match the path from segment `j`.
148fn could(rule: &[Segment], path: &[Partial]) -> bool {
149    let (r, p) = (rule.len(), path.len());
150    let mut memo = vec![vec![false; p + 1]; r + 1];
151    for i in (0..=r).rev() {
152        for j in (0..=p).rev() {
153            memo[i][j] = if i == r && j == p {
154                true
155            } else if j < p && path[j] == Partial::Rest {
156                memo[i][j + 1] || (i < r && memo[i + 1][j])
157            } else if i < r && rule[i] == Segment::Any {
158                memo[i + 1][j] || (j < p && memo[i][j + 1])
159            } else if i < r && j < p {
160                let one = match (&rule[i], &path[j]) {
161                    (Segment::Literal(l), Partial::Known(k)) => l == k,
162                    (Segment::One, Partial::Known(k)) => !k.is_empty(),
163                    _ => true,
164                };
165                one && memo[i + 1][j + 1]
166            } else {
167                false
168            };
169        }
170    }
171    memo[0][0]
172}
173
174/// Whether `rule` matches `path`: `matched[j]` is true when the first `i`
175/// rule segments match the first `j` path segments, one row per rule segment.
176fn matches(rule: &[Segment], path: &[String]) -> bool {
177    let mut matched = vec![false; path.len() + 1];
178    matched[0] = true;
179    for segment in rule {
180        let mut next = vec![false; path.len() + 1];
181        for j in 0..=path.len() {
182            next[j] = match segment {
183                Segment::Any => matched[j] || (j > 0 && next[j - 1]),
184                Segment::One => j > 0 && matched[j - 1] && !path[j - 1].is_empty(),
185                Segment::Literal(literal) => j > 0 && matched[j - 1] && path[j - 1] == *literal,
186            };
187        }
188        matched = next;
189    }
190    matched[path.len()]
191}
192
193/// RFC 3986 `pchar` without `%` and `;`: a rule's literal is written decoded.
194fn is_literal_byte(b: u8) -> bool {
195    b.is_ascii_alphanumeric() || b"-._~!$&'()+,=:@".contains(&b)
196}
197
198/// The path of a request, decoded segment by segment, and whether its query
199/// names a method override.
200#[derive(Debug, Clone, PartialEq, Eq)]
201pub struct RequestPath {
202    segments: Vec<String>,
203    overrides_method: bool,
204}
205
206/// Why a request's path is refused rather than matched.
207#[derive(Debug, Clone, PartialEq, Eq)]
208#[non_exhaustive]
209pub enum PathRefusal {
210    /// Not an origin-form path (`/…`): absolute form, `*`, or empty.
211    NotOriginForm,
212    /// A byte outside visible ASCII, a `\`, a `#`, or a malformed `%XX`.
213    Malformed,
214    /// A segment that is, or decodes to, `.` or `..`.
215    DotSegment,
216    /// A segment that decodes to `/`, `\`, `%`, `;`, a control byte or
217    /// invalid UTF-8, or holds a `;`.
218    AmbiguousSegment,
219    /// `//`: an empty segment before the end.
220    EmptySegment,
221}
222
223impl fmt::Display for PathRefusal {
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225        f.write_str(match self {
226            Self::NotOriginForm => "the request target is not a path starting with `/`",
227            Self::Malformed => {
228                "the path holds a byte outside visible ASCII, a `\\`, a `#` or a malformed `%` \
229                 escape"
230            }
231            Self::DotSegment => "the path holds a `.` or `..` segment, in some spelling",
232            Self::AmbiguousSegment => {
233                "a path segment holds `;` or decodes to `/`, `\\`, `%`, `;` or a control byte"
234            }
235            Self::EmptySegment => "the path holds an empty segment (`//`)",
236        })
237    }
238}
239
240impl RequestPath {
241    /// The path of `target`, a request line's target, as the server would read
242    /// it; refused when the server could read it as another path.
243    pub fn parse(target: &str) -> Result<Self, PathRefusal> {
244        let Some(rest) = target.strip_prefix('/') else {
245            return Err(PathRefusal::NotOriginForm);
246        };
247        if !target.bytes().all(|b| b.is_ascii_graphic()) || target.contains(['\\', '#']) {
248            return Err(PathRefusal::Malformed);
249        }
250        let (path, query) = rest.split_once('?').unwrap_or((rest, ""));
251        let parts: Vec<&str> = if path.is_empty() {
252            Vec::new()
253        } else {
254            path.split('/').collect()
255        };
256        let mut segments = Vec::with_capacity(parts.len());
257        for (n, part) in parts.iter().enumerate() {
258            if part.is_empty() && n + 1 < parts.len() {
259                return Err(PathRefusal::EmptySegment);
260            }
261            if part.contains(';') {
262                return Err(PathRefusal::AmbiguousSegment);
263            }
264            let decoded = decode(part).ok_or(PathRefusal::Malformed)?;
265            let decoded = String::from_utf8(decoded).map_err(|_| PathRefusal::AmbiguousSegment)?;
266            if decoded == "." || decoded == ".." {
267                return Err(PathRefusal::DotSegment);
268            }
269            if decoded
270                .chars()
271                .any(|c| c.is_control() || matches!(c, '/' | '\\' | '%' | ';'))
272            {
273                return Err(PathRefusal::AmbiguousSegment);
274            }
275            segments.push(decoded);
276        }
277        let overrides_method = query.split('&').any(|pair| {
278            let name = pair.split_once('=').map_or(pair, |(name, _)| name);
279            decode(name)
280                .is_none_or(|n| n.eq_ignore_ascii_case(METHOD_OVERRIDE_PARAMETER.as_bytes()))
281        });
282        Ok(Self {
283            segments,
284            overrides_method,
285        })
286    }
287
288    /// Whether the query names a `_method` parameter (in any letter case or
289    /// encoding), or a parameter name that does not decode.
290    #[must_use]
291    pub fn overrides_method(&self) -> bool {
292        self.overrides_method
293    }
294
295    /// The path's segments, decoded, as rules match them.
296    pub(crate) fn segments(&self) -> &[String] {
297        &self.segments
298    }
299
300    /// The path with each decoded segment in lowercase: what a deny rule,
301    /// which errs wide, is matched against (`/%47ists` is `/gists`).
302    #[must_use]
303    pub(crate) fn folded(&self) -> Self {
304        Self {
305            segments: self
306                .segments
307                .iter()
308                .map(|s| s.to_ascii_lowercase())
309                .collect(),
310            overrides_method: self.overrides_method,
311        }
312    }
313}
314
315/// `text` with each `%XX` replaced by its byte; `None` for a malformed escape.
316fn decode(text: &str) -> Option<Vec<u8>> {
317    let bytes = text.as_bytes();
318    let mut out = Vec::with_capacity(bytes.len());
319    let mut i = 0;
320    while i < bytes.len() {
321        if bytes[i] == b'%' {
322            // Two hex digits exactly: `from_str_radix` would also take `+1`.
323            let hex = bytes
324                .get(i + 1..i + 3)
325                .filter(|h| h.iter().all(u8::is_ascii_hexdigit))?;
326            out.push(u8::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok()?);
327            i += 3;
328        } else {
329            out.push(bytes[i]);
330            i += 1;
331        }
332    }
333    Some(out)
334}
335
336#[cfg(test)]
337mod tests;