Skip to main content

trillium_proxy/
upstream.rs

1//! Upstream selectors
2use std::{borrow::Cow, fmt::Debug};
3use trillium::Conn;
4use url::Url;
5
6#[cfg(feature = "upstream-connection-counting")]
7mod connection_counting;
8#[cfg(feature = "upstream-random")]
9mod random;
10mod round_robin;
11
12#[cfg(feature = "upstream-connection-counting")]
13pub use connection_counting::ConnectionCounting;
14#[cfg(feature = "upstream-random")]
15pub use random::RandomSelector;
16pub use round_robin::RoundRobin;
17
18/// a trait for selecting the correct upstream
19pub trait UpstreamSelector: Debug + Send + Sync + 'static {
20    /// does what it says on the label
21    fn determine_upstream(&self, conn: &mut Conn) -> Option<Url>;
22
23    /// turn self into a `Box<dyn UpstreamSelector>`
24    fn boxed(self) -> Box<dyn UpstreamSelector>
25    where
26        Self: Sized,
27    {
28        Box::new(self.into_upstream())
29    }
30}
31
32impl UpstreamSelector for Box<dyn UpstreamSelector> {
33    fn determine_upstream(&self, conn: &mut Conn) -> Option<Url> {
34        UpstreamSelector::determine_upstream(&**self, conn)
35    }
36
37    fn boxed(self) -> Box<dyn UpstreamSelector> {
38        self
39    }
40}
41
42/// represents something that can be used as an upstream selector
43///
44/// This primarily exists so &str can be used as a synonym for `Url`.
45/// All `UpstreamSelector`s also are `IntoUpstreamSelector`
46pub trait IntoUpstreamSelector {
47    /// the type that Self will be transformed into
48    type UpstreamSelector: UpstreamSelector;
49    /// transform self into the upstream selector
50    fn into_upstream(self) -> Self::UpstreamSelector;
51}
52
53impl<U: UpstreamSelector> IntoUpstreamSelector for U {
54    type UpstreamSelector = Self;
55
56    fn into_upstream(self) -> Self {
57        self
58    }
59}
60
61impl IntoUpstreamSelector for &str {
62    type UpstreamSelector = Url;
63
64    fn into_upstream(self) -> Url {
65        let url = match Url::try_from(self) {
66            Ok(url) => url,
67            Err(_) => panic!("could not convert proxy target into a url"),
68        };
69
70        assert!(!url.cannot_be_a_base(), "{url} cannot be a base");
71        url
72    }
73}
74
75impl IntoUpstreamSelector for String {
76    type UpstreamSelector = Url;
77
78    fn into_upstream(self) -> Url {
79        (&*self).into_upstream()
80    }
81}
82
83/// Select the upstream from an absolute-form request target or HTTP/2/3 scheme and authority.
84#[derive(Debug, Copy, Clone)]
85pub struct ForwardProxy;
86impl UpstreamSelector for ForwardProxy {
87    fn determine_upstream(&self, conn: &mut Conn) -> Option<Url> {
88        let conn: &trillium_http::Conn<_> = conn.as_ref();
89        match (conn.scheme(), conn.authority()) {
90            (Some(scheme), Some(authority)) => {
91                format!("{scheme}://{authority}{}", conn.path_and_query())
92                    .parse()
93                    .ok()
94            }
95            _ => conn.path_and_query().parse().ok(),
96        }
97    }
98}
99
100impl UpstreamSelector for Url {
101    fn determine_upstream(&self, conn: &mut Conn) -> Option<Url> {
102        join_within_base(self, conn.path_and_query())
103    }
104}
105
106/// Resolve `path_and_query` against `base`, refusing to proxy anything that
107/// escapes the base's directory.
108///
109/// `Url::join` resolves `..` per RFC 3986 §5.2.4, which lets a request walk out
110/// of a base that carries a path prefix — base `…/app/` with a request path of
111/// `/../secret` resolves to `/secret`. Following the `starts_with` containment
112/// check that `trillium-static` uses for filesystem roots, an escape yields
113/// `None` so the base prefix stays a real boundary. `%2e%2e` is recognized as a
114/// `..` segment during parsing and normalized like a literal one, so encoded
115/// traversal is caught by the same check; `%2f` is left encoded and rides
116/// through as opaque path content.
117fn join_within_base(base: &Url, path_and_query: &str) -> Option<Url> {
118    // Without a trailing slash, `Url::join`'s relative-reference resolution
119    // replaces the base's last path segment instead of appending under it (base
120    // `…/api` + `/foo` → `…/foo`), silently dropping the mount prefix.
121    let base = if base.path().ends_with('/') {
122        Cow::Borrowed(base)
123    } else {
124        let mut owned = base.clone();
125        owned.set_path(&format!("{}/", base.path()));
126        Cow::Owned(owned)
127    };
128
129    // Prefix with `./` so `Url::join` treats the request path as a relative
130    // *path* rather than a relative *reference*. Without this, a colon in the
131    // first path segment (e.g. `/trillium::Handler`) is parsed as a URL scheme,
132    // yielding a `cannot_be_a_base` url. See RFC 3986 §4.2.
133    let upstream = base
134        .join(&format!("./{}", path_and_query.trim_start_matches('/')))
135        .ok()?;
136
137    let base_path = base.path();
138    let base_dir = &base_path[..=base_path.rfind('/').unwrap_or(0)];
139    upstream.path().starts_with(base_dir).then_some(upstream)
140}
141
142impl<F> UpstreamSelector for F
143where
144    F: Fn(&mut Conn) -> Option<Url> + Debug + Send + Sync + 'static,
145{
146    fn determine_upstream(&self, conn: &mut Conn) -> Option<Url> {
147        self(conn)
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::join_within_base;
154    use url::Url;
155
156    fn base(s: &str) -> Url {
157        Url::parse(s).unwrap()
158    }
159
160    #[test]
161    fn dot_segments_cannot_escape_a_base_path_prefix() {
162        let base = base("http://upstream.example/app/");
163
164        // A `..` that would climb out of the `/app/` mount is refused entirely,
165        // rather than silently proxying a path the operator never exposed. The
166        // `url` crate decodes `%2e` before resolving, so percent-encoded
167        // traversal is caught by the same containment check.
168        for escape in [
169            "/../secret",
170            "/../../etc/passwd",
171            "/a/../../secret",
172            "/%2e%2e/secret",
173        ] {
174            assert_eq!(
175                join_within_base(&base, escape),
176                None,
177                "{escape} escaped the base prefix"
178            );
179        }
180
181        // Normalization *within* the mount is fine and stays contained.
182        assert_eq!(join_within_base(&base, "/foo").unwrap().path(), "/app/foo");
183        assert_eq!(join_within_base(&base, "/a/../b").unwrap().path(), "/app/b");
184    }
185
186    #[test]
187    fn resolution_never_leaves_the_base_host() {
188        let base = base("http://upstream.example/");
189        for input in [
190            "/https://sneaky.com",
191            "/../secret",
192            "/a/../b",
193            "/trillium::Handler",
194            "//sneaky.com/path",
195        ] {
196            if let Some(url) = join_within_base(&base, input) {
197                assert_eq!(
198                    url.host_str(),
199                    Some("upstream.example"),
200                    "{input} left the base host -> {url}"
201                );
202            }
203        }
204    }
205
206    #[test]
207    fn base_without_trailing_slash_keeps_its_prefix() {
208        // A base mounted without a trailing slash appends under its final
209        // segment rather than having it replaced by relative-reference
210        // resolution.
211        let base = base("http://upstream.example/api");
212        assert_eq!(
213            join_within_base(&base, "/users").unwrap().as_str(),
214            "http://upstream.example/api/users"
215        );
216        // Traversal still can't climb out of the normalized prefix.
217        assert_eq!(join_within_base(&base, "/../secret"), None);
218    }
219
220    #[test]
221    fn query_and_first_segment_colons_survive_containment() {
222        let base = base("http://upstream.example/");
223        let url = join_within_base(&base, "/trillium::Handler?x=1&y=2").unwrap();
224        assert_eq!(url.path(), "/trillium::Handler");
225        assert_eq!(url.query(), Some("x=1&y=2"));
226    }
227}