rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Where the daemon's browser may connect. Every connection it makes comes
//! through rho's proxy (see [`rho_browser::proxy`]), which asks [`connect`]
//! to open it. Host names are looked up here, once, and the address that
//! passed the check is the one connected to, so a name whose DNS answer
//! changes cannot slip a link-local or cloud-metadata address past it.
//!
//! A user's own proxy is honored as rho's provider requests honor it:
//! `HTTPS_PROXY`, `HTTP_PROXY`, `ALL_PROXY` and `NO_PROXY`, and on macOS and
//! Windows the system's proxy settings, as reqwest reads them. Connections
//! that use it are opened through it, after the check of any address rho
//! has: one the browser named, or for a `socks5://` proxy, the name's
//! addresses, which rho looks up as curl does. An `http://` or `socks5h://`
//! proxy is given the name and looks it up itself, so rho does not check
//! where such a proxy connects. Loopback never goes through it, as Chrome
//! never sends loopback through a proxy.
//!
//! A proxy with credentials is refused: rho's proxy cannot tell the browser
//! from another account on the machine, which could borrow them.

use super::navigation::{is_link_local_or_metadata, is_localhost};
use crate::tools::web::ssrf;
use hyper_util::client::proxy::matcher::{Intercept, Matcher};
use rho_browser::proxy::upstream::Upstream;
use rho_browser::proxy::{Connect, Destination, Host};
use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;
use tokio::net::TcpStream;

/// The browser's [`Connect`], with the user's proxy settings as they are
/// now, or why the browser cannot use them.
pub(crate) fn connect() -> Result<Connect, String> {
    let proxies = Arc::new(user_proxies(Matcher::from_system())?);
    Ok(Arc::new(move |destination| {
        let proxies = Arc::clone(&proxies);
        Box::pin(async move { open(&destination, &proxies).await })
    }))
}

/// `proxies`, refused if it names a proxy rho cannot connect through.
fn user_proxies(proxies: Matcher) -> Result<Matcher, String> {
    // The matcher shows its proxies only for a URL; NO_PROXY may cover one
    // of these hosts, but hardly both.
    for url in [
        "http://example.com/",
        "https://example.com/",
        "http://rho-proxy-check.invalid/",
        "https://rho-proxy-check.invalid/",
    ] {
        if let Some(intercept) = proxies.intercept(&url.parse().expect("a valid URI")) {
            UserProxy::of(&intercept)?;
        }
    }
    Ok(proxies)
}

async fn open(destination: &Destination, proxies: &Matcher) -> io::Result<TcpStream> {
    match route(destination, proxies).await? {
        Route::Direct(addresses) => rho_browser::proxy::connect_first(&addresses).await,
        Route::ThroughAt {
            upstream,
            addresses,
        } => {
            rho_browser::proxy::race(&addresses, move |address| {
                let upstream = upstream.clone();
                async move {
                    let to = Destination {
                        host: Host::Ip(address.ip()),
                        port: address.port(),
                    };
                    upstream.connect(&to).await
                }
            })
            .await
        }
        Route::ThroughNamed { upstream, to } => upstream.connect(&to).await,
        Route::Refused(reason) => Err(io::Error::new(io::ErrorKind::PermissionDenied, reason)),
    }
}

/// How a connection is made.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Route {
    /// To these addresses, which passed the check.
    Direct(Vec<SocketAddr>),
    /// Through the user's proxy, asking it for the first of these addresses
    /// that answers; they passed the check.
    ThroughAt {
        upstream: Upstream,
        addresses: Vec<SocketAddr>,
    },
    /// Through the user's proxy, asking it for a name, which it looks up.
    ThroughNamed { upstream: Upstream, to: Destination },
    /// Not at all, for this reason.
    Refused(String),
}

/// What the browser named: an address, or a name to look up.
#[derive(Clone, Copy)]
enum Named<'a> {
    Ip(IpAddr),
    Name(&'a str),
}

impl std::fmt::Display for Named<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Ip(ip) => write!(f, "{ip}"),
            Self::Name(name) => f.write_str(name),
        }
    }
}

/// How the browser's connection to `destination` is made under `proxies`.
pub(super) async fn route(destination: &Destination, proxies: &Matcher) -> io::Result<Route> {
    let port = destination.port;
    let named = match &destination.host {
        Host::Ip(ip) => Named::Ip(*ip),
        // Chrome sends an IP literal as a name, an IPv6 one without
        // brackets.
        Host::Name(name) => match name.trim_matches(['[', ']']).parse::<IpAddr>() {
            Ok(ip) => Named::Ip(ip),
            Err(_) => Named::Name(name),
        },
    };
    match named {
        // Chrome sends none of these through a proxy of its own, so
        // neither does rho; a refused address is refused either way.
        Named::Ip(ip) if ip.is_loopback() || is_link_local_or_metadata(ip) => {
            return Ok(route_to(named, &[ip], port));
        }
        // Chrome takes these to this machine without asking DNS, which
        // may not know them.
        Named::Name(name) if is_localhost(name) => {
            let loopback = [Ipv6Addr::LOCALHOST.into(), Ipv4Addr::LOCALHOST.into()];
            return Ok(route_to(named, &loopback, port));
        }
        Named::Ip(_) | Named::Name(_) => {}
    }
    let user_proxy = match proxy_for(proxies, named, port) {
        Some(intercept) => Some(UserProxy::of(&intercept).map_err(io::Error::other)?),
        None => None,
    };
    let route = match (user_proxy, named) {
        (None, Named::Ip(ip)) => route_to(named, &[ip], port),
        (None, Named::Name(name)) => route_to(named, &look_up(name).await?, port),
        // The proxy looks the name up, so rho's lookup would say nothing
        // about where it connects.
        (
            Some(UserProxy {
                upstream,
                looks_up_names: true,
            }),
            Named::Name(name),
        ) => Route::ThroughNamed {
            upstream,
            to: Destination {
                host: Host::Name(name.to_owned()),
                port,
            },
        },
        (Some(UserProxy { upstream, .. }), Named::Ip(ip)) => Route::ThroughAt {
            upstream,
            addresses: vec![SocketAddr::new(ip, port)],
        },
        // A `socks5://` proxy is given addresses, which rho looks up and
        // checks, as curl and reqwest do.
        (
            Some(UserProxy {
                upstream,
                looks_up_names: false,
            }),
            Named::Name(name),
        ) => match route_to(named, &look_up(name).await?, port) {
            Route::Direct(addresses) => Route::ThroughAt {
                upstream,
                addresses,
            },
            refused => refused,
        },
    };
    Ok(route)
}

async fn look_up(name: &str) -> io::Result<Vec<IpAddr>> {
    let addresses = ssrf::resolve_host(name)
        .await
        .map_err(|error| io::Error::new(io::ErrorKind::NotFound, error.to_string()))?;
    if addresses.is_empty() {
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            format!("{name} has no addresses"),
        ));
    }
    Ok(addresses)
}

/// A direct connection to `addresses`, or its refusal if any is refused.
fn route_to(named: Named<'_>, addresses: &[IpAddr], port: u16) -> Route {
    match addresses.iter().find(|ip| is_link_local_or_metadata(**ip)) {
        Some(refused) => Route::Refused(format!(
            "{named} ({refused}) is a link-local or cloud-metadata address, which the browser does not connect to"
        )),
        None => Route::Direct(
            addresses
                .iter()
                .map(|ip| SocketAddr::new(*ip, port))
                .collect(),
        ),
    }
}

/// The user's proxy for `named` on `port`, if any. The proxy sees only a
/// host and port, so port 80 is taken for `http` and 443 for `https`, which
/// pick `HTTP_PROXY` and `HTTPS_PROXY`; any other port takes whichever of
/// the two is set, as its scheme is unknown.
fn proxy_for(proxies: &Matcher, named: Named<'_>, port: u16) -> Option<Intercept> {
    let host = match named {
        Named::Ip(IpAddr::V6(ip)) => format!("[{ip}]"),
        named => named.to_string(),
    };
    let schemes: &[&str] = match port {
        80 => &["http"],
        443 => &["https"],
        _ => &["http", "https"],
    };
    schemes.iter().find_map(|scheme| {
        let uri = format!("{scheme}://{host}:{port}/").parse().ok()?;
        proxies.intercept(&uri)
    })
}

/// A proxy of the user's that rho can connect through.
struct UserProxy {
    upstream: Upstream,
    /// Whether it is asked for names, which it looks up, rather than for
    /// addresses rho looked up: `http://` and `socks5h://` are; `socks5://`
    /// is not.
    looks_up_names: bool,
}

impl UserProxy {
    /// The proxy `intercept` names, or why rho cannot connect through it.
    fn of(intercept: &Intercept) -> Result<Self, String> {
        let uri = intercept.uri();
        let address = match (uri.host(), uri.port_u16()) {
            (Some(host), Some(port)) => format!("{host}:{port}"),
            // The ports reqwest assumes: 1080 for SOCKS, 80 for HTTP.
            (Some(host), None) => match uri.scheme_str() {
                Some("socks5" | "socks5h") => format!("{host}:1080"),
                _ => format!("{host}:80"),
            },
            (None, _) => return Err(format!("the proxy {uri} names no host")),
        };
        if intercept.basic_auth().is_some() || intercept.raw_auth().is_some() {
            return Err(format!(
                "the browser cannot connect through the proxy {uri}, because its URL holds a \
                 user name and password: rho's browser proxy can be reached by other accounts on \
                 this machine, which could borrow them. Use a proxy without credentials, or add \
                 the hosts the browser needs to NO_PROXY"
            ));
        }
        match uri.scheme_str() {
            Some("http") => Ok(Self {
                upstream: Upstream::Http { address },
                looks_up_names: true,
            }),
            Some(scheme @ ("socks5" | "socks5h")) => Ok(Self {
                upstream: Upstream::Socks5 { address },
                looks_up_names: scheme == "socks5h",
            }),
            _ => Err(format!(
                "the browser cannot connect through the proxy {uri} that HTTPS_PROXY, HTTP_PROXY, \
                 ALL_PROXY or the system settings name: rho's browser uses http://, socks5:// and \
                 socks5h:// proxies only. Point that variable at one of those, or add the hosts \
                 the browser needs to NO_PROXY"
            )),
        }
    }
}

/// Why the browser could not connect, for a page that failed with
/// `net::ERR_SOCKS_CONNECTION_FAILED`, which Chrome reports for every
/// connection rho's proxy did not make. The failed attempt left no reason
/// behind, so this asks again about `host` on `port`, the URL's, and says
/// what it finds now: the name may have changed since, or the failure may
/// have been a page it redirected to.
pub(crate) async fn explain(host: &str, port: u16) -> String {
    let destination = Destination {
        host: Host::Name(host.to_owned()),
        port,
    };
    let unexplained = "the browser could not connect to it, or to a page it redirected to";
    match route(&destination, &Matcher::from_system()).await {
        Ok(Route::Refused(reason)) => format!("{unexplained}; asked again, rho finds {reason}"),
        // Said as the lookup or proxy check said it: a failed lookup may be
        // a name that does not exist or a resolver that did not answer.
        Err(error) => format!("{unexplained}; asked again, {error}"),
        Ok(Route::ThroughAt { upstream, .. } | Route::ThroughNamed { upstream, .. }) => format!(
            "the proxy at {} did not connect to it, or to a page it redirected to",
            upstream.address()
        ),
        Ok(Route::Direct(_)) => unexplained.to_owned(),
    }
}

#[cfg(test)]
#[path = "connect_tests.rs"]
mod tests;