tilo-net 0.5.1

The network capability on Linux, macOS and the web: async HTTP with streaming bodies, WebSocket, WebTransport, network status, raw sockets on the desktop, and Tilo's one TLS provider and trust source.
Documentation
//! The host's fetch proxy: how a page reads cross-origin responses that the
//! site does not allow it to (CORS). The workspace host the page is admitted
//! to offers one: [`host`] is its implementation, which `tilo-server` serves
//! and, in development, `tilo-fetch-proxy`.

#[cfg(all(feature = "proxy-host", not(target_family = "wasm")))]
pub mod host;

use std::sync::RwLock;

use ::http::{HeaderMap, HeaderName, HeaderValue};
use url::Url;

use crate::NetError;
use tilo_lock::RwLockRecover as _;

pub const MARKER_HEADER: &str = "x-tilo-proxy";
/// Prefix of headers the proxy restores to their real name, both ways.
pub const FORWARD_PREFIX: &str = "x-tilo-forward-";
pub const FINAL_URL_HEADER: &str = "x-tilo-proxy-final-url";
pub const ERROR_HEADER: &str = "x-tilo-proxy-error";
pub const SESSION_HEADER: &str = "x-tilo-session";
pub const VERSION: &str = "1";
pub const MARKER_PARAM: &str = "tilo-proxy";
pub const SESSION_PARAM: &str = "tilo-session";

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ProxyUse {
    #[default]
    Never,
    /// In a page, sends cross-origin requests through the host's proxy when the
    /// host has configured one; direct otherwise, and always on the desktop.
    CrossOrigin,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ProxyFailure {
    BadRequest,
    Blocked,
    Unreachable,
    Timeout,
    TooLarge,
    Unauthorized,
    /// This device, or everyone together, asked too much of the proxy lately.
    RateLimited,
    /// The proxy relayed as much as it allows this visitor, or everyone in its
    /// workspace together, for now (a day, by default).
    OverBudget,
}

impl ProxyFailure {
    #[must_use]
    pub const fn code(self) -> &'static str {
        match self {
            Self::BadRequest => "bad-request",
            Self::Blocked => "blocked",
            Self::Unreachable => "unreachable",
            Self::Timeout => "timeout",
            Self::TooLarge => "too-large",
            Self::Unauthorized => "unauthorized",
            Self::RateLimited => "rate-limited",
            Self::OverBudget => "over-budget",
        }
    }

    #[must_use]
    pub const fn status(self) -> u16 {
        match self {
            Self::BadRequest => 400,
            Self::Blocked => 403,
            Self::Unreachable => 502,
            Self::Timeout => 504,
            Self::TooLarge => 413,
            Self::Unauthorized => 401,
            Self::RateLimited | Self::OverBudget => 429,
        }
    }

    #[must_use]
    pub fn from_code(code: &str) -> Option<Self> {
        [
            Self::BadRequest,
            Self::Blocked,
            Self::Unreachable,
            Self::Timeout,
            Self::TooLarge,
            Self::Unauthorized,
            Self::RateLimited,
            Self::OverBudget,
        ]
        .into_iter()
        .find(|failure| failure.code() == code)
    }

    fn into_error(self, message: String) -> NetError {
        match self {
            Self::Blocked => NetError::Blocked(message),
            Self::Timeout => NetError::Timeout,
            Self::TooLarge => NetError::TooLarge { limit: 0 },
            Self::BadRequest => NetError::InvalidUrl(message),
            Self::RateLimited | Self::OverBudget => {
                NetError::Status(::http::StatusCode::TOO_MANY_REQUESTS)
            }
            Self::Unreachable | Self::Unauthorized => NetError::connect(message),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Proxy {
    pub endpoint: Url,
    /// The page's session at the host, sent as [`SESSION_HEADER`]; `None` for a
    /// host that authenticates the page by its cookies.
    pub session: Option<String>,
}

#[derive(Clone)]
enum Decision {
    Page,
    Host(Option<Url>),
}

static ENDPOINT: RwLock<Decision> = RwLock::new(Decision::Page);

fn check_endpoint(endpoint: &Url) -> Result<(), NetError> {
    if !matches!(endpoint.scheme(), "http" | "https") {
        return Err(NetError::InvalidUrl(format!(
            "{endpoint}: the fetch proxy must be an http(s) endpoint"
        )));
    }
    Ok(())
}

/// Enable the host's proxy at `endpoint`, or disable it with `None`. Hosts
/// call this, not apps: every proxied request carries the app's headers and
/// body to the endpoint, so it must be the page's own host or the workspace
/// host the page is admitted to.
pub fn configure(endpoint: Option<Url>) -> Result<(), NetError> {
    if let Some(endpoint) = &endpoint {
        check_endpoint(endpoint)?;
    }
    *ENDPOINT.write_recover() = Decision::Host(endpoint);
    Ok(())
}

/// The proxy in use: the host's [`configure`] choice, else what the page
/// names in `globalThis.__tiloFetchProxy`, else none.
#[must_use]
pub fn current() -> Option<Proxy> {
    let decision = ENDPOINT.read_recover().clone();
    match decision {
        Decision::Page => page_default(),
        Decision::Host(endpoint) => endpoint.map(|endpoint| Proxy {
            endpoint,
            session: None,
        }),
    }
}

#[must_use]
pub fn endpoint() -> Option<Url> {
    current().map(|proxy| proxy.endpoint)
}

#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
fn page_default() -> Option<Proxy> {
    use wasm_bindgen::JsCast as _;
    let named = crate::web::global_get("__tiloFetchProxy")?;
    let (endpoint, session) = if let Some(function) = named.dyn_ref::<js_sys::Function>() {
        let answer = function.call0(&wasm_bindgen::JsValue::NULL).ok()?;
        let endpoint = crate::web::get(&answer, "endpoint")?.as_string()?;
        let session = crate::web::get(&answer, "session").and_then(|value| value.as_string());
        (endpoint, session)
    } else {
        (named.as_string()?, None)
    };
    let endpoint = crate::web::page_url()?.join(&endpoint).ok()?;
    check_endpoint(&endpoint).ok()?;
    Some(Proxy { endpoint, session })
}

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
fn page_default() -> Option<Proxy> {
    None
}

/// Headers a browser will not let a page set; they travel under
/// [`FORWARD_PREFIX`].
fn browser_forbidden(name: &HeaderName) -> bool {
    const FORBIDDEN: &[&str] = &[
        "accept-charset",
        "accept-encoding",
        "access-control-request-headers",
        "access-control-request-method",
        "connection",
        "content-length",
        "cookie",
        "date",
        "dnt",
        "expect",
        "host",
        "keep-alive",
        "origin",
        "referer",
        "te",
        "trailer",
        "transfer-encoding",
        "upgrade",
        "user-agent",
        "via",
    ];
    let name = name.as_str();
    FORBIDDEN.contains(&name) || name.starts_with("proxy-") || name.starts_with("sec-")
}

pub fn route(
    proxy: &Proxy,
    target: &Url,
    headers: &HeaderMap,
) -> Result<(Url, HeaderMap), NetError> {
    let mut url = proxy.endpoint.clone();
    url.query_pairs_mut().append_pair("url", target.as_str());
    let mut routed = HeaderMap::with_capacity(headers.len().saturating_add(2));
    routed.insert(
        HeaderName::from_static(MARKER_HEADER),
        HeaderValue::from_static(VERSION),
    );
    if let Some(session) = &proxy.session {
        routed.insert(
            HeaderName::from_static(SESSION_HEADER),
            HeaderValue::from_str(session)
                .map_err(|error| NetError::InvalidRequest(error.to_string()))?,
        );
    }
    for (name, value) in headers {
        let name = if browser_forbidden(name) {
            HeaderName::try_from(format!("{FORWARD_PREFIX}{name}"))
                .map_err(|error| NetError::InvalidRequest(error.to_string()))?
        } else {
            name.clone()
        };
        routed.append(name, value.clone());
    }
    Ok((url, routed))
}

/// The URL a page element that cannot send headers (a media element) loads
/// `target` from through `proxy`.
#[must_use]
pub fn media_url(proxy: &Proxy, target: &Url) -> Url {
    let mut url = proxy.endpoint.clone();
    {
        let mut query = url.query_pairs_mut();
        query.append_pair("url", target.as_str());
        query.append_pair(MARKER_PARAM, VERSION);
        if let Some(session) = &proxy.session {
            query.append_pair(SESSION_PARAM, session);
        }
    }
    url
}

pub fn unwrap_response(
    target: &Url,
    headers: &HeaderMap,
    body_if_failed: impl FnOnce() -> String,
) -> Result<(HeaderMap, Url), NetError> {
    if let Some(code) = headers.get(ERROR_HEADER) {
        let failure = code
            .to_str()
            .ok()
            .and_then(ProxyFailure::from_code)
            .unwrap_or(ProxyFailure::Unreachable);
        return Err(failure.into_error(body_if_failed()));
    }
    let mut url = target.clone();
    let mut unwrapped = HeaderMap::with_capacity(headers.len());
    for (name, value) in headers {
        if name == FINAL_URL_HEADER {
            if let Some(final_url) = value.to_str().ok().and_then(|v| Url::parse(v).ok()) {
                url = final_url;
            }
        } else if let Some(original) = name.as_str().strip_prefix(FORWARD_PREFIX) {
            if let Ok(original) = HeaderName::try_from(original) {
                unwrapped.append(original, value.clone());
            }
        } else {
            unwrapped.append(name.clone(), value.clone());
        }
    }
    Ok((unwrapped, url))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn url(s: &str) -> Url {
        Url::parse(s).unwrap()
    }

    tilo_test_env::scenario! {
        fn the_fetch_proxy_wraps_a_request_and_unwraps_its_answer;

        phase a_request_routes_through_the_endpoint;
        {
            let mut headers = HeaderMap::new();
            headers.insert("accept", HeaderValue::from_static("application/json"));
            headers.insert("user-agent", HeaderValue::from_static("Tilo"));
            headers.insert("cookie", HeaderValue::from_static("a=1"));
            let proxy = Proxy {
                endpoint: url("https://cloud.example/_tilo/net/fetch"),
                session: Some("ab12".into()),
            };
            let (routed, sent) = route(
                &proxy,
                &url("https://api.example/v1/items?page=2&q=a b"),
                &headers,
            )
            .unwrap();
            assert_eq!(
                routed.as_str(),
                "https://cloud.example/_tilo/net/fetch?url=https%3A%2F%2Fapi.example%2Fv1%2Fitems%3Fpage%3D2%26q%3Da%2520b"
            );
            let target: String = routed
                .query_pairs()
                .find(|(k, _)| k == "url")
                .map(|(_, v)| v.into_owned())
                .unwrap();
            assert_eq!(target, "https://api.example/v1/items?page=2&q=a%20b");
            assert_eq!(sent[MARKER_HEADER], VERSION);
            assert_eq!(sent[SESSION_HEADER], "ab12");
            assert_eq!(sent["accept"], "application/json");
            assert_eq!(sent["x-tilo-forward-user-agent"], "Tilo");
            assert_eq!(sent["x-tilo-forward-cookie"], "a=1");
            assert!(!sent.contains_key("user-agent"));
        }

        phase a_response_unwraps_to_the_target_view;
        {
            let mut headers = HeaderMap::new();
            headers.insert("content-type", HeaderValue::from_static("text/xml"));
            headers.insert(
                FINAL_URL_HEADER,
                HeaderValue::from_static("https://api.example/moved"),
            );
            headers.append("x-tilo-forward-set-cookie", HeaderValue::from_static("s=1"));
            headers.append(
                "x-tilo-forward-www-authenticate",
                HeaderValue::from_static("Basic realm=\"api\""),
            );
            let (unwrapped, final_url) =
                unwrap_response(&url("https://api.example/"), &headers, String::new).unwrap();
            assert_eq!(final_url.as_str(), "https://api.example/moved");
            assert_eq!(unwrapped["set-cookie"], "s=1");
            assert_eq!(unwrapped["www-authenticate"], "Basic realm=\"api\"");
            assert_eq!(unwrapped["content-type"], "text/xml");
            assert!(!unwrapped.contains_key(FINAL_URL_HEADER));
        }

        phase a_proxy_failure_is_an_error_not_a_response;
        {
            let mut headers = HeaderMap::new();
            headers.insert(ERROR_HEADER, HeaderValue::from_static("blocked"));
            let failed = unwrap_response(&url("http://10.0.0.1/"), &headers, || {
                "private address".into()
            });
            assert_eq!(failed, Err(NetError::Blocked("private address".into())));
            for failure in [
                ProxyFailure::BadRequest,
                ProxyFailure::Blocked,
                ProxyFailure::Unreachable,
                ProxyFailure::Timeout,
                ProxyFailure::TooLarge,
                ProxyFailure::Unauthorized,
                ProxyFailure::RateLimited,
                ProxyFailure::OverBudget,
            ] {
                assert_eq!(ProxyFailure::from_code(failure.code()), Some(failure));
            }
        }

        phase configure_refuses_non_http_endpoints;
        {
            assert!(configure(Some(url("ftp://x/"))).is_err());
            assert_eq!(endpoint(), None);
        }
    }
}