Skip to main content

tilo_net/
proxy.rs

1//! The host's fetch proxy: how a page reads cross-origin responses that the
2//! site does not allow it to (CORS). The workspace host the page is admitted
3//! to offers one: [`host`] is its implementation, which `tilo-server` serves
4//! and, in development, `tilo-fetch-proxy`.
5
6#[cfg(all(feature = "proxy-host", not(target_family = "wasm")))]
7pub mod host;
8
9use std::sync::RwLock;
10
11use ::http::{HeaderMap, HeaderName, HeaderValue};
12use url::Url;
13
14use crate::NetError;
15use tilo_lock::RwLockRecover as _;
16
17pub const MARKER_HEADER: &str = "x-tilo-proxy";
18/// Prefix of headers the proxy restores to their real name, both ways.
19pub const FORWARD_PREFIX: &str = "x-tilo-forward-";
20pub const FINAL_URL_HEADER: &str = "x-tilo-proxy-final-url";
21pub const ERROR_HEADER: &str = "x-tilo-proxy-error";
22pub const SESSION_HEADER: &str = "x-tilo-session";
23pub const VERSION: &str = "1";
24pub const MARKER_PARAM: &str = "tilo-proxy";
25pub const SESSION_PARAM: &str = "tilo-session";
26
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
28pub enum ProxyUse {
29    #[default]
30    Never,
31    /// In a page, sends cross-origin requests through the host's proxy when the
32    /// host has configured one; direct otherwise, and always on the desktop.
33    CrossOrigin,
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub enum ProxyFailure {
38    BadRequest,
39    Blocked,
40    Unreachable,
41    Timeout,
42    TooLarge,
43    Unauthorized,
44    /// This device, or everyone together, asked too much of the proxy lately.
45    RateLimited,
46    /// The proxy relayed as much as it allows this visitor, or everyone in its
47    /// workspace together, for now (a day, by default).
48    OverBudget,
49}
50
51impl ProxyFailure {
52    #[must_use]
53    pub const fn code(self) -> &'static str {
54        match self {
55            Self::BadRequest => "bad-request",
56            Self::Blocked => "blocked",
57            Self::Unreachable => "unreachable",
58            Self::Timeout => "timeout",
59            Self::TooLarge => "too-large",
60            Self::Unauthorized => "unauthorized",
61            Self::RateLimited => "rate-limited",
62            Self::OverBudget => "over-budget",
63        }
64    }
65
66    #[must_use]
67    pub const fn status(self) -> u16 {
68        match self {
69            Self::BadRequest => 400,
70            Self::Blocked => 403,
71            Self::Unreachable => 502,
72            Self::Timeout => 504,
73            Self::TooLarge => 413,
74            Self::Unauthorized => 401,
75            Self::RateLimited | Self::OverBudget => 429,
76        }
77    }
78
79    #[must_use]
80    pub fn from_code(code: &str) -> Option<Self> {
81        [
82            Self::BadRequest,
83            Self::Blocked,
84            Self::Unreachable,
85            Self::Timeout,
86            Self::TooLarge,
87            Self::Unauthorized,
88            Self::RateLimited,
89            Self::OverBudget,
90        ]
91        .into_iter()
92        .find(|failure| failure.code() == code)
93    }
94
95    fn into_error(self, message: String) -> NetError {
96        match self {
97            Self::Blocked => NetError::Blocked(message),
98            Self::Timeout => NetError::Timeout,
99            Self::TooLarge => NetError::TooLarge { limit: 0 },
100            Self::BadRequest => NetError::InvalidUrl(message),
101            Self::RateLimited | Self::OverBudget => {
102                NetError::Status(::http::StatusCode::TOO_MANY_REQUESTS)
103            }
104            Self::Unreachable | Self::Unauthorized => NetError::connect(message),
105        }
106    }
107}
108
109#[derive(Clone, Debug, PartialEq, Eq)]
110pub struct Proxy {
111    pub endpoint: Url,
112    /// The page's session at the host, sent as [`SESSION_HEADER`]; `None` for a
113    /// host that authenticates the page by its cookies.
114    pub session: Option<String>,
115}
116
117#[derive(Clone)]
118enum Decision {
119    Page,
120    Host(Option<Url>),
121}
122
123static ENDPOINT: RwLock<Decision> = RwLock::new(Decision::Page);
124
125fn check_endpoint(endpoint: &Url) -> Result<(), NetError> {
126    if !matches!(endpoint.scheme(), "http" | "https") {
127        return Err(NetError::InvalidUrl(format!(
128            "{endpoint}: the fetch proxy must be an http(s) endpoint"
129        )));
130    }
131    Ok(())
132}
133
134/// Enable the host's proxy at `endpoint`, or disable it with `None`. Hosts
135/// call this, not apps: every proxied request carries the app's headers and
136/// body to the endpoint, so it must be the page's own host or the workspace
137/// host the page is admitted to.
138pub fn configure(endpoint: Option<Url>) -> Result<(), NetError> {
139    if let Some(endpoint) = &endpoint {
140        check_endpoint(endpoint)?;
141    }
142    *ENDPOINT.write_recover() = Decision::Host(endpoint);
143    Ok(())
144}
145
146/// The proxy in use: the host's [`configure`] choice, else what the page
147/// names in `globalThis.__tiloFetchProxy`, else none.
148#[must_use]
149pub fn current() -> Option<Proxy> {
150    let decision = ENDPOINT.read_recover().clone();
151    match decision {
152        Decision::Page => page_default(),
153        Decision::Host(endpoint) => endpoint.map(|endpoint| Proxy {
154            endpoint,
155            session: None,
156        }),
157    }
158}
159
160#[must_use]
161pub fn endpoint() -> Option<Url> {
162    current().map(|proxy| proxy.endpoint)
163}
164
165#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
166fn page_default() -> Option<Proxy> {
167    use wasm_bindgen::JsCast as _;
168    let named = crate::web::global_get("__tiloFetchProxy")?;
169    let (endpoint, session) = if let Some(function) = named.dyn_ref::<js_sys::Function>() {
170        let answer = function.call0(&wasm_bindgen::JsValue::NULL).ok()?;
171        let endpoint = crate::web::get(&answer, "endpoint")?.as_string()?;
172        let session = crate::web::get(&answer, "session").and_then(|value| value.as_string());
173        (endpoint, session)
174    } else {
175        (named.as_string()?, None)
176    };
177    let endpoint = crate::web::page_url()?.join(&endpoint).ok()?;
178    check_endpoint(&endpoint).ok()?;
179    Some(Proxy { endpoint, session })
180}
181
182#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
183fn page_default() -> Option<Proxy> {
184    None
185}
186
187/// Headers a browser will not let a page set; they travel under
188/// [`FORWARD_PREFIX`].
189fn browser_forbidden(name: &HeaderName) -> bool {
190    const FORBIDDEN: &[&str] = &[
191        "accept-charset",
192        "accept-encoding",
193        "access-control-request-headers",
194        "access-control-request-method",
195        "connection",
196        "content-length",
197        "cookie",
198        "date",
199        "dnt",
200        "expect",
201        "host",
202        "keep-alive",
203        "origin",
204        "referer",
205        "te",
206        "trailer",
207        "transfer-encoding",
208        "upgrade",
209        "user-agent",
210        "via",
211    ];
212    let name = name.as_str();
213    FORBIDDEN.contains(&name) || name.starts_with("proxy-") || name.starts_with("sec-")
214}
215
216pub fn route(
217    proxy: &Proxy,
218    target: &Url,
219    headers: &HeaderMap,
220) -> Result<(Url, HeaderMap), NetError> {
221    let mut url = proxy.endpoint.clone();
222    url.query_pairs_mut().append_pair("url", target.as_str());
223    let mut routed = HeaderMap::with_capacity(headers.len().saturating_add(2));
224    routed.insert(
225        HeaderName::from_static(MARKER_HEADER),
226        HeaderValue::from_static(VERSION),
227    );
228    if let Some(session) = &proxy.session {
229        routed.insert(
230            HeaderName::from_static(SESSION_HEADER),
231            HeaderValue::from_str(session)
232                .map_err(|error| NetError::InvalidRequest(error.to_string()))?,
233        );
234    }
235    for (name, value) in headers {
236        let name = if browser_forbidden(name) {
237            HeaderName::try_from(format!("{FORWARD_PREFIX}{name}"))
238                .map_err(|error| NetError::InvalidRequest(error.to_string()))?
239        } else {
240            name.clone()
241        };
242        routed.append(name, value.clone());
243    }
244    Ok((url, routed))
245}
246
247/// The URL a page element that cannot send headers (a media element) loads
248/// `target` from through `proxy`.
249#[must_use]
250pub fn media_url(proxy: &Proxy, target: &Url) -> Url {
251    let mut url = proxy.endpoint.clone();
252    {
253        let mut query = url.query_pairs_mut();
254        query.append_pair("url", target.as_str());
255        query.append_pair(MARKER_PARAM, VERSION);
256        if let Some(session) = &proxy.session {
257            query.append_pair(SESSION_PARAM, session);
258        }
259    }
260    url
261}
262
263pub fn unwrap_response(
264    target: &Url,
265    headers: &HeaderMap,
266    body_if_failed: impl FnOnce() -> String,
267) -> Result<(HeaderMap, Url), NetError> {
268    if let Some(code) = headers.get(ERROR_HEADER) {
269        let failure = code
270            .to_str()
271            .ok()
272            .and_then(ProxyFailure::from_code)
273            .unwrap_or(ProxyFailure::Unreachable);
274        return Err(failure.into_error(body_if_failed()));
275    }
276    let mut url = target.clone();
277    let mut unwrapped = HeaderMap::with_capacity(headers.len());
278    for (name, value) in headers {
279        if name == FINAL_URL_HEADER {
280            if let Some(final_url) = value.to_str().ok().and_then(|v| Url::parse(v).ok()) {
281                url = final_url;
282            }
283        } else if let Some(original) = name.as_str().strip_prefix(FORWARD_PREFIX) {
284            if let Ok(original) = HeaderName::try_from(original) {
285                unwrapped.append(original, value.clone());
286            }
287        } else {
288            unwrapped.append(name.clone(), value.clone());
289        }
290    }
291    Ok((unwrapped, url))
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    fn url(s: &str) -> Url {
299        Url::parse(s).unwrap()
300    }
301
302    tilo_test_env::scenario! {
303        fn the_fetch_proxy_wraps_a_request_and_unwraps_its_answer;
304
305        phase a_request_routes_through_the_endpoint;
306        {
307            let mut headers = HeaderMap::new();
308            headers.insert("accept", HeaderValue::from_static("application/json"));
309            headers.insert("user-agent", HeaderValue::from_static("Tilo"));
310            headers.insert("cookie", HeaderValue::from_static("a=1"));
311            let proxy = Proxy {
312                endpoint: url("https://cloud.example/_tilo/net/fetch"),
313                session: Some("ab12".into()),
314            };
315            let (routed, sent) = route(
316                &proxy,
317                &url("https://api.example/v1/items?page=2&q=a b"),
318                &headers,
319            )
320            .unwrap();
321            assert_eq!(
322                routed.as_str(),
323                "https://cloud.example/_tilo/net/fetch?url=https%3A%2F%2Fapi.example%2Fv1%2Fitems%3Fpage%3D2%26q%3Da%2520b"
324            );
325            let target: String = routed
326                .query_pairs()
327                .find(|(k, _)| k == "url")
328                .map(|(_, v)| v.into_owned())
329                .unwrap();
330            assert_eq!(target, "https://api.example/v1/items?page=2&q=a%20b");
331            assert_eq!(sent[MARKER_HEADER], VERSION);
332            assert_eq!(sent[SESSION_HEADER], "ab12");
333            assert_eq!(sent["accept"], "application/json");
334            assert_eq!(sent["x-tilo-forward-user-agent"], "Tilo");
335            assert_eq!(sent["x-tilo-forward-cookie"], "a=1");
336            assert!(!sent.contains_key("user-agent"));
337        }
338
339        phase a_response_unwraps_to_the_target_view;
340        {
341            let mut headers = HeaderMap::new();
342            headers.insert("content-type", HeaderValue::from_static("text/xml"));
343            headers.insert(
344                FINAL_URL_HEADER,
345                HeaderValue::from_static("https://api.example/moved"),
346            );
347            headers.append("x-tilo-forward-set-cookie", HeaderValue::from_static("s=1"));
348            headers.append(
349                "x-tilo-forward-www-authenticate",
350                HeaderValue::from_static("Basic realm=\"api\""),
351            );
352            let (unwrapped, final_url) =
353                unwrap_response(&url("https://api.example/"), &headers, String::new).unwrap();
354            assert_eq!(final_url.as_str(), "https://api.example/moved");
355            assert_eq!(unwrapped["set-cookie"], "s=1");
356            assert_eq!(unwrapped["www-authenticate"], "Basic realm=\"api\"");
357            assert_eq!(unwrapped["content-type"], "text/xml");
358            assert!(!unwrapped.contains_key(FINAL_URL_HEADER));
359        }
360
361        phase a_proxy_failure_is_an_error_not_a_response;
362        {
363            let mut headers = HeaderMap::new();
364            headers.insert(ERROR_HEADER, HeaderValue::from_static("blocked"));
365            let failed = unwrap_response(&url("http://10.0.0.1/"), &headers, || {
366                "private address".into()
367            });
368            assert_eq!(failed, Err(NetError::Blocked("private address".into())));
369            for failure in [
370                ProxyFailure::BadRequest,
371                ProxyFailure::Blocked,
372                ProxyFailure::Unreachable,
373                ProxyFailure::Timeout,
374                ProxyFailure::TooLarge,
375                ProxyFailure::Unauthorized,
376                ProxyFailure::RateLimited,
377                ProxyFailure::OverBudget,
378            ] {
379                assert_eq!(ProxyFailure::from_code(failure.code()), Some(failure));
380            }
381        }
382
383        phase configure_refuses_non_http_endpoints;
384        {
385            assert!(configure(Some(url("ftp://x/"))).is_err());
386            assert_eq!(endpoint(), None);
387        }
388    }
389}