trillium_proxy/
upstream.rs1use 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
18pub trait UpstreamSelector: Debug + Send + Sync + 'static {
20 fn determine_upstream(&self, conn: &mut Conn) -> Option<Url>;
22
23 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
42pub trait IntoUpstreamSelector {
47 type UpstreamSelector: UpstreamSelector;
49 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#[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
106fn join_within_base(base: &Url, path_and_query: &str) -> Option<Url> {
118 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 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 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 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 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 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}